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
cmoulton/grokRouterAndStrongTypes
grok101/Post.swift
1
1873
// // Post.swift // grok101 // // Created by Christina Moulton on 2015-10-20. // Copyright © 2015 Teak Mobile Inc. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class Post:ResponseJSONObjectSerializable { var title:String? var body:String? var id:Int? var userId:Int? required init?(aTitle: String?, aBody: String?, anId: Int?, aUserId: Int?) { self.title = aTitle self.body = aBody self.id = anId self.userId = aUserId } required init?(json: SwiftyJSON.JSON) { self.title = json["title"].string self.body = json["body"].string self.id = json["id"].int self.userId = json["userId"].int } func toJSON() -> Dictionary<String, AnyObject> { var json = Dictionary<String, AnyObject>() if let title = title { json["title"] = title } if let body = body { json["body"] = body } if let id = id { json["id"] = id } if let userId = userId { json["userId"] = userId } return json } func description() -> String { return "ID: \(self.id)" + "User ID: \(self.userId)" + "Title: \(self.title)\n" + "Body: \(self.body)\n" } // MARK: API Calls class func postByID(id: Int, completionHandler: (Result<Post, NSError>) -> Void) { Alamofire.request(PostRouter.Get(id)) .responseObject { (response: Response<Post, NSError>) in completionHandler(response.result) } } // POST / Create func save(completionHandler: (Result<Post, NSError>) -> Void) { guard let fields:Dictionary<String, AnyObject> = self.toJSON() else { print("error: error converting newPost fields to JSON") return } Alamofire.request(PostRouter.Create(fields)) .responseObject { (response: Response<Post, NSError>) in completionHandler(response.result) } } }
mit
f32594f8bdcd702e3ecbd3a0fb72ddb7
23.644737
84
0.617521
3.72167
false
false
false
false
radazzouz/firefox-ios
Client/Frontend/UIConstants.swift
2
5613
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared public struct UIConstants { static let AboutHomePage = URL(string: "\(WebServer.sharedInstance.base)/about/home/")! static let AppBackgroundColor = UIColor.black static let SystemBlueColor = UIColor(red: 0 / 255, green: 122 / 255, blue: 255 / 255, alpha: 1) static let PrivateModePurple = UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1) static let PrivateModeLocationBackgroundColor = UIColor(red: 31 / 255, green: 31 / 255, blue: 31 / 255, alpha: 1) static let PrivateModeLocationBorderColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.15) static let PrivateModeActionButtonTintColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.8) static let PrivateModeTextHighlightColor = UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1) static let PrivateModeInputHighlightColor = UIColor(red: 120 / 255, green: 120 / 255, blue: 165 / 255, alpha: 1) static let PrivateModeAssistantToolbarBackgroundColor = UIColor(red: 89 / 255, green: 89 / 255, blue: 89 / 255, alpha: 1) static let PrivateModeToolbarTintColor = UIColor(red: 74 / 255, green: 74 / 255, blue: 74 / 255, alpha: 1) static let ToolbarHeight: CGFloat = 44 static let DefaultRowHeight: CGFloat = 58 static let DefaultPadding: CGFloat = 10 static let SnackbarButtonHeight: CGFloat = 48 // Static fonts static let DefaultChromeSize: CGFloat = 14 static let DefaultChromeSmallSize: CGFloat = 11 static let PasscodeEntryFontSize: CGFloat = 36 static let DefaultChromeFont: UIFont = UIFont.systemFont(ofSize: DefaultChromeSize, weight: UIFontWeightRegular) static let DefaultChromeBoldFont = UIFont.boldSystemFont(ofSize: DefaultChromeSize) static let DefaultChromeSmallFontBold = UIFont.boldSystemFont(ofSize: DefaultChromeSmallSize) static let PasscodeEntryFont = UIFont.systemFont(ofSize: PasscodeEntryFontSize, weight: UIFontWeightBold) // These highlight colors are currently only used on Snackbar buttons when they're pressed static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9) static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0) static let PanelBackgroundColor = UIColor.white static let SeparatorColor = UIColor(rgb: 0xcccccc) static let HighlightBlue = UIColor(red:76/255, green:158/255, blue:255/255, alpha:1) static let DestructiveRed = UIColor(red: 255/255, green: 64/255, blue: 0/255, alpha: 1.0) static let BorderColor = UIColor.black.withAlphaComponent(0.25) static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1) // These colours are used on the Menu static let MenuToolbarBackgroundColorNormal = UIColor(red: 241/255, green: 241/255, blue: 241/255, alpha: 1.0) static let MenuToolbarBackgroundColorPrivate = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1.0) static let MenuToolbarTintColorNormal = BackgroundColor static let MenuToolbarTintColorPrivate = UIColor.white static let MenuBackgroundColorNormal = UIColor(red: 223/255, green: 223/255, blue: 223/255, alpha: 1.0) static let MenuBackgroundColorPrivate = UIColor(red: 59/255, green: 59/255, blue: 59/255, alpha: 1.0) static let MenuSelectedItemTintColor = UIColor(red: 0.30, green: 0.62, blue: 1.0, alpha: 1.0) static let MenuDisabledItemTintColor = UIColor.lightGray // settings static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0) static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0) static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0) static let TableViewDisabledRowTextColor = UIColor.lightGray static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4) static let TableViewHeaderFooterHeight = CGFloat(44) static let TableViewRowErrorTextColor = UIColor(red: 255/255, green: 0/255, blue: 26/255, alpha: 1.0) static let TableViewRowWarningTextColor = UIColor(red: 245/255, green: 166/255, blue: 35/255, alpha: 1.0) static let TableViewRowActionAccessoryColor = UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1.0) // Firefox Orange static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1) // List of Default colors to use for Favicon backgrounds static let DefaultColorStrings = ["2e761a", "399320", "40a624", "57bd35", "70cf5b", "90e07f", "b1eea5", "881606", "aa1b08", "c21f09", "d92215", "ee4b36", "f67964", "ffa792", "025295", "0568ba", "0675d3", "0996f8", "2ea3ff", "61b4ff", "95cdff", "00736f", "01908b", "01a39d", "01bdad", "27d9d2", "58e7e6", "89f4f5", "c84510", "e35b0f", "f77100", "ff9216", "ffad2e", "ffc446", "ffdf81", "911a2e", "b7223b", "cf2743", "ea385e", "fa526e", "ff7a8d", "ffa7b3" ] // Passcode dot gray static let PasscodeDotColor = UIColor(rgb: 0x4A4A4A) /// JPEG compression quality for persisted screenshots. Must be between 0-1. static let ScreenshotQuality: Float = 0.3 static let ActiveScreenshotQuality: CGFloat = 0.5 static let OKString = NSLocalizedString("OK", comment: "OK button") static let CancelString = NSLocalizedString("Cancel", comment: "Label for Cancel button") }
mpl-2.0
30c7a6187261d0876b5f0a5cd813de02
66.626506
458
0.72047
3.635363
false
false
false
false
CanyFrog/HCComponent
HCSource/UIFont+Extension.swift
1
2337
// // UIFont+Extension.swift // HCComponents // // Created by Magee Huang on 4/28/17. // Copyright © 2017 Person Inc. All rights reserved. // import Foundation // MARK: - load font icon public extension UIFont { private static var iconFonts: [String: AnyClass]? = nil /// register font public static func registerFont(name: String, clz: AnyClass) { if iconFonts == nil { iconFonts = Dictionary() } if iconFonts?[name] != nil || UIFont.familyNames.contains(name) { return } guard let fontUrl = Bundle.resourceUrl(clz: clz, fileName: name, fileExtension: "ttf") else { fatalError("\(name) not found in bundle") } guard let data = NSData(contentsOf: fontUrl), let provider = CGDataProvider(data: data) else { return } let font = CGFont(provider) // raise error var error: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(font, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as! NSError NSException(name: .internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } // success iconFonts?[name] = clz } /// unregister font public static func unregisterFont(name: String, clz: AnyClass) { if iconFonts?[name] == nil || !UIFont.familyNames.contains(name) { return } guard let fontUrl = Bundle.resourceUrl(clz: clz, fileName: name, fileExtension: "ttf") else { fatalError("\(name) not found in bundle") } var error: Unmanaged<CFError>? if !CTFontManagerUnregisterFontsForURL(fontUrl as CFURL, .none, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as! NSError NSException(name: .internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } // unregister success iconFonts?[name] = nil } public static func unregisterAllFont() { _ = iconFonts?.map{ unregisterFont(name: $0, clz: $1) } } }
mit
7209119ef5cc23a4122854edff8a9a81
42.259259
149
0.652825
4.738337
false
false
false
false
aschwaighofer/swift
test/SILOptimizer/exclusivity_static_diagnostics.swift
2
25505
// RUN: %target-swift-frontend -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify // RUN: %target-swift-frontend -enforce-exclusivity=checked -swift-version 4 -emit-sil -primary-file %s -o /dev/null -verify -enable-ownership-stripping-after-serialization import Swift func takesTwoInouts<T>(_ p1: inout T, _ p2: inout T) { } func simpleInoutDiagnostic() { var i = 7 // FIXME: This diagnostic should be removed if static enforcement is // turned on by default. // expected-error@+4{{inout arguments are not allowed to alias each other}} // expected-note@+3{{previous aliasing argument}} // expected-error@+2{{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} takesTwoInouts(&i, &i) } func inoutOnInoutParameter(p: inout Int) { // expected-error@+4{{inout arguments are not allowed to alias each other}} // expected-note@+3{{previous aliasing argument}} // expected-error@+2{{overlapping accesses to 'p', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} takesTwoInouts(&p, &p) } func swapNoSuppression(_ i: Int, _ j: Int) { var a: [Int] = [1, 2, 3] // expected-error@+2{{overlapping accesses to 'a', but modification requires exclusive access; consider calling MutableCollection.swapAt(_:_:)}} // expected-note@+1{{conflicting access is here}} swap(&a[i], &a[j]) } class SomeClass { } struct StructWithMutatingMethodThatTakesSelfInout { var f = SomeClass() mutating func mutate(_ other: inout StructWithMutatingMethodThatTakesSelfInout) { } mutating func mutate(_ other: inout SomeClass) { } mutating func callMutatingMethodThatTakesSelfInout() { // expected-error@+4{{inout arguments are not allowed to alias each other}} // expected-note@+3{{previous aliasing argument}} // expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} mutate(&self) } mutating func callMutatingMethodThatTakesSelfStoredPropInout() { // expected-error@+2{{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} mutate(&self.f) } } var globalStruct1 = StructWithMutatingMethodThatTakesSelfInout() func callMutatingMethodThatTakesGlobalStoredPropInout() { // expected-error@+2{{overlapping accesses to 'globalStruct1', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} globalStruct1.mutate(&globalStruct1.f) } class ClassWithFinalStoredProp { final var s1: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout() final var s2: StructWithMutatingMethodThatTakesSelfInout = StructWithMutatingMethodThatTakesSelfInout() final var i = 7 func callMutatingMethodThatTakesClassStoredPropInout() { s1.mutate(&s2.f) // no-warning // expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} s1.mutate(&s1.f) let local1 = self // expected-error@+2{{overlapping accesses to 's1', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} local1.s1.mutate(&local1.s1.f) } } func violationWithGenericType<T>(_ p: T) { var local = p // expected-error@+4{{inout arguments are not allowed to alias each other}} // expected-note@+3{{previous aliasing argument}} // expected-error@+2{{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} takesTwoInouts(&local, &local) } // Helper. struct StructWithTwoStoredProp { var f1: Int = 7 var f2: Int = 8 } // Take an unsafe pointer to a stored property while accessing another stored property. func violationWithUnsafePointer(_ s: inout StructWithTwoStoredProp) { withUnsafePointer(to: &s.f1) { (ptr) in // expected-error@-1 {{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}} _ = s.f1 // expected-note@-1 {{conflicting access is here}} } // Statically treat accesses to separate stored properties in structs as // accessing separate storage. withUnsafePointer(to: &s.f1) { (ptr) in // no-error _ = s.f2 } } // Tests for Fix-Its to replace swap(&collection[a], &collection[b]) with // collection.swapAt(a, b) struct StructWithField { var f = 12 } struct StructWithFixits { var arrayProp: [Int] = [1, 2, 3] var dictionaryProp: [Int : Int] = [0 : 10, 1 : 11] mutating func shouldHaveFixIts<T>(_ i: Int, _ j: Int, _ param: T, _ paramIndex: T.Index) where T : MutableCollection { var array1 = [1, 2, 3] // expected-error@+2{{overlapping accesses}}{{5-41=array1.swapAt(i + 5, j - 2)}} // expected-note@+1{{conflicting access is here}} swap(&array1[i + 5], &array1[j - 2]) // expected-error@+2{{overlapping accesses}}{{5-49=self.arrayProp.swapAt(i, j)}} // expected-note@+1{{conflicting access is here}} swap(&self.arrayProp[i], &self.arrayProp[j]) var localOfGenericType = param // expected-error@+2{{overlapping accesses}}{{5-75=localOfGenericType.swapAt(paramIndex, paramIndex)}} // expected-note@+1{{conflicting access is here}} swap(&localOfGenericType[paramIndex], &localOfGenericType[paramIndex]) // expected-error@+2{{overlapping accesses}}{{5-39=array1.swapAt(i, j)}} // expected-note@+1{{conflicting access is here}} Swift.swap(&array1[i], &array1[j]) // no-crash } mutating func shouldHaveNoFixIts(_ i: Int, _ j: Int) { var s = StructWithField() // expected-error@+2{{overlapping accesses}}{{none}} // expected-note@+1{{conflicting access is here}} swap(&s.f, &s.f) var array1 = [1, 2, 3] var array2 = [1, 2, 3] // Swapping between different arrays should cannot have the // Fix-It. swap(&array1[i], &array2[j]) // no-warning no-fixit swap(&array1[i], &self.arrayProp[j]) // no-warning no-fixit // Dictionaries aren't MutableCollections so don't support swapAt(). // expected-error@+2{{overlapping accesses}}{{none}} // expected-note@+1{{conflicting access is here}} swap(&dictionaryProp[i], &dictionaryProp[j]) // We could safely Fix-It this but don't now because the left and // right bases are not textually identical. // expected-error@+2{{overlapping accesses}}{{none}} // expected-note@+1{{conflicting access is here}} swap(&self.arrayProp[i], &arrayProp[j]) // We could safely Fix-It this but we're not that heroic. // We don't suppress when swap() is used as a value let mySwap: (inout Int, inout Int) -> () = swap // expected-error@+2{{overlapping accesses}}{{none}} // expected-note@+1{{conflicting access is here}} mySwap(&array1[i], &array1[j]) func myOtherSwap<T>(_ a: inout T, _ b: inout T) { swap(&a, &b) // no-warning } // expected-error@+2{{overlapping accesses}}{{none}} // expected-note@+1{{conflicting access is here}} mySwap(&array1[i], &array1[j]) } } func takesInoutAndNoEscapeClosure<T>(_ p: inout T, _ c: () -> ()) { } func callsTakesInoutAndNoEscapeClosure() { var local = 5 takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} local = 8 // expected-note {{conflicting access is here}} } } func inoutReadWriteInout(x: inout Int) { // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} takesInoutAndNoEscapeClosure(&x, { _ = x }) } func inoutWriteWriteInout(x: inout Int) { // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} takesInoutAndNoEscapeClosure(&x, { x = 42 }) } func callsTakesInoutAndNoEscapeClosureWithRead() { var local = 5 takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} _ = local // expected-note {{conflicting access is here}} } } func takesInoutAndNoEscapeClosureThatThrows<T>(_ p: inout T, _ c: () throws -> ()) { } func callsTakesInoutAndNoEscapeClosureThatThrowsWithNonThrowingClosure() { var local = 5 takesInoutAndNoEscapeClosureThatThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} local = 8 // expected-note {{conflicting access is here}} } } func takesInoutAndNoEscapeClosureAndThrows<T>(_ p: inout T, _ c: () -> ()) throws { } func callsTakesInoutAndNoEscapeClosureAndThrows() { var local = 5 try! takesInoutAndNoEscapeClosureAndThrows(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} local = 8 // expected-note {{conflicting access is here}} } } func takesTwoNoEscapeClosures(_ c1: () -> (), _ c2: () -> ()) { } func callsTakesTwoNoEscapeClosures() { var local = 7 takesTwoNoEscapeClosures({local = 8}, {local = 9}) // no-error _ = local } func takesInoutAndEscapingClosure<T>(_ p: inout T, _ c: @escaping () -> ()) { } func callsTakesInoutAndEscapingClosure() { var local = 5 takesInoutAndEscapingClosure(&local) { // no-error local = 8 } } func callsClosureLiteralImmediately() { var i = 7; // Closure literals that are called immediately are considered nonescaping _ = ({ (p: inout Int) in i // expected-note@-1 {{conflicting access is here}} } )(&i) // expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}} } func callsStoredClosureLiteral() { var i = 7; let c = { (p: inout Int) in i} // Closure literals that are stored and later called are treated as escaping // We don't expect a static exclusivity diagnostic here, but the issue // will be caught at run time _ = c(&i) // no-error } // Calling this with an inout expression for the first parameter performs a // read access for the duration of a call func takesUnsafePointerAndNoEscapeClosure<T>(_ p: UnsafePointer<T>, _ c: () -> ()) { } // Calling this with an inout expression for the first parameter performs a // modify access for the duration of a call func takesUnsafeMutablePointerAndNoEscapeClosure<T>(_ p: UnsafeMutablePointer<T>, _ c: () -> ()) { } func callsTakesUnsafePointerAndNoEscapeClosure() { var local = 1 takesUnsafePointerAndNoEscapeClosure(&local) { // expected-note {{conflicting access is here}} local = 2 // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} } } func callsTakesUnsafePointerAndNoEscapeClosureThatReads() { var local = 1 // Overlapping reads takesUnsafePointerAndNoEscapeClosure(&local) { _ = local // no-error } } func callsTakesUnsafeMutablePointerAndNoEscapeClosureThatReads() { var local = 1 // Overlapping modify and read takesUnsafeMutablePointerAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} _ = local // expected-note {{conflicting access is here}} } } func takesThrowingAutoClosureReturningGeneric<T: Equatable>(_ : @autoclosure () throws -> T) { } func takesInoutAndClosure<T>(_: inout T, _ : () -> ()) { } func callsTakesThrowingAutoClosureReturningGeneric() { var i = 0 takesInoutAndClosure(&i) { // expected-error {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}} takesThrowingAutoClosureReturningGeneric(i) // expected-note {{conflicting access is here}} } } struct StructWithMutatingMethodThatTakesAutoclosure { var f = 2 mutating func takesAutoclosure(_ p: @autoclosure () throws -> ()) rethrows { } } func conflictOnSubPathInNoEscapeAutoclosure() { var s = StructWithMutatingMethodThatTakesAutoclosure() s.takesAutoclosure(s.f = 2) // expected-error@-1 {{overlapping accesses to 's', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2 {{conflicting access is here}} } func conflictOnWholeInNoEscapeAutoclosure() { var s = StructWithMutatingMethodThatTakesAutoclosure() takesInoutAndNoEscapeClosure(&s.f) { // expected-error@-1 {{overlapping accesses to 's.f', but modification requires exclusive access; consider copying to a local variable}} s = StructWithMutatingMethodThatTakesAutoclosure() // expected-note@-1 {{conflicting access is here}} } } struct ParameterizedStruct<T> { mutating func takesFunctionWithGenericReturnType(_ f: (Int) -> T) {} } func testReabstractionThunk(p1: inout ParameterizedStruct<Int>, p2: inout ParameterizedStruct<Int>) { // Since takesFunctionWithGenericReturnType() takes a closure with a generic // return type it expects the value to be returned @out. But the closure // here has an 'Int' return type, so the compiler uses a reabstraction thunk // to pass the closure to the method. // This tests that we still detect access violations for closures passed // using a reabstraction thunk. p1.takesFunctionWithGenericReturnType { _ in // expected-error@-1 {{overlapping accesses to 'p1', but modification requires exclusive access; consider copying to a local variable}} p2 = p1 // expected-note@-1 {{conflicting access is here}} return 3 } } func takesNoEscapeBlockClosure ( _ p: inout Int, _ c: @convention(block) () -> () ) { } func takesEscapingBlockClosure ( _ p: inout Int, _ c: @escaping @convention(block) () -> () ) { } func testCallNoEscapeBlockClosure() { var i = 7 takesNoEscapeBlockClosure(&i) { // expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}} i = 7 // expected-note@-1 {{conflicting access is here}} } } func testCallNoEscapeBlockClosureRead() { var i = 7 takesNoEscapeBlockClosure(&i) { // expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}} _ = i // expected-note@-1 {{conflicting access is here}} } } func testCallEscapingBlockClosure() { var i = 7 takesEscapingBlockClosure(&i) { // no-warning i = 7 } } func testCallNonEscapingWithEscapedBlock() { var i = 7 let someBlock : @convention(block) () -> () = { i = 8 } takesNoEscapeBlockClosure(&i, someBlock) // no-warning } func takesInoutAndClosureWithGenericArg<T>(_ p: inout Int, _ c: (T) -> Int) { } func callsTakesInoutAndClosureWithGenericArg() { var i = 7 takesInoutAndClosureWithGenericArg(&i) { (p: Int) in // expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}} return i + p // expected-note@-1 {{conflicting access is here}} } } func takesInoutAndClosureTakingNonOptional(_ p: inout Int, _ c: (Int) -> ()) { } func callsTakesInoutAndClosureTakingNonOptionalWithClosureTakingOptional() { var i = 7 // Test for the thunk converting an (Int?) -> () to an (Int) -> () takesInoutAndClosureTakingNonOptional(&i) { (p: Int?) in // expected-error@-1 {{overlapping accesses to 'i', but modification requires exclusive access; consider copying to a local variable}} i = 8 // expected-note@-1 {{conflicting access is here}} } } // Helper. func doOne(_ f: () -> ()) { f() } func noEscapeBlock() { var x = 3 doOne { // expected-error@+2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@+1{{conflicting access is here}} takesInoutAndNoEscapeClosure(&x, { _ = x }) } } func inoutSeparateStructStoredProperties() { var s = StructWithTwoStoredProp() takesTwoInouts(&s.f1, &s.f2) // no-error } func inoutSameStoredProperty() { var s = StructWithTwoStoredProp() takesTwoInouts(&s.f1, &s.f1) // expected-error@-1{{overlapping accesses to 's.f1', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2{{conflicting access is here}} } func inoutSeparateTupleElements() { var t = (1, 4) takesTwoInouts(&t.0, &t.1) // no-error } func inoutSameTupleElement() { var t = (1, 4) takesTwoInouts(&t.0, &t.0) // expected-error@-1{{overlapping accesses to 't.0', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2{{conflicting access is here}} } func inoutSameTupleNamedElement() { var t = (name1: 1, name2: 4) takesTwoInouts(&t.name2, &t.name2) // expected-error@-1{{overlapping accesses to 't.name2', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2{{conflicting access is here}} } func inoutSamePropertyInSameTuple() { var t = (name1: 1, name2: StructWithTwoStoredProp()) takesTwoInouts(&t.name2.f1, &t.name2.f1) // expected-error@-1{{overlapping accesses to 't.name2.f1', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2{{conflicting access is here}} } // Noescape closures and separate stored structs func callsTakesInoutAndNoEscapeClosureNoWarningOnSeparateStored() { var local = StructWithTwoStoredProp() takesInoutAndNoEscapeClosure(&local.f1) { local.f2 = 8 // no-error } } func callsTakesInoutAndNoEscapeClosureWarningOnSameStoredProp() { var local = StructWithTwoStoredProp() takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}} local.f1 = 8 // expected-note {{conflicting access is here}} } } func callsTakesInoutAndNoEscapeClosureWarningOnAggregateAndStoredProp() { var local = StructWithTwoStoredProp() takesInoutAndNoEscapeClosure(&local) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} local.f1 = 8 // expected-note {{conflicting access is here}} } } func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndAggregate() { var local = StructWithTwoStoredProp() takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}} local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}} } } func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothPropertyAndAggregate() { var local = StructWithTwoStoredProp() takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}} local.f1 = 8 // We want the diagnostic on the access for the aggregate and not the projection. local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}} } } func callsTakesInoutAndNoEscapeClosureWarningOnStoredPropAndBothAggregateAndProperty() { var local = StructWithTwoStoredProp() takesInoutAndNoEscapeClosure(&local.f1) { // expected-error {{overlapping accesses to 'local.f1', but modification requires exclusive access; consider copying to a local variable}} // We want the diagnostic on the access for the aggregate and not the projection. local = StructWithTwoStoredProp() // expected-note {{conflicting access is here}} local.f1 = 8 } } struct MyStruct<T> { var prop = 7 mutating func inoutBoundGenericStruct() { takesTwoInouts(&prop, &prop) // expected-error@-1{{overlapping accesses to 'self.prop', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2{{conflicting access is here}} } } func testForLoopCausesReadAccess() { var a: [Int] = [1] takesInoutAndNoEscapeClosure(&a) { // expected-error {{overlapping accesses to 'a', but modification requires exclusive access; consider copying to a local variable}} for _ in a { // expected-note {{conflicting access is here}} } } } func testKeyPathStructField() { let getF = \StructWithField.f var local = StructWithField() takesInoutAndNoEscapeClosure(&local[keyPath: getF]) { // expected-error {{overlapping accesses to 'local', but modification requires exclusive access; consider copying to a local variable}} local.f = 17 // expected-note {{conflicting access is here}} } } func testKeyPathWithClassFinalStoredProperty() { let getI = \ClassWithFinalStoredProp.i let local = ClassWithFinalStoredProp() // Ideally we would diagnose statically here, but it is not required by the // model. takesTwoInouts(&local[keyPath: getI], &local[keyPath: getI]) } func takesInoutAndOptionalClosure(_: inout Int, _ f: (()->())?) { f!() } // An optional closure is not considered @noescape: // This violation will only be caught dynamically. // // apply %takesInoutAndOptionalClosure(%closure) // : $@convention(thin) (@inout Int, @owned Optional<@callee_guaranteed () -> ()>) -> () func testOptionalClosure() { var x = 0 takesInoutAndOptionalClosure(&x) { x += 1 } } func takesInoutAndOptionalBlock(_: inout Int, _ f: (@convention(block) ()->())?) { f!() } // An optional block is not be considered @noescape. // This violation will only be caught dynamically. func testOptionalBlock() { var x = 0 takesInoutAndOptionalBlock(&x) { x += 1 } } // Diagnost a conflict on a noescape closure that is conditionally passed as a function argument. // // <rdar://problem/42560459> [Exclusivity] Failure to statically diagnose a conflict when passing conditional noescape closures. struct S { var x: Int mutating func takeNoescapeClosure(_ f: ()->()) { f() } mutating func testNoescapePartialApplyPhiUse(z : Bool) { func f1() { x = 1 // expected-note {{conflicting access is here}} } func f2() { x = 1 // expected-note {{conflicting access is here}} } takeNoescapeClosure(z ? f1 : f2) // expected-error@-1 2 {{overlapping accesses to 'self', but modification requires exclusive access; consider copying to a local variable}} } } func doit(x: inout Int, _ fn: () -> ()) {} func nestedConflict(x: inout Int) { doit(x: &x, x == 0 ? { x = 1 } : { x = 2}) // expected-error@-1 2{{overlapping accesses to 'x', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2 2{{conflicting access is here}} } // Avoid diagnosing a conflict on disjoint struct properies when one is a `let`. // This requires an address projection before loading the `let` property. // // <rdar://problem/35561050> [SR-10145][Exclusivity] SILGen loads entire struct when reading captured 'let' stored property struct DisjointLetMember { var dummy: AnyObject // Make this a nontrivial struct because the SIL is more involved. mutating func get(makeValue: ()->Int) -> Int { return makeValue() } } class IntWrapper { var x = 0 } struct DisjointLet { let a = 2 // Using a `let` forces a full load. let b: IntWrapper var cache: DisjointLetMember init(b: IntWrapper) { self.b = b self.cache = DisjointLetMember(dummy: b) } mutating func testDisjointLet() -> Int { // Access to inout `self` for member .cache`. return cache.get { // Access to captured `self` for member .cache`. a + b.x } } } // ----------------------------------------------------------------------------- // coroutineWithClosureArg: AccessedSummaryAnalysis must consider // begin_apply a valid user of partial_apply. // // Test that this does not assert in hasExpectedUsesOfNoEscapePartialApply. // // This test needs two closures, one to capture the variable, another // to recapture the variable, so AccessSummary is forced to process // the closure. func coroutineWithClosureArg(i: Int, x: inout Int, d: inout Dictionary<Int, Int>) { { d[i, default: x] = 0 }() } // ----------------------------------------------------------------------------- // struct TestConflictInCoroutineClosureArg { static let defaultKey = 0 var dictionary = [defaultKey:0] mutating func incrementValue(at key: Int) { dictionary[key, default: dictionary[TestConflictInCoroutineClosureArg.defaultKey]!] += 1 // expected-error@-2 {{overlapping accesses to 'self.dictionary', but modification requires exclusive access; consider copying to a local variable}} // expected-note@-2 {{conflicting access is here}} } }
apache-2.0
773ecd3bac8b04f41fcdf51b7db62edf
36.562592
191
0.707351
4.208746
false
false
false
false
br1sk/brisk-ios
Brisk iOS/Radar/EnterDetailsViewController.swift
1
2283
import UIKit import InterfaceBacked final class TextView: UITextView, KeyboardObservable { private var observers: [Any]? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) observers = keyboardObservers() } deinit { removeObservers(observers ?? []) } } final class EnterDetailsViewController: UIViewController, StoryboardBacked { // MARK: - Types enum Styling { case normal, placeholder } // MARK: - Properties @IBOutlet weak var textView: TextView! @IBOutlet weak var textBottomSpaceConstraint: NSLayoutConstraint! var prefilledContent = "" var placeholder = "" var onDisappear: (String) -> Void = { _ in } // MARK: - UIViewController Methods override func viewWillAppear(_ animated: Bool) { if placeholder.isNotEmpty && prefilledContent.isEmpty { applyStyling(.placeholder) textView.text = placeholder } else { applyStyling(.normal) textView.text = prefilledContent } } override func viewDidAppear(_ animated: Bool) { textView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { if placeholder.isEmpty || textView.text != placeholder { onDisappear(textView.text) } } // MARK: - Private Methods fileprivate func moveCursorToStart() { DispatchQueue.main.async { // swiftlint:disable:next legacy_constructor self.textView.selectedRange = NSMakeRange(0, 0) } } fileprivate func applyStyling(_ styling: Styling) { switch styling { case .normal: textView.textColor = UIColor.darkText case .placeholder: textView.textColor = UIColor.lightGray } } } // MARK: - UITextViewDelegate Methods extension EnterDetailsViewController: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { if textView.text == placeholder { moveCursorToStart() } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let length = textView.text.count + text.count - range.length if length > 0 { if textView.text == placeholder { applyStyling(.normal) textView.text = "" } } else { applyStyling(.placeholder) moveCursorToStart() } return true } }
mit
b4212eaae3b1d27b65b03f2ed5c2cdaa
22.060606
113
0.689006
4.251397
false
false
false
false
davidpaul0880/ChristiansSongs
christiansongs/MasterViewController.swift
1
18473
// // MasterViewController.swift // christiansongs // // Created by jijo on 3/9/15. // Copyright (c) 2015 jeesmon. All rights reserved. // import UIKit import CoreData extension NSManagedObject { func uppercaseFirstLetterOfName() -> String { self.willAccessValueForKey("uppercaseFirstLetterOfName") let us = self.valueForKey("title_ml")!.uppercaseString as NSString let restr = us.substringToIndex(1) self.didAccessValueForKey("uppercaseFirstLetterOfName") return String(restr) } func uppercaseFirstLetterOfEngName() -> String { self.willAccessValueForKey("uppercaseFirstLetterOfEngName") let us = self.valueForKey("title_en")!.uppercaseString as NSString let restr = us.substringToIndex(1) self.didAccessValueForKey("uppercaseFirstLetterOfEngName") return String(restr) } } enum LangType { case Malyalam case Englisg } class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchBarDelegate, UISearchDisplayDelegate { //@IBOutlet weak var searchhBar: UISearchBar! typealias Closure = () -> () private var closures = [String: Closure]() var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil var selectedSongFromBM : Songs? //@IBOutlet weak var searchBar : UISearchBar! //@IBOutlet weak var searchDisplayController : UISearchDisplayController! var language : LangType = LangType.Malyalam var titleField : String { if language == LangType.Malyalam { return "title_ml" }else{ return "title_en" } } func infoClicked() { [self.performSegueWithIdentifier("showInfo", sender: self)] } func bookMarkClicked(){ } func languageChanged(sender:UIBarButtonItem!) { if sender.title == "ENG" { language = LangType.Englisg sender.title = "MAL" }else{ language = LangType.Malyalam sender.title = "ENG" } _fetchedResultsController = nil self.tableView.reloadData() } func reFetchData(searchText : String, Scope selectedScope : Int){ //("searchText =\(searchText)") let fetchRequest = self.fetchedResultsController.fetchRequest //if selectedScope == 0 { let predicate = NSPredicate(format: "(title_en BEGINSWITH[cd] %@ or title_ml BEGINSWITH[cd] %@)", argumentArray: [searchText,searchText]) fetchRequest.predicate = predicate /*}else{ let predicate = NSPredicate(format: "(%@ CONTAINS[c] %@)", argumentArray: [titleField, searchText]) fetchRequest.predicate = predicate }*/ var error: NSError? = nil do { try _fetchedResultsController!.performFetch() } catch let error1 as NSError { error = error1 // 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. //println("Unresolved error \(error), \(error.userInfo)") abort() } self.tableView.reloadData() } func delayed(delay: Double, name: String, closure: Closure){ closures[name] = closure dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ) , dispatch_get_main_queue()){ if let clor = self.closures[name] { clor() self.closures[name] = nil } } } func cancelDelayed(name: String) { closures[name] = nil } func searchBar(searchBar: UISearchBar, textDidChange searchText: String){ //self performSelector:@selector(sendInlineSearch:) withObject:searchBar afterDelay:1.0]; //[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendInlineSearch:) object:searchBar]; //self.cancelDelayed("search") //self.delayed(0.5, name: "search"){ self.reFetchData(searchText, Scope: 0) //} //self.reFetchData(searchText, Scope: 0) //self.searchDisplayController!.searchBar.selectedScopeButtonIndex } /*func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { self.reFetchData(searchBar.text, Scope: selectedScope) }*/ func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = nil let fetchRequest = self.fetchedResultsController.fetchRequest fetchRequest.predicate = nil var error: NSError? = nil do { try _fetchedResultsController!.performFetch() } catch let error1 as NSError { error = error1 // 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. //println("Unresolved error \(error), \(error.userInfo)") abort() } searchBar.resignFirstResponder() self.tableView.reloadData() } //optional func searchBarSearchButtonClicked(searchBar: UISearchBar) // called when keyboard search button pressed //optional func searchBarCancelButtonClicked(searchBar: UISearchBar) override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewWillAppear(animated: Bool) { //self.navigationController!.toolbarHidden = false; selectedSongFromBM = nil; super.viewWillAppear(animated); } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //self.navigationController!.toolbarHidden = true; let isPad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad if isPad { if self.detailViewController?.songObj == nil { self.detailViewController!.songObj = BMDao().getSelectedSong((34)) if self.detailViewController!.songObj != nil { self.detailViewController!.configureView() } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //self.navigationItem.leftBarButtonItem = self.editButtonItem() let btn : UIButton = UIButton(type: UIButtonType.InfoLight) btn.addTarget(self, action: Selector("infoClicked"), forControlEvents: UIControlEvents.TouchUpInside) //let infoButton = UIBarButtonItem(customView: btn) self.navigationItem.leftBarButtonItem?.customView = btn let titlee = language == LangType.Malyalam ? "ENG" : "MAL" let langbuttom = UIBarButtonItem(title: titlee, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("languageChanged:")) langbuttom.possibleTitles = (NSSet(array: ["ENG", "MAL"]) as! Set<String>) self.navigationItem.rightBarButtonItem = langbuttom if let split = self.splitViewController { let controllers:[UINavigationController] = split.viewControllers as! [UINavigationController] self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /*func insertNewObject(sender: AnyObject) { let context = self.fetchedResultsController.managedObjectContext let entity = self.fetchedResultsController.fetchRequest.entity! let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as NSManagedObject // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. newManagedObject.setValue(NSDate(), forKey: "timeStamp") // Save the context. var error: NSError? = nil if !context.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } }*/ // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController if selectedSongFromBM != nil { controller.language = self.language controller.songObj = selectedSongFromBM } else if let indexPath = self.tableView.indexPathForSelectedRow { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Songs controller.language = self.language controller.songObj = object } controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true let orientation = UIApplication.sharedApplication().statusBarOrientation if orientation.isPortrait { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.hideMaster() // Portrait } else { // Landscape } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.name } override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return self.fetchedResultsController.sectionForSectionIndexTitle(title, atIndex: index) } override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return self.fetchedResultsController.sectionIndexTitles } /*override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true }*/ /* override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let context = self.fetchedResultsController.managedObjectContext context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) var error: NSError? = nil if !context.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } } */ func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Songs if language == LangType.Malyalam { cell.textLabel!.text = object.title_ml }else{ cell.textLabel!.text = object.title_en } } // MARK: - Fetched results controller var fetchedResultsController: MyNSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Songs", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 //caseInsensitiveCompare localizedCaseInsensitiveCompare localizedStandardCompare // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: titleField, ascending: true, selector: Selector("caseInsensitiveCompare:")) //let sortDescriptors = [sortDescriptor] fetchRequest.sortDescriptors = [sortDescriptor] var keypath = "uppercaseFirstLetterOfName" if language == LangType.Englisg { keypath = "uppercaseFirstLetterOfEngName" } // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = MyNSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: keypath, cacheName: nil) aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController var error: NSError? = nil do { try _fetchedResultsController!.performFetch() } catch let error1 as NSError { error = error1 // 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. //println("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: MyNSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?){ switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) default: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() //("end fetch"); } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } */ }
gpl-2.0
b004183660773056479722be51e5f3c7
38.220807
360
0.637904
6.009434
false
false
false
false
ddaguro/clintonconcord
OIMApp/NavigationCell.swift
1
1072
// // NavigationTableCell.swift // OIMApp // // Created by Linh NGUYEN on 5/6/15. // Copyright (c) 2015 Persistent Systems. All rights reserved. // import Foundation import UIKit class NavigationCell : UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var countLabel: UILabel! @IBOutlet var countContainer: UIView! override func awakeFromNib() { titleLabel.font = UIFont(name: MegaTheme.boldFontName, size: 16) titleLabel.textColor = UIColor.whiteColor() countLabel.font = UIFont(name: MegaTheme.boldFontName, size: 13) countLabel.textColor = UIColor.whiteColor() countContainer.backgroundColor = UIColor(red: 0.33, green: 0.62, blue: 0.94, alpha: 1.0) countContainer.layer.cornerRadius = 15 } override func setSelected(selected: Bool, animated: Bool) { let countNotAvailable = countLabel.text == nil countContainer.hidden = countNotAvailable countLabel.hidden = countNotAvailable } }
mit
f40fb41bffa96e2188540cb703eb41ee
27.236842
96
0.652985
4.600858
false
false
false
false
infinitetoken/Arcade
Sources/Adapters/Core Data/CoreDataAdapter.swift
1
7725
// // CoreDataAdapter.swift // Arcade // // Created by A.C. Wright Design on 10/30/17. // Copyright © 2017 A.C. Wright Design. All rights reserved. // import Foundation import CoreData open class CoreDataAdapter { public static var type: Arcade.AdapterType = .coreData public enum AdapterError: LocalizedError { case entityNotFound(String) case entityNotStorable case invalidResult public var errorDescription: String? { switch self { case .entityNotFound(_): return "Entity Not Found" case .entityNotStorable: return "Entity Not Storable" case .invalidResult: return "Invalid Result" } } public var failureReason: String? { switch self { case .entityNotFound(let entityName): return "The entity (\(entityName)) is not a valid entity name." case .entityNotStorable: return "The entity provided could not be converted to storable object." case .invalidResult: return "The fetched results were invalid." } } public var recoverySuggestion: String? { switch self { case .entityNotFound(_): return "Provide a valid entity name." case .entityNotStorable: return "Provide a valid storable entity." case .invalidResult: return "Try a different request." } } } public var managedObjectContext: NSManagedObjectContext public var persistentIdName: String public init(managedObjectContext: NSManagedObjectContext, persistentIdName: String = "id") { self.managedObjectContext = managedObjectContext self.persistentIdName = persistentIdName } } extension CoreDataAdapter: Adapter { @discardableResult public func insert<I>(storable: I) async throws -> I where I : Storable { guard let table = I.table as? CoreDataTable else { throw AdapterError.entityNotFound(I.table.name) } guard let entity = NSEntityDescription.entity(forEntityName: table.entityName, in: self.managedObjectContext) else { throw AdapterError.entityNotFound(table.entityName) } guard let object = NSManagedObject(entity: entity, insertInto: self.managedObjectContext) as? CoreDataEntity else { throw AdapterError.entityNotStorable } object.update(with: storable) if self.managedObjectContext.hasChanges { try self.managedObjectContext.save() } return storable } public func find<I>(id: String) async throws -> I? where I : Viewable { guard let table = I.table as? CoreDataTable else { throw AdapterError.entityNotFound(I.table.name) } guard let entity = NSEntityDescription.entity(forEntityName: table.entityName, in: self.managedObjectContext), let entityName = entity.name else { throw AdapterError.entityNotFound(table.entityName) } let expression = Expression.equal(self.persistentIdName, id) let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName) fetchRequest.fetchLimit = 1 fetchRequest.predicate = expression.predicate() guard let result = try self.managedObjectContext.fetch(fetchRequest) as? [CoreDataEntity] else { throw AdapterError.invalidResult } if let object = result.map({ (object) -> Storable in return object.storable }).first as? I { return object } else { return nil } } public func fetch<I>(query: Query?, sorts: [Sort] = [], limit: Int = 0, offset: Int = 0) async throws -> [I] where I : Viewable { guard let table = I.table as? CoreDataTable else { throw AdapterError.entityNotFound(I.table.name) } guard let entity = NSEntityDescription.entity(forEntityName: table.entityName, in: self.managedObjectContext), let entityName = entity.name else { throw AdapterError.entityNotFound(table.entityName) } let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName) fetchRequest.predicate = query?.predicate() fetchRequest.sortDescriptors = sorts.map({ (sort) -> NSSortDescriptor in return sort.sortDescriptor() }) fetchRequest.fetchLimit = limit fetchRequest.fetchOffset = offset guard let result = try self.managedObjectContext.fetch(fetchRequest) as? [CoreDataEntity] else { throw AdapterError.invalidResult } return result.map({ (object) -> Storable in return object.storable }) as! [I] } @discardableResult public func update<I>(storable: I) async throws -> I where I : Storable { guard let table = I.table as? CoreDataTable else { throw AdapterError.entityNotFound(I.table.name) } guard let entity = NSEntityDescription.entity(forEntityName: table.entityName, in: self.managedObjectContext), let entityName = entity.name else { throw AdapterError.entityNotFound(table.entityName) } let expression = Expression.equal(self.persistentIdName, storable.persistentId) let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName) fetchRequest.fetchLimit = 1 fetchRequest.predicate = expression.predicate() guard let result = try self.managedObjectContext.fetch(fetchRequest) as? [CoreDataEntity] else { throw AdapterError.invalidResult } if let object = result.first { object.update(with: storable) if self.managedObjectContext.hasChanges { try self.managedObjectContext.save() } return storable } else { return try await self.insert(storable: storable) } } @discardableResult public func delete<I>(storable: I) async throws -> I where I : Storable { guard let table = I.table as? CoreDataTable else { throw AdapterError.entityNotFound(I.table.name) } guard let entity = NSEntityDescription.entity(forEntityName: table.entityName, in: self.managedObjectContext), let entityName = entity.name else { throw AdapterError.entityNotFound(table.entityName) } let expression = Expression.equal(self.persistentIdName, storable.persistentId) let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName) fetchRequest.fetchLimit = 1 fetchRequest.predicate = expression.predicate() guard let result = try self.managedObjectContext.fetch(fetchRequest) as? [CoreDataEntity] else { throw AdapterError.invalidResult } if let object = result.first { self.managedObjectContext.delete(object as! NSManagedObject) if self.managedObjectContext.hasChanges { try self.managedObjectContext.save() } } return storable } public func count<T>(table: T, query: Query?) async throws -> Int where T : Table { guard let table = table as? CoreDataTable else { throw AdapterError.entityNotFound(table.name) } guard let entity = NSEntityDescription.entity(forEntityName: table.entityName, in: self.managedObjectContext), let entityName = entity.name else { throw AdapterError.entityNotFound(table.entityName) } let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName) fetchRequest.predicate = query?.predicate() return try self.managedObjectContext.count(for: fetchRequest) } }
mit
26106ad3a14249feda4ba60cca5c07f7
42.638418
208
0.658467
5.375087
false
false
false
false
notbenoit/tvOS-Twitch
Code/tvOS/TopShelf/ServiceProvider.swift
1
2546
// Copyright (c) 2015 Benoit Layer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import TVServices import ReactiveSwift final class ServiceProvider: NSObject, TVTopShelfProvider { let twitchClient = TwitchAPIClient() override init() { super.init() } // MARK: - TVTopShelfProvider protocol var topShelfStyle: TVTopShelfContentStyle { return .sectioned } var topShelfItems: [TVContentItem] { let semaphore = DispatchSemaphore(value: 0) let topGamesItem = TVContentItem(contentIdentifier: TVContentIdentifier(identifier: "topGames", container: nil)!)! topGamesItem.title = "Top Games" var items: [TVContentItem] = [] twitchClient.getTopGames(0) .on(terminated: { semaphore.signal() }) .flatMapError { _ in SignalProducer.empty } .startWithValues { response in items += response.objects.map(item(from:)) } let _ = semaphore.wait(timeout: DispatchTime.distantFuture) topGamesItem.topShelfItems = items return [topGamesItem] } } private func item(from topGame: TopGame) -> TVContentItem { let item = TVContentItem(contentIdentifier: TVContentIdentifier(identifier: String(topGame.game.id), container: nil)!) let components = NSURLComponents() components.scheme = "twitch" components.path = "game" components.queryItems = [URLQueryItem(name: "name", value: topGame.game.name)] item?.imageShape = .poster item?.displayURL = components.url! item?.imageURL = URL(string: topGame.game.box.large)! item?.title = topGame.game.name return item! }
bsd-3-clause
5bcedea206cd06a120aed611dfd66efc
37
119
0.753731
3.99686
false
false
false
false
jefflinwood/volunteer-recognition-ios
APASlapApp/APASlapApp/BaseViewController.swift
1
1571
// // BaseViewController.swift // APASlapApp // // Created by Jeffrey Linwood on 6/3/17. // Copyright © 2017 Jeff Linwood. All rights reserved. // import UIKit import Firebase class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func styleTopToolbar(topToolbarView: UIView) { topToolbarView.layer.shadowOffset = CGSize(width: 0, height: 0.4) topToolbarView.layer.shadowRadius = 4.0 topToolbarView.layer.shadowColor = UIColor.black.cgColor topToolbarView.layer.shadowOpacity = 0.6 } func styleButton(button: UIButton) { button.layer.borderColor = UIColor.white.cgColor button.layer.borderWidth = 1.0 button.layer.cornerRadius = 4.0 } func showErrorMessage(errorMessage:String) { let alertController = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) present(alertController, animated: true, completion: nil) } func showMessage(title:String, message:String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) present(alertController, animated: true, completion: nil) } }
mit
42ae2453560d8c979aeefefc1c3a4779
29.784314
110
0.682803
4.524496
false
false
false
false
yzyzsun/arduino-bluetooth-music-player
iOS/ArduinoBluetoothMusicPlayer/BLEManager.swift
1
5185
// // BLEManager.swift // ArduinoBluetoothMusicPlayer // // Created by yzyzsun on 2015-09-03. // Copyright (c) 2015 yzyzsun. All rights reserved. // import Foundation import CoreBluetooth import UIKit let BlunoServiceUUID = CBUUID(string: "DFB0") let BlunoSerialUUID = CBUUID(string: "DFB1") enum BlunoCommand: String { case Pause = "a" case Resume = "b" case Backward = "c" case Forward = "d" case Prev = "e" case Next = "f" case VolumeUp = "g" case VolumeDown = "h" case VolumeChange = "i" case ModeNormal = "j" case ModeShuffle = "k" case ModeRepeatList = "l" case ModeRepeatSingle = "m" } class BLEManager: NSObject { override init() { super.init() centralManager = CBCentralManager(delegate: self, queue: nil) } static let sharedInstance = BLEManager() private var centralManager: CBCentralManager! private var bluno: CBPeripheral! private var blunoSerial: CBCharacteristic! private var rootViewController: ViewController! private func startScanning() { centralManager.scanForPeripheralsWithServices([BlunoServiceUUID], options: nil) rootViewController.appendToLog("Scanning for bluetooth devices...\r\n") } func clearPeripheral() { bluno = nil blunoSerial = nil } var ready: Bool { return blunoSerial != nil } func sendCommand(command: BlunoCommand) { if !ready { return } bluno.writeValue(command.rawValue.dataUsingEncoding(NSASCIIStringEncoding)!, forCharacteristic: blunoSerial, type: CBCharacteristicWriteType.WithoutResponse) } func sendCommand(command: BlunoCommand, var changeVolumeTo volume: UInt8) { if !ready { return } bluno.writeValue(command.rawValue.dataUsingEncoding(NSASCIIStringEncoding)!, forCharacteristic: blunoSerial, type: CBCharacteristicWriteType.WithoutResponse) bluno.writeValue(NSData(bytes: &volume, length: 1), forCharacteristic: blunoSerial, type: CBCharacteristicWriteType.WithoutResponse) } } extension BLEManager: CBCentralManagerDelegate { func centralManagerDidUpdateState(central: CBCentralManager) { rootViewController = UIApplication.sharedApplication().keyWindow!.rootViewController as! ViewController switch central.state { case .PoweredOn: startScanning() case .PoweredOff: rootViewController.appendToLog("Bluetooth is shut down, please turn it on.\r\n") clearPeripheral() case .Unsupported: let alert = UIAlertController(title: "您的设备不支持蓝牙 4.0", message: nil, preferredStyle: UIAlertControllerStyle.Alert) rootViewController.presentViewController(alert, animated: true, completion: nil) default: break } } func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { if (bluno != nil) { return } bluno = peripheral centralManager.connectPeripheral(bluno, options: nil) } func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { peripheral.delegate = self rootViewController.appendToLog("Successfully connected to \(bluno.name).\r\n") centralManager.stopScan() bluno.delegate = self bluno.discoverServices([BlunoServiceUUID]) } func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { rootViewController.appendToLog("Oops! Connection is broken.\r\n") clearPeripheral() startScanning() } } extension BLEManager: CBPeripheralDelegate { func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { if let err = error { rootViewController.appendToLog(err.description) return } for service in bluno.services! { if service.UUID == BlunoServiceUUID { bluno.discoverCharacteristics([BlunoSerialUUID], forService: service) } } } func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { if let err = error { rootViewController.appendToLog(err.description) return } for characteristic in service.characteristics! { if characteristic.UUID == BlunoSerialUUID { rootViewController.appendToLog("[Ready]\r\n") blunoSerial = characteristic } } } func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { if let err = error { rootViewController.appendToLog(err.description) return } rootViewController.appendToLog(NSString(data: characteristic.value!, encoding: NSASCIIStringEncoding) as! String) } }
mit
05e3743f8a88918c3c5d6293aa721349
32.335484
165
0.66286
5.315844
false
false
false
false
imjerrybao/SKTUtils
Examples/Tests/SKTUtilsTests/IntTests.swift
2
2955
import XCTest class IntTests: XCTestCase { func testClampedHalfOpenRange() { XCTAssertEqual(10.clamped(-5 ..< 7), 6) XCTAssertEqual(7.clamped(-5 ..< 7), 6) XCTAssertEqual(6.clamped(-5 ..< 7), 6) XCTAssertEqual(5.clamped(-5 ..< 7), 5) XCTAssertEqual(1.clamped(-5 ..< 7), 1) XCTAssertEqual(0.clamped(-5 ..< 7), 0) XCTAssertEqual((-4).clamped(-5 ..< 7), -4) XCTAssertEqual((-5).clamped(-5 ..< 7), -5) XCTAssertEqual((-6).clamped(-5 ..< 7), -5) XCTAssertEqual((-10).clamped(-5 ..< 7), -5) } func testClampedEmptyHalfOpenRange() { XCTAssertEqual(10.clamped(7 ..< 7), 6) // weird, huh! XCTAssertEqual((-10).clamped(7 ..< 7), 7) } func testClampedOpenRange() { XCTAssertEqual(10.clamped(-5 ... 7), 7) XCTAssertEqual(8.clamped(-5 ... 7), 7) XCTAssertEqual(7.clamped(-5 ... 7), 7) XCTAssertEqual(6.clamped(-5 ... 7), 6) XCTAssertEqual(1.clamped(-5 ... 7), 1) XCTAssertEqual(0.clamped(-5 ... 7), 0) XCTAssertEqual((-4).clamped(-5 ... 7), -4) XCTAssertEqual((-5).clamped(-5 ... 7), -5) XCTAssertEqual((-6).clamped(-5 ... 7), -5) XCTAssertEqual((-10).clamped(-5 ... 7), -5) } func testClampedEmptyOpenRange() { XCTAssertEqual(10.clamped(7 ... 7), 7) XCTAssertEqual((-10).clamped(7 ... 7), 7) } func testClamped() { XCTAssertEqual(10.clamped(-5, 6), 6) XCTAssertEqual(7.clamped(-5, 6), 6) XCTAssertEqual(6.clamped(-5, 6), 6) XCTAssertEqual(5.clamped(-5, 6), 5) XCTAssertEqual(1.clamped(-5, 6), 1) XCTAssertEqual(0.clamped(-5, 6), 0) XCTAssertEqual((-4).clamped(-5, 6), -4) XCTAssertEqual((-5).clamped(-5, 6), -5) XCTAssertEqual((-6).clamped(-5, 6), -5) XCTAssertEqual((-10).clamped(-5, 6), -5) } func testClampedReverseOrder() { XCTAssertEqual(10.clamped(6, -5), 6) XCTAssertEqual(7.clamped(6, -5), 6) XCTAssertEqual(6.clamped(6, -5), 6) XCTAssertEqual(5.clamped(6, -5), 5) XCTAssertEqual(1.clamped(6, -5), 1) XCTAssertEqual(0.clamped(6, -5), 0) XCTAssertEqual((-4).clamped(6, -5), -4) XCTAssertEqual((-5).clamped(6, -5), -5) XCTAssertEqual((-6).clamped(6, -5), -5) XCTAssertEqual((-10).clamped(6, -5), -5) } func testThatClampedDoesNotChangeOriginalValue() { let original = 50 let clamped = original.clamped(100 ... 200) XCTAssertEqual(original, 50) } func testThatClampReturnsNewValue() { var original = 50 original.clamp(100 ... 200) XCTAssertEqual(original, 100) } func testThatRandomStaysInHalfOpenRange() { for i in 0..<1000 { let v = Int.random(-10 ..< 10) XCTAssert(v >= -10 && v < 10) let w = Int.random(10) XCTAssert(w >= 0 && w < 10) } } func testThatRandomStaysInOpenRange() { for i in 0..<1000 { let v = Int.random(-10 ... 10) XCTAssert(v >= -10 && v <= 10) let w = Int.random(min: -10, max: 10) XCTAssert(w >= -10 && w <= 10) } } }
mit
99c683360a3f7792d9f1b12f235b1d20
28.848485
61
0.588156
3.365604
false
true
false
false
nheagy/WordPress-iOS
WordPress/Classes/Networking/PeopleRemote.swift
1
2831
import Foundation class PeopleRemote: ServiceRemoteREST { func getTeamFor(siteID: Int, success: People -> (), failure: ErrorType -> ()) { let endpoint = "sites/\(siteID)/users" let path = pathForEndpoint(endpoint, withVersion: ServiceRemoteRESTApiVersion_1_1) let parameters = [ "number": 50, "fields": "ID, nice_name, first_name, last_name, name, avatar_URL, roles, is_super_admin", ] api.GET(path, parameters: parameters, success: { (operation, responseObject) -> Void in if let people = try? self.peopleFromResponse(responseObject, siteID: siteID) { success(people) } else { failure(Error.DecodeError) } }, failure: { (operation, error) -> Void in failure(error) }) } private func peopleFromResponse(responseObject: AnyObject, siteID: Int) throws -> People { let response = responseObject as? [String: AnyObject] let users = response.flatMap { return $0["users"] as? [[String: AnyObject]] } guard let unwrappedUsers = users else { throw Error.DecodeError } let people = unwrappedUsers.map { (user: [String: AnyObject]) -> Person? in guard let ID = user["ID"] as? Int else { return nil } guard let username = user["nice_name"] as? String else { return nil } guard let displayName = user["name"] as? String else { return nil } let firstName = user["first_name"] as? String let lastName = user["last_name"] as? String let avatarURL = (user["avatar_URL"] as? String) .flatMap { NSURL(string: $0)} .flatMap { Gravatar($0)?.canonicalURL } let isSuperAdmin = user["is_super_admin"] as? Bool ?? false let roles = user["roles"] as? [String] let role = roles?.map({ (role: String) -> Person.Role in return Person.Role(string: role) }).sort().first ?? .Unsupported return Person(ID: ID, username: username, firstName: firstName, lastName: lastName, displayName: displayName, role: role, siteID: siteID, avatarURL: avatarURL, isSuperAdmin: isSuperAdmin) } let errorCount = people.reduce(0) { (sum, person) -> Int in if person == nil { return sum + 1 } return sum } if errorCount > 0 { throw Error.DecodeError } return people.flatMap { $0 } } enum Error: ErrorType { case DecodeError } }
gpl-2.0
8a559078470fd94d1eabd46296e2ae7f
34.848101
199
0.527729
4.790186
false
false
false
false
wayfair/brickkit-ios
Tests/Behaviors/OffsetLayoutBehaviorTests.swift
1
3834
// // OffsetLayoutBehaviorTests.swift // BrickKit // // Created by Justin Shiiba on 6/8/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import XCTest @testable import BrickKit class OffsetLayoutBehaviorTests: BrickFlowLayoutBaseTests { var behavior:OffsetLayoutBehavior! override func setUp() { super.setUp() layout.zIndexBehavior = .bottomUp } func testEmptyCollectionView() { behavior = OffsetLayoutBehavior(dataSource: FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: nil)) self.layout.behaviors.insert(behavior) setDataSources(SectionsCollectionViewDataSource(sections: []), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300)) XCTAssertFalse(behavior.hasInvalidatableAttributes()) let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) XCTAssertNil(attributes?.frame) } func testOriginOffset() { let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: nil) behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout) self.layout.behaviors.insert(behavior) setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300)) let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 320, height: 300)) } func testSizeOffset() { let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: nil, sizeOffset: CGSize(width: -40, height: 20)) behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout) self.layout.behaviors.insert(behavior) setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300)) let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) XCTAssertEqual(attributes?.frame, CGRect(x: 0, y: 0, width: 280, height: 320)) } func testOriginAndSizeOffset() { let fixedOffsetLayoutBehavior = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: CGSize(width: -40, height: 20)) behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayoutBehavior) self.layout.behaviors.insert(behavior) setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300)) let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320)) } func testOffsetAfterScroll() { let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: CGSize(width: -40, height: 20)) behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout) self.layout.behaviors.insert(behavior) setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300)) let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320)) layout.collectionView?.contentOffset.y = 60 XCTAssertTrue(behavior.hasInvalidatableAttributes()) layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling)) XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320)) } }
apache-2.0
0e4f251bd2d6b3dd87eaf5b428eb7241
50.106667
165
0.733107
4.971466
false
true
false
false
kickstarter/ios-oss
Library/ViewModels/HTML Parser/AudioVideoViewElementCellViewModel.swift
1
3673
import AVFoundation import KsApi import Prelude import ReactiveSwift import UIKit public protocol AudioVideoViewElementCellViewModelInputs { /// Call to configure with a `AudioVideoViewElement` representing raw audio/video view with an optional `AVPlayer` and `UIImage`` if its ready with its asset. func configureWith(element: AudioVideoViewElement, player: AVPlayer?, thumbnailImage: UIImage?) /// Call to send a pause signal to `AVPlayer` to pause the playing audio/video and return a seek time. func pausePlayback() -> CMTime /// Call to record current playback seektime to resume playback later. func recordSeektime(_ seekTime: CMTime) } public protocol AudioVideoViewElementCellViewModelOutputs { /// Emits a signal to pause playback of audio/video var pauseAudioVideo: Signal<Void, Never> { get } /// Emits an optional `UIImage` that is the thumbnail image for the video. var thumbnailImage: Signal<UIImage, Never> { get } /// Emits an optional `AVPlayer` with an `AVPlayerItem` for audio/video view with a preset seektime if the element contained one. var audioVideoItem: Signal<AVPlayer, Never> { get } } public protocol AudioVideoViewElementCellViewModelType { var inputs: AudioVideoViewElementCellViewModelInputs { get } var outputs: AudioVideoViewElementCellViewModelOutputs { get } } public final class AudioVideoViewElementCellViewModel: AudioVideoViewElementCellViewModelType, AudioVideoViewElementCellViewModelInputs, AudioVideoViewElementCellViewModelOutputs { // MARK: Initializers public init() { self.audioVideoItem = self.audioVideoViewElementWithPlayerAndThumbnailProperty.signal .switchMap { audioVideoElementWithPlayer -> SignalProducer<AVPlayer?, Never> in guard let player = audioVideoElementWithPlayer?.player else { return SignalProducer(value: nil) } let seekTime = audioVideoElementWithPlayer?.element.seekPosition ?? .zero let validPlayTime = seekTime.isValid ? seekTime : .zero player.currentItem?.seek(to: validPlayTime, completionHandler: nil) return SignalProducer(value: player) } .skipNil() self.pauseAudioVideo = self.pausePlaybackProperty.signal.ignoreValues() self.thumbnailImage = self.audioVideoViewElementWithPlayerAndThumbnailProperty.signal .skipNil() .switchMap { (element, _, thumbnailImage) -> SignalProducer<UIImage?, Never> in guard element.seekPosition == .zero else { return SignalProducer(value: nil) } return SignalProducer(value: thumbnailImage) } .skipNil() } fileprivate let pausePlaybackProperty = MutableProperty<Void>(()) public func pausePlayback() -> CMTime { self.pausePlaybackProperty.value = () return self.seekTimeProperty.value } fileprivate let seekTimeProperty = MutableProperty<CMTime>(.zero) public func recordSeektime(_ seekTime: CMTime) { self.seekTimeProperty.value = seekTime } fileprivate let audioVideoViewElementWithPlayerAndThumbnailProperty = MutableProperty<(element: AudioVideoViewElement, player: AVPlayer?, thumbnailImage: UIImage?)?>(nil) public func configureWith(element: AudioVideoViewElement, player: AVPlayer?, thumbnailImage: UIImage?) { self.audioVideoViewElementWithPlayerAndThumbnailProperty.value = (element, player, thumbnailImage) } public let pauseAudioVideo: Signal<Void, Never> public let audioVideoItem: Signal<AVPlayer, Never> public let thumbnailImage: Signal<UIImage, Never> public var inputs: AudioVideoViewElementCellViewModelInputs { self } public var outputs: AudioVideoViewElementCellViewModelOutputs { self } }
apache-2.0
565c653031a6307cf67da5fe693ff72a
38.923913
160
0.762047
5.262178
false
false
false
false
davidozhang/spycodes
Spycodes/Managers/SCStoreKitManager.swift
1
921
import StoreKit class SCStoreKitManager { static var reviewRequestedForSession = false static func requestReviewIfAllowed() { if reviewRequestedForSession { return } if let appOpens = SCUsageStatisticsManager.instance.getDiscreteUsageStatisticsValue(type: .appOpens) { switch appOpens { case 5, 10: SCStoreKitManager.requestReview() case _ where appOpens > 0 && appOpens % 25 == 0: SCStoreKitManager.requestReview() default: break } } // TODO: Figure out how to incorporate game plays into determining when to request reviews } fileprivate static func requestReview() { if #available(iOS 10.3, *) { SKStoreReviewController.requestReview() SCStoreKitManager.reviewRequestedForSession = true } } }
mit
83b97c600bd0f44dc2ac4e4285908b1a
28.709677
110
0.603692
5.323699
false
false
false
false
PurpleSweetPotatoes/SwiftKit
SwiftKit/ui/BQVerifyCodeView.swift
1
3421
// // BQVerifyCodeView.swift // swift-Test // // Created by MrBai on 2017/6/15. // Copyright © 2017年 MrBai. All rights reserved. // import UIKit class BQVerifyCodeView: UIView { //MARK: - ***** Ivars ***** private var verCode: String = "" private var codeNum: Int = 0 private var disturbLineNum: Int = 0 private var fontSize: CGFloat = 0 var textColor: UIColor? /// 是否区分大小写 var checkStrict = false //MARK: - ***** Class Method ***** //MARK: - ***** initialize Method ***** init(frame: CGRect, fontSize: CGFloat = 20, codeNum: Int = 4, disturbLineNum: Int = 5) { super.init(frame: frame) self.codeNum = codeNum self.disturbLineNum = disturbLineNum self.fontSize = fontSize } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - ***** public Method ***** func verify(str:String) -> Bool { if self.checkStrict { return str == self.verCode } return str.uppercased() == self.verCode.uppercased() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.setNeedsDisplay() } //MARK: - ***** private Method ***** override func draw(_ rect: CGRect) { super.draw(rect) self.verCode = "" let charArr = ["0", "1","2","3","4","5","6","7","8","9","a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] let context = UIGraphicsGetCurrentContext()! context.clear(rect) context.setFillColor(self.backgroundColor?.cgColor ?? UIColor.randomColor.cgColor) context.fill(rect) //填字 let charWidth = rect.width / CGFloat(self.codeNum) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center var attrs = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: self.fontSize), NSAttributedString.Key.paragraphStyle: paragraphStyle] for i in 0 ..< self.codeNum { let index = Int(arc4random_uniform(UInt32(charArr.count))) let code = charArr[index] attrs[NSAttributedString.Key.foregroundColor] = self.textColor ?? UIColor.randomColor code.draw(at: CGPoint(x: charWidth * CGFloat(i) + (charWidth - self.fontSize) * 0.5, y: (rect.height - self.fontSize) * 0.5), withAttributes: attrs) self.verCode += code } //划线 context.setLineWidth(1) for _ in 0 ..< self.disturbLineNum { context.setStrokeColor(UIColor.randomColor.cgColor) context.move(to: self.randomPoint()) context.addLine(to: self.randomPoint()) context.strokePath() } } private func randomPoint() -> CGPoint { let x = CGFloat(arc4random_uniform(UInt32(self.bounds.size.width))) let y = CGFloat(arc4random_uniform(UInt32(self.bounds.size.height))) return CGPoint(x: x, y: y) } //MARK: - ***** LoadData Method ***** //MARK: - ***** respond event Method ***** //MARK: - ***** Protocol ***** //MARK: - ***** create Method ***** }
apache-2.0
2cffe238b5bfe3c630a05e617730d88b
36.733333
323
0.557126
3.740088
false
false
false
false
firebase/SwiftLint
Source/SwiftLintFramework/Rules/LegacyConstructorRule.swift
4
6950
// // LegacyConstructorRule.swift // SwiftLint // // Created by Marcelo Fabri on 29/11/15. // Copyright © 2015 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct LegacyConstructorRule: CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "legacy_constructor", name: "Legacy Constructor", description: "Swift constructors are preferred over legacy convenience functions.", nonTriggeringExamples: [ "CGPoint(x: 10, y: 10)", "CGPoint(x: xValue, y: yValue)", "CGSize(width: 10, height: 10)", "CGSize(width: aWidth, height: aHeight)", "CGRect(x: 0, y: 0, width: 10, height: 10)", "CGRect(x: xVal, y: yVal, width: aWidth, height: aHeight)", "CGVector(dx: 10, dy: 10)", "CGVector(dx: deltaX, dy: deltaY)", "NSPoint(x: 10, y: 10)", "NSPoint(x: xValue, y: yValue)", "NSSize(width: 10, height: 10)", "NSSize(width: aWidth, height: aHeight)", "NSRect(x: 0, y: 0, width: 10, height: 10)", "NSRect(x: xVal, y: yVal, width: aWidth, height: aHeight)", "NSRange(location: 10, length: 1)", "NSRange(location: loc, length: len)", "UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)", "UIEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)", "NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)", "NSEdgeInsets(top: aTop, left: aLeft, bottom: aBottom, right: aRight)" ], triggeringExamples: [ "↓CGPointMake(10, 10)", "↓CGPointMake(xVal, yVal)", "↓CGSizeMake(10, 10)", "↓CGSizeMake(aWidth, aHeight)", "↓CGRectMake(0, 0, 10, 10)", "↓CGRectMake(xVal, yVal, width, height)", "↓CGVectorMake(10, 10)", "↓CGVectorMake(deltaX, deltaY)", "↓NSMakePoint(10, 10)", "↓NSMakePoint(xVal, yVal)", "↓NSMakeSize(10, 10)", "↓NSMakeSize(aWidth, aHeight)", "↓NSMakeRect(0, 0, 10, 10)", "↓NSMakeRect(xVal, yVal, width, height)", "↓NSMakeRange(10, 1)", "↓NSMakeRange(loc, len)", "↓UIEdgeInsetsMake(0, 0, 10, 10)", "↓UIEdgeInsetsMake(top, left, bottom, right)", "↓NSEdgeInsetsMake(0, 0, 10, 10)", "↓NSEdgeInsetsMake(top, left, bottom, right)" ], corrections: [ "↓CGPointMake(10, 10 )\n": "CGPoint(x: 10, y: 10)\n", "↓CGPointMake(xPos, yPos )\n": "CGPoint(x: xPos, y: yPos)\n", "↓CGSizeMake(10, 10)\n": "CGSize(width: 10, height: 10)\n", "↓CGSizeMake( aWidth, aHeight )\n": "CGSize(width: aWidth, height: aHeight)\n", "↓CGRectMake(0, 0, 10, 10)\n": "CGRect(x: 0, y: 0, width: 10, height: 10)\n", "↓CGRectMake(xPos, yPos , width, height)\n": "CGRect(x: xPos, y: yPos, width: width, height: height)\n", "↓CGVectorMake(10, 10)\n": "CGVector(dx: 10, dy: 10)\n", "↓CGVectorMake(deltaX, deltaY)\n": "CGVector(dx: deltaX, dy: deltaY)\n", "↓NSMakePoint(10, 10 )\n": "NSPoint(x: 10, y: 10)\n", "↓NSMakePoint(xPos, yPos )\n": "NSPoint(x: xPos, y: yPos)\n", "↓NSMakeSize(10, 10)\n": "NSSize(width: 10, height: 10)\n", "↓NSMakeSize( aWidth, aHeight )\n": "NSSize(width: aWidth, height: aHeight)\n", "↓NSMakeRect(0, 0, 10, 10)\n": "NSRect(x: 0, y: 0, width: 10, height: 10)\n", "↓NSMakeRect(xPos, yPos , width, height)\n": "NSRect(x: xPos, y: yPos, width: width, height: height)\n", "↓NSMakeRange(10, 1)\n": "NSRange(location: 10, length: 1)\n", "↓NSMakeRange(loc, len)\n": "NSRange(location: loc, length: len)\n", "↓CGVectorMake(10, 10)\n↓NSMakeRange(10, 1)\n": "CGVector(dx: 10, dy: 10)\n" + "NSRange(location: 10, length: 1)\n", "↓CGVectorMake(dx, dy)\n↓NSMakeRange(loc, len)\n": "CGVector(dx: dx, dy: dy)\n" + "NSRange(location: loc, length: len)\n", "↓UIEdgeInsetsMake(0, 0, 10, 10)\n": "UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)\n", "↓UIEdgeInsetsMake(top, left, bottom, right)\n": "UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)\n", "↓NSEdgeInsetsMake(0, 0, 10, 10)\n": "NSEdgeInsets(top: 0, left: 0, bottom: 10, right: 10)\n", "↓NSEdgeInsetsMake(top, left, bottom, right)\n": "NSEdgeInsets(top: top, left: left, bottom: bottom, right: right)\n" ] ) public func validate(file: File) -> [StyleViolation] { let constructors = ["CGRectMake", "CGPointMake", "CGSizeMake", "CGVectorMake", "NSMakePoint", "NSMakeSize", "NSMakeRect", "NSMakeRange", "UIEdgeInsetsMake", "NSEdgeInsetsMake"] let pattern = "\\b(" + constructors.joined(separator: "|") + ")\\b" return file.match(pattern: pattern, with: [.identifier]).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } public func correct(file: File) -> [Correction] { let twoVarsOrNum = RegexHelpers.twoVariableOrNumber let patterns = [ "CGPointMake\\(\\s*\(twoVarsOrNum)\\s*\\)": "CGPoint(x: $1, y: $2)", "CGSizeMake\\(\\s*\(twoVarsOrNum)\\s*\\)": "CGSize(width: $1, height: $2)", "CGRectMake\\(\\s*\(twoVarsOrNum)\\s*,\\s*\(twoVarsOrNum)\\s*\\)": "CGRect(x: $1, y: $2, width: $3, height: $4)", "CGVectorMake\\(\\s*\(twoVarsOrNum)\\s*\\)": "CGVector(dx: $1, dy: $2)", "NSMakePoint\\(\\s*\(twoVarsOrNum)\\s*\\)": "NSPoint(x: $1, y: $2)", "NSMakeSize\\(\\s*\(twoVarsOrNum)\\s*\\)": "NSSize(width: $1, height: $2)", "NSMakeRect\\(\\s*\(twoVarsOrNum)\\s*,\\s*\(twoVarsOrNum)\\s*\\)": "NSRect(x: $1, y: $2, width: $3, height: $4)", "NSMakeRange\\(\\s*\(twoVarsOrNum)\\s*\\)": "NSRange(location: $1, length: $2)", "UIEdgeInsetsMake\\(\\s*\(twoVarsOrNum)\\s*,\\s*\(twoVarsOrNum)\\s*\\)": "UIEdgeInsets(top: $1, left: $2, bottom: $3, right: $4)", "NSEdgeInsetsMake\\(\\s*\(twoVarsOrNum)\\s*,\\s*\(twoVarsOrNum)\\s*\\)": "NSEdgeInsets(top: $1, left: $2, bottom: $3, right: $4)" ] return file.correct(legacyRule: self, patterns: patterns) } }
mit
3cc906d3317982993e66c71d35e64e8f
50.201493
93
0.534762
3.856661
false
false
false
false
rajeejones/SavingPennies
Pods/IBAnimatable/IBAnimatable/PlaceholderDesignable.swift
5
2582
// // Created by Jake Lin on 11/19/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit public protocol PlaceholderDesignable { /** `color` within `::-webkit-input-placeholder`, `::-moz-placeholder` or `:-ms-input-placeholder` */ var placeholderColor: UIColor? { get set } var placeholderText: String? { get set } } public extension PlaceholderDesignable where Self: UITextField { var placeholderText: String? { get { return "" } set {} } public func configurePlaceholderColor() { if let placeholderColor = placeholderColor, let placeholder = placeholder { attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: placeholderColor]) } } } public extension PlaceholderDesignable where Self: UITextView { public func configure(placeholderLabel: UILabel, placeholderLabelConstraints: inout [NSLayoutConstraint]) { placeholderLabel.font = font placeholderLabel.textColor = placeholderColor placeholderLabel.textAlignment = textAlignment placeholderLabel.text = placeholderText placeholderLabel.numberOfLines = 0 placeholderLabel.backgroundColor = .clear placeholderLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(placeholderLabel) update(placeholderLabel, using: &placeholderLabelConstraints) } public func update(_ placeholderLabel: UILabel, using constraints: inout [NSLayoutConstraint]) { var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]", options: [], metrics: nil, views: ["placeholder": placeholderLabel]) newConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(\(textContainerInset.top))-[placeholder]", options: [], metrics: nil, views: ["placeholder": placeholderLabel]) newConstraints.append(NSLayoutConstraint(item: placeholderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0))) removeConstraints(constraints) addConstraints(newConstraints) constraints = newConstraints } }
gpl-3.0
8c1f6be8441b4ec2fddbfa1c488c13fb
41.311475
159
0.668346
6.174641
false
false
false
false
robertherdzik/RHSideButtons
RHSideButtons/RHSideButtons/RHSideButtons.swift
1
7807
// // RHSideButtons.swift // RHSideButtons // // Created by Robert Herdzik on 20/05/16. // Copyright © 2016 Robert Herdzik. All rights reserved. // import UIKit public protocol RHSideButtonsDelegate: class { func sideButtons(_ sideButtons: RHSideButtons, didSelectButtonAtIndex index: Int) func sideButtons(_ sideButtons: RHSideButtons, didTriggerButtonChangeStateTo state: RHButtonState) } public protocol RHSideButtonsDataSource: class { func sideButtonsNumberOfButtons(_ sideButtons: RHSideButtons) -> Int func sideButtons(_ sideButtons: RHSideButtons, buttonAtIndex index: Int) -> RHButtonView } public enum RHButtonState: Int { case hidden = 0 case shown } public class RHSideButtons { public weak var parentView: UIView? public weak var delegate: RHSideButtonsDelegate? public weak var dataSource: RHSideButtonsDataSource? fileprivate let buttonSize = CGSize(width: 55, height: 55) fileprivate let verticalSpacing = CGFloat(15) fileprivate var hideStateOffset: CGFloat { get { guard let parentView = parentView else { return 0 } let parentViewWidth = parentView.bounds.width let hideOffsetX = buttonSize.width * (3/2) var resultPosX = parentViewWidth + hideOffsetX if (triggerButton.frame.origin.x + buttonSize.width/2 < parentViewWidth / 2) { resultPosX = -(hideOffsetX + buttonSize.width) } return resultPosX } } fileprivate var buttonsArr = [RHButtonView]() fileprivate let buttonsAnimator: RHSideButtonAnimatorProtocol fileprivate var descriptionArr = [String]() fileprivate(set) var state: RHButtonState = .hidden { didSet { aniamateButtonForState(state) {} markTriggerButtonAsPressed(state == .shown) buttonsAnimator.animateTriggerButton(triggerButton, state: state) {} } } public var triggerButton: RHTriggerButtonView! public init(parentView: UIView, triggerButton: RHTriggerButtonView, buttonsAnimator: RHSideButtonAnimatorProtocol) { self.parentView = parentView self.triggerButton = triggerButton self.buttonsAnimator = buttonsAnimator setup() } convenience public init(parentView: UIView, triggerButton: RHTriggerButtonView) { // At this moment "RHSideButtonAnimator" is only existing and default button animator self.init(parentView: parentView, triggerButton: triggerButton, buttonsAnimator: RHSideButtonAnimator()) } fileprivate func setup() { setDefaultTriggerButtonPosition() setupTriggerButton() layoutButtons() } fileprivate func setupTriggerButton() { guard let parentView = parentView else { return } setDefaultTriggerButtonPosition() triggerButton.delegate = self parentView.addSubview(triggerButton) parentView.bringSubview(toFront: triggerButton) } fileprivate func setDefaultTriggerButtonPosition() { guard let parentView = parentView else { return } triggerButton.frame = CGRect(x: parentView.bounds.width - buttonSize.width, y: parentView.bounds.height - buttonSize.height, width: buttonSize.width, height: buttonSize.height) } fileprivate func markTriggerButtonAsPressed(_ pressed: Bool) { triggerButton.markAsPressed(pressed) } fileprivate func layoutButtons() { var prevButton: RHButtonView? = nil for button in buttonsArr { var buttonPosY = CGFloat(0) if let prevButton = prevButton { buttonPosY = prevButton.frame.minY - verticalSpacing - buttonSize.height } else { // Spacing has to be applied to prevent jumping rest of buttons let spacingFromTriggerButtonY = CGFloat(18) // TODO add offset according to scale buttonPosY = triggerButton.frame.midY - spacingFromTriggerButtonY - verticalSpacing - buttonSize.height } let buttonPosX = getButtonPoxXAccordingToState(state) // Buttons should be laid out according to center of trigger button button.frame = CGRect(origin: CGPoint(x: buttonPosX, y: buttonPosY), size: buttonSize) prevButton = button } } fileprivate func getButtonPoxXAccordingToState(_ state: RHButtonState) -> CGFloat { return state == .hidden ? hideStateOffset : triggerButton.frame.midX - buttonSize.width/2 } fileprivate func removeButtons() { _ = buttonsArr.map{ $0.removeFromSuperview() } buttonsArr.removeAll() } fileprivate func addButtons() { guard let numberOfButtons = dataSource?.sideButtonsNumberOfButtons(self) else { return } for index in 0..<numberOfButtons { guard let button = dataSource?.sideButtons(self, buttonAtIndex: index) else { return } button.delegate = self parentView?.addSubview(button) parentView?.bringSubview(toFront: button) buttonsArr.append(button) } } fileprivate func aniamateButtonForState(_ state: RHButtonState, completition: (() -> ())? = nil) { let buttonPosX = getButtonPoxXAccordingToState(state) let targetPoint = CGPoint(x: buttonPosX, y: 0) buttonsAnimator.animateButtonsPositionX(buttonsArr, targetPos: targetPoint, completition: completition) } /** Method reload whole buttons. Use this method right after you made some changes in Side Buttons model. */ public func reloadButtons() { removeButtons() addButtons() layoutButtons() } /** Use this method for positioning of trigger button (should be invoken right after your view of ViewController is loaded and has proper frame). - parameter position: position of right button, have in mind that if you set position of trigger button you need to substract/add his width or height (it depends on position in view axis) */ public func setTriggerButtonPosition(_ position: CGPoint) { let scale = state == .hidden ? CGFloat(1) : CGFloat (0.5) let offset = triggerButton.frame.size.width/2 * scale let newPosition = state == .hidden ? position : CGPoint(x: position.x + offset, y: position.y + offset) triggerButton.frame = CGRect(origin: newPosition, size: triggerButton.frame.size) reloadButtons() } /** If you want to hide trigger button in some point of lifecycle of your VC you can using this method */ public func hideTriggerButton() { hideButtons() triggerButton.isHidden = true } /** Method shows trigger button (if was hidden before) */ public func showTriggerButton() { hideButtons() triggerButton.isHidden = false } /** Method show with animation all side buttons */ public func showButtons() { state = .shown } /** Method hide with animation all side buttons */ public func hideButtons() { state = .hidden } } extension RHSideButtons: RHButtonViewDelegate { public func didSelectButton(_ buttonView: RHButtonView) { if let indexOfButton = buttonsArr.index(of: buttonView) { delegate?.sideButtons(self, didSelectButtonAtIndex: indexOfButton) state = .hidden } else { state = state == .shown ? .hidden : .shown delegate?.sideButtons(self, didTriggerButtonChangeStateTo: state) } } }
mit
01fdf19bf666715b501cdb6ab157b4b6
34.807339
192
0.652063
5.228399
false
false
false
false
SPECURE/rmbt-ios-client
Sources/ServerHelper.swift
1
17425
/***************************************************************************************************** * Copyright 2016 SPECURE GmbH * * 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 Alamofire import AlamofireObjectMapper import ObjectMapper /// class ServerHelper { /// class func configureAlamofireManager() -> Alamofire.Session { let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = 30 // seconds configuration.timeoutIntervalForResource = 30 configuration.allowsCellularAccess = true configuration.httpShouldUsePipelining = true let alamofireManager = Alamofire.Session(configuration: configuration) updateHeadersAlamofireManager(alamofireManager) // print(Bundle.main.preferredLocalizations) return alamofireManager } class func updateHeadersAlamofireManager(_ alamofireManager: Alamofire.Session) { var headers: [AnyHashable: Any] = [:] // Set user agent if let userAgent = UserDefaults.getRequestUserAgent() { headers = [ "User-Agent": userAgent, "Accept-Language": PREFFERED_LANGUAGE ] } if let clientIdentifier = RMBTConfig.sharedInstance.clientIdentifier { headers["X-Nettest-Client"] = clientIdentifier } alamofireManager.sessionConfiguration.httpAdditionalHeaders = headers } /// class func requestArray<T: BasicResponse>(_ manager: Alamofire.Session, baseUrl: String?, method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: [T]) -> (), error failure: @escaping ErrorCallback) { // add basic request values (TODO: make device independent -> for osx, tvos) var parameters: [String: AnyObject]? if let reqObj = requestObject { BasicRequestBuilder.addBasicRequestValues(reqObj) parameters = reqObj.toJSON() as [String : AnyObject]? Log.logger.debug { () -> String in if let jsonString = Mapper().toJSONString(reqObj, prettyPrint: true) { return "Requesting \(path) with object: \n\(jsonString)" } return "Requesting \(path) with object: <json serialization failed>" } } var encoding: ParameterEncoding = JSONEncoding.default if method == .get || method == .delete { // GET and DELETE request don't support JSON bodies... encoding = URLEncoding.default } let basePath = (baseUrl != nil ? baseUrl! : "") + path manager .request(basePath, method: method, parameters: parameters, encoding: encoding, headers: [:]) // maybe use alamofire router later? (https://grokswift.com/router/) .validate() // https://github.com/Alamofire/Alamofire#validation // need custom code to get body from error (see https://github.com/Alamofire/Alamofire/issues/233) /*.responseString { response in Log.logger.debug { debugPrint(response) return "Response for \(path): \n\(response.result.value)" } }*/ .responseArray(completionHandler: { (response: AFDataResponse<[T]>) in switch response.result { case .success(let responseArray): Log.logger.debug { debugPrint(response) if let jsonString = Mapper().toJSONString(responseArray, prettyPrint: true) { return "Response for \(path) with object: \n\(jsonString)" } return "Response for \(path) with object: <json serialization failed>" } success(responseArray) case .failure(let error): Log.logger.debug("\(error)") // TODO: error callback /*if let responseObj = response.result.value as? String { Log.logger.debug("error msg from server: \(responseObj)") }*/ failure(error as Error) } }) // .responseArray { (response: DataResponse<[T]>, error) in // switch response.result { // case .success: // if let responseArray: [T] = response.result.value { // // Log.logger.debug { // debugPrint(response) // // if let jsonString = Mapper().toJSONString(responseArray, prettyPrint: true) { // return "Response for \(path) with object: \n\(jsonString)" // } // // return "Response for \(path) with object: <json serialization failed>" // } // // success(responseArray) // } // case .failure(let error): // Log.logger.debug("\(error)") // TODO: error callback // // /*if let responseObj = response.result.value as? String { // Log.logger.debug("error msg from server: \(responseObj)") // }*/ // // failure(error as Error) // } // } } /// class func request<T: BasicResponse>(_ manager: Alamofire.Session, baseUrl: String?, method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: T) -> (), error failure: @escaping ErrorCallback) { // add basic request values (TODO: make device independent -> for osx, tvos) var parameters: [String: AnyObject]? if let reqObj = requestObject { BasicRequestBuilder.addBasicRequestValues(reqObj) parameters = reqObj.toJSON() as [String : AnyObject]? Log.logger.debug { () -> String in if let jsonString = Mapper().toJSONString(reqObj, prettyPrint: true) { return "Requesting \(path) with object: \n\(jsonString)" } return "Requesting \(path) with object: <json serialization failed>" } } var encoding: ParameterEncoding = JSONEncoding.default if method == .get || method == .delete { // GET and DELETE request don't support JSON bodies... encoding = URLEncoding.default } let url = (baseUrl != nil ? baseUrl! : "") + path var headers: HTTPHeaders? if let clientIdentifier = RMBTConfig.sharedInstance.clientIdentifier { headers = HTTPHeaders(["X-Nettest-Client": clientIdentifier]) } manager .request(url, method: method, parameters: parameters, encoding: encoding, headers: headers) // maybe use alamofire router later? (https://grokswift.com/router/) .validate() // https://github.com/Alamofire/Alamofire#validation // need custom code to get body from error (see https://github.com/Alamofire/Alamofire/issues/233) .responseObject { (response: AFDataResponse<T>) in print(String(data: response.data ?? Data(), encoding: .utf8)) switch response.result { case .success(let responseObj): Log.logger.debug { debugPrint(response) if let jsonString = Mapper().toJSONString(responseObj, prettyPrint: true) { return "Response for \(path) with object: \n\(jsonString)" } return "Response for \(path) with object: <json serialization failed>" } success(responseObj) case .failure(let error): Log.logger.debug("\(error)") // TODO: error callback debugPrint(response) var resultError = error if let data = response.data, let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers), let jsonDictionary = jsonObject as? [String: Any] { print(jsonDictionary) if let errorString = jsonDictionary["error"] as? String { // NSError().asAFError(orFailWith: errorString) resultError = NSError(domain: "error", code: -1, userInfo: [NSLocalizedDescriptionKey : errorString]).asAFError ?? resultError } if let errorArray = jsonDictionary["error"] as? [String], errorArray.count > 0, let errorString = errorArray.first { resultError = NSError(domain: "error", code: -1, userInfo: [NSLocalizedDescriptionKey : errorString]).asAFError ?? resultError } } /*if let responseObj = response.result.value as? String { Log.logger.debug("error msg from server: \(responseObj)") }*/ failure(resultError as Error) } } } /// class func request<T: BasicResponse>(_ manager: Alamofire.Session, baseUrl: String?, method: Alamofire.HTTPMethod, path: String, requestObjects: [BasicRequest]?, key: String?, success: @escaping (_ response: T) -> (), error failure: @escaping ErrorCallback) { // add basic request values (TODO: make device independent -> for osx, tvos) var parameters: [String: AnyObject]? var parametersObjects: [[String: AnyObject]] = [] if let reqObjs = requestObjects { for reqObj in reqObjs { BasicRequestBuilder.addBasicRequestValues(reqObj) // parameters = reqObj.toJSON() as [String : AnyObject]? // break parametersObjects.append(reqObj.toJSON() as [String : AnyObject]) Log.logger.debug { () -> String in if let jsonString = Mapper().toJSONString(reqObj, prettyPrint: true) { return "Requesting \(path) with object: \n\(jsonString)" } return "Requesting \(path) with object: <json serialization failed>" } } } if let key = key { parameters = [key: parametersObjects as AnyObject] } var encoding: ParameterEncoding = JSONEncoding.default if method == .get || method == .delete { // GET and DELETE request don't support JSON bodies... encoding = URLEncoding.default } let url = (baseUrl != nil ? baseUrl! : "") + path var headers: HTTPHeaders? if let clientIdentifier = RMBTConfig.sharedInstance.clientIdentifier { headers = HTTPHeaders(["X-Nettest-Client": clientIdentifier]) } manager .request(url, method: method, parameters: parameters, encoding: encoding, headers: nil) // maybe use alamofire router later? (https://grokswift.com/router/) .validate() // https://github.com/Alamofire/Alamofire#validation // need custom code to get body from error (see https://github.com/Alamofire/Alamofire/issues/233) .responseObject { (response: AFDataResponse<T>) in switch response.result { case .success(let responseObj): Log.logger.debug { debugPrint(response) if let jsonString = Mapper().toJSONString(responseObj, prettyPrint: true) { return "Response for \(path) with object: \n\(jsonString)" } return "Response for \(path) with object: <json serialization failed>" } success(responseObj) case .failure(let error): Log.logger.debug("\(error)") // TODO: error callback debugPrint(response) /*if let responseObj = response.result.value as? String { Log.logger.debug("error msg from server: \(responseObj)") }*/ failure(error as Error) } } } /// class func requestCustomArray<T: Mappable>(_ manager: Alamofire.Session, baseUrl: String?, method: Alamofire.HTTPMethod, path: String, requestObject: BasicRequest?, success: @escaping (_ response: [T]) -> (), error failure: @escaping ErrorCallback) { // add basic request values (TODO: make device independent -> for osx, tvos) var parameters: [String: AnyObject]? if let reqObj = requestObject { BasicRequestBuilder.addBasicRequestValues(reqObj) parameters = reqObj.toJSON() as [String : AnyObject]? Log.logger.debug { () -> String in if let jsonString = Mapper().toJSONString(reqObj, prettyPrint: true) { return "Requesting \(path) with object: \n\(jsonString)" } return "Requesting \(path) with object: <json serialization failed>" } } var encoding: ParameterEncoding = JSONEncoding.default if method == .get || method == .delete { // GET and DELETE request don't support JSON bodies... encoding = URLEncoding.default } let url = (baseUrl != nil ? baseUrl! : "") + path var headers: HTTPHeaders? if let clientIdentifier = RMBTConfig.sharedInstance.clientIdentifier { headers = HTTPHeaders(["X-Nettest-Client": clientIdentifier]) } manager .request(url, method: method, parameters: parameters, encoding: encoding, headers: headers) // maybe use alamofire router later? (https://grokswift.com/router/) // .validate() // https://github.com/Alamofire/Alamofire#validation // need custom code to get body from error (see https://github.com/Alamofire/Alamofire/issues/233) .responseArray(completionHandler: { (response: DataResponse<[T], AFError>) in print(String(data: response.data ?? Data(), encoding: .utf8)) switch response.result { case .success(let responseObj): Log.logger.debug { debugPrint(response) if let jsonString = Mapper().toJSONString(responseObj, prettyPrint: true) { return "Response for \(path) with object: \n\(jsonString)" } return "Response for \(path) with object: <json serialization failed>" } success(responseObj) case .failure(let error): Log.logger.debug("\(error)") // TODO: error callback debugPrint(response) var resultError = error if let data = response.data, let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers), let jsonDictionary = jsonObject as? [String: Any] { print(jsonDictionary) if let errorString = jsonDictionary["error"] as? String { // NSError().asAFError(orFailWith: errorString) resultError = NSError(domain: "error", code: -1, userInfo: [NSLocalizedDescriptionKey : errorString]).asAFError ?? resultError } if let errorArray = jsonDictionary["error"] as? [String], errorArray.count > 0, let errorString = errorArray.first { resultError = NSError(domain: "error", code: -1, userInfo: [NSLocalizedDescriptionKey : errorString]).asAFError ?? resultError } } /*if let responseObj = response.result.value as? String { Log.logger.debug("error msg from server: \(responseObj)") }*/ failure(resultError as Error) } }) } }
apache-2.0
10df73ecce3883fcf8fe6eef5cde92fa
45.220159
264
0.539512
5.637334
false
false
false
false
Romdeau4/16POOPS
Helps_Kitchen_iOS/Help's Kitchen/SeatedViewController.swift
1
2773
// // StatusViewController.swift // Help's Kitchen // // Created by Stephen Ulmer on 2/13/17. // Copyright © 2017 Stephen Ulmer. All rights reserved. // import UIKit import Firebase class SeatedViewController: CustomTableViewController { let ref = FIRDatabase.database().reference(fromURL: DataAccess.URL) override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(handleAddItems)) navigationItem.leftBarButtonItem?.tintColor = CustomColor.amber500 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Pay", style: .plain, target: self, action: #selector(handlePay)) // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { let uid = FIRAuth.auth()?.currentUser?.uid if uid == nil { return }else{ ref.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in let values = snapshot.value as? [String : AnyObject] let userHasPaid = values?["customerHasPaid"] as! Bool if userHasPaid { self.dismiss(animated: true, completion: nil) } }) } } func handleAddItems() { let addItemsController = AddItemsViewController() let navController = CustomNavigationController(rootViewController: addItemsController) self.present(navController, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.backgroundColor = UIColor.black return cell } func handlePay() { let paymentController = PaymentViewController() let navController = CustomNavigationController(rootViewController: paymentController) self.present(navController, animated: true, completion: { guard let uid = FIRAuth.auth()?.currentUser?.uid else{ return } self.ref.child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in let values = snapshot.value as? [String : AnyObject] let customerHasPaid = values?["customerHasPaid"] as! Bool if customerHasPaid { self.dismiss(animated: true, completion: nil) } }) }) } }
mit
0615972c24b012595796b74a520403f0
30.5
134
0.579365
5.478261
false
false
false
false
djflsdl08/BasicIOS
FoodTracker/FoodTracker/MealViewController.swift
1
3939
// // MealViewController.swift // FoodTracker // // Created by 김예진 on 2017. 10. 17.. // Copyright © 2017년 Kim,Yejin. All rights reserved. // import UIKit import os.log class MealViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { //MARK : Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var phtoImageView: UIImageView! @IBOutlet weak var RatingControl: RatingControl! @IBOutlet weak var saveButton: UIBarButtonItem! var meal : Meal? override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self if let meal = meal { navigationItem.title = meal.name nameTextField.text = meal.name phtoImageView.image = meal.photo RatingControl.rating = meal.rating } updateSaveButtonState() } //MARK : UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Hide the keyboard textField.resignFirstResponder() return true } func textFieldDidBeginEditing(_ textField: UITextField) { // Disable the Save button while editing saveButton.isEnabled = false } func textFieldDidEndEditing(_ textField: UITextField) { updateSaveButtonState() navigationItem.title = textField.text } //MARK: Navigation @IBAction func cancel(_ sender: UIBarButtonItem) { let isPresentingInAddMealMode = presentingViewController is UINavigationController if isPresentingInAddMealMode { dismiss(animated: true, completion: nil) } else if let owningNavigationController = navigationController { owningNavigationController.popViewController(animated: true) } else { fatalError("The MealViewController is not inside a navigation controller") } } override func prepare(for segue : UIStoryboardSegue, sender: Any?) { // This method lets you configure a view controller before it's presented. super.prepare(for: segue, sender : sender) guard let button = sender as? UIBarButtonItem, button === saveButton else { os_log("The save button was not pressed, cancelling", log : OSLog.default, type : .debug) return } let name = nameTextField.text ?? "" let photo = phtoImageView.image let rating = RatingControl.rating meal = Meal(name : name, photo : photo, rating : rating) } //MARK : Actions @IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) { nameTextField.resignFirstResponder() // Hide keyboard let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .photoLibrary imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } //MARK : UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated : true, completion : nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { fatalError("Expected a dictionary containing an image, but was provided the following: \(info)") } phtoImageView.image = selectedImage dismiss(animated : true, completion : nil) } //MARK: Private methods private func updateSaveButtonState() { // Disable the Save button if the text field is empty let text = nameTextField.text ?? "" saveButton.isEnabled = !text.isEmpty } }
mit
e23ec7a4085e7548d7b6aa0379ff674d
34.089286
119
0.659288
5.728863
false
false
false
false
Kalito98/Find-me-a-band
Find me a band/Find me a band/ViewControllers/AccountViewController.swift
1
4577
// // AccountViewController.swift // Find me a band // // Created by Kaloyan Yanev on 3/25/17. // Copyright © 2017 Kaloyan Yanev. All rights reserved. // import UIKit import SwiftSpinner import Toaster class AccountViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, BandsDataDelegate { var sessionManager: SessionManager? var bands: [BandModel] = [] var bandsData: BandsData? @IBOutlet weak var labelBandsCreated: UILabel! @IBOutlet weak var labelHello: UILabel! @IBOutlet weak var bandsTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() bandsData = BandsData() sessionManager = SessionManager() let bandsCell = UINib(nibName: "BandTableViewCell", bundle: nil) self.bandsTableView.register(bandsCell, forCellReuseIdentifier: "band-cell") self.bandsTableView.rowHeight = 70 } override func viewWillAppear(_ animated: Bool) { self.loadBands() self.loadProfile() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.bands.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "band-cell", for: indexPath) as! BandTableViewCell cell.textLableBandName.text = "Genre: \(self.bands[indexPath.row].genre!)" cell.textLableBandCreator.text = "Creator: \(self.bands[indexPath.row].creator!)" cell.textLableBandGenre.text = self.bands[indexPath.row].name return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { self.deleteBandAt(index: indexPath.row) } else if editingStyle == .insert { } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.showDetails(band: self.bands[indexPath.row]) } @IBAction func signOut(_ sender: UIButton) { sessionManager?.removeSession() let storyboardName: String = "Main" let storyboard = UIStoryboard(name: storyboardName, bundle: nil) let tabBarController = storyboard.instantiateViewController(withIdentifier: "navigationControllerUnauth") as? UINavigationController self.present(tabBarController!, animated: true, completion: nil) } func loadBands() { self.bandsData?.delegate = self var username = Dictionary<String, Any>() username["username"] = sessionManager?.getUsername() SwiftSpinner.show("Loading Account") bandsData?.getByUser(username: username) } func showDetails(band: BandModel) { let nextVC = storyboard?.instantiateViewController(withIdentifier: "bandsDetailsView") as! BandsDetailsViewController nextVC.band = band navigationController?.pushViewController(nextVC, animated: true) } func loadProfile() { let username = sessionManager?.getUsername() weak var weakSelf = self DispatchQueue.main.async { weakSelf?.labelHello.text = "Hello, \(username! as String)" } } func deleteBandAt(index: Int) { self.bandsData?.delegate = self SwiftSpinner.show("Deleting Band") let band = self.bands[index] bandsData?.deleteBand(band: band.toJSON()! as Dictionary<String, Any>) } func didReceiveBandsData(bandsData: Any) { let dataArray = bandsData as! [Dictionary<String, Any>] self.bands = [BandModel].from(jsonArray: dataArray)! weak var weakSelf = self DispatchQueue.main.async { weakSelf?.labelBandsCreated.text = "Bands Created: \(self.bands.count)" weakSelf?.bandsTableView.reloadData() } SwiftSpinner.hide() } func didReceiveBandsError(error: HttpError) { SwiftSpinner.hide() } func didDeleteBands() { self.loadBands() SwiftSpinner.hide() Toast(text: "Successfully deleted band", duration: Delay.short).show() } }
mit
dc845dcc64503f0c7b6430d14c5cc824
33.666667
140
0.659747
4.899358
false
false
false
false
Touchwonders/Transition
Examples/ModalTransitionsExample/ModalTransitionsExample/ShapesModel.swift
1
1661
// // MIT License // // Copyright (c) 2017 Touchwonders B.V. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /** * This is a very simple model that counts shapes. */ class ShapesModel { static let shared = ShapesModel() private var counters = [Shape: Int]() init() { Shape.all.forEach { self.counters[$0] = 0 } } func count(for shape: Shape) -> Int { return counters[shape] ?? 0 } func increment(shape: Shape, amount: Int = 1) { counters[shape] = count(for: shape) + amount } }
mit
c49db9e83a08d1b2c4e032c8e7547f93
34.340426
84
0.679711
4.269923
false
false
false
false
Shvier/Dota2Helper
Dota2Helper/Dota2Helper/Main/Setting/Controller/DHSDKViewController.swift
1
2698
// // DHSDKViewController.swift // Dota2Helper // // Created by Shvier on 10/20/16. // Copyright © 2016 Shvier. All rights reserved. // import UIKit class DHSDKViewController: UITableViewController { let dataSource: [NSDictionary] = [ ["name": "Bugtags", "author": "北京八哥科技有限责任公司", "url": "https://www.bugtags.com/"], ["name": "Fabric", "author": "Twitter, Inc.", "url": "https://get.fabric.io/"], ["name": "Kingfisher", "author": "@onevcat", "url": "https://github.com/onevcat/Kingfisher"], ["name": "MJRefresh", "author": "@CoderMJLee", "url": "https://github.com/CoderMJLee/MJRefresh"], ["name": "Reachability.Swift", "author": "@ashleymills", "url": "https://github.com/ashleymills/Reachability.swift"], ["name": "SDCycleScrollView", "author": "@gsdios", "url": "https://github.com/gsdios/SDCycleScrollView"], ["name": "Youku SDK", "author": "Youku Tudou Inc.", "url": "http://cloud.youku.com/"] ] override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.tintColor = kThemeColor tableView?.register(DHSDKTableViewCell.self, forCellReuseIdentifier: kSDKCellReuseIdentifier) tableView.tableFooterView = UIView() tableView.reloadData() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let _ = navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - UITableViewDelegate extension DHSDKViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let dict: NSDictionary = dataSource[indexPath.row] UIApplication.shared.openURL(URL(string: dict["url"] as! String)!) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kSDKCellReuseIdentifier, for: indexPath) as! DHSDKTableViewCell let dict: NSDictionary = dataSource[indexPath.row] cell.sdkNameLabel.text = dict["name"] as? String cell.authorNameLabel.text = dict["author"] as? String return cell } }
apache-2.0
0d589c8a4c5d030a7230ff45348f4aef
38.895522
128
0.663674
4.484899
false
false
false
false
mohsenShakiba/ListView
Example/ListView/CrazyViewController.swift
1
3228
// // CrazyViewController.swift // ListView // // Created by mohsen shakiba on 2/13/1396 AP. // Copyright © 1396 CocoaPods. All rights reserved. // import Foundation import ListView class CrazyViewController: ListViewController { override func viewDidLoad() { super.viewDidLoad() self.setupListView() } func setupListView() { cell(LabelCell.self) .setup { (cell) in cell.label.text = "back" cell.size(100, 20, 20, 20) } .click { (_) in self.dismiss(animated: true, completion: nil) } .commit() cell(LabelCell.self) .setup { (cell) in cell.label.text = "go carazy" cell.size(20, 20, 20, 20) } .click { (_) in self.initCrazy() } .commit() for i in 0...9 { section({ (s) in for l in 0...9 { s.reusableCell(LabelCell.self) .update({ (cell) in cell.label.text = String(l + (i * 10)) }) .commit(String(l + (i * 10))) } }) .finalize(String(i)) } } func initCrazy() { Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(CrazyViewController.crazyOperation), userInfo: nil, repeats: true) } func crazyOperation() { self.beginUpdates() for i in 0...10 { let id = String(i) if let section = self.sectionBy(id: id) { let ran = getRandomNumber() if ran % 2 == 0 { // print("hiding section", id) section.hide() }else{ // print("shwoing section", id) section.show() } } } for i in 0...100 { let id = String(i) if let cell = self.rowBy(id: id) { let ran = getRandomNumber() % 4 if ran == 0 { // cell.hide() if let si = cell.sectionIndex { if let section = sectionBy(id: String(si)) { section.reusableCell(LabelCell.self) .update({ (cell) in cell.label.text = "new" + String(section.visibleRows.count) }) .commit() } } }else if ran == 1 { // cell.show() cell.remove() } // else if ran == 2 { // } // else if ran == 3 { // // } } } self.endUpdates(false) } private func getRandomNumber() -> Int { let A: UInt32 = 0 let B: UInt32 = 25 let number = arc4random_uniform(B - A + 1) + A return Int(number) } }
mit
f02bb6da421c89c4ab27f0d6370b7b4a
28.072072
148
0.392935
4.704082
false
false
false
false
nathawes/swift
test/stdlib/BridgeStorage.swift
9
5261
//===--- BridgeStorage.swift ----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Bridged types are notionally single-word beasts that either store // an objc class or a native Swift class. We'd like to be able to // distinguish these cases efficiently. // //===----------------------------------------------------------------------===// // RUN: %target-run-stdlib-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Swift //===--- Code mimics the stdlib without using spare pointer bits ----------===// import SwiftShims protocol BridgeStorage { associatedtype Native : AnyObject associatedtype ObjC : AnyObject init(native: Native, isFlagged: Bool) init(native: Native) init(objC: ObjC) mutating func isUniquelyReferencedNative() -> Bool mutating func isUniquelyReferencedUnflaggedNative() -> Bool var isNative: Bool {get} var isObjC: Bool {get} var nativeInstance: Native {get} var unflaggedNativeInstance: Native {get} var objCInstance: ObjC {get} } extension _BridgeStorage : BridgeStorage {} //===----------------------------------------------------------------------===// //===--- Testing code -----------------------------------------------------===// //===----------------------------------------------------------------------===// import StdlibUnittest var allTests = TestSuite("DiscriminatedBridgeObject") class C { deinit { print("bye C!") } } import Foundation func isOSAtLeast(_ major: Int, _ minor: Int, patch: Int = 0) -> Bool { // isOperatingSystemAtLeastVersion() is unavailable on some OS versions. if #available(iOS 8.0, OSX 10.10, *) { let procInfo: AnyObject = ProcessInfo.processInfo return procInfo.isOperatingSystemAtLeast( OperatingSystemVersion(majorVersion: major, minorVersion: minor, patchVersion: patch)) } return false } func expectTagged(_ s: NSString, _ expected: Bool) -> NSString { #if arch(x86_64) let mask: UInt = 0x8000000000000001 #elseif arch(arm64) let mask: UInt = 0x8000000000000000 #else let mask: UInt = 0 #endif var osSupportsTaggedStrings: Bool #if os(iOS) // NSTaggedPointerString is enabled starting in iOS 9.0. osSupportsTaggedStrings = isOSAtLeast(9,0) #elseif os(tvOS) || os(watchOS) // NSTaggedPointerString is supported in all versions of TVOS and watchOS. osSupportsTaggedStrings = true #elseif os(OSX) // NSTaggedPointerString is enabled starting in OS X 10.10. osSupportsTaggedStrings = isOSAtLeast(10,10) #endif let taggedStringsSupported = osSupportsTaggedStrings && mask != 0 let tagged = unsafeBitCast(s, to: UInt.self) & mask != 0 if taggedStringsSupported && expected == tagged { // okay } else if !taggedStringsSupported && !tagged { // okay } else { let un = !tagged ? "un" : "" fatalError("Unexpectedly \(un)tagged pointer for string \"\(s)\"") } return s } var taggedNSString : NSString { return expectTagged(NSString(format: "foo"), true) } var unTaggedNSString : NSString { return expectTagged("fûtbōl" as NSString, false) } allTests.test("_BridgeStorage") { typealias B = _BridgeStorage<C> let oy: NSString = "oy" expectTrue(B(objC: oy).objCInstance === oy) for flag in [false, true] { do { var b = B(native: C(), isFlagged: flag) expectFalse(b.isObjC) expectTrue(b.isNative) expectEqual(!flag, b.isUnflaggedNative) expectTrue(b.isUniquelyReferencedNative()) if !flag { expectTrue(b.isUniquelyReferencedUnflaggedNative()) } } do { let c = C() var b = B(native: c, isFlagged: flag) expectFalse(b.isObjC) expectTrue(b.isNative) expectFalse(b.isUniquelyReferencedNative()) expectEqual(!flag, b.isUnflaggedNative) expectTrue(b.nativeInstance === c) if !flag { expectTrue(b.unflaggedNativeInstance === c) expectFalse(b.isUniquelyReferencedUnflaggedNative()) } } } var b = B(native: C(), isFlagged: false) expectTrue(b.isUniquelyReferencedNative()) // Add a reference and verify that it's still native but no longer unique var c = b expectFalse(b.isUniquelyReferencedNative()) _fixLifetime(b) // make sure b is not killed early _fixLifetime(c) // make sure c is not killed early let n = C() var bb = B(native: n) expectTrue(bb.nativeInstance === n) expectTrue(bb.isNative) expectTrue(bb.isUnflaggedNative) expectFalse(bb.isObjC) var d = B(objC: taggedNSString) expectFalse(d.isUniquelyReferencedNative()) expectFalse(d.isNative) expectFalse(d.isUnflaggedNative) expectTrue(d.isObjC) d = B(objC: unTaggedNSString) expectFalse(d.isUniquelyReferencedNative()) expectFalse(d.isNative) expectFalse(d.isUnflaggedNative) expectTrue(d.isObjC) } runAllTests()
apache-2.0
70fae43801b814f3c01b64a7aa718a8a
27.737705
80
0.638334
4.353477
false
false
false
false
i-schuetz/rest_client_ios
clojushop_client_ios/LoginRegisterViewController.swift
1
3142
// // LoginViewController.swift // clojushop_client_ios // // Created by ischuetz on 07/06/2014. // Copyright (c) 2014 ivanschuetz. All rights reserved. // import Foundation class LoginRegisterViewController:BaseViewController { @IBOutlet var loginNameField:UITextField! @IBOutlet var loginPWField:UITextField! @IBOutlet var viewWorkaround:UIView! //FIXME workaround didnt work override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.tabBarItem.title = "Login / Register" } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func fillWithTestData() { loginNameField.text = "user1" loginPWField.text = "test123" } override func viewDidLoad() { super.viewDidLoad() self.fillWithTestData() //FIXME nothing works - tap listener not called. Probably because the root view outlet is cant be attached? // let tap:UIGestureRecognizer = UIGestureRecognizer(target: self, action: "dismissKeyboard:") let tap:UIGestureRecognizer = UIGestureRecognizer(target: viewWorkaround, action: "dismissKeyboard:") self.view.addGestureRecognizer(tap) } func dismissKeyboard() { loginNameField.resignFirstResponder() loginPWField.resignFirstResponder() } override func viewDidDisappear(animated: Bool) { self.setProgressHidden(true) //clear possible progressbar we started last time showing user account. Do it here instad immediately after to avoid flickering on transition } func getUser() { DataStore.sharedDataStore().getUser( {(user:User!) -> Void in self.showUserAccountTab(user) }, failureHandler: {(Int) -> Bool in return false}) } @IBAction func login(sender: UIButton) { let loginName:String = loginNameField.text let loginPW:String = loginPWField.text self.setProgressHidden(false) DataStore.sharedDataStore().login(loginName, password: loginPW, successHandler: {() -> Void in self.getUser() }, failureHandler: {(Int) -> Bool in return false}) } @IBAction func register(sender: UIButton) { let registerController:RegisterViewController = RegisterViewController(nibName: "RegisterViewController", bundle: nil) self.navigationController?.pushViewController(registerController, animated: true) } func showUserAccountTab(user:User) { let userAccountController: UserAccountViewController = UserAccountViewController(nibName: "UserAccountViewController", bundle: nil) userAccountController.user = user self.navigationController?.tabBarItem.title = "User account" self.navigationController?.pushViewController(userAccountController, animated: true) self.navigationController?.navigationBarHidden = true } }
apache-2.0
41109e67b0b1bafca4bc09a5e454529b
34.314607
178
0.669001
5.316413
false
false
false
false
i-miss-you/Kingfisher
Kingfisher/UIImageView+Kingfisher.swift
11
15372
// // UIImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Set Images /** * Set image to use from web. */ public extension UIImageView { /** Set an image with a resource. It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource`. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use. :param: resource Resource object contains information such as `cacheKey` and `downloadURL`. :returns: A task represents the retriving process. */ public func kf_setImageWithResource(resource: Resource) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL. It will ask for Kingfisher's manager to get the image for the URL. The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use. If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want. :param: URL The URL of image. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource and a placeholder image. :param: resource Resource object contains information such as `cacheKey` and `downloadURL`. :param: placeholderImage A placeholder image when retrieving the image at URL. :returns: A task represents the retriving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a placeholder image. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource, a placaholder image and options. :param: resource Resource object contains information such as `cacheKey` and `downloadURL`. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :returns: A task represents the retriving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placaholder image and options. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource, a placeholder image, options and completion handler. :param: resource Resource object contains information such as `cacheKey` and `downloadURL`. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retriving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options and completion handler. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. :param: resource Resource object contains information such as `cacheKey` and `downloadURL`. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: progressBlock Called when the image downloading progress gets updated. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retriving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { let showIndicatorWhenLoading = kf_showIndicatorWhenLoading var indicator: UIActivityIndicatorView? = nil if showIndicatorWhenLoading { indicator = kf_indicator indicator?.hidden = false indicator?.startAnimating() } image = placeholderImage kf_setWebURL(resource.downloadURL) let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }, completionHandler: {[weak self] (image, error, cacheType, imageURL) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if let sSelf = self where imageURL == sSelf.kf_webURL && image != nil { sSelf.image = image; indicator?.stopAnimating() } completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) }) }) return task } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: progressBlock Called when the image downloading progress gets updated. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(Resource(downloadURL: URL), placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var showIndicatorWhenLoadingKey: Void? public extension UIImageView { /// Get the image URL binded to this image view. public var kf_webURL: NSURL? { get { return objc_getAssociatedObject(self, &lastURLKey) as? NSURL } } private func kf_setWebURL(URL: NSURL) { objc_setAssociatedObject(self, &lastURLKey, URL, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } /// Whether show an animating indicator when the image view is loading an image or not. /// Default is false. public var kf_showIndicatorWhenLoading: Bool { get { if let result = objc_getAssociatedObject(self, &showIndicatorWhenLoadingKey) as? NSNumber { return result.boolValue } else { return false } } set { if kf_showIndicatorWhenLoading == newValue { return } else { if newValue { let indicator = UIActivityIndicatorView(activityIndicatorStyle:.Gray) indicator.center = center indicator.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleBottomMargin | .FlexibleTopMargin indicator.hidden = true indicator.hidesWhenStopped = true self.addSubview(indicator) kf_setIndicator(indicator) } else { kf_indicator?.removeFromSuperview() kf_setIndicator(nil) } objc_setAssociatedObject(self, &showIndicatorWhenLoadingKey, NSNumber(bool: newValue), UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } } /// The indicator view showing when loading. This will be `nil` if `kf_showIndicatorWhenLoading` is false. /// You may want to use this to set the indicator style or color when you set `kf_showIndicatorWhenLoading` to true. public var kf_indicator: UIActivityIndicatorView? { get { return objc_getAssociatedObject(self, &indicatorKey) as? UIActivityIndicatorView } } private func kf_setIndicator(indicator: UIActivityIndicatorView?) { objc_setAssociatedObject(self, &indicatorKey, indicator, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } // MARK: - Deprecated public extension UIImageView { @availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil) } @availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler) } @availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler) } }
mit
7193f2188da5d5fb0f36ffb07b95c829
45.301205
242
0.649753
5.729407
false
false
false
false
pman215/ToastNotifications
ToastNotificationsTests/ViewAnimationTaskQueueTests.swift
1
4000
// // ViewAnimationTaskQueueTests.swift // ToastNotifications // // Created by pman215 on 6/7/16. // Copyright © 2016 pman215. All rights reserved. // @testable import ToastNotifications import XCTest internal extension ViewAnimationTask { convenience init() { self.init(view: UIView(), animation: ViewAnimation()) } } class ViewAnimationTaskQueueTests: XCTestCase { func testQueueInitialState() { let queue = ViewAnimationTaskQueue() XCTAssertEqual(queue.state, .new) XCTAssertEqual(queue.tasks.count, 0) } func testQueueTaskWithoutProcessing() { let view = UIView() let task1 = ViewAnimationTask(view: view, animation: ViewAnimation()) let task2 = ViewAnimationTask(view: view, animation: ViewAnimation()) let queue = ViewAnimationTaskQueue() queue.queue(task: task1) queue.queue(task: task2) XCTAssertEqual(queue.state, .new) XCTAssertEqual(queue.tasks.count, 2) } func testQueueCanProcess() { let task1 = ViewAnimationTask() let task2 = ViewAnimationTask() let queue = ViewAnimationTaskQueue() queue.queue(task: task1) queue.queue(task: task2) queue.process() XCTAssertTrue(queue.state == .processing) XCTAssertEqual(queue.tasks.count, 2) XCTAssertTrue(task1.state == .animating) // Simulate animation did finish queue.dequeue(task: task1) XCTAssertEqual(queue.state, .processing) XCTAssertEqual(queue.tasks.count, 1) XCTAssertTrue(task2.state == .animating) // Simulate animation did finish queue.dequeue(task: task2) XCTAssertEqual(queue.state, .finished) XCTAssertEqual(queue.tasks.count, 0) } func testQueueFinishesImmediatelyWithoutTasks() { let queue = ViewAnimationTaskQueue() queue.process() XCTAssertEqual(queue.state, .finished) } func testQueueCancelWhileProcessing() { let task1 = ViewAnimationTask() let task2 = ViewAnimationTask() let queue = ViewAnimationTaskQueue() queue.queue(task: task1) queue.queue(task: task2) queue.process() queue.cancel() XCTAssertEqual(queue.state, .finished) XCTAssertTrue(queue.tasks.isEmpty) XCTAssertEqual(task1.state, .finished) XCTAssertEqual(task2.state, .finished) } func testQueueCanCancelBeforeStartProcessing() { let task1 = ViewAnimationTask() let task2 = ViewAnimationTask() let queue = ViewAnimationTaskQueue() queue.queue(task: task1) queue.queue(task: task2) queue.cancel() XCTAssertEqual(queue.state, .finished) XCTAssertTrue(queue.tasks.isEmpty) XCTAssertEqual(task1.state, .finished) XCTAssertEqual(task2.state, .finished) } func testQueueNotifiesDelegateDidFinishProcessing() { class TestDelegate: ViewAnimationTaskQueueDelegate { var queueDidFinishProcessingHandler: (()-> Void)? func queueDidFinishProcessing(_ queue: ViewAnimationTaskQueue) { queueDidFinishProcessingHandler?() } } let expectation = self.expectation(description: #function) let delegate = TestDelegate() delegate.queueDidFinishProcessingHandler = { expectation.fulfill() } let task1 = ViewAnimationTask() let task2 = ViewAnimationTask() let queue = ViewAnimationTaskQueue() queue.delegate = delegate queue.queue(task: task1) queue.queue(task: task2) queue.process() waitForExpectations(timeout: 1.0) { (_) in XCTAssertEqual(queue.tasks.count, 0) XCTAssertEqual(queue.state, .finished) XCTAssertEqual(task1.state, .finished) XCTAssertEqual(task2.state, .finished) } } }
mit
980dc8db1e3c5ea38b557c5578502e30
25.309211
77
0.637409
4.937037
false
true
false
false
mltbnz/FeedbackServer
Sources/App/Models/Project.swift
1
2187
// // Project.swift // Feedback // // Created by Malte Bünz on 23.06.17. // // import Foundation import FluentProvider import Vapor import HTTP final class Project: Model { let storage = Storage() static let nameKey = "name" var exists: Bool = false var id: Node? var name: String // MARK: Initializers init(name: String) { self.name = name } init(node: Node) throws { id = try node.get(Project.idKey) name = try node.get(Project.nameKey) } init(from json: JSON?) throws { guard let jso = json else { throw Abort.badRequest } name = try jso.get(Project.nameKey) } init(row: Row) throws { id = try row.get(Project.idKey) name = try row.get(Project.nameKey) } // MARK: Maker func makeNode(context: Context) throws -> Node { return try Node(node: [ Project.idKey: id, Project.nameKey: name ]) } func makeRow() throws -> Row { var row = Row() try row.set(Project.nameKey, name) return row } } extension Project: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string(Project.nameKey) } } static func revert(_ database: Database) throws { try database.delete(self) } } extension Project: JSONRepresentable, ResponseRepresentable { func makeJSON() throws -> JSON { var json = JSON() try json.set(Project.idKey, id) try json.set(Project.nameKey, name) return json } } extension Project: Updateable { public static var updateableKeys: [UpdateableKey<Project>] { return [ UpdateableKey(Project.nameKey, String.self) { project, name in project.name = name } ] } } extension Project { func feedback() throws -> [Feedback] { return try children(type: Feedback.self, foreignIdKey: Feedback.projectIdKey).all() } }
mit
91fbac1732657b4e8cf615bef434e914
20.223301
74
0.559469
4.261209
false
false
false
false
MingLoan/PageTabBarController
sources/PageTabBar.swift
1
13713
// // PageTabBar.swift // PageTabBarController // // Created by Keith Chan on 4/9/2017. // Copyright © 2017 com.mingloan. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit internal protocol PageTabBarDelegate: class { func pageTabBarCurrentIndex(_ tabBar: PageTabBar) -> Int func pageTabBar(_ tabBar: PageTabBar, indexDidChanged index: Int) } @objc public enum PageTabBarPosition: Int { case topAttached = 0 case topInsetAttached case bottom } public enum PageTabBarIndicatorPosition { case top(offset: CGFloat) case bottom(offset: CGFloat) } public enum PageTabBarIndicatorLineWidth { case fill case contentWidth } internal enum PageTabBarItemArrangement { case fixedWidth(width: CGFloat) case compact } public typealias LineWidthUnit = Int @objcMembers open class PageTabBar: UIView { public struct BarAppearanceSettings { public var isTranslucent: Bool public var translucentFactor: CGFloat public var barTintColor: UIColor? public var topLineHidden: Bool public var bottomLineHidden: Bool public var topLineColor: UIColor? public var bottomLineColor: UIColor? public var topLineWidth: LineWidthUnit public var bottomLineWidth: LineWidthUnit } public struct IndicatorLineAppearanceSettings { public var isHidden: Bool public var lineHeight: CGFloat public var lineWidth: PageTabBarIndicatorLineWidth public var lineColor: UIColor? public var position: PageTabBarIndicatorPosition } public static var defaultBarAppearanceSettings = BarAppearanceSettings(isTranslucent: false, translucentFactor: 0.6, barTintColor: .white, topLineHidden: false, bottomLineHidden: false, topLineColor: .lightGray, bottomLineColor: .lightGray, topLineWidth: 1, bottomLineWidth: 1) public static var defaultIndicatorLineAppearanceSettings = IndicatorLineAppearanceSettings(isHidden: false, lineHeight: 1, lineWidth: .fill, lineColor: UIApplication.shared.delegate?.window??.tintColor, position: PageTabBarIndicatorPosition.bottom(offset: 0)) open var appearance: BarAppearanceSettings = PageTabBar.defaultBarAppearanceSettings { didSet { backdropView.translucentFactor = appearance.translucentFactor backdropView.barTintColor = appearance.barTintColor ?? .white backdropView.isTranslucent = appearance.isTranslucent topLine.isHidden = appearance.topLineHidden bottomLine.isHidden = appearance.bottomLineHidden topLine.backgroundColor = appearance.topLineColor bottomLine.backgroundColor = appearance.bottomLineColor let topLineWidth = CGFloat(appearance.topLineWidth) / UIScreen.main.scale topLine.frame = CGRect(x: 0, y: 0, width: bounds.width, height: topLineWidth) let bottomLineWidth = CGFloat(appearance.bottomLineWidth) / UIScreen.main.scale bottomLine.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bottomLineWidth) setNeedsDisplay() } } open var indicatorLineAppearance: IndicatorLineAppearanceSettings = PageTabBar.defaultIndicatorLineAppearanceSettings { didSet { indicatorLine.isHidden = indicatorLineAppearance.isHidden indicatorLine.backgroundColor = indicatorLineAppearance.lineColor indicatorLine.frame = CGRect(x: indicatorLine.frame.minX, y: indicatorLineOriginY, width: indicatorLineWidth(at: 0), height: indicatorLineHeight) } } // Private Getter private var indicatorLineHeight: CGFloat { return indicatorLineAppearance.lineHeight } private var indicatorLineOriginY: CGFloat { switch indicatorLineAppearance.position { case let .top(offset): return offset case let .bottom(offset): return barHeight - indicatorLineHeight - offset } } // Delegates internal weak var delegate: PageTabBarDelegate? override open var intrinsicContentSize: CGSize { return CGSize(width: UIScreen.main.bounds.width, height: barHeight) } override open var bounds: CGRect { didSet { repositionAndResizeIndicatorView() } } open var barHeight = CGFloat(44) { didSet { guard oldValue != barHeight else { return } indicatorLine.frame.origin = CGPoint(x: indicatorLine.frame.minX, y: indicatorLineOriginY) bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: barHeight) } } internal var isInteracting = false { didSet { isUserInteractionEnabled = !isInteracting } } private var items = [PageTabBarItem]() private var itemWidth: CGFloat { if items.count == 0 { return 0 } return bounds.width/CGFloat(items.count) } private var indicatorLine: UIView = { let line = UIView() line.backgroundColor = .blue return line }() private var topLine: UIView = { let line = UIView() line.backgroundColor = .lightGray return line }() private var bottomLine: UIView = { let line = UIView() line.backgroundColor = .lightGray return line }() private var itemStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.alignment = .fill stackView.spacing = 0 return stackView }() private let backdropView: PageTabBarBackdropView = { let backdropView = PageTabBarBackdropView(frame: CGRect(x: 0, y: 0, width: 375, height: 44)) backdropView.barTintColor = UIColor.white backdropView.translatesAutoresizingMaskIntoConstraints = false return backdropView }() convenience init(tabBarItems: [PageTabBarItem]) { self.init(frame: CGRect(x: 0, y: 0, width: 100, height: 44)) items = tabBarItems commonInit() } private func commonInit() { backdropView.isTranslucent = false backdropView.barTintColor = appearance.barTintColor ?? .white addSubview(backdropView) NSLayoutConstraint.activate([backdropView.topAnchor.constraint(equalTo: topAnchor), backdropView.leftAnchor.constraint(equalTo: leftAnchor), backdropView.bottomAnchor.constraint(equalTo: bottomAnchor), backdropView.rightAnchor.constraint(equalTo: rightAnchor)]) items.forEach { itemStackView.addArrangedSubview($0) $0.delegate = self } itemStackView.frame = bounds itemStackView.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(itemStackView) var lineWidth = CGFloat(appearance.topLineWidth) / UIScreen.main.scale topLine.frame = CGRect(x: 0, y: 0, width: bounds.width, height: lineWidth) addSubview(topLine) topLine.translatesAutoresizingMaskIntoConstraints = false topLine.topAnchor.constraint(equalTo: topAnchor).isActive = true topLine.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true topLine.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true lineWidth = CGFloat(appearance.bottomLineWidth) / UIScreen.main.scale bottomLine.frame = CGRect(x: 0, y: bounds.height - lineWidth, width: bounds.width, height: lineWidth) addSubview(bottomLine) bottomLine.translatesAutoresizingMaskIntoConstraints = false bottomLine.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true bottomLine.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true bottomLine.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true addSubview(indicatorLine) } override open func layoutSubviews() { super.layoutSubviews() var lineWidth = CGFloat(appearance.topLineWidth) / UIScreen.main.scale topLine.frame = CGRect(x: 0, y: 0, width: bounds.width, height: lineWidth) lineWidth = CGFloat(appearance.bottomLineWidth) / UIScreen.main.scale bottomLine.frame = CGRect(x: 0, y: bounds.height - lineWidth, width: bounds.width, height: lineWidth) } internal func setIndicatorPosition(_ position: CGFloat, animated: Bool = false) { if animated { UIView.animate(withDuration: 0.2, animations: { self.setIndicatorPosition(position) }) return } indicatorLine.center.x = position + itemWidth/2 let index = Int(indicatorLine.center.x/itemWidth) let oldWidth = indicatorLine.bounds.width let newWidth = indicatorLineWidth(at: index) if oldWidth != newWidth { UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState], animations: { self.indicatorLine.bounds = CGRect(x: 0, y: 0, width: newWidth, height: self.indicatorLineHeight) }, completion: nil) } else { indicatorLine.bounds = CGRect(x: 0, y: 0, width: newWidth, height: self.indicatorLineHeight) } for (idx, button) in items.enumerated() { button.isSelected = idx == index ? true : false } } private func repositionAndResizeIndicatorView() { guard let index = delegate?.pageTabBarCurrentIndex(self) else { return } layoutIfNeeded() let centerX = itemWidth / 2 + ceil(CGFloat(index) * itemWidth) indicatorLine.center = CGPoint(x: centerX, y: indicatorLineOriginY + indicatorLineHeight / 2) indicatorLine.bounds = CGRect(x: 0, y: 0, width: indicatorLineWidth(at: index), height: indicatorLineHeight) for (idx, button) in items.enumerated() { button.isSelected = idx == index ? true : false } } internal func replaceTabBarItems(_ newTabBarItems: [PageTabBarItem]) { itemStackView.arrangedSubviews.forEach { itemStackView.removeArrangedSubview($0) $0.removeFromSuperview() } newTabBarItems.forEach { itemStackView.addArrangedSubview($0) $0.delegate = self } items = newTabBarItems repositionAndResizeIndicatorView() } /* Public Methods * */ open func setBarHeight(_ height: CGFloat, animated: Bool) { if animated { UIView.animate(withDuration: 0.3, animations: { self.barHeight = height }) } else { barHeight = height } } /** * Line Width Calculation */ private func indicatorLineWidth(at index: Int) -> CGFloat { switch indicatorLineAppearance.lineWidth { case .fill: return itemWidth case .contentWidth: return items[index].tabBarButtonContentWidth } } } extension PageTabBar: PageTabBarItemDelegate { func pageTabBarItemDidTap(_ item: PageTabBarItem) { if let index = items.firstIndex(of: item) { delegate?.pageTabBar(self, indexDidChanged: index) } } }
mit
c2888966ec5eed2002ac2fe5929377be
37.301676
157
0.608299
5.654433
false
false
false
false
blinksh/blink
Settings/ViewControllers/BKHosts/HostView.swift
1
18274
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink 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. // // Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import SwiftUI import CloudKit struct FileDomainView: View { @EnvironmentObject private var _nav: Nav var domain: FileProviderDomain let refreshList: () -> () @State private var _displayName: String = "" @State private var _remotePath: String = "" @State private var _loaded = false @State private var _errorMessage = "" var body: some View { List { Section { Field("Name", $_displayName, next: "Path", placeholder: "Required") Field("Path", $_remotePath, next: "", placeholder: "root folder on the remote") } } .listStyle(GroupedListStyle()) .navigationBarTitle("Files.app Location") .navigationBarItems( trailing: Group { Button("Update", action: { do { try _validate() } catch { _errorMessage = error.localizedDescription return } domain.displayName = _displayName.trimmingCharacters(in: .whitespacesAndNewlines) domain.remotePath = _remotePath.trimmingCharacters(in: .whitespacesAndNewlines) refreshList() _nav.navController.popViewController(animated: true) } )//.disabled(_conflictedICloudHost != nil) } ) .onAppear { if !_loaded { _loaded = true _displayName = domain.displayName _remotePath = domain.remotePath } } .alert(errorMessage: $_errorMessage) } private func _validate() throws { let cleanDisplayName = _displayName.trimmingCharacters(in: .whitespacesAndNewlines) if cleanDisplayName.isEmpty { throw FormValidationError.general(message: "Name is required", field: "Name") } } } fileprivate struct FileDomainRow: View { let domain: FileProviderDomain let refreshList: () -> () var body: some View { Row( content: { HStack { Text(domain.displayName) Spacer() Text(domain.remotePath).font(.system(.subheadline)) } }, details: { FileDomainView(domain: domain, refreshList: refreshList) } ) } } struct FormLabel: View { let text: String var minWidth: CGFloat = 86 var body: some View { Text(text).frame(minWidth: minWidth, alignment: .leading) } } struct Field: View { private let _id: String private let _label: String private let _placeholder: String @Binding private var value: String private let _next: String? private let _secureTextEntry: Bool private let _enabled: Bool private let _kbType: UIKeyboardType init(_ label: String, _ value: Binding<String>, next: String, placeholder: String, id: String? = nil, secureTextEntry: Bool = false, enabled: Bool = true, kbType: UIKeyboardType = .default) { _id = id ?? label _label = label _value = value _placeholder = placeholder _next = next _secureTextEntry = secureTextEntry _enabled = enabled _kbType = kbType } var body: some View { HStack { FormLabel(text: _label) FixedTextField( _placeholder, text: $value, id: _id, nextId: _next, secureTextEntry: _secureTextEntry, keyboardType: _kbType, autocorrectionType: .no, autocapitalizationType: .none, enabled: _enabled ) } } } struct FieldSSHKey: View { @Binding var value: String var enabled: Bool = true var body: some View { Row( content: { HStack { FormLabel(text: "Key") Spacer() Text(value.isEmpty ? "None" : value) .font(.system(.subheadline)).foregroundColor(.secondary) } }, details: { KeyPickerView(currentKey: enabled ? $value : .constant(value)) } ) } } fileprivate struct FieldMoshPrediction: View { @Binding var value: BKMoshPrediction var enabled: Bool var body: some View { Row( content: { HStack { FormLabel(text: "Prediction") Spacer() Text(value.label).font(.system(.subheadline)).foregroundColor(.secondary) } }, details: { MoshPredictionPickerView(currentValue: enabled ? $value : .constant(value)) } ) } } struct FieldTextArea: View { private let _label: String @Binding private var value: String private let _enabled: Bool init(_ label: String, _ value: Binding<String>, enabled: Bool = true) { _label = label _value = value _enabled = enabled } var body: some View { Row( content: { FormLabel(text: _label) }, details: { // TextEditor can't change background color RoundedRectangle(cornerRadius: 4, style: .circular) .fill(Color.primary) .overlay( TextEditor(text: _value) .font(.system(.body)) .autocapitalization(.none) .disableAutocorrection(true) .opacity(0.9).disabled(!_enabled) ) .padding() .navigationTitle(_label) .navigationBarTitleDisplayMode(.inline) } ) } } struct HostView: View { @EnvironmentObject private var _nav: Nav @State private var _host: BKHosts? @State private var _conflictedICloudHost: BKHosts? = nil @State private var _alias: String = "" @State private var _hostName: String = "" @State private var _port: String = "" @State private var _user: String = "" @State private var _password: String = "" @State private var _sshKeyName: String = "" @State private var _proxyCmd: String = "" @State private var _proxyJump: String = "" @State private var _sshConfigAttachment: String = HostView.__sshConfigAttachmentExample @State private var _moshServer: String = "" @State private var _moshPort: String = "" @State private var _moshPrediction: BKMoshPrediction = BKMoshPredictionAdaptive @State private var _moshCommand: String = "" @State private var _domains: [FileProviderDomain] = [] @State private var _domainsListVersion = 0; @State private var _loaded = false @State private var _enabled: Bool = true @State private var _errorMessage: String = "" private var _iCloudVersion: Bool private var _reloadList: () -> () init(host: BKHosts?, iCloudVersion: Bool = false, reloadList: @escaping () -> ()) { _host = host _iCloudVersion = iCloudVersion _conflictedICloudHost = host?.iCloudConflictCopy _reloadList = reloadList } private func _usageHint() -> String { var alias = _alias.trimmingCharacters(in: .whitespacesAndNewlines) if alias.count < 2 { alias = "[alias]" } return "Use `mosh \(alias)` or `ssh \(alias)` from the shell to connect." } var body: some View { List { if let iCloudCopy = _conflictedICloudHost { Section( header: Label("CONFLICT DETECTED", systemImage: "exclamationmark.icloud.fill"), footer: Text("A conflict has been detected. Please choose a version to save to continue.").foregroundColor(.red) ) { Row( content: { Label("iCloud Version", systemImage: "icloud") }, details: { HostView(host: iCloudCopy, iCloudVersion: true, reloadList: _reloadList) } ) Button( action: { _saveICloudVersion() _nav.navController.popViewController(animated: true) }, label: { Label("Save iCloud Version", systemImage: "icloud.and.arrow.down") } ) Button( action: { _saveLocalVersion() _nav.navController.popViewController(animated: true) }, label: { Label("Save Local Version", systemImage: "icloud.and.arrow.up") } ) } } Section( header: Text(_conflictedICloudHost == nil ? "" : "Local Verion"), footer: Text(verbatim: _usageHint()) ) { Field("Alias", $_alias, next: "HostName", placeholder: "Required") }.disabled(!_enabled) Section(header: Text("SSH")) { Field("HostName", $_hostName, next: "Port", placeholder: "Host or IP address. Required", enabled: _enabled, kbType: .URL) Field("Port", $_port, next: "User", placeholder: "22", enabled: _enabled, kbType: .numberPad) Field("User", $_user, next: "Password", placeholder: BKDefaults.defaultUserName(), enabled: _enabled) Field("Password", $_password, next: "ProxyCmd", placeholder: "Ask Every Time", secureTextEntry: true, enabled: _enabled) FieldSSHKey(value: $_sshKeyName, enabled: _enabled) Field("ProxyCmd", $_proxyCmd, next: "ProxyJump", placeholder: "ssh -W %h:%p bastion", enabled: _enabled) Field("ProxyJump", $_proxyJump, next: "Server", placeholder: "bastion1,bastion2", enabled: _enabled) FieldTextArea("SSH Config", $_sshConfigAttachment, enabled: _enabled) } Section(header: Text("MOSH")) { Field("Server", $_moshServer, next: "moshPort", placeholder: "path/to/mosh-server") Field("Port", $_moshPort, next: "moshCommand", placeholder: "UDP PORT[:PORT2]", id: "moshPort", kbType: .numbersAndPunctuation) Field("Command", $_moshCommand, next: "Alias", placeholder: "screen -r or tmux attach", id: "moshCommand") FieldMoshPrediction(value: $_moshPrediction, enabled: _enabled) }.disabled(!_enabled) Section(header: Label("Files.app", systemImage: "folder")) { ForEach(_domains, content: { FileDomainRow(domain: $0, refreshList: _refreshDomainsList) }) .onDelete { indexSet in _domains.remove(atOffsets: indexSet) } Button( action: { let displayName = _alias.trimmingCharacters(in: .whitespacesAndNewlines) _domains.append(FileProviderDomain( id:UUID(), displayName: displayName.isEmpty ? "Location Name" : displayName, remotePath: "~", proto: "sftp" )) }, label: { Label("Add Location", systemImage: "folder.badge.plus") } ) } .id(_domainsListVersion) .disabled(!_enabled) } .listStyle(GroupedListStyle()) .alert(errorMessage: $_errorMessage) .navigationBarItems( trailing: Group { if !_iCloudVersion { Button("Save", action: { do { try _validate() } catch { _errorMessage = error.localizedDescription return } _saveHost() _reloadList() _nav.navController.popViewController(animated: true) }).disabled(_conflictedICloudHost != nil) } } ) .navigationBarTitle(_host == nil ? "New Host" : _iCloudVersion ? "iCloud Host Version" : "Host" ) .onAppear { if !_loaded { loadHost() _loaded = true } } } private static var __sshConfigAttachmentExample: String { "# Compression no" } func loadHost() { if let host = _host { _alias = host.host ?? "" _hostName = host.hostName ?? "" _port = host.port == nil ? "" : host.port.stringValue _user = host.user ?? "" _password = host.password ?? "" _sshKeyName = host.key ?? "" _proxyCmd = host.proxyCmd ?? "" _proxyJump = host.proxyJump ?? "" _sshConfigAttachment = host.sshConfigAttachment ?? "" if _sshConfigAttachment.isEmpty { _sshConfigAttachment = HostView.__sshConfigAttachmentExample } if let moshPort = host.moshPort { if let moshPortEnd = host.moshPortEnd { _moshPort = "\(moshPort):\(moshPortEnd)" } else { _moshPort = moshPort.stringValue } } _moshPrediction.rawValue = UInt32(host.prediction.intValue) _moshServer = host.moshServer ?? "" _moshCommand = host.moshStartup ?? "" _domains = FileProviderDomain.listFrom(jsonString: host.fpDomainsJSON) _enabled = !( _conflictedICloudHost != nil || _iCloudVersion) } } private func _validate() throws { let cleanAlias = _alias.trimmingCharacters(in: .whitespacesAndNewlines) if cleanAlias.isEmpty { throw FormValidationError.general( message: "Alias is required." ) } if let _ = cleanAlias.rangeOfCharacter(from: .whitespacesAndNewlines) { throw FormValidationError.general( message: "Spaces are not permitted in the alias." ) } if let _ = BKHosts.withHost(cleanAlias), cleanAlias != _host?.host { throw FormValidationError.general( message: "Cannot have two hosts with the same alias." ) } let cleanHostName = _hostName.trimmingCharacters(in: .whitespacesAndNewlines) if let _ = cleanHostName.rangeOfCharacter(from: .whitespacesAndNewlines) { throw FormValidationError.general(message: "Spaces are not permitted in the host name.") } if cleanHostName.isEmpty { throw FormValidationError.general( message: "HostName is required." ) } let cleanUser = _user.trimmingCharacters(in: .whitespacesAndNewlines) if let _ = cleanUser.rangeOfCharacter(from: .whitespacesAndNewlines) { throw FormValidationError.general(message: "Spaces are not permitted in the user name.") } } private func _saveHost() { let savedHost = BKHosts.saveHost( _host?.host.trimmingCharacters(in: .whitespacesAndNewlines), withNewHost: _alias.trimmingCharacters(in: .whitespacesAndNewlines), hostName: _hostName.trimmingCharacters(in: .whitespacesAndNewlines), sshPort: _port.trimmingCharacters(in: .whitespacesAndNewlines), user: _user.trimmingCharacters(in: .whitespacesAndNewlines), password: _password, hostKey: _sshKeyName, moshServer: _moshServer, moshPortRange: _moshPort, startUpCmd: _moshCommand, prediction: _moshPrediction, proxyCmd: _proxyCmd, proxyJump: _proxyJump, sshConfigAttachment: _sshConfigAttachment == HostView.__sshConfigAttachmentExample ? "" : _sshConfigAttachment, fpDomainsJSON: FileProviderDomain.toJson(list: _domains) ) guard let host = savedHost else { return } BKHosts.updateHost(host.host, withiCloudId: host.iCloudRecordId, andLastModifiedTime: Date()) BKiCloudSyncHandler.shared()?.check(forReachabilityAndSync: nil) #if targetEnvironment(macCatalyst) #else _NSFileProviderManager.syncWithBKHosts() #endif } private func _saveICloudVersion() { guard let host = _host, let iCloudHost = host.iCloudConflictCopy, let syncHandler = BKiCloudSyncHandler.shared() else { return } if let recordId = host.iCloudRecordId { syncHandler.deleteRecord(recordId, of: BKiCloudRecordTypeHosts) } let moshPort = iCloudHost.moshPort let moshPortEnd = iCloudHost.moshPortEnd var moshPortRange = moshPort?.stringValue ?? "" if let moshPort = moshPort, let moshPortEnd = moshPortEnd { moshPortRange = "\(moshPort):\(moshPortEnd)" } BKHosts.saveHost( host.host, withNewHost: iCloudHost.host, hostName: iCloudHost.hostName, sshPort: iCloudHost.port?.stringValue ?? "", user: iCloudHost.user, password: iCloudHost.password, hostKey: iCloudHost.key, moshServer: iCloudHost.moshServer, moshPortRange: moshPortRange, startUpCmd: iCloudHost.moshStartup, prediction: BKMoshPrediction(UInt32(iCloudHost.prediction?.intValue ?? 0)), proxyCmd: iCloudHost.proxyCmd, proxyJump: iCloudHost.proxyJump, sshConfigAttachment: iCloudHost.sshConfigAttachment, fpDomainsJSON: iCloudHost.fpDomainsJSON ) BKHosts.updateHost( iCloudHost.host, withiCloudId: iCloudHost.iCloudRecordId, andLastModifiedTime: iCloudHost.lastModifiedTime ) BKHosts.markHost(iCloudHost.host, for: BKHosts.record(fromHost: host), withConflict: false) syncHandler.check(forReachabilityAndSync: nil) _NSFileProviderManager.syncWithBKHosts() } private func _saveLocalVersion() { guard let host = _host, let syncHandler = BKiCloudSyncHandler.shared() else { return } syncHandler.deleteRecord(host.iCloudConflictCopy.iCloudRecordId, of: BKiCloudRecordTypeHosts) if (host.iCloudRecordId == nil) { BKHosts.markHost(host.iCloudConflictCopy.host, for: BKHosts.record(fromHost: host), withConflict: false) } syncHandler.check(forReachabilityAndSync: nil) } private func _refreshDomainsList() { _domainsListVersion += 1 } } enum FormValidationError: Error, LocalizedError { case general(message: String, field: String? = nil) var errorDescription: String? { switch self { case .general(message: let message, field: _): return message } } }
gpl-3.0
36e7d441244de36e9fafe0e3229ab3ca
31.632143
193
0.623399
4.529995
false
false
false
false
moonagic/MagicOcean
MagicOcean/ViewControllers/SizeTableView.swift
1
4906
// // SizeTableView.swift // MagicOcean // // Created by Wu Hengmin on 16/6/19. // Copyright © 2016年 Wu Hengmin. All rights reserved. // import UIKit import MJRefresh import Alamofire import SwiftyJSON struct SizeTeplete { var memory:Int var price:Int var disk:Int var transfer:Int var vcpus:Int var slug:String } protocol SelectSizeDelegate { func didSelectSize(size: SizeTeplete) } class SizeTableView: UITableViewController { var data:NSMutableArray = [] var sizeData:[SizeTeplete] = Array<SizeTeplete>() var delegate: SelectSizeDelegate? override func viewDidLoad() { super.viewDidLoad() setStatusBarAndNavigationBar(navigation: self.navigationController!) tableView.tableFooterView = UIView.init(frame: CGRect.zero) setupMJRefresh() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let result:NSData = UserDefaults().object(forKey: "sizes") as? NSData { self.data = NSKeyedUnarchiver.unarchiveObject(with: result as Data) as! NSMutableArray } else { self.tableView.mj_header.beginRefreshing() } } func setupMJRefresh() { let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(mjRefreshData)) header?.isAutomaticallyChangeAlpha = true; header?.lastUpdatedTimeLabel.isHidden = true; self.tableView.mj_header = header; } @objc func mjRefreshData() { self.loadSizes(page: 1, per_page: 100) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 91 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sizeData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier:String = "sizecell" let cell:SizeCell = tableView.dequeueReusableCell(withIdentifier: identifier) as! SizeCell let size = sizeData[indexPath.row] // cell.priceLabel.text = "$\(String(format: "%.2f", Float(size.price)))" cell.memoryAndCPUsLabel.text = "\(size.memory)MB / \(size.vcpus)CPUs" cell.diskLabel.text = "\(size.disk)GB SSD" cell.transferLabel.text = "Transfer \(size.transfer)TB" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let size = sizeData[indexPath.row] self.delegate?.didSelectSize(size: size) self.dismiss(animated: true) { } } @IBAction func cancellPressed(sender: AnyObject) { self.dismiss(animated: true) { } } func loadSizes(page: Int, per_page: Int) { // curl -X GET -H "Content-Type: application/json" -H "Authorization: Bearer b7d03a6947b217efb6f3ec3bd3504582" "https://api.digitalocean.com/v2/images?page=1&per_page=1" let Headers = [ "Content-Type": "application/json", "Authorization": "Bearer "+Account.sharedInstance.Access_Token ] weak var weakSelf = self Alamofire.request(BASE_URL+URL_SIZES+"?page=\(page)&per_page=\(per_page)", method: .get , parameters: nil, encoding: URLEncoding.default, headers: Headers).responseJSON { response in if let strongSelf = weakSelf { if let JSONObj = response.result.value { let dic = JSONObj as! NSDictionary let jsonString = dictionary2JsonString(dic: dic as! Dictionary<String, Any>) print(jsonString) if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) { if let json = try? JSON(data: dataFromString) { if let sizes = json["sizes"].array { for s in sizes { strongSelf.sizeData.append(SizeTeplete(memory: s["memory"].int!, price: s["price_monthly"].int!, disk: s["disk"].int!, transfer: s["transfer"].int!, vcpus: s["vcpus"].int!, slug: s["slug"].string!)) } } } } } DispatchQueue.main.async { strongSelf.tableView.reloadData() strongSelf.tableView.mj_header.endRefreshing() } } } } }
mit
5a2993aa0e9276e7b79087f923eb9f9b
34.021429
234
0.591271
4.718961
false
false
false
false
huangboju/GesturePassword
GesturePassword/Classes/Keychain.swift
1
85124
// // Keychain.swift // KeychainAccess // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Security import LocalAuthentication public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error" public enum ItemClass { case genericPassword case internetPassword } public enum Accessibility { /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will migrate to a new device when using encrypted backups. */ case whenUnlocked /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accesible by background applications. Items with this attribute will migrate to a new device when using encrypted backups. */ case afterFirstUnlock /** Item data can always be accessed regardless of the lock state of the device. This is not recommended for anything except system use. Items with this attribute will migrate to a new device when using encrypted backups. */ case always /** Item data can only be accessed while the device is unlocked. This class is only available if a passcode is set on the device. This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode will cause all items in this class to be deleted. */ case whenPasscodeSetThisDeviceOnly /** Item data can only be accessed while the device is unlocked. This is recommended for items that only need be accesible while the application is in the foreground. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. */ case whenUnlockedThisDeviceOnly /** Item data can only be accessed once the device has been unlocked after a restart. This is recommended for items that need to be accessible by background applications. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device these items will be missing. */ case afterFirstUnlockThisDeviceOnly /** Item data can always be accessed regardless of the lock state of the device. This option is not recommended for anything except system use. Items with this attribute will never migrate to a new device, so after a backup is restored to a new device, these items will be missing. */ case alwaysThisDeviceOnly } public struct AuthenticationPolicy: OptionSet { /** User presence policy using Touch ID or Passcode. Touch ID does not have to be available or enrolled. Item is still accessible by Touch ID even if fingers are added or removed. */ @available(iOS 8.0, OSX 10.10, *) public static let userPresence = AuthenticationPolicy(rawValue: 1 << 0) /** Constraint: Touch ID (any finger). Touch ID must be available and at least one finger must be enrolled. Item is still accessible by Touch ID even if fingers are added or removed. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let touchIDAny = AuthenticationPolicy(rawValue: 1 << 1) /** Constraint: Touch ID from the set of currently enrolled fingers. Touch ID must be available and at least one finger must be enrolled. When fingers are added or removed, the item is invalidated. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let touchIDCurrentSet = AuthenticationPolicy(rawValue: 1 << 3) /** Constraint: Device passcode */ @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) public static let devicePasscode = AuthenticationPolicy(rawValue: 1 << 4) /** Constraint logic operation: when using more than one constraint, at least one of them must be satisfied. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let or = AuthenticationPolicy(rawValue: 1 << 14) /** Constraint logic operation: when using more than one constraint, all must be satisfied. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let and = AuthenticationPolicy(rawValue: 1 << 15) /** Create access control for private key operations (i.e. sign operation) */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let privateKeyUsage = AuthenticationPolicy(rawValue: 1 << 30) /** Security: Application provided password for data encryption key generation. This is not a constraint but additional item encryption mechanism. */ @available(iOS 9.0, *) @available(OSX, unavailable) @available(watchOS, unavailable) public static let applicationPassword = AuthenticationPolicy(rawValue: 1 << 31) public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } } public struct Attributes { fileprivate let attributes: [String: Any] init(attributes: [String: Any]) { self.attributes = attributes } public subscript(key: String) -> Any? { get { return attributes[key] } } } public final class Keychain { fileprivate let options: Options // MARK: public convenience init() { var options = Options() if let bundleIdentifier = Bundle.main.bundleIdentifier { options.service = bundleIdentifier } self.init(options) } fileprivate init(_ opts: Options) { options = opts } // MARK: public func get(_ key: String) throws -> String? { return try getString(key) } public func getString(_ key: String) throws -> String? { guard let data = try getData(key) else { return nil } guard let string = String(data: data, encoding: .utf8) else { print("failed to convert data to string") throw Status.conversionError } return string } public func getData(_ key: String) throws -> Data? { var query = options.query() query[MatchLimit] = MatchLimitOne query[ReturnData] = kCFBooleanTrue query[AttributeAccount] = key var result: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: guard let data = result as? Data else { throw Status.unexpectedError } return data case errSecItemNotFound: return nil default: throw securityError(status: status) } } public func get<T>(_ key: String, handler: (Attributes?) -> T) throws -> T { var query = options.query() query[MatchLimit] = MatchLimitOne query[ReturnData] = kCFBooleanTrue query[ReturnAttributes] = kCFBooleanTrue query[ReturnRef] = kCFBooleanTrue query[ReturnPersistentRef] = kCFBooleanTrue query[AttributeAccount] = key var result: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) switch status { case errSecSuccess: guard let attributes = result as? [String: Any] else { throw Status.unexpectedError } return handler(Attributes(attributes: attributes)) case errSecItemNotFound: return handler(nil) default: throw securityError(status: status) } } // MARK: public func set(_ value: String, key: String) throws { guard let data = value.data(using: .utf8, allowLossyConversion: false) else { print("failed to convert string to data") throw Status.conversionError } try set(data, key: key) } public func set(_ value: Data, key: String) throws { var query = options.query() query[AttributeAccount] = key if #available(iOS 9.0, *) { query[UseAuthenticationUI] = UseAuthenticationUIFail } else { query[UseNoAuthenticationUI] = kCFBooleanTrue } var status = SecItemCopyMatching(query as CFDictionary, nil) switch status { case errSecSuccess, errSecInteractionNotAllowed: var query = options.query() query[AttributeAccount] = key var (attributes, error) = options.attributes(key: nil, value: value) if let error = error { print(error.localizedDescription) throw error } options.attributes.forEach { attributes.updateValue($1, forKey: $0) } if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) { try remove(key) try set(value, key: key) } else { status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) if status != errSecSuccess { throw securityError(status: status) } } case errSecItemNotFound: var (attributes, error) = options.attributes(key: key, value: value) if let error = error { print(error.localizedDescription) throw error } options.attributes.forEach { attributes.updateValue($1, forKey: $0) } status = SecItemAdd(attributes as CFDictionary, nil) if status != errSecSuccess { throw securityError(status: status) } default: throw securityError(status: status) } } public subscript(key: String) -> String? { get { return (((try? get(key)) as String??)).flatMap { $0 } } set { if let value = newValue { do { try set(value, key: key) } catch {} } else { do { try remove(key) } catch {} } } } public subscript(string key: String) -> String? { get { return self[key] } set { self[key] = newValue } } // MARK: public func remove(_ key: String) throws { var query = options.query() query[AttributeAccount] = key let status = SecItemDelete(query as CFDictionary) if status != errSecSuccess && status != errSecItemNotFound { throw securityError(status: status) } } // MARK: @discardableResult fileprivate class func securityError(status: OSStatus) -> Error { let error = Status(status: status) print("OSStatus error:[\(error.errorCode)] \(error.description)") return error } @discardableResult fileprivate func securityError(status: OSStatus) -> Error { return type(of: self).securityError(status: status) } } struct Options { var itemClass: ItemClass = .genericPassword var service: String = "" var accessGroup: String? = nil var server: URL! var accessibility: Accessibility = .afterFirstUnlock var authenticationPolicy: AuthenticationPolicy? var synchronizable: Bool = false var label: String? var comment: String? var authenticationPrompt: String? var authenticationContext: AnyObject? var attributes = [String: Any]() } /** Class Key Constant */ private let Class = String(kSecClass) /** Attribute Key Constants */ private let AttributeAccessible = String(kSecAttrAccessible) @available(iOS 8.0, OSX 10.10, *) private let AttributeAccessControl = String(kSecAttrAccessControl) private let AttributeAccessGroup = String(kSecAttrAccessGroup) private let AttributeSynchronizable = String(kSecAttrSynchronizable) private let AttributeComment = String(kSecAttrComment) private let AttributeLabel = String(kSecAttrLabel) private let AttributeAccount = String(kSecAttrAccount) private let AttributeService = String(kSecAttrService) private let SynchronizableAny = kSecAttrSynchronizableAny /** Search Constants */ private let MatchLimit = String(kSecMatchLimit) private let MatchLimitOne = kSecMatchLimitOne private let MatchLimitAll = kSecMatchLimitAll /** Return Type Key Constants */ private let ReturnData = String(kSecReturnData) private let ReturnAttributes = String(kSecReturnAttributes) private let ReturnRef = String(kSecReturnRef) private let ReturnPersistentRef = String(kSecReturnPersistentRef) /** Value Type Key Constants */ private let ValueData = String(kSecValueData) private let ValueRef = String(kSecValueRef) private let ValuePersistentRef = String(kSecValuePersistentRef) /** Other Constants */ @available(iOS 8.0, OSX 10.10, *) private let UseOperationPrompt = String(kSecUseOperationPrompt) #if os(iOS) @available(iOS, introduced: 8.0, deprecated: 9.0, message: "Use a UseAuthenticationUI instead.") private let UseNoAuthenticationUI = String(kSecUseNoAuthenticationUI) #endif @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUI = String(kSecUseAuthenticationUI) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationContext = String(kSecUseAuthenticationContext) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUIAllow = String(kSecUseAuthenticationUIAllow) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUIFail = String(kSecUseAuthenticationUIFail) @available(iOS 9.0, OSX 10.11, *) @available(watchOS, unavailable) private let UseAuthenticationUISkip = String(kSecUseAuthenticationUISkip) /** Credential Key Constants */ private let SharedPassword = String(kSecSharedPassword) extension Options { func query() -> [String: Any] { var query = [String: Any]() query[Class] = itemClass.rawValue query[AttributeSynchronizable] = SynchronizableAny switch itemClass { case .genericPassword: query[AttributeService] = service // Access group is not supported on any simulators. #if (!arch(i386) && !arch(x86_64)) || (!os(iOS) && !os(watchOS) && !os(tvOS)) if let accessGroup = self.accessGroup { query[AttributeAccessGroup] = accessGroup } #endif default: fatalError("错误啦") } if #available(OSX 10.10, *) { if authenticationPrompt != nil { query[UseOperationPrompt] = authenticationPrompt } } if #available(iOS 9.0, OSX 10.11, *) { if authenticationContext != nil { query[UseAuthenticationContext] = authenticationContext } } return query } func attributes(key: String?, value: Data) -> ([String: Any], Error?) { var attributes: [String: Any] if key != nil { attributes = query() attributes[AttributeAccount] = key } else { attributes = [String: Any]() } attributes[ValueData] = value if label != nil { attributes[AttributeLabel] = label } if comment != nil { attributes[AttributeComment] = comment } if let policy = authenticationPolicy { if #available(OSX 10.10, *) { var error: Unmanaged<CFError>? guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue as CFTypeRef, SecAccessControlCreateFlags(rawValue: CFOptionFlags(policy.rawValue)), &error) else { if let error = error?.takeUnretainedValue() { return (attributes, error.error) } return (attributes, Status.unexpectedError) } attributes[AttributeAccessControl] = accessControl } else { print("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.") } } else { attributes[AttributeAccessible] = accessibility.rawValue } attributes[AttributeSynchronizable] = synchronizable ? kCFBooleanTrue : kCFBooleanFalse return (attributes, nil) } } // MARK: extension Attributes: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "\(attributes)" } public var debugDescription: String { return description } } extension ItemClass: RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { switch rawValue { case String(kSecClassGenericPassword): self = .genericPassword case String(kSecClassInternetPassword): self = .internetPassword default: return nil } } public var rawValue: String { switch self { case .genericPassword: return String(kSecClassGenericPassword) case .internetPassword: return String(kSecClassInternetPassword) } } public var description: String { switch self { case .genericPassword: return "GenericPassword" case .internetPassword: return "InternetPassword" } } } extension Accessibility: RawRepresentable, CustomStringConvertible { public init?(rawValue: String) { if #available(OSX 10.10, *) { switch rawValue { case String(kSecAttrAccessibleWhenUnlocked): self = .whenUnlocked case String(kSecAttrAccessibleAfterFirstUnlock): self = .afterFirstUnlock case String(kSecAttrAccessibleAlways): self = .always case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly): self = .whenPasscodeSetThisDeviceOnly case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): self = .whenUnlockedThisDeviceOnly case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): self = .afterFirstUnlockThisDeviceOnly case String(kSecAttrAccessibleAlwaysThisDeviceOnly): self = .alwaysThisDeviceOnly default: return nil } } else { switch rawValue { case String(kSecAttrAccessibleWhenUnlocked): self = .whenUnlocked case String(kSecAttrAccessibleAfterFirstUnlock): self = .afterFirstUnlock case String(kSecAttrAccessibleAlways): self = .always case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly): self = .whenUnlockedThisDeviceOnly case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly): self = .afterFirstUnlockThisDeviceOnly case String(kSecAttrAccessibleAlwaysThisDeviceOnly): self = .alwaysThisDeviceOnly default: return nil } } } public var rawValue: String { switch self { case .whenUnlocked: return String(kSecAttrAccessibleWhenUnlocked) case .afterFirstUnlock: return String(kSecAttrAccessibleAfterFirstUnlock) case .always: return String(kSecAttrAccessibleAlways) case .whenPasscodeSetThisDeviceOnly: if #available(OSX 10.10, *) { return String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly) } else { fatalError("'Accessibility.WhenPasscodeSetThisDeviceOnly' is not available on this version of OS.") } case .whenUnlockedThisDeviceOnly: return String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly) case .afterFirstUnlockThisDeviceOnly: return String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) case .alwaysThisDeviceOnly: return String(kSecAttrAccessibleAlwaysThisDeviceOnly) } } public var description: String { switch self { case .whenUnlocked: return "WhenUnlocked" case .afterFirstUnlock: return "AfterFirstUnlock" case .always: return "Always" case .whenPasscodeSetThisDeviceOnly: return "WhenPasscodeSetThisDeviceOnly" case .whenUnlockedThisDeviceOnly: return "WhenUnlockedThisDeviceOnly" case .afterFirstUnlockThisDeviceOnly: return "AfterFirstUnlockThisDeviceOnly" case .alwaysThisDeviceOnly: return "AlwaysThisDeviceOnly" } } } extension CFError { var error: NSError { let domain = CFErrorGetDomain(self) as String let code = CFErrorGetCode(self) let userInfo = CFErrorCopyUserInfo(self) as! [String: Any] return NSError(domain: domain, code: code, userInfo: userInfo) } } public enum Status: OSStatus, Error { case success = 0 case unimplemented = -4 case diskFull = -34 case io = -36 case opWr = -49 case param = -50 case wrPerm = -61 case allocate = -108 case userCanceled = -128 case badReq = -909 case internalComponent = -2070 case notAvailable = -25291 case readOnly = -25292 case authFailed = -25293 case noSuchKeychain = -25294 case invalidKeychain = -25295 case duplicateKeychain = -25296 case duplicateCallback = -25297 case invalidCallback = -25298 case duplicateItem = -25299 case itemNotFound = -25300 case bufferTooSmall = -25301 case dataTooLarge = -25302 case noSuchAttr = -25303 case invalidItemRef = -25304 case invalidSearchRef = -25305 case noSuchClass = -25306 case noDefaultKeychain = -25307 case interactionNotAllowed = -25308 case readOnlyAttr = -25309 case wrongSecVersion = -25310 case keySizeNotAllowed = -25311 case noStorageModule = -25312 case noCertificateModule = -25313 case noPolicyModule = -25314 case interactionRequired = -25315 case dataNotAvailable = -25316 case dataNotModifiable = -25317 case createChainFailed = -25318 case invalidPrefsDomain = -25319 case inDarkWake = -25320 case aclNotSimple = -25240 case policyNotFound = -25241 case invalidTrustSetting = -25242 case noAccessForItem = -25243 case invalidOwnerEdit = -25244 case trustNotAvailable = -25245 case unsupportedFormat = -25256 case unknownFormat = -25257 case keyIsSensitive = -25258 case multiplePrivKeys = -25259 case passphraseRequired = -25260 case invalidPasswordRef = -25261 case invalidTrustSettings = -25262 case noTrustSettings = -25263 case pkcs12VerifyFailure = -25264 case invalidCertificate = -26265 case notSigner = -26267 case policyDenied = -26270 case invalidKey = -26274 case decode = -26275 case `internal` = -26276 case unsupportedAlgorithm = -26268 case unsupportedOperation = -26271 case unsupportedPadding = -26273 case itemInvalidKey = -34000 case itemInvalidKeyType = -34001 case itemInvalidValue = -34002 case itemClassMissing = -34003 case itemMatchUnsupported = -34004 case useItemListUnsupported = -34005 case useKeychainUnsupported = -34006 case useKeychainListUnsupported = -34007 case returnDataUnsupported = -34008 case returnAttributesUnsupported = -34009 case returnRefUnsupported = -34010 case returnPersitentRefUnsupported = -34011 case valueRefUnsupported = -34012 case valuePersistentRefUnsupported = -34013 case returnMissingPointer = -34014 case matchLimitUnsupported = -34015 case itemIllegalQuery = -34016 case waitForCallback = -34017 case missingEntitlement = -34018 case upgradePending = -34019 case mpSignatureInvalid = -25327 case otrTooOld = -25328 case otrIDTooNew = -25329 case serviceNotAvailable = -67585 case insufficientClientID = -67586 case deviceReset = -67587 case deviceFailed = -67588 case appleAddAppACLSubject = -67589 case applePublicKeyIncomplete = -67590 case appleSignatureMismatch = -67591 case appleInvalidKeyStartDate = -67592 case appleInvalidKeyEndDate = -67593 case conversionError = -67594 case appleSSLv2Rollback = -67595 case quotaExceeded = -67596 case fileTooBig = -67597 case invalidDatabaseBlob = -67598 case invalidKeyBlob = -67599 case incompatibleDatabaseBlob = -67600 case incompatibleKeyBlob = -67601 case hostNameMismatch = -67602 case unknownCriticalExtensionFlag = -67603 case noBasicConstraints = -67604 case noBasicConstraintsCA = -67605 case invalidAuthorityKeyID = -67606 case invalidSubjectKeyID = -67607 case invalidKeyUsageForPolicy = -67608 case invalidExtendedKeyUsage = -67609 case invalidIDLinkage = -67610 case pathLengthConstraintExceeded = -67611 case invalidRoot = -67612 case crlExpired = -67613 case crlNotValidYet = -67614 case crlNotFound = -67615 case crlServerDown = -67616 case crlBadURI = -67617 case unknownCertExtension = -67618 case unknownCRLExtension = -67619 case crlNotTrusted = -67620 case crlPolicyFailed = -67621 case idpFailure = -67622 case smimeEmailAddressesNotFound = -67623 case smimeBadExtendedKeyUsage = -67624 case smimeBadKeyUsage = -67625 case smimeKeyUsageNotCritical = -67626 case smimeNoEmailAddress = -67627 case smimeSubjAltNameNotCritical = -67628 case sslBadExtendedKeyUsage = -67629 case ocspBadResponse = -67630 case ocspBadRequest = -67631 case ocspUnavailable = -67632 case ocspStatusUnrecognized = -67633 case endOfData = -67634 case incompleteCertRevocationCheck = -67635 case networkFailure = -67636 case ocspNotTrustedToAnchor = -67637 case recordModified = -67638 case ocspSignatureError = -67639 case ocspNoSigner = -67640 case ocspResponderMalformedReq = -67641 case ocspResponderInternalError = -67642 case ocspResponderTryLater = -67643 case ocspResponderSignatureRequired = -67644 case ocspResponderUnauthorized = -67645 case ocspResponseNonceMismatch = -67646 case codeSigningBadCertChainLength = -67647 case codeSigningNoBasicConstraints = -67648 case codeSigningBadPathLengthConstraint = -67649 case codeSigningNoExtendedKeyUsage = -67650 case codeSigningDevelopment = -67651 case resourceSignBadCertChainLength = -67652 case resourceSignBadExtKeyUsage = -67653 case trustSettingDeny = -67654 case invalidSubjectName = -67655 case unknownQualifiedCertStatement = -67656 case mobileMeRequestQueued = -67657 case mobileMeRequestRedirected = -67658 case mobileMeServerError = -67659 case mobileMeServerNotAvailable = -67660 case mobileMeServerAlreadyExists = -67661 case mobileMeServerServiceErr = -67662 case mobileMeRequestAlreadyPending = -67663 case mobileMeNoRequestPending = -67664 case mobileMeCSRVerifyFailure = -67665 case mobileMeFailedConsistencyCheck = -67666 case notInitialized = -67667 case invalidHandleUsage = -67668 case pvcReferentNotFound = -67669 case functionIntegrityFail = -67670 case internalError = -67671 case memoryError = -67672 case invalidData = -67673 case mdsError = -67674 case invalidPointer = -67675 case selfCheckFailed = -67676 case functionFailed = -67677 case moduleManifestVerifyFailed = -67678 case invalidGUID = -67679 case invalidHandle = -67680 case invalidDBList = -67681 case invalidPassthroughID = -67682 case invalidNetworkAddress = -67683 case crlAlreadySigned = -67684 case invalidNumberOfFields = -67685 case verificationFailure = -67686 case unknownTag = -67687 case invalidSignature = -67688 case invalidName = -67689 case invalidCertificateRef = -67690 case invalidCertificateGroup = -67691 case tagNotFound = -67692 case invalidQuery = -67693 case invalidValue = -67694 case callbackFailed = -67695 case aclDeleteFailed = -67696 case aclReplaceFailed = -67697 case aclAddFailed = -67698 case aclChangeFailed = -67699 case invalidAccessCredentials = -67700 case invalidRecord = -67701 case invalidACL = -67702 case invalidSampleValue = -67703 case incompatibleVersion = -67704 case privilegeNotGranted = -67705 case invalidScope = -67706 case pvcAlreadyConfigured = -67707 case invalidPVC = -67708 case emmLoadFailed = -67709 case emmUnloadFailed = -67710 case addinLoadFailed = -67711 case invalidKeyRef = -67712 case invalidKeyHierarchy = -67713 case addinUnloadFailed = -67714 case libraryReferenceNotFound = -67715 case invalidAddinFunctionTable = -67716 case invalidServiceMask = -67717 case moduleNotLoaded = -67718 case invalidSubServiceID = -67719 case attributeNotInContext = -67720 case moduleManagerInitializeFailed = -67721 case moduleManagerNotFound = -67722 case eventNotificationCallbackNotFound = -67723 case inputLengthError = -67724 case outputLengthError = -67725 case privilegeNotSupported = -67726 case deviceError = -67727 case attachHandleBusy = -67728 case notLoggedIn = -67729 case algorithmMismatch = -67730 case keyUsageIncorrect = -67731 case keyBlobTypeIncorrect = -67732 case keyHeaderInconsistent = -67733 case unsupportedKeyFormat = -67734 case unsupportedKeySize = -67735 case invalidKeyUsageMask = -67736 case unsupportedKeyUsageMask = -67737 case invalidKeyAttributeMask = -67738 case unsupportedKeyAttributeMask = -67739 case invalidKeyLabel = -67740 case unsupportedKeyLabel = -67741 case invalidKeyFormat = -67742 case unsupportedVectorOfBuffers = -67743 case invalidInputVector = -67744 case invalidOutputVector = -67745 case invalidContext = -67746 case invalidAlgorithm = -67747 case invalidAttributeKey = -67748 case missingAttributeKey = -67749 case invalidAttributeInitVector = -67750 case missingAttributeInitVector = -67751 case invalidAttributeSalt = -67752 case missingAttributeSalt = -67753 case invalidAttributePadding = -67754 case missingAttributePadding = -67755 case invalidAttributeRandom = -67756 case missingAttributeRandom = -67757 case invalidAttributeSeed = -67758 case missingAttributeSeed = -67759 case invalidAttributePassphrase = -67760 case missingAttributePassphrase = -67761 case invalidAttributeKeyLength = -67762 case missingAttributeKeyLength = -67763 case invalidAttributeBlockSize = -67764 case missingAttributeBlockSize = -67765 case invalidAttributeOutputSize = -67766 case missingAttributeOutputSize = -67767 case invalidAttributeRounds = -67768 case missingAttributeRounds = -67769 case invalidAlgorithmParms = -67770 case missingAlgorithmParms = -67771 case invalidAttributeLabel = -67772 case missingAttributeLabel = -67773 case invalidAttributeKeyType = -67774 case missingAttributeKeyType = -67775 case invalidAttributeMode = -67776 case missingAttributeMode = -67777 case invalidAttributeEffectiveBits = -67778 case missingAttributeEffectiveBits = -67779 case invalidAttributeStartDate = -67780 case missingAttributeStartDate = -67781 case invalidAttributeEndDate = -67782 case missingAttributeEndDate = -67783 case invalidAttributeVersion = -67784 case missingAttributeVersion = -67785 case invalidAttributePrime = -67786 case missingAttributePrime = -67787 case invalidAttributeBase = -67788 case missingAttributeBase = -67789 case invalidAttributeSubprime = -67790 case missingAttributeSubprime = -67791 case invalidAttributeIterationCount = -67792 case missingAttributeIterationCount = -67793 case invalidAttributeDLDBHandle = -67794 case missingAttributeDLDBHandle = -67795 case invalidAttributeAccessCredentials = -67796 case missingAttributeAccessCredentials = -67797 case invalidAttributePublicKeyFormat = -67798 case missingAttributePublicKeyFormat = -67799 case invalidAttributePrivateKeyFormat = -67800 case missingAttributePrivateKeyFormat = -67801 case invalidAttributeSymmetricKeyFormat = -67802 case missingAttributeSymmetricKeyFormat = -67803 case invalidAttributeWrappedKeyFormat = -67804 case missingAttributeWrappedKeyFormat = -67805 case stagedOperationInProgress = -67806 case stagedOperationNotStarted = -67807 case verifyFailed = -67808 case querySizeUnknown = -67809 case blockSizeMismatch = -67810 case publicKeyInconsistent = -67811 case deviceVerifyFailed = -67812 case invalidLoginName = -67813 case alreadyLoggedIn = -67814 case invalidDigestAlgorithm = -67815 case invalidCRLGroup = -67816 case certificateCannotOperate = -67817 case certificateExpired = -67818 case certificateNotValidYet = -67819 case certificateRevoked = -67820 case certificateSuspended = -67821 case insufficientCredentials = -67822 case invalidAction = -67823 case invalidAuthority = -67824 case verifyActionFailed = -67825 case invalidCertAuthority = -67826 case invaldCRLAuthority = -67827 case invalidCRLEncoding = -67828 case invalidCRLType = -67829 case invalidCRL = -67830 case invalidFormType = -67831 case invalidID = -67832 case invalidIdentifier = -67833 case invalidIndex = -67834 case invalidPolicyIdentifiers = -67835 case invalidTimeString = -67836 case invalidReason = -67837 case invalidRequestInputs = -67838 case invalidResponseVector = -67839 case invalidStopOnPolicy = -67840 case invalidTuple = -67841 case multipleValuesUnsupported = -67842 case notTrusted = -67843 case noDefaultAuthority = -67844 case rejectedForm = -67845 case requestLost = -67846 case requestRejected = -67847 case unsupportedAddressType = -67848 case unsupportedService = -67849 case invalidTupleGroup = -67850 case invalidBaseACLs = -67851 case invalidTupleCredendtials = -67852 case invalidEncoding = -67853 case invalidValidityPeriod = -67854 case invalidRequestor = -67855 case requestDescriptor = -67856 case invalidBundleInfo = -67857 case invalidCRLIndex = -67858 case noFieldValues = -67859 case unsupportedFieldFormat = -67860 case unsupportedIndexInfo = -67861 case unsupportedLocality = -67862 case unsupportedNumAttributes = -67863 case unsupportedNumIndexes = -67864 case unsupportedNumRecordTypes = -67865 case fieldSpecifiedMultiple = -67866 case incompatibleFieldFormat = -67867 case invalidParsingModule = -67868 case databaseLocked = -67869 case datastoreIsOpen = -67870 case missingValue = -67871 case unsupportedQueryLimits = -67872 case unsupportedNumSelectionPreds = -67873 case unsupportedOperator = -67874 case invalidDBLocation = -67875 case invalidAccessRequest = -67876 case invalidIndexInfo = -67877 case invalidNewOwner = -67878 case invalidModifyMode = -67879 case missingRequiredExtension = -67880 case extendedKeyUsageNotCritical = -67881 case timestampMissing = -67882 case timestampInvalid = -67883 case timestampNotTrusted = -67884 case timestampServiceNotAvailable = -67885 case timestampBadAlg = -67886 case timestampBadRequest = -67887 case timestampBadDataFormat = -67888 case timestampTimeNotAvailable = -67889 case timestampUnacceptedPolicy = -67890 case timestampUnacceptedExtension = -67891 case timestampAddInfoNotAvailable = -67892 case timestampSystemFailure = -67893 case signingTimeMissing = -67894 case timestampRejection = -67895 case timestampWaiting = -67896 case timestampRevocationWarning = -67897 case timestampRevocationNotification = -67898 case unexpectedError = -99999 } extension Status: RawRepresentable, CustomStringConvertible { public init(status: OSStatus) { if let mappedStatus = Status(rawValue: status) { self = mappedStatus } else { self = .unexpectedError } } public var description: String { switch self { case .success: return "No error." case .unimplemented: return "Function or operation not implemented." case .diskFull: return "The disk is full." case .io: return "I/O error (bummers)" case .opWr: return "file already open with with write permission" case .param: return "One or more parameters passed to a function were not valid." case .wrPerm: return "write permissions error" case .allocate: return "Failed to allocate memory." case .userCanceled: return "User canceled the operation." case .badReq: return "Bad parameter or invalid state for operation." case .internalComponent: return "" case .notAvailable: return "No keychain is available. You may need to restart your computer." case .readOnly: return "This keychain cannot be modified." case .authFailed: return "The user name or passphrase you entered is not correct." case .noSuchKeychain: return "The specified keychain could not be found." case .invalidKeychain: return "The specified keychain is not a valid keychain file." case .duplicateKeychain: return "A keychain with the same name already exists." case .duplicateCallback: return "The specified callback function is already installed." case .invalidCallback: return "The specified callback function is not valid." case .duplicateItem: return "The specified item already exists in the keychain." case .itemNotFound: return "The specified item could not be found in the keychain." case .bufferTooSmall: return "There is not enough memory available to use the specified item." case .dataTooLarge: return "This item contains information which is too large or in a format that cannot be displayed." case .noSuchAttr: return "The specified attribute does not exist." case .invalidItemRef: return "The specified item is no longer valid. It may have been deleted from the keychain." case .invalidSearchRef: return "Unable to search the current keychain." case .noSuchClass: return "The specified item does not appear to be a valid keychain item." case .noDefaultKeychain: return "A default keychain could not be found." case .interactionNotAllowed: return "User interaction is not allowed." case .readOnlyAttr: return "The specified attribute could not be modified." case .wrongSecVersion: return "This keychain was created by a different version of the system software and cannot be opened." case .keySizeNotAllowed: return "This item specifies a key size which is too large." case .noStorageModule: return "A required component (data storage module) could not be loaded. You may need to restart your computer." case .noCertificateModule: return "A required component (certificate module) could not be loaded. You may need to restart your computer." case .noPolicyModule: return "A required component (policy module) could not be loaded. You may need to restart your computer." case .interactionRequired: return "User interaction is required, but is currently not allowed." case .dataNotAvailable: return "The contents of this item cannot be retrieved." case .dataNotModifiable: return "The contents of this item cannot be modified." case .createChainFailed: return "One or more certificates required to validate this certificate cannot be found." case .invalidPrefsDomain: return "The specified preferences domain is not valid." case .inDarkWake: return "In dark wake, no UI possible" case .aclNotSimple: return "The specified access control list is not in standard (simple) form." case .policyNotFound: return "The specified policy cannot be found." case .invalidTrustSetting: return "The specified trust setting is invalid." case .noAccessForItem: return "The specified item has no access control." case .invalidOwnerEdit: return "Invalid attempt to change the owner of this item." case .trustNotAvailable: return "No trust results are available." case .unsupportedFormat: return "Import/Export format unsupported." case .unknownFormat: return "Unknown format in import." case .keyIsSensitive: return "Key material must be wrapped for export." case .multiplePrivKeys: return "An attempt was made to import multiple private keys." case .passphraseRequired: return "Passphrase is required for import/export." case .invalidPasswordRef: return "The password reference was invalid." case .invalidTrustSettings: return "The Trust Settings Record was corrupted." case .noTrustSettings: return "No Trust Settings were found." case .pkcs12VerifyFailure: return "MAC verification failed during PKCS12 import (wrong password?)" case .invalidCertificate: return "This certificate could not be decoded." case .notSigner: return "A certificate was not signed by its proposed parent." case .policyDenied: return "The certificate chain was not trusted due to a policy not accepting it." case .invalidKey: return "The provided key material was not valid." case .decode: return "Unable to decode the provided data." case .`internal`: return "An internal error occurred in the Security framework." case .unsupportedAlgorithm: return "An unsupported algorithm was encountered." case .unsupportedOperation: return "The operation you requested is not supported by this key." case .unsupportedPadding: return "The padding you requested is not supported." case .itemInvalidKey: return "A string key in dictionary is not one of the supported keys." case .itemInvalidKeyType: return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef." case .itemInvalidValue: return "A value in a dictionary is an invalid (or unsupported) CF type." case .itemClassMissing: return "No kSecItemClass key was specified in a dictionary." case .itemMatchUnsupported: return "The caller passed one or more kSecMatch keys to a function which does not support matches." case .useItemListUnsupported: return "The caller passed in a kSecUseItemList key to a function which does not support it." case .useKeychainUnsupported: return "The caller passed in a kSecUseKeychain key to a function which does not support it." case .useKeychainListUnsupported: return "The caller passed in a kSecUseKeychainList key to a function which does not support it." case .returnDataUnsupported: return "The caller passed in a kSecReturnData key to a function which does not support it." case .returnAttributesUnsupported: return "The caller passed in a kSecReturnAttributes key to a function which does not support it." case .returnRefUnsupported: return "The caller passed in a kSecReturnRef key to a function which does not support it." case .returnPersitentRefUnsupported: return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it." case .valueRefUnsupported: return "The caller passed in a kSecValueRef key to a function which does not support it." case .valuePersistentRefUnsupported: return "The caller passed in a kSecValuePersistentRef key to a function which does not support it." case .returnMissingPointer: return "The caller passed asked for something to be returned but did not pass in a result pointer." case .matchLimitUnsupported: return "The caller passed in a kSecMatchLimit key to a call which does not support limits." case .itemIllegalQuery: return "The caller passed in a query which contained too many keys." case .waitForCallback: return "This operation is incomplete, until the callback is invoked (not an error)." case .missingEntitlement: return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." case .upgradePending: return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command." case .mpSignatureInvalid: return "Signature invalid on MP message" case .otrTooOld: return "Message is too old to use" case .otrIDTooNew: return "Key ID is too new to use! Message from the future?" case .serviceNotAvailable: return "The required service is not available." case .insufficientClientID: return "The client ID is not correct." case .deviceReset: return "A device reset has occurred." case .deviceFailed: return "A device failure has occurred." case .appleAddAppACLSubject: return "Adding an application ACL subject failed." case .applePublicKeyIncomplete: return "The public key is incomplete." case .appleSignatureMismatch: return "A signature mismatch has occurred." case .appleInvalidKeyStartDate: return "The specified key has an invalid start date." case .appleInvalidKeyEndDate: return "The specified key has an invalid end date." case .conversionError: return "A conversion error has occurred." case .appleSSLv2Rollback: return "A SSLv2 rollback error has occurred." case .quotaExceeded: return "The quota was exceeded." case .fileTooBig: return "The file is too big." case .invalidDatabaseBlob: return "The specified database has an invalid blob." case .invalidKeyBlob: return "The specified database has an invalid key blob." case .incompatibleDatabaseBlob: return "The specified database has an incompatible blob." case .incompatibleKeyBlob: return "The specified database has an incompatible key blob." case .hostNameMismatch: return "A host name mismatch has occurred." case .unknownCriticalExtensionFlag: return "There is an unknown critical extension flag." case .noBasicConstraints: return "No basic constraints were found." case .noBasicConstraintsCA: return "No basic CA constraints were found." case .invalidAuthorityKeyID: return "The authority key ID is not valid." case .invalidSubjectKeyID: return "The subject key ID is not valid." case .invalidKeyUsageForPolicy: return "The key usage is not valid for the specified policy." case .invalidExtendedKeyUsage: return "The extended key usage is not valid." case .invalidIDLinkage: return "The ID linkage is not valid." case .pathLengthConstraintExceeded: return "The path length constraint was exceeded." case .invalidRoot: return "The root or anchor certificate is not valid." case .crlExpired: return "The CRL has expired." case .crlNotValidYet: return "The CRL is not yet valid." case .crlNotFound: return "The CRL was not found." case .crlServerDown: return "The CRL server is down." case .crlBadURI: return "The CRL has a bad Uniform Resource Identifier." case .unknownCertExtension: return "An unknown certificate extension was encountered." case .unknownCRLExtension: return "An unknown CRL extension was encountered." case .crlNotTrusted: return "The CRL is not trusted." case .crlPolicyFailed: return "The CRL policy failed." case .idpFailure: return "The issuing distribution point was not valid." case .smimeEmailAddressesNotFound: return "An email address mismatch was encountered." case .smimeBadExtendedKeyUsage: return "The appropriate extended key usage for SMIME was not found." case .smimeBadKeyUsage: return "The key usage is not compatible with SMIME." case .smimeKeyUsageNotCritical: return "The key usage extension is not marked as critical." case .smimeNoEmailAddress: return "No email address was found in the certificate." case .smimeSubjAltNameNotCritical: return "The subject alternative name extension is not marked as critical." case .sslBadExtendedKeyUsage: return "The appropriate extended key usage for SSL was not found." case .ocspBadResponse: return "The OCSP response was incorrect or could not be parsed." case .ocspBadRequest: return "The OCSP request was incorrect or could not be parsed." case .ocspUnavailable: return "OCSP service is unavailable." case .ocspStatusUnrecognized: return "The OCSP server did not recognize this certificate." case .endOfData: return "An end-of-data was detected." case .incompleteCertRevocationCheck: return "An incomplete certificate revocation check occurred." case .networkFailure: return "A network failure occurred." case .ocspNotTrustedToAnchor: return "The OCSP response was not trusted to a root or anchor certificate." case .recordModified: return "The record was modified." case .ocspSignatureError: return "The OCSP response had an invalid signature." case .ocspNoSigner: return "The OCSP response had no signer." case .ocspResponderMalformedReq: return "The OCSP responder was given a malformed request." case .ocspResponderInternalError: return "The OCSP responder encountered an internal error." case .ocspResponderTryLater: return "The OCSP responder is busy, try again later." case .ocspResponderSignatureRequired: return "The OCSP responder requires a signature." case .ocspResponderUnauthorized: return "The OCSP responder rejected this request as unauthorized." case .ocspResponseNonceMismatch: return "The OCSP response nonce did not match the request." case .codeSigningBadCertChainLength: return "Code signing encountered an incorrect certificate chain length." case .codeSigningNoBasicConstraints: return "Code signing found no basic constraints." case .codeSigningBadPathLengthConstraint: return "Code signing encountered an incorrect path length constraint." case .codeSigningNoExtendedKeyUsage: return "Code signing found no extended key usage." case .codeSigningDevelopment: return "Code signing indicated use of a development-only certificate." case .resourceSignBadCertChainLength: return "Resource signing has encountered an incorrect certificate chain length." case .resourceSignBadExtKeyUsage: return "Resource signing has encountered an error in the extended key usage." case .trustSettingDeny: return "The trust setting for this policy was set to Deny." case .invalidSubjectName: return "An invalid certificate subject name was encountered." case .unknownQualifiedCertStatement: return "An unknown qualified certificate statement was encountered." case .mobileMeRequestQueued: return "The MobileMe request will be sent during the next connection." case .mobileMeRequestRedirected: return "The MobileMe request was redirected." case .mobileMeServerError: return "A MobileMe server error occurred." case .mobileMeServerNotAvailable: return "The MobileMe server is not available." case .mobileMeServerAlreadyExists: return "The MobileMe server reported that the item already exists." case .mobileMeServerServiceErr: return "A MobileMe service error has occurred." case .mobileMeRequestAlreadyPending: return "A MobileMe request is already pending." case .mobileMeNoRequestPending: return "MobileMe has no request pending." case .mobileMeCSRVerifyFailure: return "A MobileMe CSR verification failure has occurred." case .mobileMeFailedConsistencyCheck: return "MobileMe has found a failed consistency check." case .notInitialized: return "A function was called without initializing CSSM." case .invalidHandleUsage: return "The CSSM handle does not match with the service type." case .pvcReferentNotFound: return "A reference to the calling module was not found in the list of authorized callers." case .functionIntegrityFail: return "A function address was not within the verified module." case .internalError: return "An internal error has occurred." case .memoryError: return "A memory error has occurred." case .invalidData: return "Invalid data was encountered." case .mdsError: return "A Module Directory Service error has occurred." case .invalidPointer: return "An invalid pointer was encountered." case .selfCheckFailed: return "Self-check has failed." case .functionFailed: return "A function has failed." case .moduleManifestVerifyFailed: return "A module manifest verification failure has occurred." case .invalidGUID: return "An invalid GUID was encountered." case .invalidHandle: return "An invalid handle was encountered." case .invalidDBList: return "An invalid DB list was encountered." case .invalidPassthroughID: return "An invalid passthrough ID was encountered." case .invalidNetworkAddress: return "An invalid network address was encountered." case .crlAlreadySigned: return "The certificate revocation list is already signed." case .invalidNumberOfFields: return "An invalid number of fields were encountered." case .verificationFailure: return "A verification failure occurred." case .unknownTag: return "An unknown tag was encountered." case .invalidSignature: return "An invalid signature was encountered." case .invalidName: return "An invalid name was encountered." case .invalidCertificateRef: return "An invalid certificate reference was encountered." case .invalidCertificateGroup: return "An invalid certificate group was encountered." case .tagNotFound: return "The specified tag was not found." case .invalidQuery: return "The specified query was not valid." case .invalidValue: return "An invalid value was detected." case .callbackFailed: return "A callback has failed." case .aclDeleteFailed: return "An ACL delete operation has failed." case .aclReplaceFailed: return "An ACL replace operation has failed." case .aclAddFailed: return "An ACL add operation has failed." case .aclChangeFailed: return "An ACL change operation has failed." case .invalidAccessCredentials: return "Invalid access credentials were encountered." case .invalidRecord: return "An invalid record was encountered." case .invalidACL: return "An invalid ACL was encountered." case .invalidSampleValue: return "An invalid sample value was encountered." case .incompatibleVersion: return "An incompatible version was encountered." case .privilegeNotGranted: return "The privilege was not granted." case .invalidScope: return "An invalid scope was encountered." case .pvcAlreadyConfigured: return "The PVC is already configured." case .invalidPVC: return "An invalid PVC was encountered." case .emmLoadFailed: return "The EMM load has failed." case .emmUnloadFailed: return "The EMM unload has failed." case .addinLoadFailed: return "The add-in load operation has failed." case .invalidKeyRef: return "An invalid key was encountered." case .invalidKeyHierarchy: return "An invalid key hierarchy was encountered." case .addinUnloadFailed: return "The add-in unload operation has failed." case .libraryReferenceNotFound: return "A library reference was not found." case .invalidAddinFunctionTable: return "An invalid add-in function table was encountered." case .invalidServiceMask: return "An invalid service mask was encountered." case .moduleNotLoaded: return "A module was not loaded." case .invalidSubServiceID: return "An invalid subservice ID was encountered." case .attributeNotInContext: return "An attribute was not in the context." case .moduleManagerInitializeFailed: return "A module failed to initialize." case .moduleManagerNotFound: return "A module was not found." case .eventNotificationCallbackNotFound: return "An event notification callback was not found." case .inputLengthError: return "An input length error was encountered." case .outputLengthError: return "An output length error was encountered." case .privilegeNotSupported: return "The privilege is not supported." case .deviceError: return "A device error was encountered." case .attachHandleBusy: return "The CSP handle was busy." case .notLoggedIn: return "You are not logged in." case .algorithmMismatch: return "An algorithm mismatch was encountered." case .keyUsageIncorrect: return "The key usage is incorrect." case .keyBlobTypeIncorrect: return "The key blob type is incorrect." case .keyHeaderInconsistent: return "The key header is inconsistent." case .unsupportedKeyFormat: return "The key header format is not supported." case .unsupportedKeySize: return "The key size is not supported." case .invalidKeyUsageMask: return "The key usage mask is not valid." case .unsupportedKeyUsageMask: return "The key usage mask is not supported." case .invalidKeyAttributeMask: return "The key attribute mask is not valid." case .unsupportedKeyAttributeMask: return "The key attribute mask is not supported." case .invalidKeyLabel: return "The key label is not valid." case .unsupportedKeyLabel: return "The key label is not supported." case .invalidKeyFormat: return "The key format is not valid." case .unsupportedVectorOfBuffers: return "The vector of buffers is not supported." case .invalidInputVector: return "The input vector is not valid." case .invalidOutputVector: return "The output vector is not valid." case .invalidContext: return "An invalid context was encountered." case .invalidAlgorithm: return "An invalid algorithm was encountered." case .invalidAttributeKey: return "A key attribute was not valid." case .missingAttributeKey: return "A key attribute was missing." case .invalidAttributeInitVector: return "An init vector attribute was not valid." case .missingAttributeInitVector: return "An init vector attribute was missing." case .invalidAttributeSalt: return "A salt attribute was not valid." case .missingAttributeSalt: return "A salt attribute was missing." case .invalidAttributePadding: return "A padding attribute was not valid." case .missingAttributePadding: return "A padding attribute was missing." case .invalidAttributeRandom: return "A random number attribute was not valid." case .missingAttributeRandom: return "A random number attribute was missing." case .invalidAttributeSeed: return "A seed attribute was not valid." case .missingAttributeSeed: return "A seed attribute was missing." case .invalidAttributePassphrase: return "A passphrase attribute was not valid." case .missingAttributePassphrase: return "A passphrase attribute was missing." case .invalidAttributeKeyLength: return "A key length attribute was not valid." case .missingAttributeKeyLength: return "A key length attribute was missing." case .invalidAttributeBlockSize: return "A block size attribute was not valid." case .missingAttributeBlockSize: return "A block size attribute was missing." case .invalidAttributeOutputSize: return "An output size attribute was not valid." case .missingAttributeOutputSize: return "An output size attribute was missing." case .invalidAttributeRounds: return "The number of rounds attribute was not valid." case .missingAttributeRounds: return "The number of rounds attribute was missing." case .invalidAlgorithmParms: return "An algorithm parameters attribute was not valid." case .missingAlgorithmParms: return "An algorithm parameters attribute was missing." case .invalidAttributeLabel: return "A label attribute was not valid." case .missingAttributeLabel: return "A label attribute was missing." case .invalidAttributeKeyType: return "A key type attribute was not valid." case .missingAttributeKeyType: return "A key type attribute was missing." case .invalidAttributeMode: return "A mode attribute was not valid." case .missingAttributeMode: return "A mode attribute was missing." case .invalidAttributeEffectiveBits: return "An effective bits attribute was not valid." case .missingAttributeEffectiveBits: return "An effective bits attribute was missing." case .invalidAttributeStartDate: return "A start date attribute was not valid." case .missingAttributeStartDate: return "A start date attribute was missing." case .invalidAttributeEndDate: return "An end date attribute was not valid." case .missingAttributeEndDate: return "An end date attribute was missing." case .invalidAttributeVersion: return "A version attribute was not valid." case .missingAttributeVersion: return "A version attribute was missing." case .invalidAttributePrime: return "A prime attribute was not valid." case .missingAttributePrime: return "A prime attribute was missing." case .invalidAttributeBase: return "A base attribute was not valid." case .missingAttributeBase: return "A base attribute was missing." case .invalidAttributeSubprime: return "A subprime attribute was not valid." case .missingAttributeSubprime: return "A subprime attribute was missing." case .invalidAttributeIterationCount: return "An iteration count attribute was not valid." case .missingAttributeIterationCount: return "An iteration count attribute was missing." case .invalidAttributeDLDBHandle: return "A database handle attribute was not valid." case .missingAttributeDLDBHandle: return "A database handle attribute was missing." case .invalidAttributeAccessCredentials: return "An access credentials attribute was not valid." case .missingAttributeAccessCredentials: return "An access credentials attribute was missing." case .invalidAttributePublicKeyFormat: return "A public key format attribute was not valid." case .missingAttributePublicKeyFormat: return "A public key format attribute was missing." case .invalidAttributePrivateKeyFormat: return "A private key format attribute was not valid." case .missingAttributePrivateKeyFormat: return "A private key format attribute was missing." case .invalidAttributeSymmetricKeyFormat: return "A symmetric key format attribute was not valid." case .missingAttributeSymmetricKeyFormat: return "A symmetric key format attribute was missing." case .invalidAttributeWrappedKeyFormat: return "A wrapped key format attribute was not valid." case .missingAttributeWrappedKeyFormat: return "A wrapped key format attribute was missing." case .stagedOperationInProgress: return "A staged operation is in progress." case .stagedOperationNotStarted: return "A staged operation was not started." case .verifyFailed: return "A cryptographic verification failure has occurred." case .querySizeUnknown: return "The query size is unknown." case .blockSizeMismatch: return "A block size mismatch occurred." case .publicKeyInconsistent: return "The public key was inconsistent." case .deviceVerifyFailed: return "A device verification failure has occurred." case .invalidLoginName: return "An invalid login name was detected." case .alreadyLoggedIn: return "The user is already logged in." case .invalidDigestAlgorithm: return "An invalid digest algorithm was detected." case .invalidCRLGroup: return "An invalid CRL group was detected." case .certificateCannotOperate: return "The certificate cannot operate." case .certificateExpired: return "An expired certificate was detected." case .certificateNotValidYet: return "The certificate is not yet valid." case .certificateRevoked: return "The certificate was revoked." case .certificateSuspended: return "The certificate was suspended." case .insufficientCredentials: return "Insufficient credentials were detected." case .invalidAction: return "The action was not valid." case .invalidAuthority: return "The authority was not valid." case .verifyActionFailed: return "A verify action has failed." case .invalidCertAuthority: return "The certificate authority was not valid." case .invaldCRLAuthority: return "The CRL authority was not valid." case .invalidCRLEncoding: return "The CRL encoding was not valid." case .invalidCRLType: return "The CRL type was not valid." case .invalidCRL: return "The CRL was not valid." case .invalidFormType: return "The form type was not valid." case .invalidID: return "The ID was not valid." case .invalidIdentifier: return "The identifier was not valid." case .invalidIndex: return "The index was not valid." case .invalidPolicyIdentifiers: return "The policy identifiers are not valid." case .invalidTimeString: return "The time specified was not valid." case .invalidReason: return "The trust policy reason was not valid." case .invalidRequestInputs: return "The request inputs are not valid." case .invalidResponseVector: return "The response vector was not valid." case .invalidStopOnPolicy: return "The stop-on policy was not valid." case .invalidTuple: return "The tuple was not valid." case .multipleValuesUnsupported: return "Multiple values are not supported." case .notTrusted: return "The trust policy was not trusted." case .noDefaultAuthority: return "No default authority was detected." case .rejectedForm: return "The trust policy had a rejected form." case .requestLost: return "The request was lost." case .requestRejected: return "The request was rejected." case .unsupportedAddressType: return "The address type is not supported." case .unsupportedService: return "The service is not supported." case .invalidTupleGroup: return "The tuple group was not valid." case .invalidBaseACLs: return "The base ACLs are not valid." case .invalidTupleCredendtials: return "The tuple credentials are not valid." case .invalidEncoding: return "The encoding was not valid." case .invalidValidityPeriod: return "The validity period was not valid." case .invalidRequestor: return "The requestor was not valid." case .requestDescriptor: return "The request descriptor was not valid." case .invalidBundleInfo: return "The bundle information was not valid." case .invalidCRLIndex: return "The CRL index was not valid." case .noFieldValues: return "No field values were detected." case .unsupportedFieldFormat: return "The field format is not supported." case .unsupportedIndexInfo: return "The index information is not supported." case .unsupportedLocality: return "The locality is not supported." case .unsupportedNumAttributes: return "The number of attributes is not supported." case .unsupportedNumIndexes: return "The number of indexes is not supported." case .unsupportedNumRecordTypes: return "The number of record types is not supported." case .fieldSpecifiedMultiple: return "Too many fields were specified." case .incompatibleFieldFormat: return "The field format was incompatible." case .invalidParsingModule: return "The parsing module was not valid." case .databaseLocked: return "The database is locked." case .datastoreIsOpen: return "The data store is open." case .missingValue: return "A missing value was detected." case .unsupportedQueryLimits: return "The query limits are not supported." case .unsupportedNumSelectionPreds: return "The number of selection predicates is not supported." case .unsupportedOperator: return "The operator is not supported." case .invalidDBLocation: return "The database location is not valid." case .invalidAccessRequest: return "The access request is not valid." case .invalidIndexInfo: return "The index information is not valid." case .invalidNewOwner: return "The new owner is not valid." case .invalidModifyMode: return "The modify mode is not valid." case .missingRequiredExtension: return "A required certificate extension is missing." case .extendedKeyUsageNotCritical: return "The extended key usage extension was not marked critical." case .timestampMissing: return "A timestamp was expected but was not found." case .timestampInvalid: return "The timestamp was not valid." case .timestampNotTrusted: return "The timestamp was not trusted." case .timestampServiceNotAvailable: return "The timestamp service is not available." case .timestampBadAlg: return "An unrecognized or unsupported Algorithm Identifier in timestamp." case .timestampBadRequest: return "The timestamp transaction is not permitted or supported." case .timestampBadDataFormat: return "The timestamp data submitted has the wrong format." case .timestampTimeNotAvailable: return "The time source for the Timestamp Authority is not available." case .timestampUnacceptedPolicy: return "The requested policy is not supported by the Timestamp Authority." case .timestampUnacceptedExtension: return "The requested extension is not supported by the Timestamp Authority." case .timestampAddInfoNotAvailable: return "The additional information requested is not available." case .timestampSystemFailure: return "The timestamp request cannot be handled due to system failure." case .signingTimeMissing: return "A signing time was expected but was not found." case .timestampRejection: return "A timestamp transaction was rejected." case .timestampWaiting: return "A timestamp transaction is waiting." case .timestampRevocationWarning: return "A timestamp authority revocation warning was issued." case .timestampRevocationNotification: return "A timestamp authority revocation notification was issued." case .unexpectedError: return "Unexpected error has occurred." } } } extension Status: CustomNSError { public static let errorDomain = KeychainAccessErrorDomain public var errorCode: Int { return Int(rawValue) } public var errorUserInfo: [String : Any] { return [NSLocalizedDescriptionKey: description] } }
mit
ce0488d79b5bbafc3e588723dab69c01
42.920537
217
0.611034
5.711084
false
false
false
false
neoplastic/ReactiveRealm
ReactiveRealm/AppDelegate.swift
2
3375
// // AppDelegate.swift // ReactiveRealm // // Created by David Wong on 9/04/2016. // Copyright © 2016 5dayapp. All rights reserved. // import UIKit import RealmSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } } let realm = try! Realm()
mit
d32da5a7a6e799e230f05508082065e9
51.71875
285
0.764671
6.123412
false
false
false
false
vector-im/riot-ios
Riot/Modules/Room/ContextualMenu/ReactionsMenu/ReactionsMenuViewModel.swift
2
3416
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation @objc final class ReactionsMenuViewModel: NSObject, ReactionsMenuViewModelType { // MARK: - Properties private let reactions = ["👍", "👎", "😄", "🎉", "😕", "❤️", "🚀", "👀"] private var currentViewDatas: [ReactionMenuItemViewData] = [] // MARK: Private private let aggregatedReactions: MXAggregatedReactions? private let reactionsViewData: [ReactionMenuItemViewData] = [] private let eventId: String // MARK: Public @objc weak var coordinatorDelegate: ReactionsMenuViewModelCoordinatorDelegate? weak var viewDelegate: ReactionsMenuViewModelViewDelegate? // MARK: - Setup @objc init(aggregatedReactions: MXAggregatedReactions?, eventId: String) { self.aggregatedReactions = aggregatedReactions self.eventId = eventId } // MARK: - Public func process(viewAction: ReactionsMenuViewAction) { switch viewAction { case .loadData: self.loadData() case .tap(let reaction): if let viewData = self.currentViewDatas.first(where: { $0.emoji == reaction }) { if viewData.isSelected { self.coordinatorDelegate?.reactionsMenuViewModel(self, didRemoveReaction: reaction, forEventId: self.eventId) } else { self.coordinatorDelegate?.reactionsMenuViewModel(self, didAddReaction: reaction, forEventId: self.eventId) } } case .moreReactions: self.coordinatorDelegate?.reactionsMenuViewModelDidTapMoreReactions(self, forEventId: self.eventId) } } // MARK: - Private private func loadData() { let reactionCounts = self.aggregatedReactions?.withNonZeroCount()?.reactions ?? [] var quickReactionsWithUserReactedFlag: [String: Bool] = Dictionary(uniqueKeysWithValues: self.reactions.map { ($0, false) }) reactionCounts.forEach { (reactionCount) in if let hasUserReacted = quickReactionsWithUserReactedFlag[reactionCount.reaction], hasUserReacted == false { quickReactionsWithUserReactedFlag[reactionCount.reaction] = reactionCount.myUserHasReacted } } let reactionMenuItemViewDatas: [ReactionMenuItemViewData] = self.reactions.map { reaction -> ReactionMenuItemViewData in let isSelected = quickReactionsWithUserReactedFlag[reaction] ?? false return ReactionMenuItemViewData(emoji: reaction, isSelected: isSelected) } self.currentViewDatas = reactionMenuItemViewDatas self.viewDelegate?.reactionsMenuViewModel(self, didUpdateViewState: ReactionsMenuViewState.loaded(reactionsViewData: reactionMenuItemViewDatas)) } }
apache-2.0
8b964927d002e616ed137b3e13d28b9e
38.430233
152
0.677676
5.306729
false
false
false
false
jspahrsummers/Moya
Demo/DemoTests/MoyaProviderSpec.swift
1
12532
// // MoyaProviderSpec.swift // MoyaTests // // Created by Ash Furrow on 2014-08-16. // Copyright (c) 2014 Ash Furrow. All rights reserved. // import Quick import Moya import Nimble class MoyaProviderSpec: QuickSpec { override func spec() { describe("valid enpoints") { describe("with stubbed responses") { describe("a provider", { () -> () in var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider(endpointsClosure: endpointsClosure, stubResponses: true) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target, completion: { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) } }) let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } it("returns stubbed data for user profile request") { var message: String? let target: GitHub = .UserProfile("ashfurrow") provider.request(target, completion: { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) } }) let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } it("returns equivalent Endpoint instances for the same target") { let target: GitHub = .Zen let endpoint1 = provider.endpoint(target, method: Moya.DefaultMethod(), parameters: Moya.DefaultParameters()) let endpoint2 = provider.endpoint(target, method: Moya.DefaultMethod(), parameters: Moya.DefaultParameters()) expect(endpoint1).to(equal(endpoint2)) } }) describe("a provider with a custom endpoint resolver", { () -> () in var provider: MoyaProvider<GitHub>! var executed = false let newSampleResponse = "New Sample Response" beforeEach { executed = false let endpointResolution = { (endpoint: Endpoint<GitHub>) -> (NSURLRequest) in executed = true return endpoint.urlRequest } provider = MoyaProvider(endpointsClosure: endpointsClosure, endpointResolver: endpointResolution, stubResponses: true) } it("executes the endpoint resolver") { let target: GitHub = .Zen provider.request(target, completion: { (data, statusCode, response, error) in }) let sampleData = target.sampleData as NSData expect(executed).to(beTruthy()) } }) describe("a reactive provider", { () -> () in var provider: ReactiveMoyaProvider<GitHub>! beforeEach { provider = ReactiveMoyaProvider(endpointsClosure: endpointsClosure, stubResponses: true) } it("returns a MoyaResponse object") { var called = false provider.request(.Zen).subscribeNext({ (object) -> Void in if let response = object as? MoyaResponse { called = true } }) expect(called).to(beTruthy()) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target).subscribeNext({ (object) -> Void in if let response = object as? MoyaResponse { message = NSString(data: response.data, encoding: NSUTF8StringEncoding) } }) let sampleData = target.sampleData as NSData expect(message).toNot(beNil()) } it("returns correct data for user profile request") { var receivedResponse: NSDictionary? let target: GitHub = .UserProfile("ashfurrow") provider.request(target).subscribeNext({ (object) -> Void in if let response = object as? MoyaResponse { receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary } }) let sampleData = target.sampleData as NSData let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as NSDictionary expect(receivedResponse).toNot(beNil()) } it("returns identical signals for inflight requests") { let target: GitHub = .Zen var response: MoyaResponse! // The synchronous nature of stubbed responses makes this kind of tricky. We use the // subscribeNext closure to get the provider into a state where the signal has been // added to the inflightRequests dictionary. Then we ask for an identical request, // which should return the same signal. We can't *test* those signals equivalency // due to the use of RACSignal.defer, but we can check if the number of inflight // requests went up or not. let outerSignal = provider.request(target) outerSignal.subscribeNext({ (object) -> Void in response = object as? MoyaResponse expect(provider.inflightRequests.count).to(equal(1)) // Create a new signal and force subscription, so that the inflightRequests dictionary is accessed. let innerSignal = provider.request(target) innerSignal.subscribeNext({ (object) -> Void in // nop }) expect(provider.inflightRequests.count).to(equal(1)) }) expect(provider.inflightRequests.count).to(equal(0)) } }) } describe("with stubbed errors") { describe("a provider", { () -> () in var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider(endpointsClosure: failureEndpointsClosure, stubResponses: true) } it("returns stubbed data for zen request") { var errored = false let target: GitHub = .Zen provider.request(target, completion: { (object, statusCode, response, error) in if error != nil { errored = true } }) let sampleData = target.sampleData as NSData expect(errored).toEventually(beTruthy()) } it("returns stubbed data for user profile request") { var errored = false let target: GitHub = .UserProfile("ashfurrow") provider.request(target, completion: { (object, statusCode, response, error) in if error != nil { errored = true } }) let sampleData = target.sampleData as NSData expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1) } it("returns stubbed error data when present") { var errorMessage = "" let target: GitHub = .UserProfile("ashfurrow") provider.request(target, completion: { (object, statusCode, response, error) in if let object = object { errorMessage = NSString(data: object, encoding: NSUTF8StringEncoding)! } }) expect{errorMessage}.toEventually(equal("Houston, we have a problem"), timeout: 1, pollInterval: 0.1) } }) describe("a reactive provider", { () -> () in var provider: ReactiveMoyaProvider<GitHub>! beforeEach { provider = ReactiveMoyaProvider(endpointsClosure: failureEndpointsClosure, stubResponses: true) } it("returns stubbed data for zen request") { var errored = false let target: GitHub = .Zen provider.request(target).subscribeError({ (error) -> Void in errored = true }) expect(errored).to(beTruthy()) } it("returns correct data for user profile request") { var errored = false let target: GitHub = .UserProfile("ashfurrow") provider.request(target).subscribeError({ (error) -> Void in errored = true }) expect(errored).to(beTruthy()) } }) describe("a failing reactive provider") { var provider: ReactiveMoyaProvider<GitHub>! beforeEach { provider = ReactiveMoyaProvider(endpointsClosure: failureEndpointsClosure, stubResponses: true) } it("returns the HTTP status code as the error code") { var code: Int? provider.request(.Zen).subscribeError({ (error) -> Void in code = error.code }) expect(code).toNot(beNil()) expect(code).to(equal(401)) } } } } } }
mit
018f81d4de87ae4bcce6b670c8db83a8
47.573643
151
0.425471
7.298777
false
false
false
false
nikriek/Heimdall.swift
Heimdall/Heimdall.swift
5
11301
import Result public let HeimdallErrorDomain = "HeimdallErrorDomain" /// The token endpoint responded with invalid data. public let HeimdallErrorInvalidData = 1 /// The request could not be authorized (e.g., no refresh token available). public let HeimdallErrorNotAuthorized = 2 /// The all-seeing and all-hearing guardian sentry of your application who /// stands on the rainbow bridge network to authorize relevant requests. @objc public class Heimdall: NSObject { public let tokenURL: NSURL private let credentials: OAuthClientCredentials? private let accessTokenStore: OAuthAccessTokenStore private var accessToken: OAuthAccessToken? { get { return accessTokenStore.retrieveAccessToken() } set { accessTokenStore.storeAccessToken(newValue) } } private let httpClient: HeimdallHTTPClient /// The request authenticator that is used to authenticate requests. public let resourceRequestAuthenticator: HeimdallResourceRequestAuthenticator /// Returns a Bool indicating whether the client's access token store /// currently holds an access token. /// /// **Note:** It's not checked whether the stored access token, if any, has /// already expired. public var hasAccessToken: Bool { return accessToken != nil } /// Initializes a new client. /// /// :param: tokenURL The token endpoint URL. /// :param: credentials The OAuth client credentials. If both an identifier /// and a secret are set, client authentication is performed via HTTP /// Basic Authentication. Otherwise, if only an identifier is set, it is /// encoded as parameter. Default: `nil` (unauthenticated client). /// :param: accessTokenStore The (persistent) access token store. /// Default: `OAuthAccessTokenKeychainStore`. /// :param: httpClient The HTTP client that should be used for requesting /// access tokens. Default: `HeimdallHTTPClientNSURLSession`. /// :param: resourceRequestAuthenticator The request authenticator that is /// used to authenticate requests. Default: /// `HeimdallResourceRequestAuthenticatorHTTPAuthorizationHeader`. /// /// :returns: A new client initialized with the given token endpoint URL, /// credentials and access token store. public init(tokenURL: NSURL, credentials: OAuthClientCredentials? = nil, accessTokenStore: OAuthAccessTokenStore = OAuthAccessTokenKeychainStore(), httpClient: HeimdallHTTPClient = HeimdallHTTPClientNSURLSession(), resourceRequestAuthenticator: HeimdallResourceRequestAuthenticator = HeimdallResourceRequestAuthenticatorHTTPAuthorizationHeader()) { self.tokenURL = tokenURL self.credentials = credentials self.accessTokenStore = accessTokenStore self.httpClient = httpClient self.resourceRequestAuthenticator = resourceRequestAuthenticator } /// Invalidates the currently stored access token, if any. /// /// Unlike `clearAccessToken` this will only invalidate the access token so /// that Heimdall will try to refresh the token using the refresh token /// automatically. /// /// **Note:** Sets the access token's expiration date to /// 1 January 1970, GMT. public func invalidateAccessToken() { accessToken = accessToken?.copy(expiresAt: NSDate(timeIntervalSince1970: 0)) } /// Clears the currently stored access token, if any. /// /// After calling this method the user needs to reauthenticate using /// `requestAccessToken`. public func clearAccessToken() { accessTokenStore.storeAccessToken(nil) } /// Requests an access token with the resource owner's password credentials. /// /// **Note:** The completion closure may be invoked on any thread. /// /// :param: username The resource owner's username. /// :param: password The resource owner's password. /// :param: completion A callback to invoke when the request completed. public func requestAccessToken(#username: String, password: String, completion: Result<Void, NSError> -> ()) { requestAccessToken(grant: .ResourceOwnerPasswordCredentials(username, password)) { result in completion(result.map { _ in return }) } } /// Requests an access token with the given grant type URI and parameters /// /// **Note:** The completion closure may be invoked on any thread. /// /// :param: grantType The grant type URI of the extension grant /// :param: parameters The required parameters for the external grant /// :param: completion A callback to invoke when the request completed. public func requestAccessToken(#grantType: String, parameters: [String: String], completion: Result<Void, NSError> -> ()) { requestAccessToken(grant: .Extension(grantType, parameters)) { result in completion(result.map { _ in return }) } } /// Requests an access token with the given authorization grant. /// /// The client is authenticated via HTTP Basic Authentication if both an /// identifier and a secret are set in its credentials. Otherwise, if only /// an identifier is set, it is encoded as parameter. /// /// :param: grant The authorization grant (e.g., refresh). /// :param: completion A callback to invoke when the request completed. private func requestAccessToken(#grant: OAuthAuthorizationGrant, completion: Result<OAuthAccessToken, NSError> -> ()) { let request = NSMutableURLRequest(URL: tokenURL) var parameters = grant.parameters if let credentials = credentials { if let secret = credentials.secret { request.setHTTPAuthorization(.BasicAuthentication(username: credentials.id, password: secret)) } else { parameters["client_id"] = credentials.id } } request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setHTTPBody(parameters: parameters) httpClient.sendRequest(request) { data, response, error in if let error = error { completion(.failure(error)) } else if (response as! NSHTTPURLResponse).statusCode == 200 { switch OAuthAccessToken.decode(data) { case let .Success(accessToken): self.accessToken = accessToken.value completion(.success(accessToken.value)) default: let userInfo = [ NSLocalizedDescriptionKey: NSLocalizedString("Could not authorize grant", comment: ""), NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("Expected access token, got: %@.", comment: ""), NSString(data: data, encoding: NSUTF8StringEncoding) ?? "nil") ] let error = NSError(domain: HeimdallErrorDomain, code: HeimdallErrorInvalidData, userInfo: userInfo) completion(.failure(error)) } } else { switch OAuthError.decode(data) { case let .Success(error): completion(.failure(error.value.nsError)) default: let userInfo = [ NSLocalizedDescriptionKey: NSLocalizedString("Could not authorize grant", comment: ""), NSLocalizedFailureReasonErrorKey: String(format: NSLocalizedString("Expected error, got: %@.", comment: ""), NSString(data: data, encoding: NSUTF8StringEncoding) ?? "nil") ] let error = NSError(domain: HeimdallErrorDomain, code: HeimdallErrorInvalidData, userInfo: userInfo) completion(.failure(error)) } } } } /// Alters the given request by adding authentication with an access token. /// /// :param: request An unauthenticated NSURLRequest. /// :param: accessToken The access token to be used for authentication. /// /// :returns: The given request authorized using the resource request /// authenticator. private func authenticateRequest(request: NSURLRequest, accessToken: OAuthAccessToken) -> NSURLRequest { return self.resourceRequestAuthenticator.authenticateResourceRequest(request, accessToken: accessToken) } /// Alters the given request by adding authentication, if possible. /// /// In case of an expired access token and the presence of a refresh token, /// automatically tries to refresh the access token. If refreshing the /// access token fails, the access token is cleared. /// /// **Note:** If the access token must be refreshed, network I/O is /// performed. /// /// **Note:** The completion closure may be invoked on any thread. /// /// :param: request An unauthenticated NSURLRequest. /// :param: completion A callback to invoke with the authenticated request. public func authenticateRequest(request: NSURLRequest, completion: Result<NSURLRequest, NSError> -> ()) { if let accessToken = accessToken { if accessToken.expiresAt != nil && accessToken.expiresAt < NSDate() { if let refreshToken = accessToken.refreshToken { requestAccessToken(grant: .RefreshToken(refreshToken)) { result in completion(result.analysis(ifSuccess: { accessToken in let authenticatedRequest = self.authenticateRequest(request, accessToken: accessToken) return .success(authenticatedRequest) }, ifFailure: { error in if contains([ HeimdallErrorDomain, OAuthErrorDomain ], error.domain) { self.clearAccessToken() } return .failure(error) })) } } else { let userInfo = [ NSLocalizedDescriptionKey: NSLocalizedString("Could not add authorization to request", comment: ""), NSLocalizedFailureReasonErrorKey: NSLocalizedString("Access token expired, no refresh token available.", comment: "") ] let error = NSError(domain: HeimdallErrorDomain, code: HeimdallErrorNotAuthorized, userInfo: userInfo) completion(.failure(error)) } } else { let request = authenticateRequest(request, accessToken: accessToken) completion(.success(request)) } } else { let userInfo = [ NSLocalizedDescriptionKey: NSLocalizedString("Could not add authorization to request", comment: ""), NSLocalizedFailureReasonErrorKey: NSLocalizedString("Not authorized.", comment: "") ] let error = NSError(domain: HeimdallErrorDomain, code: HeimdallErrorNotAuthorized, userInfo: userInfo) completion(.failure(error)) } } }
apache-2.0
3668d1add8e83ceea7cb9f91e30b4fcd
47.922078
352
0.642598
5.733638
false
false
false
false
JohnnyDevMode/Hoard
Hoard/DiskContext.swift
1
3541
// // DiskContext.swift // Hoard // // Created by John Bailey on 4/13/17. // Copyright © 2017 DevMode Studios. All rights reserved. // import Foundation public class DiskContext : TraversableContext { private let fileManager = FileManager.default private let dirUrl : URL public init(dirUrl: URL) { self.dirUrl = dirUrl if !fileManager.fileExists(atPath: dirUrl.path) { do { try fileManager.createDirectory(at: dirUrl, withIntermediateDirectories: true, attributes: [:]) // TODO: Find directories to populate child contexts MAYBE } catch let error as NSError { print("Error creating directoroy: \(error)") } } } public override func putLocal<T>(key: String, value: T) { if let persistable = value as? Persistable, let data = persistable.asData() { writeData(path: key, data: data) } } public override func getLocal<T>(key: String) -> T? { if let data = readData(path: key), T.self is Persistable.Type { return (T.self as? Persistable.Type)?.init(data: data) as? T } return nil } public override func removeLocal(key: String) { let childUrl = self.childUrl(childName: key) if fileManager.fileExists(atPath: childUrl.path) { do { try fileManager.removeItem(at: childUrl) } catch let error as NSError { print("Remove error: \(error)") } } } public override func clear() { do { for file in try fileManager.contentsOfDirectory(atPath: dirUrl.path) { try fileManager.removeItem(atPath: "\(dirUrl.path)/\(file)") } } catch let error as NSError { print("Clear Error: \(error)") } } public override func clean(deep: Bool) { clean(directory: dirUrl.path, deep: deep) } private func clean(directory: String, deep: Bool) { super.clean(deep: deep) do { for file in try fileManager.contentsOfDirectory(atPath: directory) { let child = directory.appending("/\(file)") var isDir: ObjCBool = false if (fileManager.fileExists(atPath: child, isDirectory: &isDir)) { if isDir.boolValue { if childContexts[file] == nil { clean(directory: child, deep: deep) } } else { let attributes = try fileManager.attributesOfItem(atPath: child) as NSDictionary if let created = attributes.fileCreationDate(), Date().timeIntervalSince(created) > expiry { try fileManager.removeItem(atPath: child) } else if deep, let modifed = attributes.fileModificationDate(), (Date().timeIntervalSince(modifed) / expiry) > ROT_THRESHOLD { try fileManager.removeItem(atPath: child) } } } } } catch let error as NSError { print("Clean Error: \(error)") } } private func childUrl(childName: String) -> URL { return dirUrl.appendingPathComponent(childName) } private func writeData(path: String, data: Data) { do { try data.write(to: childUrl(childName: path)) } catch let error as NSError { print("Write Error: \(error)") } } private func readData(path: String) -> Data? { do { return try Data(contentsOf: childUrl(childName: path)) } catch let error as NSError { print("Read Error: \(error)") } return nil } override func createChild(key: String) -> TraversableContext { return DiskContext(dirUrl: childUrl(childName: key)) } }
mit
d4d06b56ec61311f615591ce99cfcc71
28.747899
139
0.620904
4.26506
false
false
false
false
noehou/TWB
TWB/TWB/Classes/Compose/ComposeTextView.swift
1
1092
// // ComposeTextView.swift // TWB // // Created by Tommaso on 2017/5/23. // Copyright © 2017年 Tommaso. All rights reserved. // import UIKit import SnapKit class ComposeTextView: UITextView { //MARK:- 懒加载属性 lazy var placeHolderLabel :UILabel = UILabel() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } } // //MARK:- 设置UI界面 extension ComposeTextView { func setupUI(){ //1、添加子控件 addSubview(placeHolderLabel) //2、设置frame placeHolderLabel.snp_makeConstraints { (make) in make.top.equalTo(8) make.left.equalTo(10) } //3、设置placeholderlabel属性 placeHolderLabel.textColor = UIColor.lightGray placeHolderLabel.font = font //4、设置placeholderlabel的文字 placeHolderLabel.text = "分享新鲜事..." //5、设置内容的内边距 textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) } }
mit
3ac7becde92bc1d72231ab38923ba97d
21.795455
81
0.598205
4.323276
false
false
false
false
cactis/SwiftEasyKit
Source/Classes/PopupView.swift
1
2143
// // PopupView.swift import UIKit open class PopupView: DefaultView { open var delegate: UIView! public var contentView = UIScrollView() public var closeBtn: UIImageView! public var padding: CGFloat = 10 public var closeBtnSize: CGFloat = 25 public var radius: CGFloat = 6 public var didDismiss: (_ popupView: PopupView) -> () = {_ in } public var didSuccess: (_ popupView: PopupView) -> () = {_ in } override public init(frame: CGRect) { super.init(frame: frame) layout([contentView]) closeBtn = contentView.addImageView(UIImage.fontAwesomeIcon(name: .close, textColor: K.Color.button, size: CGSize(width: closeBtnSize, height: closeBtnSize))) closeBtn.whenTapped(self, action: #selector(closeBtnTapped(_:))) } public init(didDismiss: @escaping (_ popupView: PopupView) -> () = {_ in }) { super.init(frame: .zero) self.didDismiss = didDismiss } @objc open func closeBtnTapped(_ sender: AnyObject?) { parentViewController()!.dismiss(animated: true) { () -> Void in self.didDismiss(self) } } @objc open func closeBtnTapped(didDismiss: @escaping () -> () = {}) { parentViewController()!.dismiss(animated: true) { didDismiss() } } override open func styleUI() { super.styleUI() radiused(radius) backgroundColor = K.Color.popup } override open func bindUI() { super.bindUI() contentView.whenTapped(self, action: #selector(contentViewTapped)) } @objc open func contentViewTapped() { contentView.endEditing(true) } open func layoutBase() { anchorInCenter(withWidth: UIScreen.main.bounds.width / 5 * 4, height: UIScreen.main.bounds.height / 2) } override open func layoutSubviews() { super.layoutSubviews() layoutBase() fixedConstraints() contentView.fillSuperview(left: padding, right: padding, top: padding, bottom: padding) } open func fixedConstraints() { closeBtn.anchorTopRight(withRightPadding: 10, topPadding: 10, width: closeBtnSize , height: closeBtnSize) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
c0c4d3f59658af7b921eb3c736e93e6a
27.573333
162
0.685954
4.218504
false
false
false
false
lnds/9d9l
desafio4/swift/Sources/main.swift
1
891
import Foundation func usage() { print("Uso: huffman [-c|-d] archivo_entrada archivo_salida") exit(-1) } func comprimir(input: String, output: String) { let reader = BitInputStream(inputFile: input) let writer = BitOutputStream(outputFile: output) let tree = HuffTree(buildFrom: reader) tree.compress(readFrom: reader, writeTo: writer) } func descomprimir(input: String, output: String) { let reader = BitInputStream(inputFile: input) let writer = BitOutputStream(outputFile: output) let tree = HuffTree(readFrom: reader) tree.decompress(readFrom: reader, writeTo: writer) } let args = ProcessInfo.processInfo.arguments let argc = ProcessInfo.processInfo.arguments.count if argc != 4 { usage() } else { if args[1] == "-c" { comprimir(input: args[2], output: args[3]) } else if args[1] == "-d" { descomprimir(input: args[2], output: args[3]) } else { usage() } }
mit
568a59eb90bed317d5c715128c4fab45
22.447368
61
0.708193
2.989933
false
false
false
false
Keenan144/SpaceKase
SpaceKase/boundary.swift
1
2430
// // boundary.swift // SpaceKase // // Created by Keenan Sturtevant on 6/5/16. // Copyright © 2016 Keenan Sturtevant. All rights reserved. // import Foundation import SpriteKit class Boundary: SKScene, SKPhysicsContactDelegate { class func setBottomBoundary(boundaryCategory: UInt32, rockCategory: UInt32, frame: CGRect) -> SKSpriteNode { var boundary = SKSpriteNode(color: UIColor.blackColor(), size: CGSize(width: frame.width, height: 1)) boundary.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: frame.width, height: 1)) boundary.position = CGPoint(x: frame.midX, y: frame.minY) boundary = setBoundary(boundary, boundaryCategory: boundaryCategory, rockCategory: rockCategory) print("Boundary.setBottom") return boundary } class func setRightSideBoundary(boundaryCategory: UInt32, rockCategory: UInt32, frame: CGRect) -> SKSpriteNode { var boundary = SKSpriteNode(color: UIColor.blackColor(), size: CGSize(width: 1, height: frame.height)) boundary.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 1, height: frame.height)) boundary.position = CGPoint(x: frame.maxX, y: frame.midY) boundary = setBoundary(boundary, boundaryCategory: boundaryCategory, rockCategory: rockCategory) print("Boundary.setRightSide") return boundary } class func setLeftSideBoundary(boundaryCategory: UInt32, rockCategory: UInt32, frame: CGRect) -> SKSpriteNode { var boundary = SKSpriteNode(color: UIColor.blackColor(), size: CGSize(width: 1, height: frame.height)) boundary.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 1, height: frame.height)) boundary.position = CGPoint(x: frame.minX, y: frame.midY) boundary = setBoundary(boundary, boundaryCategory: boundaryCategory, rockCategory: rockCategory) print("Boundary.setLeftSide") return boundary } class func setBoundary(boundary: SKSpriteNode, boundaryCategory: UInt32, rockCategory: UInt32) -> SKSpriteNode { boundary.physicsBody?.dynamic = false boundary.physicsBody?.categoryBitMask = boundaryCategory boundary.physicsBody?.contactTestBitMask = rockCategory boundary.physicsBody?.collisionBitMask = 0; boundary.physicsBody?.usesPreciseCollisionDetection = true print("Boundary.set") return boundary } }
mit
89e29eaabebbb1b5eed77261ba3036eb
47.58
116
0.715109
4.809901
false
false
false
false
ppraveentr/MobileCore
Sources/CoreUtility/Generic/FlattenIterator.swift
1
2282
// // FlattenIterator.swift // MobileCore-CoreUtility // // Created by Praveen Prabhakar on 15/03/18. // Copyright © 2018 Praveen Prabhakar. All rights reserved. // import Foundation import UIKit public protocol FlattenIterator: Collection { @discardableResult mutating func stripNilElements() -> Self } extension Array: FlattenIterator { // Optional Protocol implementation: intentionally empty } extension Dictionary: FlattenIterator { // Optional Protocol implementation: intentionally empty } public extension FlattenIterator { @discardableResult mutating func stripNilElements() -> Self { // Sub-Elements let stripSubElements = { (_ val: inout Any) -> Any in if var asJson = val as? [String: Any?] { return asJson.stripNilElements() } else if var asList = val as? [Any?] { return asList.stripNilElements() } return val } // swiftlint:disable force_unwrapping // swiftlint:disable force_cast // Dic if var dicSub = self as? [String: Any?] { dicSub = dicSub.filter { $1 != nil } self = dicSub.mapValues { val -> Any in var value = val return stripSubElements(&value!) } as! Self } // Array else if var dicArray = self as? [Any?] { dicArray = dicArray.filter({ $0 != nil }) self = dicArray.map { val -> Any in var value = val return stripSubElements(&value!) } as! Self } // swiftlint:enable force_unwrapping // swiftlint:enable force_cast return self } } public extension Dictionary { mutating func merge(another: [Key: Value]) { for (key, value) in another { self[key] = value } } } public extension Dictionary where Value: RangeReplaceableCollection { mutating func merge(another: [Key: Value]) { for (key, value) in another { if let collection = self[key] { self[key] = collection + value } else { self[key] = value } } } }
mit
bdba7e41a724216ade289df7b8217f32
26.154762
69
0.552389
4.664622
false
false
false
false
krze/ProcessTestSummaries
ProcessTestSummaries/ArgumentOptionsParser.swift
2
1908
// // ArgumentOptionsParser.swift // ProcessTestSummaries // // Created by Teodor Nacu on 23/05/16. // Copyright © 2016 Teo. All rights reserved. // import Foundation /// Used to parse command line arguments with options starting with " --" prefix struct ArgumentOptionsParser { static let kArgsSeparator = " --" // parse the arguments and return a dictionary of options values func parseArgs() -> [String: String] { let args = CommandLine.arguments let arguments = args.joined(separator: " ") var argsOptionValues = arguments.components(separatedBy: ArgumentOptionsParser.kArgsSeparator) argsOptionValues.remove(at: 0) var parsedOptions = [String: String]() for argsOptionValue in argsOptionValues { let rangeToRemove = argsOptionValue.range(of: " ") let optionName = argsOptionValue.substring(to: rangeToRemove?.lowerBound ?? argsOptionValue.endIndex) var optionValue = argsOptionValue optionValue.replaceSubrange(optionValue.startIndex..<(rangeToRemove?.upperBound ?? optionValue.endIndex), with: "") parsedOptions[optionName] = optionValue } return parsedOptions } func validateOptionIsNotEmpty(optionName: String, optionValue: String) { if optionValue.isEmpty { try! CustomErrorType.invalidArgument(error: "\(ArgumentOptionsParser.kArgsSeparator)\(optionName) option value is empty.").throwsError() } } func validateOptionExistsAndIsNotEmpty(optionName: String, optionValue: String?) { guard let optionValue = optionValue else { try! CustomErrorType.invalidArgument(error: "\(ArgumentOptionsParser.kArgsSeparator)\(optionName) option value was not found.").throwsError() return } validateOptionIsNotEmpty(optionName: optionName, optionValue: optionValue) } }
mit
64fe629cf81a080914a71c28f62d1bbf
41.377778
153
0.69376
5.210383
false
false
false
false
mozilla-mobile/focus-ios
Blockzilla/Utilities/AdsTelemetryHelper.swift
1
5288
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Glean import WebKit public enum BasicSearchProvider: String { case google case duckduckgo case yahoo case bing } public struct SearchProviderModel { let name: String let regexp: String let queryParam: String let codeParam: String let codePrefixes: [String] let followOnParams: [String] let extraAdServersRegexps: [String] public static let searchProviderList = [ SearchProviderModel(name: BasicSearchProvider.google.rawValue, regexp: #"^https:\/\/www\.google\.(?:.+)\/search"#, queryParam: "q", codeParam: "client", codePrefixes: ["firefox"], followOnParams: ["oq", "ved", "ei"], extraAdServersRegexps: [ #"^https?:\/\/www\.google(?:adservices)?\.com\/(?:pagead\/)?aclk"#, #"^(http|https):\/\/clickserve.dartsearch.net\/link\/"#]), SearchProviderModel(name: BasicSearchProvider.duckduckgo.rawValue, regexp: #"^https:\/\/duckduckgo\.com\/"#, queryParam: "q", codeParam: "t", codePrefixes: ["f"], followOnParams: [], extraAdServersRegexps: [ #"^https:\/\/duckduckgo.com\/y\.js"#, #"^https:\/\/www\.amazon\.(?:[a-z.]{2,24}).*(?:tag=duckduckgo-)"#]), SearchProviderModel(name: BasicSearchProvider.yahoo.rawValue, regexp: #"^https:\/\/(?:.*)search\.yahoo\.com\/search"#, queryParam: "p", codeParam: "", codePrefixes: [], followOnParams: [], extraAdServersRegexps: [#"^(http|https):\/\/clickserve.dartsearch.net\/link\/"#, #"^https:\/\/www\.bing\.com\/acli?c?k"#, #"^https:\/\/www\.bing\.com\/fd\/ls\/GLinkPingPost\.aspx.*acli?c?k"#]), SearchProviderModel(name: BasicSearchProvider.bing.rawValue, regexp: #"^https:\/\/www\.bing\.com\/search"#, queryParam: "q", codeParam: "pc", codePrefixes: ["MOZ", "MZ"], followOnParams: ["oq"], extraAdServersRegexps: [#"^https:\/\/www\.bing\.com\/acli?c?k"#, #"^https:\/\/www\.bing\.com\/fd\/ls\/GLinkPingPost\.aspx.*acli?c?k"#]) ] } extension SearchProviderModel { func listAdUrls(urls: [String]) -> [String] { let predicates: [((String) -> Bool)] = extraAdServersRegexps.map { regex in return { url in return url.range(of: regex, options: .regularExpression) != nil } } var adUrls = [String]() for url in urls { for predicate in predicates { guard predicate(url) else { continue } adUrls.append(url) } } return adUrls } } class AdsTelemetryHelper { var getURL: (() -> URL?)! var adsTelemetryUrlList: [String] = [String]() { didSet { startingSearchUrlWithAds = getURL() } } var adsTelemetryRedirectUrlList: [URL] = [URL]() var startingSearchUrlWithAds: URL? var adsProviderName: String = "" func trackAds(message: WKScriptMessage) { guard let body = message.body as? [String: Any], let provider = getProviderForMessage(message: body), let urls = body["urls"] as? [String] else { return } let adUrls = provider.listAdUrls(urls: urls) if !adUrls.isEmpty { trackAdsFoundOnPage(providerName: provider.name) adsProviderName = provider.name adsTelemetryUrlList = adUrls adsTelemetryRedirectUrlList.removeAll() } } func getProviderForMessage(message: [String: Any]) -> SearchProviderModel? { guard let url = message["url"] as? String else { return nil } for provider in SearchProviderModel.searchProviderList { guard url.range(of: provider.regexp, options: .regularExpression) != nil else { continue } return provider } return nil } func trackClickedAds(with nextURL: URL?) { if adsTelemetryUrlList.count > 0, let adUrl = nextURL?.absoluteString { if adsTelemetryUrlList.contains(adUrl) { if !adsProviderName.isEmpty { trackAdsClickedOnPage(providerName: adsProviderName) } adsTelemetryUrlList.removeAll() adsTelemetryRedirectUrlList.removeAll() adsProviderName = "" } } } func trackAdsFoundOnPage(providerName: String) { GleanMetrics.BrowserSearch.withAds["provider-\(providerName)"].add() } func trackAdsClickedOnPage(providerName: String) { GleanMetrics.BrowserSearch.adClicks["provider-\(providerName)"].add() } }
mpl-2.0
9e80242bd59ffb756f3e7d6f2ddcf376
39.060606
221
0.547088
4.914498
false
false
false
false
couchbits/iOSToolbox
Example/iOSToolbox/ViewController.swift
1
6638
// // ViewController.swift // iOSToolbox // // Created by git on 09/12/2017. // Copyright (c) 2017 git. All rights reserved. // import UIKit import iOSToolbox import PureLayout extension UIViewController: UIViewControllerPresentable {} extension UIViewController: ErrorPresentable {} extension UIViewController: ActionDialogPresentable {} extension UIView: ProgressVisualizable {} extension UIView: Loadable {} class ViewController: UIViewController { var isLoading = false override func viewDidLoad() { super.viewDidLoad() self.view.initializeLoadable(color: UIColor.red) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.action, handler: { _ in self.presentError(title: "Left Bar Button", message: "Left Bar Button Item Tapped", buttonTitle: "ok") }) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Toggle Loading", handler: { _ in self.isLoading.toggle() self.view.setLoading(self.isLoading) }) self.view.initializeLoadable(settings: LoadableSettings(color: .red, blockingViewSettings: LoadableSettings.BlockingViewSettings())) let scrollView = UIScrollView() view.addSubview(scrollView) scrollView.autoPin(toTopLayoutGuideOf: self, withInset: 16) scrollView.autoPinEdges(toSuperviewMarginsExcludingEdge: .top) let stackView = UIStackView() scrollView.addSubview(stackView) stackView.autoAlignAxis(toSuperviewAxis: .vertical) stackView.autoMatch(.width, to: .width, of: scrollView) [.top, .bottom].forEach { stackView.autoPinEdge(toSuperviewEdge: $0) } stackView.axis = .vertical stackView.alignment = .center stackView.distribution = .fill stackView.spacing = 8.0 addSwitchExtension(stackView: stackView) addButtonExtensions(stackView: stackView) addSegmentedControlExtension(stackView: stackView) addTextField(stackView: stackView) let progressView = UIView() progressView.translatesAutoresizingMaskIntoConstraints = false progressView.widthAnchor.constraint(equalToConstant: 100).isActive = true progressView.heightAnchor.constraint(equalToConstant: 100).isActive = true progressView.backgroundColor = .yellow stackView.addArrangedSubview(progressView) progressView.initializeProgressVisualizable(color: .red) var progress = 0.1 progressView.addGestureRecognizer(UITapGestureRecognizer(tap: { _ in if progress >= 1 { progress = 0 } else { progress += 0.1 } var progressView = progressView progressView.progress = progress })) let segmentedSlider = SegmentedSlider(titles: ["Aktiv innerhalb der letzten Woche", "Aktiv innerhalb der letzten 30 Tage", "Alle Tiere"], configuration: SegmentedSliderConfiguration()) segmentedSlider.valueChangedHandler = { index in print("SegmendSlider: \(index)") } stackView.addArrangedSubview(segmentedSlider) let floatingActionButton = FloatingActionButton(image: UIImage(named: "Layers")?.withRenderingMode(.alwaysTemplate), color: .red, primary: true, size: .large) view.addSubview(floatingActionButton) view.rightAnchor.constraint(equalTo: floatingActionButton.rightAnchor, constant: 32).isActive = true view.bottomAnchor.constraint(equalTo: floatingActionButton.bottomAnchor, constant: 32).isActive = true } func addSwitchExtension(stackView: UIStackView) { stackView.addArrangedSubview(UISwitch(valueChanged: { (object) in self.presentError(title: "Value Changed", message: object.isOn ? "An" : "Aus", buttonTitle: "ok") })) let switchWithChangedBlock = UISwitch(valueChanged: { (s) in self.presentError(title: "DARF NICHT ANGEZEIGT WERDEN", message: "WENN DIESE MELDUNG KOMMT, DANN ISTS KAPUTT", buttonTitle: "ok") }) switchWithChangedBlock.valueChanged = { (object) in self.presentError(title: "Another Value Changed ", message: object.isOn ? "An" : "Aus", buttonTitle: "ok") } stackView.addArrangedSubview(switchWithChangedBlock) } func addButtonExtensions(stackView: UIStackView) { let button = UIButton() button.setTitle("Inside / Outside", for: .normal) button.setTitleColor(UIColor.black, for: .normal) button.touchUpInside = { _ in self.presentError(title: "Touch up inside", message: "Drinnen", buttonTitle: "ok") } button.touchUpOutside = { _ in self.presentError(title: "Touch up outside", message: "Draussen", buttonTitle: "ok") } stackView.addArrangedSubview(button) } func addSegmentedControlExtension(stackView: UIStackView) { var segmentedControl = UISegmentedControl(items: ["Loading Off", "Loading On"]) segmentedControl.valueChanged = { segmentedControl in print("Selected segments: \(segmentedControl.selectedSegmentIndex)") } segmentedControl.selectedSegmentIndex = 0 stackView.addArrangedSubview(segmentedControl) segmentedControl = UISegmentedControl(valueChanged: { segmentedControl in self.presentError(title: "ValueChanged", message: segmentedControl.titleForSegment(at: segmentedControl.selectedSegmentIndex) ?? "Invalid", buttonTitle: "ok") }) segmentedControl.insertSegment(withTitle: "Four", at: 0, animated: true) segmentedControl.insertSegment(withTitle: "Five", at: 1, animated: true) segmentedControl.insertSegment(withTitle: "Six", at: 2, animated: true) stackView.addArrangedSubview(segmentedControl) } func addTextField(stackView: UIStackView) { let label = UILabel(font: UIFont.systemFont(ofSize: 16), color: .red) let textField = UITextField { (textField) in if textField.text.isBlank { label.text = "EMPTY" label.textColor = .red } else { label.text = textField.text label.textColor = .blue } } label.text = "EMPTY" textField.placeholder = "Bitte Text eingeben" stackView.addArrangedSubview(label) stackView.addArrangedSubview(textField) } }
mit
c86923f2eba62056c4ab5253190fbee1
43.550336
166
0.661344
5.149728
false
false
false
false
apple/swift
validation-test/compiler_crashers_2_fixed/0168-rdar40164371.swift
38
602
// RUN: %target-swift-frontend -emit-sil %s protocol X1 { associatedtype X3 : X4 } protocol X4 { associatedtype X15 } protocol X7 { } protocol X9 : X7 { associatedtype X10 : X7 } struct X12 : X9 { typealias X10 = X12 } struct X13<I1 : X7> : X9 { typealias X10 = X13<I1> } struct X14<G : X4> : X4 where G.X15 : X9 { typealias X15 = X13<G.X15.X10> } struct X17<A : X4> : X1 where A.X15 == X12 { typealias X3 = X14<A> } struct X18 : X4 { typealias X15 = X12 } @_transparent func callee<T>(_: T) where T : X1 { let _: T.X3.X15? = nil } func caller(b: X17<X18>) { callee(b) }
apache-2.0
eb65cb9221b5bd6157fd2aa8d285a686
12.681818
44
0.606312
2.288973
false
false
false
false
airbnb/lottie-ios
Sources/Private/Model/DotLottie/Zip/ZipEntry+ZIP64.swift
2
6103
// // Entry+ZIP64.swift // ZIPFoundation // // Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation // MARK: - ExtensibleDataField protocol ExtensibleDataField { var headerID: UInt16 { get } var dataSize: UInt16 { get } } // MARK: - ExtraFieldHeaderID private enum ExtraFieldHeaderID: UInt16 { case zip64ExtendedInformation = 0x0001 } extension ZipEntry { enum EntryError: Error { case invalidDataError } struct ZIP64ExtendedInformation: ExtensibleDataField { let headerID: UInt16 = ExtraFieldHeaderID.zip64ExtendedInformation.rawValue let dataSize: UInt16 static let headerSize: UInt16 = 4 let uncompressedSize: UInt64 let compressedSize: UInt64 let relativeOffsetOfLocalHeader: UInt64 let diskNumberStart: UInt32 } var zip64ExtendedInformation: ZIP64ExtendedInformation? { centralDirectoryStructure.zip64ExtendedInformation } } typealias Field = ZipEntry.ZIP64ExtendedInformation.Field extension ZipEntry.LocalFileHeader { var validFields: [Field] { var fields: [Field] = [] if uncompressedSize == .max { fields.append(.uncompressedSize) } if compressedSize == .max { fields.append(.compressedSize) } return fields } } extension ZipEntry.CentralDirectoryStructure { var validFields: [Field] { var fields: [Field] = [] if uncompressedSize == .max { fields.append(.uncompressedSize) } if compressedSize == .max { fields.append(.compressedSize) } if relativeOffsetOfLocalHeader == .max { fields.append(.relativeOffsetOfLocalHeader) } if diskNumberStart == .max { fields.append(.diskNumberStart) } return fields } var zip64ExtendedInformation: ZipEntry.ZIP64ExtendedInformation? { extraFields?.compactMap { $0 as? ZipEntry.ZIP64ExtendedInformation }.first } } extension ZipEntry.ZIP64ExtendedInformation { // MARK: Lifecycle init?(data: Data, fields: [Field]) { let headerLength = 4 guard fields.reduce(0, { $0 + $1.size }) + headerLength == data.count else { return nil } var readOffset = headerLength func value<T>(of field: Field) throws -> T where T: BinaryInteger { if fields.contains(field) { defer { readOffset += MemoryLayout<T>.size } guard readOffset + field.size <= data.count else { throw ZipEntry.EntryError.invalidDataError } return data.scanValue(start: readOffset) } else { return 0 } } do { dataSize = data.scanValue(start: 2) uncompressedSize = try value(of: .uncompressedSize) compressedSize = try value(of: .compressedSize) relativeOffsetOfLocalHeader = try value(of: .relativeOffsetOfLocalHeader) diskNumberStart = try value(of: .diskNumberStart) } catch { return nil } } init?(zip64ExtendedInformation: ZipEntry.ZIP64ExtendedInformation?, offset: UInt64) { // Only used when removing entry, if no ZIP64 extended information exists, // then this information will not be newly added either guard let existingInfo = zip64ExtendedInformation else { return nil } relativeOffsetOfLocalHeader = offset >= UInt32.max ? offset : 0 uncompressedSize = existingInfo.uncompressedSize compressedSize = existingInfo.compressedSize diskNumberStart = existingInfo.diskNumberStart let tempDataSize = [relativeOffsetOfLocalHeader, uncompressedSize, compressedSize] .filter { $0 != 0 } .reduce(UInt16(0)) { $0 + UInt16(MemoryLayout.size(ofValue: $1)) } dataSize = tempDataSize + (diskNumberStart > 0 ? UInt16(MemoryLayout.size(ofValue: diskNumberStart)) : 0) if dataSize == 0 { return nil } } // MARK: Internal enum Field { case uncompressedSize case compressedSize case relativeOffsetOfLocalHeader case diskNumberStart var size: Int { switch self { case .uncompressedSize, .compressedSize, .relativeOffsetOfLocalHeader: return 8 case .diskNumberStart: return 4 } } } var data: Data { var headerID = headerID var dataSize = dataSize var uncompressedSize = uncompressedSize var compressedSize = compressedSize var relativeOffsetOfLFH = relativeOffsetOfLocalHeader var diskNumberStart = diskNumberStart var data = Data() withUnsafePointer(to: &headerID) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } withUnsafePointer(to: &dataSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } if uncompressedSize != 0 || compressedSize != 0 { withUnsafePointer(to: &uncompressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } withUnsafePointer(to: &compressedSize) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } } if relativeOffsetOfLocalHeader != 0 { withUnsafePointer(to: &relativeOffsetOfLFH) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } } if diskNumberStart != 0 { withUnsafePointer(to: &diskNumberStart) { data.append(UnsafeBufferPointer(start: $0, count: 1)) } } return data } static func scanForZIP64Field(in data: Data, fields: [Field]) -> ZipEntry.ZIP64ExtendedInformation? { guard data.isEmpty == false else { return nil } var offset = 0 var headerID: UInt16 var dataSize: UInt16 let extraFieldLength = data.count let headerSize = Int(ZipEntry.ZIP64ExtendedInformation.headerSize) while offset < extraFieldLength - headerSize { headerID = data.scanValue(start: offset) dataSize = data.scanValue(start: offset + 2) let nextOffset = offset + headerSize + Int(dataSize) guard nextOffset <= extraFieldLength else { return nil } if headerID == ExtraFieldHeaderID.zip64ExtendedInformation.rawValue { return ZipEntry.ZIP64ExtendedInformation(data: data.subdata(in: offset..<nextOffset), fields: fields) } offset = nextOffset } return nil } }
apache-2.0
17e830b9a842c773c31971eb1d876661
33.089385
109
0.70354
4.553731
false
false
false
false
eebean2/DevTools
Example/DevTools/HomeThemeManager.swift
1
1312
// // HomeThemeManager.swift // DevTools // // Created by Erik Bean on 8/18/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import DevTools extension ViewController { @IBAction func changeTheme(_ sender: UIButton) { let titleProfile = UIThemeProfile.label(defaultTextColor: .black, themeTextColor: .white) let title = UIThemeElement(element: dtTitle, profile: titleProfile) do { // try dtTitle.enableTheme(profile: titleProfile) try title.enableTheme() } catch let error { print(error.localizedDescription) } let backProfile = UIThemeProfile.view(defaultBackground: .groupTableViewBackground, themeBackground: .black) backProfile.statusBar = true let background = UIThemeElement(element: view, profile: backProfile) try! background.enableTheme() // if !manager.isThemeOn { // do { // try manager.enableTheme(animated: false) // } catch let error { // print(error.localizedDescription) // } // } else { // do { // try manager.disableTheme() // } catch let error { // print(error.localizedDescription) // } // } } }
mit
64481572adcc3d2c0fe019f0622a7818
30.97561
116
0.591152
4.355482
false
false
false
false
loopwxservices/WXKDarkSky
Sources/WXKDarkSky/DarkSkyRequest.swift
1
5304
// // DarkSkyRequest.swift // WXKDarkSky // // © 2020; MIT License. // // Please see the included LICENSE file for details. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif /** The DarkSkyRequest class contains some networking utilities for working with the Dark Sky API. - warning: Do **not** use this to make client-side requests directly to the Dark Sky API! This can put your API key at risk of compromise, and leave you with no way to replace your API key should it become compromised. */ public final class DarkSkyRequest { /// Your Dark Sky API key. private var key: String /** Initializes the `DarkSkyRequest` object with the provided API key. - warning: Do **not** use this to make client-side requests directly to the Dark Sky API! This can put your API key at risk of compromise, and leave you with no way to replace your API key should it become compromised. - parameter key: The API key to use for requests originating from this instance. */ public init(key: String) { self.key = key } @available(*, unavailable, message: "Networking functionality has been removed and will not return data. Please use your own networking code to obtain data.") public func loadData(point: Point, time: Date? = nil, options: Options = Options.defaults, completionHandler: @escaping (DarkSkyResponse?, Error?) -> Void) { completionHandler(nil, DarkSkyError.removedNetworkingFunctionality) } /** Builds a URL for a Dark Sky API request. - warning: Do **not** use this to make client-side requests directly to the Dark Sky API! This can put your API key at risk of compromise, and leave you with no way to replace your API key should it become compromised. - parameter key: The API key to use for the request. - parameter point: A latitude-longitude pair for the request. - parameter time: If present, the time for a Time Machine request before or after the current time. - parameter options: Options to use for the request. - returns: If a URL can be created, returns a `URL`. If not, returns nil. */ public func buildURL(point: Point, time: Date? = nil, options: Options = Options.defaults) -> URL? { /// String describing the requested latitude-longitude pair. let coordinates = String(describing: point) // Build a URL to query. var components = URLComponents() components.scheme = "https" components.host = "api.darksky.net" if let time = time { // If this is a Time Machine request, modify the path to include a time. let unixTime = String(describing: time.unixTime) components.path = "/forecast/\(key)/\(coordinates),\(unixTime)" } else { // If no time was given, assume that we're getting the current data. components.path = "/forecast/\(key)/\(coordinates)" } switch options { case Options.defaults: break default: // If any of the options differ from the defaults, build a query string. components.queryItems = [] // Now, from the options, build a query string. // If data blocks are to be excluded, exclude them. if options.exclude != Options.defaults.exclude { // We have to have a roundabout way of getting the exclusion list here. var excludeBlocks: [String] = [] for block in options.exclude { excludeBlocks.append(String(describing: block)) } // Here, we probably have a string like '["currently", "alerts", "flags"]', which is not good for a URL. let excludeList = String(describing: excludeBlocks).replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "") // After getting a string like "currently,alerts,flags" we can create a query item. let excludeQuery = URLQueryItem(name: "exclude", value: excludeList) components.queryItems?.append(excludeQuery) } // If the language is something other than the default, add a language query item. if options.language != Options.defaults.language { let languageQuery = URLQueryItem(name: "lang", value: String(describing: options.language)) components.queryItems?.append(languageQuery) } // If the units are something other than the default, add a units query item. if options.units != Options.defaults.units { let unitsQuery = URLQueryItem(name: "units", value: String(describing: options.units)) components.queryItems?.append(unitsQuery) } // If the "extend hourly" option differs from the default, add "extend=hourly". if options.extendHourly != Options.defaults.extendHourly { let extendQuery = URLQueryItem(name: "extend", value: "hourly") components.queryItems?.append(extendQuery) } } return components.url } }
mit
a5f2bf7fde0292ba0bfa366e862273ee
46.774775
228
0.641901
4.743292
false
false
false
false
roecrew/AudioKit
AudioKit/Common/MIDI/Enums/AKMIDIStatus.swift
3
2119
// // AKMIDIStatus.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // /// Potential MIDI Status messages /// /// - NoteOff: /// something resembling a keyboard key release /// - NoteOn: /// triggered when a new note is created, or a keyboard key press /// - PolyphonicAftertouch: /// rare MIDI control on controllers in which every key has separate touch sensing /// - ControllerChange: /// wide range of control types including volume, expression, modulation /// and a host of unnamed controllers with numbers /// - ProgramChange: /// messages are associated with changing the basic character of the sound preset /// - ChannelAftertouch: /// single aftertouch for all notes on a given channel (most common aftertouch type in keyboards) /// - PitchWheel: /// common keyboard control that allow for a pitch to be bent up or down a given number of semitones /// - SystemCommand: /// differ from system to system /// public enum AKMIDIStatus: Int { /// Note off is something resembling a keyboard key release case NoteOff = 8 /// Note on is triggered when a new note is created, or a keyboard key press case NoteOn = 9 /// Polyphonic aftertouch is a rare MIDI control on controllers in which /// every key has separate touch sensing case PolyphonicAftertouch = 10 /// Controller changes represent a wide range of control types including volume, /// expression, modulation and a host of unnamed controllers with numbers case ControllerChange = 11 /// Program change messages are associated with changing the basic character of the sound preset case ProgramChange = 12 /// A single aftertouch for all notes on a given channel /// (most common aftertouch type in keyboards) case ChannelAftertouch = 13 /// A pitch wheel is a common keyboard control that allow for a pitch to be /// bent up or down a given number of semitones case PitchWheel = 14 /// System commands differ from system to system case SystemCommand = 15 }
mit
d13dc0fe3ef2205b9d54ce756ddfdadd
40.54902
103
0.714353
4.675497
false
false
false
false
TruckMuncher/TruckMuncher-iOS
TruckMuncher/api/RString.swift
1
635
// // RString.swift // TruckMuncher // // Created by Josh Ault on 10/28/14. // Copyright (c) 2014 TruckMuncher. All rights reserved. // import UIKit import Realm class RString: RLMObject { dynamic var value = "" class func initFromString(string: String) -> RString { let rstring = RString() rstring.value = string return rstring } override func isEqual(object: AnyObject?) -> Bool { if let object = object as? RString { return value == object.value } return false } override var hash: Int { return value.hashValue } }
gpl-2.0
3b9d5e2cdc023c72c91abc44068d1439
19.483871
58
0.590551
4.233333
false
false
false
false
yoller/HanekeSwift
HanekeTests/UIImage+HanekeTests.swift
1
7275
// // UIImage+HanekeTests.swift // Haneke // // Created by Hermes Pique on 8/10/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit import XCTest import ImageIO import MobileCoreServices @testable import Haneke enum ExifOrientation : UInt32 { case Up = 1 case Down = 3 case Left = 8 case Right = 6 case UpMirrored = 2 case DownMirrored = 4 case LeftMirrored = 5 case RightMirrored = 7 } class UIImage_HanekeTests: XCTestCase { func testHasAlphaTrue() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSize(width: 1, height: 1), false) XCTAssertTrue(image.hnk_hasAlpha()) } func testHasAlphaFalse() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSize(width: 1, height: 1), true) XCTAssertFalse(image.hnk_hasAlpha()) } func testDataPNG() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSize(width: 1, height: 1), false) let expectedData = UIImagePNGRepresentation(image) let data = image.hnk_data() XCTAssertEqual(data!, expectedData) } func testDataJPEG() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSize(width: 1, height: 1), true) let expectedData = UIImageJPEGRepresentation(image, 1) let data = image.hnk_data() XCTAssertEqual(data!, expectedData) } func testDataNil() { let image = UIImage() XCTAssertNil(image.hnk_data()) } func testDecompressedImage_UIGraphicsContext_Opaque() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSizeMake(10, 10)) let decompressedImage = image.hnk_decompressedImage() XCTAssertNotEqual(image, decompressedImage) XCTAssertTrue(decompressedImage.isEqualPixelByPixel(image)) } func testDecompressedImage_UIGraphicsContext_NotOpaque() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSizeMake(10, 10), false) let decompressedImage = image.hnk_decompressedImage() XCTAssertNotEqual(image, decompressedImage) XCTAssertTrue(decompressedImage.isEqualPixelByPixel(image)) } func testDecompressedImage_RGBA() { let color = UIColor(red:255, green:0, blue:0, alpha:0.5) self._testDecompressedImageUsingColor(color, alphaInfo: .PremultipliedLast) } func testDecompressedImage_ARGB() { let color = UIColor(red:255, green:0, blue:0, alpha:0.5) self._testDecompressedImageUsingColor(color, alphaInfo: .PremultipliedFirst) } func testDecompressedImage_RGBX() { self._testDecompressedImageUsingColor(alphaInfo: .NoneSkipLast) } func testDecompressedImage_XRGB() { self._testDecompressedImageUsingColor(alphaInfo: .NoneSkipFirst) } func testDecompressedImage_Gray_AlphaNone() { let color = UIColor.grayColor() let colorSpaceRef = CGColorSpaceCreateDeviceGray() self._testDecompressedImageUsingColor(color, colorSpace: colorSpaceRef, alphaInfo: .None) } func testDecompressedImage_OrientationUp() { self._testDecompressedImageWithOrientation(.Up) } func testDecompressedImage_OrientationDown() { self._testDecompressedImageWithOrientation(.Down) } func testDecompressedImage_OrientationLeft() { self._testDecompressedImageWithOrientation(.Left) } func testDecompressedImage_OrientationRight() { self._testDecompressedImageWithOrientation(.Right) } func testDecompressedImage_OrientationUpMirrored() { self._testDecompressedImageWithOrientation(.UpMirrored) } func testDecompressedImage_OrientationDownMirrored() { self._testDecompressedImageWithOrientation(.DownMirrored) } func testDecompressedImage_OrientationLeftMirrored() { self._testDecompressedImageWithOrientation(.LeftMirrored) } func testDecompressedImage_OrientationRightMirrored() { self._testDecompressedImageWithOrientation(.RightMirrored) } func testDataCompressionQuality() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSizeMake(10, 10)) let data = image.hnk_data() let notExpectedData = image.hnk_data(compressionQuality: 0.5) XCTAssertNotEqual(data, notExpectedData) } func testDataCompressionQuality_LessThan0() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSizeMake(10, 10)) let data = image.hnk_data(compressionQuality: -1.0) let expectedData = image.hnk_data(compressionQuality: 0.0) XCTAssertEqual(data, expectedData, "The min compression quality is 0.0") } func testDataCompressionQuality_MoreThan1() { let image = UIImage.imageWithColor(UIColor.redColor(), CGSizeMake(10, 10)) let data = image.hnk_data(compressionQuality: 10.0) let expectedData = image.hnk_data(compressionQuality: 1.0) XCTAssertEqual(data, expectedData, "The min compression quality is 1.0") } // MARK: Helpers func _testDecompressedImageUsingColor(color : UIColor = UIColor.greenColor(), colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB(), alphaInfo :CGImageAlphaInfo, bitsPerComponent : size_t = 8) { let size = CGSizeMake(10, 20) // Using rectangle to check if image is rotated let bitmapInfo = CGBitmapInfo.ByteOrderDefault.rawValue | alphaInfo.rawValue let context = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), bitsPerComponent, 0, colorSpace, bitmapInfo) CGContextSetFillColorWithColor(context!, color.CGColor) CGContextFillRect(context!, CGRectMake(0, 0, size.width, size.height)) let imageRef = CGBitmapContextCreateImage(context!)! let image = UIImage(CGImage: imageRef, scale:UIScreen.mainScreen().scale, orientation:.Up) let decompressedImage = image.hnk_decompressedImage() XCTAssertNotEqual(image, decompressedImage) XCTAssertTrue(decompressedImage.isEqualPixelByPixel(image), self.name!) } func _testDecompressedImageWithOrientation(orientation : ExifOrientation) { // Create a gradient image to truly test orientation let gradientImage = UIImage.imageGradientFromColor() // Use TIFF because PNG doesn't store EXIF orientation let exifProperties = NSDictionary(dictionary: [kCGImagePropertyOrientation: Int(orientation.rawValue)]) let data = NSMutableData() let imageDestinationRef = CGImageDestinationCreateWithData(data as CFMutableDataRef, kUTTypeTIFF, 1, nil)! CGImageDestinationAddImage(imageDestinationRef, gradientImage.CGImage!, exifProperties as CFDictionaryRef) CGImageDestinationFinalize(imageDestinationRef) let image = UIImage(data:data, scale:UIScreen.mainScreen().scale)! let decompressedImage = image.hnk_decompressedImage() XCTAssertNotEqual(image, decompressedImage) XCTAssertTrue(decompressedImage.isEqualPixelByPixel(image), self.name!) } }
apache-2.0
32b417b96e7655226eb8f09597fc64fe
35.928934
204
0.68646
5.32967
false
true
false
false
serbomjack/Firefox-for-windows-10-mobile
Client/Frontend/Settings/SettingsTableViewController.swift
1
44868
/* 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 Account import Base32 import Shared import UIKit import XCGLogger private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // The following are only here because we use master for L10N and otherwise these strings would disappear from the v1.0 release private let Bug1204635_S1 = NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") private let Bug1204635_S2 = NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") private let Bug1204635_S3 = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog") private let Bug1204635_S4 = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog") // A base TableViewCell, to help minimize initialization and allow recycling. class SettingsTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) indentationWidth = 0 layoutMargins = UIEdgeInsetsZero // So that the seperator line goes all the way to the left edge. separatorInset = UIEdgeInsetsZero } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // A base setting class that shows a title. You probably want to subclass this, not use it directly. class Setting { private var _title: NSAttributedString? // The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy. var url: NSURL? { return nil } // The title shown on the pref. var title: NSAttributedString? { return _title } // An optional second line of text shown on the pref. var status: NSAttributedString? { return nil } // Whether or not to show this pref. var hidden: Bool { return false } var style: UITableViewCellStyle { return .Subtitle } var accessoryType: UITableViewCellAccessoryType { return .None } // Called when the cell is setup. Call if you need the default behaviour. func onConfigureCell(cell: UITableViewCell) { cell.detailTextLabel?.attributedText = status cell.textLabel?.attributedText = title cell.accessoryType = accessoryType cell.accessoryView = nil } // Called when the pref is tapped. func onClick(navigationController: UINavigationController?) { return } // Helper method to set up and push a SettingsContentViewController func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) { if let url = self.url { let viewController = SettingsContentViewController() viewController.settingsTitle = self.title viewController.url = url navigationController?.pushViewController(viewController, animated: true) } } init(title: NSAttributedString? = nil) { self._title = title } } // A setting in the sections panel. Contains a sublist of Settings class SettingSection : Setting { private let children: [Setting] init(title: NSAttributedString? = nil, children: [Setting]) { self.children = children super.init(title: title) } var count: Int { var count = 0 for setting in children { if !setting.hidden { count++ } } return count } subscript(val: Int) -> Setting? { var i = 0 for setting in children { if !setting.hidden { if i == val { return setting } i++ } } return nil } } // A helper class for settings with a UISwitch. // Takes and optional settingsDidChange callback and status text. class BoolSetting: Setting { private let prefKey: String private let prefs: Prefs private let defaultValue: Bool private let settingDidChange: ((Bool) -> Void)? private let statusText: String? init(prefs: Prefs, prefKey: String, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) { self.prefs = prefs self.prefKey = prefKey self.defaultValue = defaultValue self.settingDidChange = settingDidChange self.statusText = statusText super.init(title: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var status: NSAttributedString? { if let text = statusText { return NSAttributedString(string: text, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } else { return nil } } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged) control.on = prefs.boolForKey(prefKey) ?? defaultValue cell.accessoryView = control } @objc func switchValueChanged(control: UISwitch) { prefs.setBool(control.on, forKey: prefKey) settingDidChange?(control.on) } } // A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to // the fxAccount happen. private class AccountSetting: Setting, FxAContentViewControllerDelegate { unowned var settings: SettingsTableViewController var profile: Profile { return settings.profile } override var title: NSAttributedString? { return nil } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } private override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) if settings.profile.getAccount() != nil { cell.selectionStyle = .None } } override var accessoryType: UITableViewCellAccessoryType { return .None } func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void { 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 account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)! settings.profile.setAccount(account) // Reload the data to reflect the new Account immediately. settings.tableView.reloadData() // And start advancing the Account state in the background as well. settings.SELrefresh() settings.navigationController?.popToRootViewControllerAnimated(true) } func contentViewControllerDidCancel(viewController: FxAContentViewController) { NSLog("didCancel") settings.navigationController?.popToRootViewControllerAnimated(true) } } private class WithAccountSetting: AccountSetting { override var hidden: Bool { return !profile.hasAccount() } } private class WithoutAccountSetting: AccountSetting { override var hidden: Bool { return profile.hasAccount() } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. private class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Sign In", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self viewController.url = settings.profile.accountConfiguration.signInURL navigationController?.pushViewController(viewController, animated: true) } } // Sync setting for disconnecting a Firefox Account. Shown when we have an account. private class DisconnectSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .None } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed]) } override func onClick(navigationController: UINavigationController?) { let alertController = UIAlertController( title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"), message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"), preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in // Do nothing. }) alertController.addAction( UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in self.settings.profile.removeAccount() // Refresh, to show that we no longer have an Account immediately. self.settings.SELrefresh() }) navigationController?.presentViewController(alertController, animated: true, completion: nil) } } private class SyncNowSetting: WithAccountSetting { private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFont]) private let syncingTitle = NSAttributedString(string: NSLocalizedString("Syncing…", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFontWeightRegular)]) override var accessoryType: UITableViewCellAccessoryType { return .None } override var style: UITableViewCellStyle { return .Value1 } override var title: NSAttributedString? { return profile.syncManager.isSyncing ? syncingTitle : syncNowTitle } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let label = NSLocalizedString("Last synced: %@", comment: "Last synced time label beside Sync Now setting option. Argument is the relative date string.") let formattedLabel = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString()) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12, weight: UIFontWeightRegular)] let range = NSMakeRange(0, attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override func onConfigureCell(cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.detailTextLabel?.attributedText = status cell.accessoryType = accessoryType cell.accessoryView = nil cell.userInteractionEnabled = !profile.syncManager.isSyncing } override func onClick(navigationController: UINavigationController?) { profile.syncManager.syncEverything() } } // Sync setting that shows the current Firefox Account status. private class AccountStatusSetting: WithAccountSetting { override var accessoryType: UITableViewCellAccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: // We link to the resend verification email page. return .DisclosureIndicator case .NeedsPassword: // We link to the re-enter password page. return .DisclosureIndicator case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return .None } } return .DisclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { switch account.actionNeeded { case .None: return nil case .NeedsVerification: return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) case .NeedsPassword: let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res case .NeedsUpgrade: let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view") let range = NSRange(location: 0, length: string.characters.count) let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1) let attrs = [NSForegroundColorAttributeName : orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } } return nil } override func onClick(navigationController: UINavigationController?) { let viewController = FxAContentViewController() viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .NeedsVerification: let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .NeedsPassword: let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email)) viewController.url = cs?.URL case .None, .NeedsUpgrade: // In future, we'll want to link to /settings and an upgrade page, respectively. return } } navigationController?.pushViewController(viewController, animated: true) } } // For great debugging! private class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! private class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! private class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } // For great debugging! private class HiddenSetting: Setting { let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } extension NSFileManager { public func removeItemInDirectory(directory: String, named: String) throws { if let file = NSURL.fileURLWithPath(directory).URLByAppendingPathComponent(named).path { try self.removeItemAtPath(file) } } } private class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let fileManager = NSFileManager.defaultManager() do { let files = try fileManager.contentsOfDirectoryAtPath(documentsPath) for file in files { if file.startsWith("browser.") || file.startsWith("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } private class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override func onClick(navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.startsWith("browser.") || file.startsWith("logins.") } } catch { print("Couldn't export browser data: \(error).") } } } // Show the current version of Firefox private class VersionSetting : Setting { let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } private override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .None } override func onClick(navigationController: UINavigationController?) { if AppConstants.BuildChannel != .Aurora { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } } } // Opens the the license page in a new tab private class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller private class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } private override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again private class ShowIntroductionSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } private class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Show an input.mozilla.org page where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the the SUMO page in a new tab private class OpenSupportPageSetting: Setting { init() { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { navigationController?.dismissViewControllerAnimated(true, completion: { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { let rootNavigationController = appDelegate.rootViewController rootNavigationController.popViewControllerAnimated(true) if let url = NSURL(string: "https://support.mozilla.org/products/ios") { appDelegate.browserViewController.openURLInNewTab(url) } } }) } } // Opens the search settings pane private class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } override var style: UITableViewCellStyle { return .Value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines navigationController?.pushViewController(viewController, animated: true) } } private class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let loginsTitle = NSLocalizedString("Logins", comment: "Label used as an item in Settings. When touched, the user will be navigated to the Logins/Password manager.") super.init(title: NSAttributedString(string: loginsTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = LoginListViewController(profile: profile) navigationController?.pushViewController(viewController, animated: true) } } private class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.") super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } private class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: NSURL? { return NSURL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } private class ChinaSyncServiceSetting: WithoutAccountSetting { override var accessoryType: UITableViewCellAccessoryType { return .None } var prefs: Prefs { return settings.profile.prefs } let prefKey = "useChinaSyncService" override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var status: NSAttributedString? { return NSAttributedString(string: "本地服务使用火狐通行证同步数据", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } override func onConfigureCell(cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged) control.on = prefs.boolForKey(prefKey) ?? true cell.accessoryView = control cell.selectionStyle = .None } @objc func switchValueChanged(toggle: UISwitch) { prefs.setObject(toggle.on, forKey: prefKey) } } // The base settings view controller. class SettingsTableViewController: UITableViewController { private let Identifier = "CellIdentifier" private let SectionHeaderIdentifier = "SectionHeaderIdentifier" private var settings = [SettingSection]() var profile: Profile! var tabManager: TabManager! override func viewDidLoad() { super.viewDidLoad() let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title") let accountDebugSettings: [Setting] if AppConstants.BuildChannel != .Aurora { accountDebugSettings = [ // Debug settings: RequirePasswordDebugSetting(settings: self), RequireUpgradeDebugSetting(settings: self), ForgetSyncAuthStateDebugSetting(settings: self), ] } else { accountDebugSettings = [] } let prefs = profile.prefs var generalSettings = [ SearchSetting(settings: self), BoolSetting(prefs: prefs, prefKey: "blockPopups", defaultValue: true, titleText: NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")), BoolSetting(prefs: prefs, prefKey: "saveLogins", defaultValue: true, titleText: NSLocalizedString("Save Logins", comment: "Setting to enable the built-in password manager")), ] let accountChinaSyncSetting: [Setting] let locale = NSLocale.currentLocale() if locale.localeIdentifier != "zh_CN" { accountChinaSyncSetting = [] } else { // Set the value of "useChinaSyncService" prefs.setObject(true, forKey: "useChinaSyncService") accountChinaSyncSetting = [ // Show China sync service setting: ChinaSyncServiceSetting(settings: self) ] } // There is nothing to show in the Customize section if we don't include the compact tab layout // setting on iPad. When more options are added that work on both device types, this logic can // be changed. if UIDevice.currentDevice().userInterfaceIdiom == .Phone { generalSettings += [ BoolSetting(prefs: prefs, prefKey: "CompactTabLayout", defaultValue: true, titleText: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview")) ] } settings += [ SettingSection(title: nil, children: [ // Without a Firefox Account: ConnectSetting(settings: self), // With a Firefox Account: AccountStatusSetting(settings: self), SyncNowSetting(settings: self) ] + accountChinaSyncSetting + accountDebugSettings), SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings) ] var privacySettings: [Setting] = [LoginsSetting(settings: self), ClearPrivateDataSetting(settings: self)] if #available(iOS 9, *) { privacySettings += [ BoolSetting(prefs: prefs, prefKey: "settings.closePrivateTabs", defaultValue: false, titleText: NSLocalizedString("Close Private Tabs", tableName: "PrivateBrowsing", comment: "Setting for closing private tabs"), statusText: NSLocalizedString("When Leaving Private Browsing", tableName: "PrivateBrowsing", comment: "Will be displayed in Settings under 'Close Private Tabs'")) ] } privacySettings += [ BoolSetting(prefs: prefs, prefKey: "crashreports.send.always", defaultValue: false, titleText: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"), settingDidChange: { configureActiveCrashReporter($0) }), PrivacyPolicySetting() ] settings += [ SettingSection(title: NSAttributedString(string: privacyTitle), children: privacySettings), SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [ ShowIntroductionSetting(settings: self), SendFeedbackSetting(), OpenSupportPageSetting() ]), SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [ VersionSetting(settings: self), LicenseAndAcknowledgementsSetting(), YourRightsSetting(), DisconnectSetting(settings: self), ExportBrowserDataSetting(settings: self), DeleteExportedDataSetting(settings: self), ]) ] navigationItem.title = NSLocalizedString("Settings", comment: "Settings") navigationItem.leftBarButtonItem = UIBarButtonItem( title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"), style: UIBarButtonItemStyle.Done, target: navigationController, action: "SELdone") tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier) tableView.registerClass(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier) tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128)) tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: NotificationProfileDidStartSyncing, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELsyncDidChangeState", name: NotificationProfileDidFinishSyncing, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) SELrefresh() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidStartSyncing, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) } @objc private func SELsyncDidChangeState() { dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } @objc private func SELrefresh() { // Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app. if let account = self.profile.getAccount() { account.advance().upon { _ in dispatch_async(dispatch_get_main_queue()) { () -> Void in self.tableView.reloadData() } } } else { self.tableView.reloadData() } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let section = settings[indexPath.section] if let setting = section[indexPath.row] { var cell: UITableViewCell! if let _ = setting.status { // Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell. // I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account. // Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it. cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil) } else { cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) } setting.onConfigureCell(cell) return cell } return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return settings.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = settings[section] return section.count } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView let sectionSetting = settings[section] if let sectionTitle = sectionSetting.title?.string { headerView.titleLabel.text = sectionTitle } // Hide the top border for the top section to avoid having a double line at the top if section == 0 { headerView.showTopBorder = false } else { headerView.showTopBorder = true } return headerView } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // empty headers should be 13px high, but headers with text should be 44 var height: CGFloat = 13 let section = settings[section] if let sectionTitle = section.title { if sectionTitle.length > 0 { height = 44 } } return height } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { let section = settings[indexPath.section] if let setting = section[indexPath.row] { setting.onClick(navigationController) } return nil } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { //make account/sign-in and close private tabs rows taller, as per design specs if indexPath.section == 0 && indexPath.row == 0 { return 64 } if #available(iOS 9, *) { if indexPath.section == 2 && indexPath.row == 2 { return 64 } } return 44 } } class SettingsTableFooterView: UIView { var logo: UIImageView = { var image = UIImageView(image: UIImage(named: "settingsFlatfox")) image.contentMode = UIViewContentMode.Center return image }() private lazy var topBorder: CALayer = { let topBorder = CALayer() topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor return topBorder }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIConstants.TableViewHeaderBackgroundColor layer.addSublayer(topBorder) addSubview(logo) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5) logo.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2) } } class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView { var showTopBorder: Bool = true { didSet { topBorder.hidden = !showTopBorder } } var showBottomBorder: Bool = true { didSet { bottomBorder.hidden = !showBottomBorder } } var titleLabel: UILabel = { var headerLabel = UILabel() var frame = headerLabel.frame frame.origin.x = 15 frame.origin.y = 25 headerLabel.frame = frame headerLabel.textColor = UIConstants.TableViewHeaderTextColor headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular) return headerLabel }() private lazy var topBorder: CALayer = { let topBorder = CALayer() topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor return topBorder }() private lazy var bottomBorder: CALayer = { let bottomBorder = CALayer() bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor return bottomBorder }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor addSubview(titleLabel) clipsToBounds = true layer.addSublayer(topBorder) layer.addSublayer(bottomBorder) } override func prepareForReuse() { super.prepareForReuse() showTopBorder = true showBottomBorder = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() bottomBorder.frame = CGRectMake(0.0, frame.size.height - 0.5, frame.size.width, 0.5) topBorder.frame = CGRectMake(0.0, 0.0, frame.size.width, 0.5) titleLabel.sizeToFit() } }
mpl-2.0
1b77fe89180bbc50baac1f4278656ba5
41.728313
323
0.685846
5.770825
false
false
false
false
insidegui/WWDC
WWDC/AppCoordinator+Bookmarks.swift
1
2427
// // AppCoordinator+Bookmarks.swift // WWDC // // Created by Guilherme Rambo on 20/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import AVFoundation import PlayerUI import RxSwift import RxCocoa import RealmSwift import RxRealm import ConfCore extension AppCoordinator: PUITimelineDelegate, VideoPlayerViewControllerDelegate { func createBookmark(at timecode: Double, with snapshot: NSImage?) { guard let session = currentPlayerController?.sessionViewModel.session else { return } storage.modify(session) { bgSession in let bookmark = Bookmark() bookmark.timecode = timecode bookmark.snapshot = snapshot?.compressedJPEGRepresentation ?? Data() bgSession.bookmarks.append(bookmark) } // TODO: begin editing new bookmark } func createFavorite() { guard let session = currentPlayerController?.sessionViewModel.session else { return } storage.setFavorite(true, onSessionsWithIDs: [session.identifier]) } func viewControllerForTimelineAnnotation(_ annotation: PUITimelineAnnotation) -> NSViewController? { guard let bookmark = annotation as? Bookmark else { return nil } return BookmarkViewController(bookmark: bookmark, storage: storage) } func timelineDidHighlightAnnotation(_ annotation: PUITimelineAnnotation?) { } func timelineDidSelectAnnotation(_ annotation: PUITimelineAnnotation?) { guard let annotation = annotation else { return } currentPlayerController?.playerView.seek(to: annotation) } func timelineCanDeleteAnnotation(_ annotation: PUITimelineAnnotation) -> Bool { return true } func timelineCanMoveAnnotation(_ annotation: PUITimelineAnnotation) -> Bool { return true } func timelineDidMoveAnnotation(_ annotation: PUITimelineAnnotation, to timestamp: Double) { storage.moveBookmark(with: annotation.identifier, to: timestamp) } func timelineDidDeleteAnnotation(_ annotation: PUITimelineAnnotation) { storage.softDeleteBookmark(with: annotation.identifier) } } extension Bookmark: PUITimelineAnnotation { public var isEmpty: Bool { return body.isEmpty } public var timestamp: Double { return timecode } public var isValid: Bool { return !isInvalidated && !isDeleted } }
bsd-2-clause
16fc8304dc32aa4def9c7894ae0f8bd0
26.568182
104
0.705688
5.273913
false
false
false
false
weareyipyip/SwiftStylable
Sources/SwiftStylable/Classes/Style/Stylers/TableViewSeparatorStyler.swift
1
1393
// // ButtonStyleSet.swift // SwiftStylable // // Created by Marcel Bloemendaal on 17/04/2018. // import Foundation class TableViewSeparatorStyler : Styler { private weak var _view: TableViewSeparatorStylable? // ----------------------------------------------------------------------------------------------------------------------- // // MARK: Initializers // // ----------------------------------------------------------------------------------------------------------------------- init(_ view: TableViewSeparatorStylable) { self._view = view } // ----------------------------------------------------------------------------------------------------------------------- // // MARK: Public methods // // ----------------------------------------------------------------------------------------------------------------------- open func applyStyle(_ style:Style) { guard let view = self._view else { return } if let tableViewSeparatorStyle = style.tableViewSeparatorStyle.tableViewSeparatorStyle { view.separatorStyle = tableViewSeparatorStyle } if let tableViewSeparatorColor = style.tableViewSeparatorStyle.tableViewSeparatorColor { view.separatorColor = tableViewSeparatorColor } } }
mit
ae02bcd1019a2dc78219de8337a85323
29.955556
126
0.387653
7.738889
false
false
false
false
Johennes/firefox-ios
Sync/Synchronizers/IndependentRecordSynchronizer.swift
1
4049
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger import Deferred private let log = Logger.syncLogger class Uploader { /** * Upload just about anything that can be turned into something we can upload. */ func sequentialPosts<T>(items: [T], by: Int, lastTimestamp: Timestamp, storageOp: ([T], Timestamp) -> DeferredTimestamp) -> DeferredTimestamp { // This needs to be a real Array, not an ArraySlice, // for the types to line up. let chunks = chunk(items, by: by).map { Array($0) } let start = deferMaybe(lastTimestamp) let perChunk: ([T], Timestamp) -> DeferredTimestamp = { (records, timestamp) in // TODO: detect interruptions -- clients uploading records during our sync -- // by using ifUnmodifiedSince. We can detect uploaded records since our download // (chain the download timestamp into this function), and we can detect uploads // that race with our own (chain download timestamps across 'walk' steps). // If we do that, we can also advance our last fetch timestamp after each chunk. log.debug("Uploading \(records.count) records.") return storageOp(records, timestamp) } return walk(chunks, start: start, f: perChunk) } } public class IndependentRecordSynchronizer: TimestampedSingleCollectionSynchronizer { /** * Just like the usual applyIncomingToStorage, but doesn't fast-forward the timestamp. */ func applyIncomingRecords<T>(records: [T], apply: T -> Success) -> Success { if records.isEmpty { log.debug("No records; done applying.") return succeed() } return walk(records, f: apply) } func applyIncomingToStorage<T>(records: [T], fetched: Timestamp, apply: T -> Success) -> Success { func done() -> Success { log.debug("Bumping fetch timestamp to \(fetched).") self.lastFetched = fetched return succeed() } if records.isEmpty { log.debug("No records; done applying.") return done() } return walk(records, f: apply) >>> done } } extension TimestampedSingleCollectionSynchronizer { /** * On each chunk that we upload, we pass along the server modified timestamp to the next, * chained through the provided `onUpload` function. * * The last chunk passes this modified timestamp out, and we assign it to lastFetched. * * The idea of this is twofold: * * 1. It does the fast-forwarding that every other Sync client does. * * 2. It allows us to (eventually) pass the last collection modified time as If-Unmodified-Since * on each upload batch, as we do between the download and the upload phase. * This alone allows us to detect conflicts from racing clients. * * In order to implement the latter, we'd need to chain the date from getSince in place of the * 0 in the call to uploadOutgoingFromStorage in each synchronizer. */ func uploadRecords<T>(records: [Record<T>], lastTimestamp: Timestamp, storageClient: Sync15CollectionClient<T>, onUpload: (POSTResult, Timestamp?) -> DeferredTimestamp) -> DeferredTimestamp { if records.isEmpty { log.debug("No modified records to upload.") return deferMaybe(lastTimestamp) } let batch = storageClient.newBatch(ifUnmodifiedSince: (lastTimestamp == 0) ? nil : lastTimestamp, onCollectionUploaded: onUpload) return batch.addRecords(records) >>> batch.endBatch >>> { let timestamp = batch.ifUnmodifiedSince ?? lastTimestamp self.setTimestamp(timestamp) return deferMaybe(timestamp) } } }
mpl-2.0
7acacb24a2c196b4fbf4361688cd9d54
39.09901
195
0.645345
4.786052
false
false
false
false
apple/swift-driver
Sources/swift-help/main.swift
1
5197
//===--------------- main.swift - Swift Help Main Entrypoint --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftOptions import ArgumentParser import enum TSCBasic.ProcessEnv import func TSCBasic.exec import class TSCBasic.Process import var TSCBasic.localFileSystem enum HelpTopic: ExpressibleByArgument, CustomStringConvertible { case driver(DriverKind) case subcommand(Subcommand) case intro init?(argument topicName: String) { if let kind = DriverKind(rawValue: topicName) { self = .driver(kind) } else if let subcommand = Subcommand(rawValue: topicName) { self = .subcommand(subcommand) } else if topicName == "intro" { self = .intro } else { return nil } } var description: String { switch self { case .driver(let kind): return kind.rawValue case .subcommand(let command): return command.rawValue case .intro: return "intro" } } } enum Subcommand: String, CaseIterable { case build, package, packageRegistry = "package-registry", packageCollection = "package-collection", run, test var description: String { switch self { case .build: return "Build Swift packages" case .package: return "Create and work on packages" case .packageRegistry: return "Interact with package registry and manage related configuration" case .packageCollection: return "Interact with package collections" case .run: return "Run a program from a package" case .test: return "Run package tests" } } } struct SwiftHelp: ParsableCommand { @Argument(help: "The topic to display help for.") var topic: HelpTopic = .driver(.interactive) @Argument(help: "The help subtopics, if applicable.") var subtopics: [String] = [] @Flag(name: .customLong("show-hidden", withSingleDash: true), help: "List hidden (unsupported) options") var showHidden: Bool = false enum Color256: CustomStringConvertible { case reset case color(foreground: UInt8?, background: UInt8?) var description: String { switch self { case .reset: return "\u{001B}[0m" case let .color(foreground, background): let foreground = foreground.map { "\u{001B}[38;5;\($0)m" } ?? "" let background = background.map { "\u{001B}[48;5;\($0)m" } ?? "" return foreground + background } } } func printIntro() { let is256Color = ProcessEnv.vars["TERM"] == "xterm-256color" let orangeRed = is256Color ? "\u{001b}[1;38;5;196m" : "" let plain = is256Color ? "\u{001b}[0m" : "" let plainBold = is256Color ? "\u{001b}[1m" : "" print(""" \(orangeRed)Welcome to Swift!\(plain) \(plainBold)Subcommands:\(plain) """) let maxSubcommandNameLength = Subcommand.allCases.map { $0.rawValue.count }.max()! for command in Subcommand.allCases { let padding = String(repeating: " ", count: maxSubcommandNameLength - command.rawValue.count) print(" \(plainBold)swift \(command.rawValue)\(plain)\(padding) \(command.description)") } // `repl` not included in `Subcommand`, also print it here. do { let padding = String(repeating: " ", count: maxSubcommandNameLength - "repl".count) print(" \(plainBold)swift repl\(plain)\(padding) Experiment with Swift code interactively") } print("\n Use \(plainBold)`swift --help`\(plain) for descriptions of available options and flags.") print("\n Use \(plainBold)`swift help <subcommand>`\(plain) for more information about a subcommand.") print() } func run() throws { let driverOptionTable = OptionTable() switch topic { case .driver(let kind): driverOptionTable.printHelp(driverKind: kind, includeHidden: showHidden) if kind == .interactive { printIntro() } case .subcommand(let subcommand): // Try to find the subcommand adjacent to the help tool. // If we didn't find the tool there, let the OS search for it. let execName = "swift-\(subcommand.rawValue)" let subcommandPath = Process.findExecutable( CommandLine.arguments[0])? .parentDirectory .appending(component: execName) ?? Process.findExecutable(execName) guard let path = subcommandPath, localFileSystem.isExecutableFile(subcommandPath!) else { fatalError("cannot find subcommand executable '\(execName)'") } // Execute the subcommand with --help. if subtopics.isEmpty { try exec(path: path.pathString, args: [execName, "--help"]) } else { try exec(path: path.pathString, args: [execName, "help"] + subtopics) } case .intro: printIntro() } } } // SwiftPM executables don't support @main. SwiftHelp.main()
apache-2.0
38f9b0541c4d68136a4e3678d426f74e
30.689024
112
0.645757
4.201293
false
false
false
false
alessandrostone/SwiftyStateMachine
StateMachine/GraphableStateMachineSchema.swift
2
5160
import Foundation /// A type, preferably an `enum`, representing states or events in /// a State Machine. Used by `GraphableStateMachineSchema` to create /// state machine graphs in the DOT graph description language [1]. /// /// Provides an array of items (states or events) used in a graph, and /// a textual representation of each item, used when assigning labels /// to graph elements. /// /// [1]: http://en.wikipedia.org/wiki/DOT_%28graph_description_language%29 public protocol DOTLabelable { /// A textual representation of `self`, suitable for creating labels /// in a graph. var DOTLabel: String { get } /// An array of items of a given type (states or events) used in a graph. static var DOTLabelableItems: [Self] { get } } /// A state machine schema with a graph of the state machine in the DOT graph /// description language [1]. /// /// Requires `State` and `Event` types to conform to the `DOTLabelable` /// protocol. /// /// The textual representation of a graph is accessible via the /// `DOTDigraph` property. On iOS, it can be saved to disk with /// the `saveDOTDigraphIfRunningInSimulator` method. /// /// For more information about state machine schemas, see /// `StateMachineSchemaType` documentation. /// /// [1]: http://en.wikipedia.org/wiki/DOT_%28graph_description_language%29 public struct GraphableStateMachineSchema<A: DOTLabelable, B: DOTLabelable, C>: StateMachineSchemaType { typealias State = A typealias Event = B typealias Subject = C public let initialState: State public let transitionLogic: (State, Event) -> (State, (Subject -> ())?)? public let DOTDigraph: String public init(initialState: State, transitionLogic: (State, Event) -> (State, (Subject -> ())?)?) { self.initialState = initialState self.transitionLogic = transitionLogic self.DOTDigraph = GraphableStateMachineSchema.DOTDigraphGivenInitialState(initialState, transitionLogic: transitionLogic) } #if os(OSX) // TODO: Figure out how to detect the "I'm running my Mac app from Xcode" // scenario. // // Verify if [`AmIBeingDebugged`][1] can be used here. In particular, // figure out if this means that an app will be rejected during App Review: // // > Important: Because the definition of the kinfo_proc structure // > (in <sys/sysctl.h>) is conditionalized by __APPLE_API_UNSTABLE, you // > should restrict use of the above code to the debug build of your // > program. // // [1]: https://developer.apple.com/library/mac/qa/qa1361/_index.html #else /// Save the textual graph representation from the `DOTDigraph` property /// to a file, preferably in a project directory, for documentation /// purposes. Works only when running in a simulator. /// /// The filepath of the graph file is relative to the filepath of the /// calling file, e.g. if you call this method from a file called /// `MyProject/InboxViewController.swift` and pass `"Inbox.dot"` as /// a filepath, the diagram will be saved as `MyProject/Inbox.dot`. /// /// Files in the DOT format [1] can be viewed in different applications, /// e.g. Graphviz [2]. /// /// [1]: https://developer.apple.com/library/mac/qa/qa1361/_index.html /// [2]: http://www.graphviz.org/ public func saveDOTDigraphIfRunningInSimulator(#filepathRelativeToCurrentFile: String, file: String = __FILE__) { if TARGET_IPHONE_SIMULATOR == 1 { let filepath = file.stringByDeletingLastPathComponent.stringByAppendingPathComponent(filepathRelativeToCurrentFile) DOTDigraph.writeToFile(filepath, atomically: true, encoding: NSUTF8StringEncoding, error: nil) } } #endif private static func DOTDigraphGivenInitialState(initialState: State, transitionLogic: (State, Event) -> (State, (Subject -> ())?)?) -> String { let states = State.DOTLabelableItems let events = Event.DOTLabelableItems var stateIndexesByLabel: [String: Int] = [:] for (i, state) in enumerate(states) { stateIndexesByLabel[label(state)] = i + 1 } func index(state: State) -> Int { return stateIndexesByLabel[label(state)]! } var digraph = "digraph {\n graph [rankdir=LR]\n\n 0 [label=\"\", shape=plaintext]\n 0 -> \(index(initialState)) [label=\"START\"]\n\n" for state in states { digraph += " \(index(state)) [label=\"\(label(state))\"]\n" } digraph += "\n" for fromState in states { for event in events { if let (toState, _) = transitionLogic(fromState, event) { digraph += " \(index(fromState)) -> \(index(toState)) [label=\"\(label(event))\"]\n" } } } digraph += "}" return digraph } } /// Helper function used when generating DOT digraph strings. private func label<T: DOTLabelable>(x: T) -> String { return x.DOTLabel.stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options: .LiteralSearch, range: nil) }
mit
cae9b2f1b41a5808c69fda1dfde999d9
39.3125
151
0.653488
4.253916
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIKitExtensions/UIScrollView+QMUI.swift
1
3802
// // UIScrollView+QMUI.swift // QMUI.swift // // Created by 伯驹 黄 on 2017/3/17. // Copyright © 2017年 伯驹 黄. All rights reserved. // extension UIScrollView: SelfAware2 { private static let _onceToken = UUID().uuidString static func awake2() { let clazz = UIScrollView.self DispatchQueue.once(token: _onceToken) { ReplaceMethod(clazz, #selector(description), #selector(qmui_description)) } } } extension UIScrollView { @objc func qmui_description() -> String { return qmui_description() + ", contentInset = \(contentInset)" } /// 判断UIScrollView是否已经处于顶部(当UIScrollView内容不够多不可滚动时,也认为是在顶部) var qmui_alreadyAtTop: Bool { if !qmui_canScroll { return true } if contentOffset.y == -qmui_contentInset.top { return true } return false } /// 判断UIScrollView是否已经处于底部(当UIScrollView内容不够多不可滚动时,也认为是在底部) var qmui_alreadyAtBottom: Bool { if !qmui_canScroll { return true } if contentOffset.y == contentSize.height + qmui_contentInset.bottom - bounds.height { return true } return false } /// UIScrollView 的真正 inset,在 iOS11 以后需要用到 adjustedContentInset 而在 iOS11 以前只需要用 contentInset var qmui_contentInset: UIEdgeInsets { if #available(iOS 11, *) { return adjustedContentInset } else { return contentInset } } /** * 判断当前的scrollView内容是否足够滚动 * @warning 避免与<i>scrollEnabled</i>混淆 */ @objc var qmui_canScroll: Bool { // 没有高度就不用算了,肯定不可滚动,这里只是做个保护 if bounds.size == .zero { return false } let canVerticalScroll = contentSize.height + qmui_contentInset.verticalValue > bounds.height let canHorizontalScoll = contentSize.width + qmui_contentInset.horizontalValue > bounds.width return canVerticalScroll || canHorizontalScoll } /** * 不管当前scrollView是否可滚动,直接将其滚动到最顶部 * @param force 是否无视qmui_canScroll而强制滚动 * @param animated 是否用动画表现 */ func qmui_scrollToTopForce(_ force: Bool, animated: Bool) { if force || (!force && qmui_canScroll) { setContentOffset(CGPoint(x: -qmui_contentInset.left, y: -qmui_contentInset.top), animated: animated) } } /** * 等同于qmui_scrollToTop(false, animated: animated) */ func qmui_scrollToTopAnimated(_ animated: Bool) { qmui_scrollToTopForce(false, animated: animated) } /// 等同于qmui_scrollToTop(false) func qmui_scrollToTop() { qmui_scrollToTopAnimated(false) } /** * 如果当前的scrollView可滚动,则将其滚动到最底部 * @param animated 是否用动画表现 * @see [UIScrollView qmui_canScroll] */ func qmui_scrollToBottomAnimated(_ animated: Bool) { if qmui_canScroll { setContentOffset(CGPoint(x: contentOffset.x, y: contentSize.height + qmui_contentInset.bottom - bounds.height), animated: animated) } } /// 等同于qmui_scrollToBottomAnimated(false) func qmui_scrollToBottom() { qmui_scrollToBottomAnimated(false) } // 立即停止滚动,用于那种手指已经离开屏幕但列表还在滚动的情况。 func qmui_stopDeceleratingIfNeeded() { if isDecelerating { setContentOffset(contentOffset, animated: false) } } }
mit
72f295a3fafe03c2387e0419d14a5526
26.595041
143
0.624438
4.158157
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Mesh/Gen3SetupBluetoothConnection.swift
1
10605
// // Created by Ido Kleinman on 7/12/18. // Maintained by Raimundas Sakalauskas // Copyright (c) 2018 Particle. All rights reserved. // import UIKit import CoreBluetooth protocol Gen3SetupBluetoothConnectionDelegate { func bluetoothConnectionBecameReady(sender: Gen3SetupBluetoothConnection) func bluetoothConnectionError(sender: Gen3SetupBluetoothConnection, error: BluetoothConnectionError, severity: Gen3SetupErrorSeverity) } protocol Gen3SetupBluetoothConnectionDataDelegate { func bluetoothConnectionDidReceiveData(sender: Gen3SetupBluetoothConnection, data: Data) } enum BluetoothConnectionError: Error, CustomStringConvertible { case FailedToHandshake case FailedToDiscoverServices case FailedToDiscoverParticleGen3Service case FailedToDiscoverCharacteristics case FailedToDiscoverParticleGen3Characteristics case FailedToEnableBluetoothConnectionNotifications case FailedToWriteValueForCharacteristic case FailedToReadValueForCharacteristic public var description: String { switch self { case .FailedToHandshake : return "Failed to perform handshake" case .FailedToDiscoverServices : return "Failed to discover bluetooth services" case .FailedToDiscoverParticleGen3Service : return "Particle Gen 3 commissioning Service not found. Try to turn bluetooth Off and On again to clear the cache." case .FailedToDiscoverCharacteristics : return "Failed to discover bluetooth characteristics" case .FailedToDiscoverParticleGen3Characteristics : return "UART service does not have required characteristics. Try to turn Bluetooth Off and On again to clear cache." case .FailedToEnableBluetoothConnectionNotifications : return "Failed to enable bluetooth characteristic notifications" case .FailedToWriteValueForCharacteristic : return "Writing value for bluetooth characteristic has failed (sending data to device failed)" case .FailedToReadValueForCharacteristic : return "Reading value for bluetooth characteristic has failed (receiving data to device failed)" } } } class Gen3SetupBluetoothConnection: NSObject, CBPeripheralDelegate, Gen3SetupBluetoothConnectionHandshakeManagerDelegate { var delegate: Gen3SetupBluetoothConnectionDelegate? var dataDelegate: Gen3SetupBluetoothConnectionDataDelegate? var isReady: Bool = false var peripheralName: String var mobileSecret: String var derivedSecret: Data? var cbPeripheral: CBPeripheral { get { return peripheral } } private var peripheral: CBPeripheral private var handshakeRetry: Int = 0 private var handshakeManager: Gen3SetupBluetoothConnectionHandshakeManager? private var particleGen3RXCharacteristic: CBCharacteristic! private var particleGen3TXCharacteristic: CBCharacteristic! required init(connectedPeripheral: CBPeripheral, credentials: Gen3SetupPeripheralCredentials) { self.peripheral = connectedPeripheral self.peripheralName = peripheral.name! self.mobileSecret = credentials.mobileSecret super.init() self.peripheral.delegate = self self.discoverServices() } private func log(_ message: String) { ParticleLogger.logInfo("BluetoothConnection", format: message, withParameters: getVaList([])) } private func fail(withReason reason: BluetoothConnectionError, severity: Gen3SetupErrorSeverity) { log("Bluetooth connection error: \(reason), severity: \(severity)") self.delegate?.bluetoothConnectionError(sender: self, error: reason, severity: severity) } func discoverServices() { self.peripheral.discoverServices([Gen3Setup.particleGen3ServiceUUID]) } func send(data aData: Data, writeType: CBCharacteristicWriteType = .withResponse) { guard self.particleGen3RXCharacteristic != nil else { log("UART RX Characteristic not found") return } var MTU = peripheral.maximumWriteValueLength(for: .withoutResponse) //using MTU for different write type is bad idea, but since xenons report bad MTU for //withResponse, it's either that or 20byte hardcoded value. Tried this with iPhone 5 / iOS 9 //and it worked so left it this way to improve communication speed. // if (writeType == .withResponse) { // //withResponse reports wrong MTU and xenon triggers disconnect // MTU = 20 // } // The following code will split the text to packets aData.withUnsafeBytes { (u8Ptr: UnsafePointer<UInt8>) in var buffer = UnsafeMutableRawPointer(mutating: UnsafeRawPointer(u8Ptr)) var len = aData.count while(len != 0){ var part: Data if len > MTU { part = Data(bytes: buffer, count: MTU) buffer = buffer + MTU len = len - MTU } else { part = Data(bytes: buffer, count: len) len = 0 } self.peripheral.writeValue(part, for: self.particleGen3RXCharacteristic!, type: writeType) } } log("Sent data: \(aData.count) Bytes") } //MARK: - CBPeripheralDelegate func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard error == nil else { log("error = \(error)") fail(withReason: .FailedToDiscoverServices, severity: .Error) return } log("Services discovered") for aService in peripheral.services! { if aService.uuid.isEqual(Gen3Setup.particleGen3ServiceUUID) { log("Particle Gen 3 commissioning Service found") self.peripheral.discoverCharacteristics(nil, for: aService) return } } fail(withReason: .FailedToDiscoverParticleGen3Service, severity: .Error) } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard error == nil else { NSLog("error = \(error)") fail(withReason: .FailedToDiscoverCharacteristics, severity: .Error) return } log("Characteristics discovered") if service.uuid.isEqual(Gen3Setup.particleGen3ServiceUUID) { for aCharacteristic in service.characteristics! { if aCharacteristic.uuid.isEqual(Gen3Setup.particleGen3TXCharacterisiticUUID) { log("Particle gen 3 setup TX Characteristic found") particleGen3TXCharacteristic = aCharacteristic } else if aCharacteristic.uuid.isEqual(Gen3Setup.particleGen3RXCharacterisiticUUID) { log("Particle gen 3 setup RX Characteristic found") particleGen3RXCharacteristic = aCharacteristic } } //Enable notifications on TX Characteristic if (particleGen3TXCharacteristic != nil && particleGen3RXCharacteristic != nil) { log("Enabling notifications for \(particleGen3TXCharacteristic!.uuid.uuidString)") self.peripheral.setNotifyValue(true, for: particleGen3TXCharacteristic!) } else { fail(withReason: .FailedToDiscoverParticleGen3Characteristics, severity: .Error) } } } func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { guard error == nil, characteristic.isNotifying == true else { NSLog("error = \(error)") fail(withReason: .FailedToEnableBluetoothConnectionNotifications, severity: .Error) return } self.handshakeManager = Gen3SetupBluetoothConnectionHandshakeManager(connection: self, mobileSecret: mobileSecret) self.handshakeManager!.delegate = self self.handshakeManager!.startHandshake() } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { guard error == nil else { NSLog("error = \(error)") fail(withReason: .FailedToWriteValueForCharacteristic, severity: .Error) return } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { guard error == nil else { NSLog("error = \(error)") fail(withReason: .FailedToReadValueForCharacteristic, severity: .Error) return } if let bytesReceived = characteristic.value { bytesReceived.withUnsafeBytes { (utf8Bytes: UnsafePointer<CChar>) in var len = bytesReceived.count if utf8Bytes[len - 1] == 0 { len -= 1 // if the string is null terminated, don't pass null terminator into NSMutableString constructor } log("Bytes received from: \(characteristic.uuid.uuidString), \(bytesReceived.count) Bytes") } if (self.isReady) { self.dataDelegate?.bluetoothConnectionDidReceiveData(sender: self, data: bytesReceived as Data) } else { self.handshakeManager!.readBytes(bytesReceived as Data) } } } //MARK: Gen3SetupBluetoothConnectionHandshakeManagerDelegate func handshakeDidFail(sender: Gen3SetupBluetoothConnectionHandshakeManager, error: HandshakeManagerError, severity: Gen3SetupErrorSeverity) { log("Handshake Error: \(error)") if (handshakeRetry < 3) { handshakeRetry += 1 } else { fail(withReason: .FailedToHandshake, severity: .Error) } //retry handshake self.handshakeManager!.delegate = nil self.handshakeManager = nil self.handshakeManager = Gen3SetupBluetoothConnectionHandshakeManager(connection: self, mobileSecret: mobileSecret) self.handshakeManager!.delegate = self self.handshakeManager!.startHandshake() } func handshakeDidSucceed(sender: Gen3SetupBluetoothConnectionHandshakeManager, derivedSecret: Data) { self.derivedSecret = derivedSecret self.handshakeManager!.delegate = nil self.handshakeManager = nil self.isReady = true self.delegate?.bluetoothConnectionBecameReady(sender: self) } }
apache-2.0
b3c9d873e150c0a82443a69d7b578894
39.323194
180
0.671664
5.668092
false
false
false
false
bullapse/la_de_rue
la de rue/FirstViewController.swift
1
2344
// // FirstViewController.swift // la de rue // // Created by Spencer Bull on 7/11/15. // Copyright (c) 2015 bullapse. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var foodTruckList: [JSON] = [] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self loadFoodTrucks() } @IBAction func loadTableView(sender: AnyObject) { loadFoodTrucks() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return foodTruckList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell let data = foodTruckList[indexPath.row] let name = data["Name"].string let isOpen = data["isOpen"].string var caption = "Closed" if (isOpen == "1") { caption = "Open" } cell.textLabel?.text = name cell.detailTextLabel?.text = caption return cell } func loadFoodTrucks() { Alamofire.request(.GET, "http://localhost:4730") .responseJSON { (_, _, json, _) in if json != nil { var jsonObj = JSON(json!) if let data = jsonObj["results"].arrayValue as [JSON]?{ self.foodTruckList = data self.tableView.reloadData() print(self.foodTruckList) } } } } // MARK: UITableViewDelegate Methods func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let row = indexPath.row // prints the whole JSON object to the console. // foodTruckList[row] return the object print(foodTruckList[row]) } }
mit
c8b4652bf5be5ed635675ac5b9abade2
26.576471
111
0.570392
5.388506
false
false
false
false
gbmksquare/RoundBorderedButton
RoundBorderedButton.swift
1
17665
// // RoundBorderedButton.swift // RoundBorderedButton // // Created by 구범모 on 2015. 4. 10.. // Copyright (c) 2015년 gbmKSquare. All rights reserved. // import UIKit @IBDesignable class RoundBorderedButton: UIControl { // MARK: Default value private static let defaultBorderWidth: CGFloat = 2 // MARK: Property @IBInspectable var title: String? { didSet { if buttonView != nil { addTitleAndImageView() } } } @IBInspectable var image: UIImage? { didSet { if buttonView != nil { addTitleAndImageView() } } } // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() if buttonView == nil { addButtonView() addTitleAndImageView() } } // MARK: Button private var buttonView: UIView? var titleLabel: UILabel? var imageView: UIImageView? private func addButtonView() { let button = UIView(frame: CGRectZero) button.backgroundColor = UIColor.clearColor() button.layer.borderWidth = borderWidth button.layer.borderColor = tintColor.CGColor button.layer.cornerRadius = bounds.width / 2 addSubview(button) buttonView = button addConstraintsFor(button, toFitInside: self) layoutIfNeeded() } private func addTitleAndImageView() { removeSubviewsFor(buttonView!) switch (title, image) { case (nil, nil): return case (_, nil): if self.titleLabel == nil { let titleLabel = addTitleViewTo(buttonView!) self.titleLabel = titleLabel } case (nil, _): if self.imageView == nil { let imageView = addImageViewTo(buttonView!) self.imageView = imageView } case (_, _): if self.titleLabel == nil && self.imageView == nil { let subview = addTitleAndImageViewTo(buttonView!) self.titleLabel = subview.titleLabel self.imageView = subview.imageView } default: return } addSelectedView() if selected == true { showSelectedView() } else { hideSelectedView() } } // MARK: Apperance @IBInspectable var borderWidth = RoundBorderedButton.defaultBorderWidth override func tintColorDidChange() { super.tintColorDidChange() buttonView?.layer.borderColor = tintColor.CGColor titleLabel?.textColor = tintColor } // MARK: Touch override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { if self.pointInside(point, withEvent: event) == true { return self } else { return super.hitTest(point, withEvent: event) } } // MARK: Selected state private var selectedBackgroundView: UIView? private var selectedContainerView: UIView? private var selectedTitleLabel: UILabel? private var selectedImageView: UIImageView? private var selectedContainerMaskView: UIView? private var showSelectedViewDuration = 0.75 private var showSelectedViewDamping: CGFloat = 0.6 private var showSelectedViewVelocity: CGFloat = 0.9 private var hideSelectedViewDuration = 0.3 private var hideSelectedViewDamping: CGFloat = 0.9 private var hideSelectedViewVelocity: CGFloat = 0.9 override var selected: Bool { willSet { if newValue == true { showSelectedView() } else { hideSelectedView() } } } private func addSelectedView() { func addSelectedBacgroundView() { let selectedBackgroundView = UIView(frame: CGRectZero) selectedBackgroundView.backgroundColor = tintColor selectedBackgroundView.layer.cornerRadius = bounds.width / 2 buttonView?.addSubview(selectedBackgroundView) self.selectedBackgroundView = selectedBackgroundView addConstraintsFor(selectedBackgroundView, toEqualSizeOf: buttonView!) } func addSelectedContainerView() { let selectedContainerMaskView = UIView(frame: buttonView!.bounds) selectedContainerMaskView.backgroundColor = UIColor.blackColor() selectedContainerMaskView.layer.cornerRadius = buttonView!.bounds.width / 2 self.selectedContainerMaskView = selectedContainerMaskView if let selectedContainerView = self.selectedContainerView { selectedContainerView.removeFromSuperview() } let selectedContainerView = UIView(frame: buttonView!.bounds) selectedContainerView.tag = 1 selectedContainerView.backgroundColor = UIColor.clearColor() selectedContainerView.maskView = selectedContainerMaskView buttonView?.addSubview(selectedContainerView) self.selectedContainerView = selectedContainerView addConstraintsFor(selectedContainerView, toEqualSizeOf: buttonView!) layoutIfNeeded() switch (title, image) { case (nil, nil): return case (_, nil): let titleLabel = addTitleViewTo(selectedContainerView) titleLabel.textColor = UIColor.whiteColor() self.selectedTitleLabel = titleLabel case (nil, _): let imageView = addImageViewTo(selectedContainerView) imageView.tintColor = UIColor.whiteColor() self.imageView = imageView case (_, _): let subviews = addTitleAndImageViewTo(selectedContainerView) subviews.titleLabel.textColor = UIColor.whiteColor() subviews.imageView.tintColor = UIColor.whiteColor() self.titleLabel = subviews.titleLabel self.imageView = subviews.imageView default: return } } selectedBackgroundView?.removeFromSuperview() selectedContainerView?.removeFromSuperview() addSelectedBacgroundView() addSelectedContainerView() } private func captureTitleAndImageView() -> UIImage? { titleLabel?.textColor = UIColor.whiteColor() imageView?.tintColor = UIColor.whiteColor() buttonView?.layer.borderColor = UIColor.clearColor().CGColor UIGraphicsBeginImageContextWithOptions(buttonView!.bounds.size, false, 0) buttonView?.drawViewHierarchyInRect(buttonView!.bounds, afterScreenUpdates: true) titleLabel?.drawViewHierarchyInRect(buttonView!.bounds, afterScreenUpdates: true) imageView?.drawViewHierarchyInRect(buttonView!.bounds, afterScreenUpdates: true) let snapshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() titleLabel?.textColor = tintColor imageView?.tintColor = tintColor buttonView?.layer.borderColor = tintColor.CGColor return snapshot } private func setSelectedViewToVisibleState() { selectedBackgroundView?.alpha = 1 selectedBackgroundView?.transform = CGAffineTransformIdentity selectedContainerMaskView?.transform = CGAffineTransformIdentity selectedContainerView?.hidden = false } private func setSelectedViewToHiddenState() { selectedBackgroundView?.alpha = 0 selectedBackgroundView?.transform = CGAffineTransformMakeScale(0.01, 0.01) selectedContainerMaskView?.transform = CGAffineTransformMakeScale(0.01, 0.01) selectedContainerView?.hidden = true } private func showSelectedView() { setSelectedViewToHiddenState() userInteractionEnabled = false UIView.animateWithDuration(showSelectedViewDuration, delay: 0, usingSpringWithDamping: showSelectedViewDamping, initialSpringVelocity: showSelectedViewVelocity, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in self.setSelectedViewToVisibleState() }) { (finished) -> Void in self.userInteractionEnabled = true } } private func hideSelectedView() { setSelectedViewToVisibleState() userInteractionEnabled = false UIView.animateWithDuration(hideSelectedViewDuration, delay: 0, usingSpringWithDamping: hideSelectedViewDamping, initialSpringVelocity: hideSelectedViewVelocity, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in self.setSelectedViewToHiddenState() }) { (finished) -> Void in self.userInteractionEnabled = true } } // MARK: Add subview helper func addTitleViewTo(superview: UIView) -> UILabel { let titleLabel = UILabel(frame: CGRectZero) titleLabel.text = title titleLabel.textColor = tintColor titleLabel.textAlignment = NSTextAlignment.Center superview.addSubview(titleLabel) addConstraintsFor(titleLabel, toEqualSizeOf: buttonView!) return titleLabel } func addImageViewTo(superview: UIView) -> UIImageView { let imageView = UIImageView(frame: CGRectZero) imageView.image = image imageView.contentMode = UIViewContentMode.Center imageView.clipsToBounds = true superview.addSubview(imageView) addConstraintFor(imageView, toFitInsideRound: buttonView!) return imageView } func addTitleAndImageViewTo(superview: UIView) -> (containerView: UIView, titleLabel: UILabel, imageView: UIImageView) { let containerView = UIView(frame: CGRectZero) containerView.tag = 1 containerView.backgroundColor = UIColor.clearColor() superview.addSubview(containerView) addConstraintFor(containerView, toFitInsideRound: buttonView!) layoutIfNeeded() let containerWidth = sqrt(2) / 2 * bounds.width let titleLabel = UILabel(frame: CGRectZero) titleLabel.text = title titleLabel.textColor = tintColor titleLabel.textAlignment = NSTextAlignment.Center containerView.addSubview(titleLabel) let imageView = UIImageView(frame: CGRectZero) imageView.image = image imageView.contentMode = UIViewContentMode.Center imageView.clipsToBounds = true containerView.addSubview(imageView) addConstraintFor(imageView, lowerSubview: titleLabel, superview: containerView, lowerViewRatio: 0.33) return (containerView, titleLabel, imageView) } func removeSubviewsFor(view: UIView) { for view in view.subviews { if view.tag == 1 { for subview in view.subviews { subview.removeFromSuperview() } view.removeFromSuperview() } } titleLabel?.removeFromSuperview() imageView?.removeFromSuperview() titleLabel = nil imageView = nil } // MARK: Auto layout helper private func addConstraintsFor(subview: UIView, toEqualSizeOf superview: UIView) { let topConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) let leftConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0) subview.setTranslatesAutoresizingMaskIntoConstraints(false) superview.addConstraints([topConstraint, bottomConstraint, leftConstraint, rightConstraint]) } private func addConstraintsFor(subview: UIView, toFitInside superview: UIView) { let fittingWidth = superview.bounds.width > superview.bounds.height ? superview.bounds.height : superview.bounds.width addConstraintFor(subview, toFitInsde: superview, width: fittingWidth) } private func addConstraintFor(subview: UIView, toFitInsideRound superview: UIView) { let fittingWidth = sqrt(2) / 2 * superview.bounds.width addConstraintFor(subview, toFitInsde: superview, width: fittingWidth) } private func addConstraintFor(subview: UIView, toFitInsde superview: UIView, width: CGFloat) { let widthConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: width) let ratioConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: subview, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) let horizontalConstraint = NSLayoutConstraint(item: subview, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) subview.setTranslatesAutoresizingMaskIntoConstraints(false) superview.addConstraints([widthConstraint, ratioConstraint, verticalConstraint, horizontalConstraint]) } private func addConstraintFor(upperSubview: UIView, lowerSubview: UIView, superview: UIView, lowerViewRatio: CGFloat) { let lowerViewHeight = superview.bounds.height * lowerViewRatio let upperViewTopConstraint = NSLayoutConstraint(item: upperSubview, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) let upperViewBottomConstraint = NSLayoutConstraint(item: upperSubview, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: lowerSubview, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) let upperViewLeftConstraint = NSLayoutConstraint(item: upperSubview, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) let upperViewRightConstraint = NSLayoutConstraint(item: upperSubview, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0) upperSubview.setTranslatesAutoresizingMaskIntoConstraints(false) superview.addConstraints([upperViewTopConstraint, upperViewBottomConstraint, upperViewLeftConstraint, upperViewRightConstraint]) let lowerViewHeightConstraint = NSLayoutConstraint(item: lowerSubview, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: lowerViewHeight) let lowerViewBottomConstraint = NSLayoutConstraint(item: lowerSubview, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) let lowerViewLeftConstraint = NSLayoutConstraint(item: lowerSubview, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) let lowerViewRightConstraint = NSLayoutConstraint(item: lowerSubview, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: superview, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0) lowerSubview.setTranslatesAutoresizingMaskIntoConstraints(false) superview.addConstraints([lowerViewHeightConstraint, lowerViewBottomConstraint, lowerViewLeftConstraint, lowerViewRightConstraint]) } }
mit
c4bf7308dc1d5ec85463ade9770826f9
40.742317
139
0.654924
6.191094
false
false
false
false
sandsmedia/SS_Authentication
SS_Authentication/Classes/ViewControllers/SSAuthenticationBaseViewController.swift
1
18700
// // SSAuthenticationBaseViewController.swift // SS_Authentication // // Created by Eddie Li on 25/05/16. // Copyright © 2016 Software and Support Media GmbH. All rights reserved. // import UIKit import Validator fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } enum ValidationError: Error { case invalid(String) } open class SSAuthenticationBaseViewController: UIViewController, UITextFieldDelegate { fileprivate var loadingView: SSAuthenticationLoadingView? var baseScrollView: UIScrollView? var textFieldsStackView: UIStackView? var buttonsStackView: UIStackView? var hideStatusBar = false var isEmailValid = false var isPasswordValid = false var isConfirmPasswordValid = false var statusBarStyle: UIStatusBarStyle = .default fileprivate var hasLoadedConstraints = false // MARK: - Initialisation convenience init() { self.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } deinit { self.emailTextField.validateOnEditingEnd(enabled: false) self.passwordTextField.validateOnEditingEnd(enabled: false) self.confirmPasswordTextField.validateOnEditingEnd(enabled: false) self.emailTextField.delegate = nil self.passwordTextField.delegate = nil self.confirmPasswordTextField.delegate = nil } // MARK: - Accessors fileprivate(set) lazy var resourceBundle: Bundle = { let bundleURL = Bundle(for: SSAuthenticationBaseViewController.self).resourceURL let _resourceBundle = Bundle(url: bundleURL!) return _resourceBundle! }() fileprivate(set) lazy var emailTextField: UITextField = { let _emailTextField = UITextField() _emailTextField.backgroundColor = SSAuthenticationManager.sharedInstance.textFieldBackgroundColour _emailTextField.delegate = self _emailTextField.keyboardType = .emailAddress _emailTextField.spellCheckingType = .no _emailTextField.autocorrectionType = .no _emailTextField.autocapitalizationType = .none _emailTextField.attributedPlaceholder = NSAttributedString(string: self.localizedString(key: "user.email"), attributes: SSAuthenticationManager.sharedInstance.textFieldPlaceholderFontAttribute) _emailTextField.leftView = UIView(frame: TEXT_FIELD_LEFT_VIEW_FRAME) _emailTextField.leftViewMode = .always _emailTextField.layer.cornerRadius = TEXT_FIELD_RADIUS _emailTextField.font = SSAuthenticationManager.sharedInstance.textFieldFont _emailTextField.textColor = SSAuthenticationManager.sharedInstance.textFieldFontColour var rules = ValidationRuleSet<String>() let emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: ValidationError.invalid(self.localizedString(key: "email_format_error.message"))) rules.add(rule: emailRule) _emailTextField.validationRules = rules _emailTextField.validationHandler = { result in self.isEmailValid = result.isValid } _emailTextField.validateOnEditingEnd(enabled: true) return _emailTextField }() fileprivate(set) lazy var passwordTextField: UITextField = { let _passwordTextField = UITextField() _passwordTextField.backgroundColor = SSAuthenticationManager.sharedInstance.textFieldBackgroundColour _passwordTextField.delegate = self _passwordTextField.spellCheckingType = .no _passwordTextField.autocorrectionType = .no _passwordTextField.autocapitalizationType = .none _passwordTextField.isSecureTextEntry = true _passwordTextField.clearsOnBeginEditing = true _passwordTextField.attributedPlaceholder = NSAttributedString(string: self.localizedString(key: "user.password"), attributes: SSAuthenticationManager.sharedInstance.textFieldPlaceholderFontAttribute) _passwordTextField.leftView = UIView(frame: TEXT_FIELD_LEFT_VIEW_FRAME) _passwordTextField.leftViewMode = .always _passwordTextField.layer.cornerRadius = TEXT_FIELD_RADIUS _passwordTextField.font = SSAuthenticationManager.sharedInstance.textFieldFont _passwordTextField.textColor = SSAuthenticationManager.sharedInstance.textFieldFontColour var rules = ValidationRuleSet<String>() let passwordRule = ValidationRulePattern(pattern: PASSWORD_VALIDATION_REGEX, error: ValidationError.invalid(self.localizedString(key: "password_valid_fail.message"))) rules.add(rule: passwordRule) _passwordTextField.validationRules = rules _passwordTextField.validationHandler = { result in self.isPasswordValid = result.isValid } _passwordTextField.validateOnEditingEnd(enabled: true) return _passwordTextField }() fileprivate(set) lazy var confirmPasswordTextField: UITextField = { let _confirmPasswordTextField = UITextField() _confirmPasswordTextField.backgroundColor = SSAuthenticationManager.sharedInstance.textFieldBackgroundColour _confirmPasswordTextField.delegate = self _confirmPasswordTextField.spellCheckingType = .no _confirmPasswordTextField.autocorrectionType = .no _confirmPasswordTextField.autocapitalizationType = .none _confirmPasswordTextField.isSecureTextEntry = true _confirmPasswordTextField.clearsOnBeginEditing = true _confirmPasswordTextField.attributedPlaceholder = NSAttributedString(string: self.localizedString(key: "user.confirm_password"), attributes: SSAuthenticationManager.sharedInstance.textFieldPlaceholderFontAttribute) _confirmPasswordTextField.leftView = UIView(frame: TEXT_FIELD_LEFT_VIEW_FRAME) _confirmPasswordTextField.leftViewMode = .always _confirmPasswordTextField.layer.cornerRadius = TEXT_FIELD_RADIUS _confirmPasswordTextField.font = SSAuthenticationManager.sharedInstance.textFieldFont _confirmPasswordTextField.textColor = SSAuthenticationManager.sharedInstance.textFieldFontColour var rules = ValidationRuleSet<String>() let confirmPasswordRule = ValidationRuleEquality(dynamicTarget: { return self.passwordTextField.text ?? "" }, error: ValidationError.invalid(self.localizedString(key: "password_not_match.message"))) let passwordRule = ValidationRulePattern(pattern: PASSWORD_VALIDATION_REGEX, error: ValidationError.invalid(self.localizedString(key: "password_valid_fail.message"))) rules.add(rule: confirmPasswordRule) rules.add(rule: passwordRule) _confirmPasswordTextField.validationRules = rules _confirmPasswordTextField.validationHandler = { result in self.isConfirmPasswordValid = result.isValid } _confirmPasswordTextField.validateOnEditingEnd(enabled: true) return _confirmPasswordTextField }() open lazy var emailFailureAlertController: UIAlertController = { let _emailFailureAlertController = UIAlertController(title: nil, message: self.localizedString(key: "email_format_error.message"), preferredStyle: .alert) let cancelAction = UIAlertAction(title: self.localizedString(key: "ok.title"), style: .cancel, handler: { (action) in self.emailTextField.becomeFirstResponder() }) _emailFailureAlertController.addAction(cancelAction) return _emailFailureAlertController }() open lazy var passwordValidFailAlertController: UIAlertController = { let _passwordValidFailAlertController = UIAlertController(title: nil, message: self.localizedString(key: "password_valid_fail.message"), preferredStyle: .alert) let cancelAction = UIAlertAction(title: self.localizedString(key: "ok.title"), style: .cancel, handler: { (action) in self.passwordTextField.text = nil self.passwordTextField.becomeFirstResponder() }) _passwordValidFailAlertController.addAction(cancelAction) return _passwordValidFailAlertController }() open lazy var confirmPasswordValidFailAlertController: UIAlertController = { let _confirmPasswordValidFailAlertController = UIAlertController(title: nil, message: self.localizedString(key: "password_not_match.message"), preferredStyle: .alert) let cancelAction = UIAlertAction(title: self.localizedString(key: "ok.title"), style: .cancel, handler: { (action) in self.confirmPasswordTextField.text = nil self.confirmPasswordTextField.becomeFirstResponder() }) _confirmPasswordValidFailAlertController.addAction(cancelAction) return _confirmPasswordValidFailAlertController }() fileprivate(set) lazy var noInternetAlertController: UIAlertController = { let _noInternetAlertController = UIAlertController(title: nil, message: self.localizedString(key: "no_internet_connection_error.message"), preferredStyle: .alert) let cancelAction = UIAlertAction(title: self.localizedString(key: "ok.title"), style: .cancel, handler: { (action) in }) _noInternetAlertController.addAction(cancelAction) return _noInternetAlertController }() // MARK: - Implementation of SSAuthenticationNavigationBarDelegate protocols func skip() { } func back() { self.emailTextField.delegate = nil self.passwordTextField.delegate = nil self.confirmPasswordTextField.delegate = nil let _ = self.navigationController?.popViewController(animated: true) } // MARK: - Implementation of UITextFieldDelegate protocols open func textFieldDidBeginEditing(_ textField: UITextField) { textField.layer.borderColor = UIColor.gray.cgColor } open func textFieldDidEndEditing(_ textField: UITextField) { if (textField.text?.characters.count > 0) { if (textField == self.emailTextField) { if (!self.isEmailValid) { textField.layer.borderColor = UIColor.red.cgColor self.present(self.emailFailureAlertController, animated: true, completion: nil) } } else if (textField == self.passwordTextField) { if (!self.isPasswordValid) { textField.layer.borderColor = UIColor.red.cgColor self.present(self.passwordValidFailAlertController, animated: true, completion: nil) } } else if (textField == self.confirmPasswordTextField) { if (!self.isConfirmPasswordValid) { textField.layer.borderColor = UIColor.red.cgColor self.present(self.confirmPasswordValidFailAlertController, animated: true, completion: nil) } } } } open func textFieldShouldReturn(_ textField: UITextField) -> Bool { return false } // MARK: - Public Methods func setup() { self.setNeedsStatusBarAppearanceUpdate() } func showLoadingView() { self.view.bringSubview(toFront: self.loadingView!) UIView.animate(withDuration: ANIMATION_DURATION, animations: { self.loadingView?.alpha = 1.0 }) } func hideLoadingView() { UIView.animate(withDuration: ANIMATION_DURATION, animations: { self.loadingView?.alpha = 0.0 }) } func localizedString(key: String) -> String { return self.resourceBundle.localizedString(forKey: key, value: nil, table: "SS_Authentication") } open func forceUpdateStatusBarStyle(_ style: UIStatusBarStyle) { self.statusBarStyle = style self.setNeedsStatusBarAppearanceUpdate() } // MARK: - Subviews fileprivate func setupBaseScrollView() { self.baseScrollView = UIScrollView() } fileprivate func setupTextFieldsStackView() { self.textFieldsStackView = UIStackView() self.textFieldsStackView?.axis = .vertical self.textFieldsStackView?.alignment = .center self.textFieldsStackView!.distribution = .equalSpacing self.textFieldsStackView?.spacing = GENERAL_SPACING } fileprivate func setupButtonsStackView() { self.buttonsStackView = UIStackView() self.buttonsStackView!.axis = .vertical self.buttonsStackView!.alignment = .center self.buttonsStackView!.distribution = .equalSpacing self.buttonsStackView?.spacing = GENERAL_SPACING } fileprivate func setupLoadingView() { self.loadingView = SSAuthenticationLoadingView() self.loadingView?.alpha = 0.0 } func setupSubviews() { self.setupBaseScrollView() self.baseScrollView?.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.baseScrollView!) self.setupTextFieldsStackView() self.textFieldsStackView?.translatesAutoresizingMaskIntoConstraints = false self.baseScrollView?.addSubview(self.textFieldsStackView!) self.setupButtonsStackView() self.buttonsStackView?.translatesAutoresizingMaskIntoConstraints = false self.baseScrollView?.addSubview(self.buttonsStackView!) self.setupLoadingView() self.loadingView!.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.loadingView!) } override open var prefersStatusBarHidden : Bool { return self.hideStatusBar } override open var preferredStatusBarStyle : UIStatusBarStyle { return self.statusBarStyle } override open func updateViewConstraints() { if (!self.hasLoadedConstraints) { let views: [String: Any] = ["base": self.baseScrollView!, "texts": self.textFieldsStackView!, "buttons": self.buttonsStackView!, "loading": self.loadingView!] let metrics = ["SPACING": GENERAL_SPACING, "LARGE_SPACING": LARGE_SPACING] self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[base]|", options: .directionMask, metrics: nil, views: views)) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[loading]", options: .directionMask, metrics: nil, views: views)) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[base]|", options: .directionMask, metrics: nil, views: views)) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[loading]", options: .directionMask, metrics: nil, views: views)) self.view.addConstraint(NSLayoutConstraint(item: self.loadingView!, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0)) self.view.addConstraint(NSLayoutConstraint(item: self.loadingView!, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0.0)) self.baseScrollView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[texts]", options: .directionMask, metrics: nil, views: views)) self.baseScrollView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[buttons]", options: .directionMask, metrics: nil, views: views)) self.baseScrollView!.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(SPACING)-[texts]-(LARGE_SPACING)-[buttons]|", options: .directionMask, metrics: metrics, views: views)) self.baseScrollView!.addConstraint(NSLayoutConstraint(item: self.textFieldsStackView!, attribute: .width, relatedBy: .equal, toItem: self.baseScrollView!, attribute: .width, multiplier: 1.0, constant: 0.0)) self.baseScrollView!.addConstraint(NSLayoutConstraint(item: self.buttonsStackView!, attribute: .centerX, relatedBy: .equal, toItem: self.baseScrollView!, attribute: .centerX, multiplier: 1.0, constant: 0.0)) self.baseScrollView!.addConstraint(NSLayoutConstraint(item: self.textFieldsStackView!, attribute: .centerX, relatedBy: .equal, toItem: self.baseScrollView!, attribute: .centerX, multiplier: 1.0, constant: 0.0)) self.baseScrollView!.addConstraint(NSLayoutConstraint(item: self.buttonsStackView!, attribute: .width, relatedBy: .equal, toItem: self.baseScrollView!, attribute: .width, multiplier: 1.0, constant: 0.0)) self.hasLoadedConstraints = true } super.updateViewConstraints() } // MARK: - View lifecycle override open func loadView() { self.view = UIView() self.view.backgroundColor = .black self.view.translatesAutoresizingMaskIntoConstraints = true self.setupSubviews() self.updateViewConstraints() } override open func viewDidLoad() { super.viewDidLoad() self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.emailTextField.delegate = self self.passwordTextField.delegate = self self.confirmPasswordTextField.delegate = self } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.emailTextField.delegate = nil self.passwordTextField.delegate = nil self.confirmPasswordTextField.delegate = nil } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
34009fbaa856bf34fec29a4253ee80e7
44.718826
222
0.686186
5.639023
false
false
false
false
JadenGeller/Calcula
Sources/Binding.swift
1
817
// // Binding.swift // Calcula // // Created by Jaden Geller on 5/22/16. // Copyright © 2016 Jaden Geller. All rights reserved. // public final class Binding { public required init() { } } extension Binding: CustomStringConvertible { public var description: String { return "{" + String(ObjectIdentifier(self).uintValue) + "}" } } extension Binding: Hashable { public var hashValue: Int { return ObjectIdentifier(self).hashValue } } extension Binding: Equatable { } public func ==(lhs: Binding, rhs: Binding) -> Bool { return lhs === rhs } extension Binding { /// Returns `true` iff `self` is not bound to any lambda argument within the term. public func isFresh(in term: Term) -> Bool { return !term.freeVariables.contains(self) } }
mit
d855878a5d4baf540fc4d5baeb351ed9
21.054054
86
0.645833
4.019704
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/ModalPresenter.swift
1
61306
// // ModalPresenter.swift // breadwallet // // Created by Adrian Corscadden on 2016-10-25. // Copyright © 2016-2019 Breadwinner AG. All rights reserved. // import UIKit import LocalAuthentication import SwiftUI import WalletKit // swiftlint:disable type_body_length // swiftlint:disable cyclomatic_complexity class ModalPresenter: Subscriber, Trackable { // MARK: - Public let keyStore: KeyStore lazy var supportCenter: SupportCenterContainer = { return SupportCenterContainer(walletAuthenticator: keyStore) }() init(keyStore: KeyStore, system: CoreSystem, window: UIWindow, alertPresenter: AlertPresenter?) { self.system = system self.window = window self.alertPresenter = alertPresenter self.keyStore = keyStore self.modalTransitionDelegate = ModalTransitionDelegate(type: .regular) self.wipeNavigationDelegate = StartNavigationDelegate() addSubscriptions() } deinit { Store.unsubscribe(self) } // MARK: - Private private let window: UIWindow private var alertPresenter: AlertPresenter? private let modalTransitionDelegate: ModalTransitionDelegate private let messagePresenter = MessageUIPresenter() private let securityCenterNavigationDelegate = SecurityCenterNavigationDelegate() private let verifyPinTransitionDelegate = PinTransitioningDelegate() private var currentRequest: PaymentRequest? private let wipeNavigationDelegate: StartNavigationDelegate private var menuNavController: UINavigationController? private let system: CoreSystem private func addSubscriptions() { Store.lazySubscribe(self, selector: { $0.rootModal != $1.rootModal }, callback: { [weak self] in self?.presentModal($0.rootModal) }) Store.subscribe(self, name: .presentFaq("", nil), callback: { [weak self] in guard let trigger = $0 else { return } if case .presentFaq(let articleId, let currency) = trigger { self?.presentFaq(articleId: articleId, currency: currency) } }) //Subscribe to prompt actions Store.subscribe(self, name: .promptUpgradePin, callback: { [weak self] _ in self?.presentUpgradePin() }) Store.subscribe(self, name: .promptPaperKey, callback: { [weak self] _ in self?.presentWritePaperKey() }) Store.subscribe(self, name: .promptBiometrics, callback: { [weak self] _ in self?.presentBiometricsMenuItem() }) Store.subscribe(self, name: .promptShareData, callback: { [weak self] _ in self?.promptShareData() }) Store.subscribe(self, name: .openFile(Data()), callback: { [weak self] in guard let trigger = $0 else { return } if case .openFile(let file) = trigger { self?.handleFile(file) } }) //URLs Store.subscribe(self, name: .receivedPaymentRequest(nil), callback: { [weak self] in guard let trigger = $0 else { return } if case let .receivedPaymentRequest(request) = trigger { if let request = request { self?.handlePaymentRequest(request: request) } } }) Store.subscribe(self, name: .scanQr, callback: { [weak self] _ in self?.handleScanQrURL() }) Store.subscribe(self, name: .authenticateForPlatform("", true, {_ in}), callback: { [weak self] in guard let trigger = $0 else { return } if case .authenticateForPlatform(let prompt, let allowBiometricAuth, let callback) = trigger { self?.authenticateForPlatform(prompt: prompt, allowBiometricAuth: allowBiometricAuth, callback: callback) } }) Store.subscribe(self, name: .confirmTransaction(nil, nil, nil, .regular, "", {_ in}), callback: { [weak self] in guard let trigger = $0 else { return } if case .confirmTransaction(let currency?, let amount?, let fee?, let displayFeeLevel, let address, let callback) = trigger { self?.confirmTransaction(currency: currency, amount: amount, fee: fee, displayFeeLevel: displayFeeLevel, address: address, callback: callback) } }) Store.subscribe(self, name: .lightWeightAlert(""), callback: { [weak self] in guard let trigger = $0 else { return } if case let .lightWeightAlert(message) = trigger { self?.showLightWeightAlert(message: message) } }) Store.subscribe(self, name: .showCurrency(nil), callback: { [weak self] in guard let trigger = $0 else { return } if case .showCurrency(let currency?) = trigger { self?.showAccountView(currency: currency, animated: true, completion: nil) } }) // Push Notifications Permission Request Store.subscribe(self, name: .registerForPushNotificationToken) { [weak self] _ in guard let top = self?.topViewController else { return } NotificationAuthorizer().requestAuthorization(fromViewController: top, completion: { granted in DispatchQueue.main.async { if granted { print("[PUSH] notification authorization granted") } else { // TODO: log event print("[PUSH] notification authorization denied") } } }) } // in-app notifications Store.subscribe(self, name: .showInAppNotification(nil)) { [weak self] (trigger) in guard let `self` = self else { return } guard let topVC = self.topViewController else { return } if case let .showInAppNotification(notification?)? = trigger { let display: (UIImage?) -> Void = { (image) in let notificationVC = InAppNotificationViewController(notification, image: image) let navigationController = ModalNavigationController(rootViewController: notificationVC) navigationController.setClearNavbar() topVC.present(navigationController, animated: true, completion: nil) } // Fetch the image first so that it's ready when we display the notification // screen to the user. if let imageUrl = notification.imageUrl, !imageUrl.isEmpty { UIImage.fetchAsync(from: imageUrl) { (image) in display(image) } } else { display(nil) } } } Store.subscribe(self, name: .openPlatformUrl("")) { [weak self] in guard let trigger = $0 else { return } if case let .openPlatformUrl(url) = trigger { self?.presentPlatformWebViewController(url) } } Store.subscribe(self, name: .handleGift(URL(string: "foo.com")!)) { [weak self] in guard let trigger = $0, let `self` = self else { return } if case let .handleGift(url) = trigger { if let gift = QRCode(url: url, viewModel: nil) { let eventName = self.makeEventName([EventContext.gift.name, Event.redeem.name]) self.saveEvent(eventName, attributes: ["\(eventName).method": "link"]) self.handleGift(qrCode: gift) } } } Store.subscribe(self, name: .reImportGift(nil)) { [weak self] in guard let trigger = $0, let `self` = self else { return } if case let .reImportGift(viewModel) = trigger { guard let gift = viewModel?.gift else { return assertionFailure() } let code = QRCode(url: URL(string: gift.url!)!, viewModel: viewModel) guard let wallet = Currencies.btc.instance?.wallet else { return assertionFailure() } let eventName = self.makeEventName([EventContext.gift.name, Event.redeem.name]) self.saveEvent(eventName, attributes: ["\(eventName).method": "reclaim"]) self.presentKeyImport(wallet: wallet, scanResult: code) } } } private func handleGift(qrCode: QRCode) { guard let wallet = Currencies.btc.instance?.wallet else { return } guard case .gift(let key, _) = qrCode else { return } guard let privKey = Key.createFromString(asPrivate: key) else { return } wallet.createSweeper(forKey: privKey) { result in DispatchQueue.main.async { let giftView = RedeemGiftViewController(qrCode: qrCode, wallet: wallet, sweeperResult: result) self.topViewController?.present(giftView, animated: true, completion: nil) } } } private func presentModal(_ type: RootModal) { guard let vc = rootModalViewController(type) else { Store.perform(action: RootModalActions.Present(modal: .none)) return } vc.transitioningDelegate = modalTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true topViewController?.present(vc, animated: true) { Store.perform(action: RootModalActions.Present(modal: .none)) Store.trigger(name: .hideStatusBar) } } func preloadSupportCenter() { supportCenter.preload() // pre-load contents for faster access } func presentFaq(articleId: String? = nil, currency: Currency? = nil) { supportCenter.modalPresentationStyle = .overFullScreen supportCenter.modalPresentationCapturesStatusBarAppearance = true supportCenter.transitioningDelegate = supportCenter var url: String if let articleId = articleId { url = "/support/article?slug=\(articleId)" if let currency = currency { url += "&currency=\(currency.supportCode)" } } else { url = "/support?" } supportCenter.navigate(to: url) topViewController?.present(supportCenter, animated: true, completion: {}) } private func rootModalViewController(_ type: RootModal) -> UIViewController? { switch type { case .none: return nil case .send(let currency): return makeSendView(currency: currency) case .receive(let currency): return makeReceiveView(currency: currency, isRequestAmountVisible: (currency.urlSchemes?.first != nil)) case .loginScan: presentLoginScan() return nil case .requestAmount(let currency, let address): let requestVc = RequestAmountViewController(currency: currency, receiveAddress: address) requestVc.shareAddress = { [weak self] uri, qrCode in self?.messagePresenter.presenter = self?.topViewController self?.messagePresenter.presentShareSheet(text: uri, image: qrCode) } return ModalViewController(childViewController: requestVc) case .buy(let currency): var url = "/buy" if let currency = currency { url += "?currency=\(currency.code)" } presentPlatformWebViewController(url) return nil case .sell(let currency): var url = "/sell" if let currency = currency { url += "?currency=\(currency.code)" } presentPlatformWebViewController(url) return nil case .trade: presentPlatformWebViewController("/trade") return nil case .receiveLegacy: guard let btc = Currencies.btc.instance else { return nil } return makeReceiveView(currency: btc, isRequestAmountVisible: false, isBTCLegacy: true) case .gift : guard let currency = Currencies.btc.instance else { return nil } guard let wallet = system.wallet(for: currency), let kvStore = Backend.kvStore else { assertionFailure(); return nil } let sender = Sender(wallet: wallet, authenticator: keyStore, kvStore: kvStore) let giftView = GiftViewController(sender: sender, wallet: wallet, currency: currency) giftView.presentVerifyPin = { [weak self, weak giftView] bodyText, success in guard let `self` = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletAuthenticator: self.keyStore, pinAuthenticationType: .transactions, success: success) vc.transitioningDelegate = self.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true giftView?.view.isFrameChangeBlocked = true giftView?.present(vc, animated: true, completion: nil) } giftView.onPublishSuccess = { [weak self] in self?.saveEvent("gift.send") self?.alertPresenter?.presentAlert(.sendSuccess, completion: {}) } topViewController?.present(giftView, animated: true, completion: { Store.perform(action: RootModalActions.Present(modal: .none)) }) return nil case .stake(let currency): return makeStakeView(currency: currency) } } private func makeStakeView(currency: Currency) -> UIViewController? { guard let wallet = system.wallet(for: currency), let kvStore = Backend.kvStore else { assertionFailure(); return nil } let sender = Sender(wallet: wallet, authenticator: keyStore, kvStore: kvStore) let stakeView = StakeViewController(currency: currency, sender: sender) stakeView.presentVerifyPin = { [weak self, weak stakeView] bodyText, success in guard let `self` = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletAuthenticator: self.keyStore, pinAuthenticationType: .transactions, success: success) vc.transitioningDelegate = self.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true stakeView?.view.isFrameChangeBlocked = true stakeView?.present(vc, animated: true, completion: nil) } stakeView.onPublishSuccess = { [weak self] in self?.alertPresenter?.presentAlert(.sendSuccess, completion: {}) } return ModalViewController(childViewController: stakeView) } private func makeSendView(currency: Currency) -> UIViewController? { guard let wallet = system.wallet(for: currency), let kvStore = Backend.kvStore else { assertionFailure(); return nil } guard !(currency.state?.isRescanning ?? false) else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let sender = Sender(wallet: wallet, authenticator: keyStore, kvStore: kvStore) let sendVC = SendViewController(sender: sender, initialRequest: currentRequest) currentRequest = nil let root = ModalViewController(childViewController: sendVC) sendVC.presentScan = presentScan(parent: root, currency: currency) sendVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let `self` = self, let root = root else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletAuthenticator: self.keyStore, pinAuthenticationType: .transactions, success: success) vc.transitioningDelegate = self.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root.view.isFrameChangeBlocked = true root.present(vc, animated: true, completion: nil) } sendVC.onPublishSuccess = { [weak self] in self?.alertPresenter?.presentAlert(.sendSuccess, completion: {}) } return root } private func makeReceiveView(currency: Currency, isRequestAmountVisible: Bool, isBTCLegacy: Bool = false) -> UIViewController? { let receiveVC = ReceiveViewController(currency: currency, isRequestAmountVisible: isRequestAmountVisible, isBTCLegacy: isBTCLegacy) let root = ModalViewController(childViewController: receiveVC) receiveVC.shareAddress = { [weak self, weak root] address, qrCode in guard let `self` = self, let root = root else { return } self.messagePresenter.presenter = root self.messagePresenter.presentShareSheet(text: address, image: qrCode) } return root } private func presentLoginScan() { guard let top = topViewController else { return } let present = presentScan(parent: top, currency: nil) present { [unowned self] scanResult in guard let scanResult = scanResult else { return } switch scanResult { case .paymentRequest(let request): let message = String(format: S.Scanner.paymentPromptMessage, request.currency.name) let alert = UIAlertController.confirmationAlert(title: S.Scanner.paymentPrompTitle, message: message) { self.currentRequest = request self.presentModal(.send(currency: request.currency)) } top.present(alert, animated: true, completion: nil) case .privateKey: let alert = UIAlertController(title: S.Settings.importTile, message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "BTC", style: .default, handler: { _ in if let wallet = Currencies.btc.instance?.wallet { self.presentKeyImport(wallet: wallet, scanResult: scanResult) } })) alert.addAction(UIAlertAction(title: "BCH", style: .default, handler: { _ in if let wallet = Currencies.bch.instance?.wallet { self.presentKeyImport(wallet: wallet, scanResult: scanResult) } })) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) top.present(alert, animated: true, completion: nil) case .deepLink(let url): UIApplication.shared.open(url) case .invalid: break case .gift: let eventName = makeEventName([EventContext.gift.name, Event.redeem.name]) saveEvent(eventName, attributes: ["\(eventName).method": "scan"]) self.handleGift(qrCode: scanResult) } } } // MARK: Settings func presentMenu() { let menuNav = UINavigationController() menuNav.setDarkStyle() // MARK: Bitcoin Menu var btcItems: [MenuItem] = [] if let btc = Currencies.btc.instance, let btcWallet = btc.wallet { // Connection mode btcItems.append(MenuItem(title: S.WalletConnectionSettings.menuTitle) { [weak self] in self?.presentConnectionModeScreen(menuNav: menuNav) }) // Rescan var rescan = MenuItem(title: S.Settings.sync, callback: { [unowned self] in menuNav.pushViewController(ReScanViewController(system: self.system, wallet: btcWallet), animated: true) }) rescan.shouldShow = { [unowned self] in self.system.connectionMode(for: btc) == .p2p_only } btcItems.append(rescan) // Nodes var nodeSelection = MenuItem(title: S.NodeSelector.title, callback: { let nodeSelector = NodeSelectorViewController(wallet: btcWallet) menuNav.pushViewController(nodeSelector, animated: true) }) nodeSelection.shouldShow = { [unowned self] in self.system.connectionMode(for: btc) == .p2p_only } btcItems.append(nodeSelection) btcItems.append(MenuItem(title: S.Settings.importTile, callback: { menuNav.dismiss(animated: true, completion: { [weak self] in guard let `self` = self else { return } self.presentKeyImport(wallet: btcWallet) }) })) var enableSegwit = MenuItem(title: S.Settings.enableSegwit, callback: { let segwitView = SegwitViewController() menuNav.pushViewController(segwitView, animated: true) }) enableSegwit.shouldShow = { return !UserDefaults.hasOptedInSegwit } var viewLegacyAddress = MenuItem(title: S.Settings.viewLegacyAddress, callback: { Backend.apiClient.sendViewLegacyAddress() Store.perform(action: RootModalActions.Present(modal: .receiveLegacy)) }) viewLegacyAddress.shouldShow = { return UserDefaults.hasOptedInSegwit } btcItems.append(enableSegwit) btcItems.append(viewLegacyAddress) } var btcMenu = MenuItem(title: String(format: S.Settings.currencyPageTitle, Currencies.btc.instance?.name ?? "Bitcoin"), subMenu: btcItems, rootNav: menuNav) btcMenu.shouldShow = { return !btcItems.isEmpty } // MARK: Bitcoin Cash Menu var bchItems: [MenuItem] = [] if let bch = Currencies.bch.instance, let bchWallet = bch.wallet { if system.connectionMode(for: bch) == .p2p_only { // Rescan bchItems.append(MenuItem(title: S.Settings.sync, callback: { [weak self] in guard let `self` = self else { return } menuNav.pushViewController(ReScanViewController(system: self.system, wallet: bchWallet), animated: true) })) } bchItems.append(MenuItem(title: S.Settings.importTile, callback: { menuNav.dismiss(animated: true, completion: { [unowned self] in self.presentKeyImport(wallet: bchWallet) }) })) } var bchMenu = MenuItem(title: String(format: S.Settings.currencyPageTitle, Currencies.bch.instance?.name ?? "Bitcoin Cash"), subMenu: bchItems, rootNav: menuNav) bchMenu.shouldShow = { return !bchItems.isEmpty } // MARK: Ethereum Menu var ethItems: [MenuItem] = [] if let eth = Currencies.eth.instance, let ethWallet = eth.wallet { if system.connectionMode(for: eth) == .p2p_only { // Rescan ethItems.append(MenuItem(title: S.Settings.sync, callback: { [weak self] in guard let `self` = self else { return } menuNav.pushViewController(ReScanViewController(system: self.system, wallet: ethWallet), animated: true) })) } } var ethMenu = MenuItem(title: String(format: S.Settings.currencyPageTitle, Currencies.eth.instance?.name ?? "Ethereum"), subMenu: ethItems, rootNav: menuNav) ethMenu.shouldShow = { return !ethItems.isEmpty } // MARK: Preferences let preferencesItems: [MenuItem] = [ // Display Currency MenuItem(title: S.Settings.currency, accessoryText: { let code = Store.state.defaultCurrencyCode let components: [String: String] = [NSLocale.Key.currencyCode.rawValue: code] let identifier = Locale.identifier(fromComponents: components) return Locale(identifier: identifier).currencyCode ?? "" }, callback: { menuNav.pushViewController(DefaultCurrencyViewController(), animated: true) }), btcMenu, bchMenu, ethMenu, // Share Anonymous Data MenuItem(title: S.Settings.shareData, callback: { menuNav.pushViewController(ShareDataViewController(), animated: true) }), // Reset Wallets MenuItem(title: S.Settings.resetCurrencies, callback: { [weak self] in guard let `self` = self else { return } menuNav.dismiss(animated: true, completion: { self.system.resetToDefaultCurrencies() }) }), // Notifications MenuItem(title: S.Settings.notifications, callback: { menuNav.pushViewController(PushNotificationsViewController(), animated: true) }) ] // MARK: Security Settings var securityItems: [MenuItem] = [ // Unlink MenuItem(title: S.Settings.wipe) { [weak self] in guard let `self` = self, let vc = self.topViewController else { return } RecoveryKeyFlowController.enterUnlinkWalletFlow(from: vc, keyMaster: self.keyStore, phraseEntryReason: .validateForWipingWallet({ [weak self] in self?.wipeWallet() })) }, // Update PIN MenuItem(title: S.UpdatePin.updateTitle) { [weak self] in guard let `self` = self else { return } let updatePin = UpdatePinViewController(keyMaster: self.keyStore, type: .update) menuNav.pushViewController(updatePin, animated: true) }, // Biometrics MenuItem(title: LAContext.biometricType() == .face ? S.SecurityCenter.Cells.faceIdTitle : S.SecurityCenter.Cells.touchIdTitle) { [weak self] in guard let `self` = self else { return } self.presentBiometricsMenuItem() }, // Paper key MenuItem(title: S.SecurityCenter.Cells.paperKeyTitle) { [weak self] in guard let `self` = self else { return } self.presentWritePaperKey(fromViewController: menuNav) }, // Portfolio data for widget MenuItem(title: S.Settings.shareWithWidget, accessoryText: { [weak self] in self?.system.widgetDataShareService.sharingEnabled ?? false ? "ON" : "OFF" }, callback: { [weak self] in self?.system.widgetDataShareService.sharingEnabled.toggle() (menuNav.topViewController as? MenuViewController)?.reloadMenu() }) ] // Add iCloud backup if #available(iOS 13.6, *) { securityItems.append( MenuItem(title: S.CloudBackup.backupMenuTitle) { let synchronizer = BackupSynchronizer(context: .existingWallet, keyStore: self.keyStore, navController: menuNav) let cloudView = CloudBackupView(synchronizer: synchronizer) let hosting = UIHostingController(rootView: cloudView) menuNav.pushViewController(hosting, animated: true) } ) } // MARK: Root Menu var rootItems: [MenuItem] = [ // Scan QR Code MenuItem(title: S.MenuButton.scan, icon: MenuItem.Icon.scan) { [weak self] in self?.presentLoginScan() }, // Manage Wallets MenuItem(title: S.MenuButton.manageWallets, icon: MenuItem.Icon.wallet) { [weak self] in guard let `self` = self, let assetCollection = self.system.assetCollection else { return } let vc = ManageWalletsViewController(assetCollection: assetCollection, coreSystem: self.system) menuNav.pushViewController(vc, animated: true) }, // Preferences MenuItem(title: S.Settings.preferences, icon: MenuItem.Icon.preferences, subMenu: preferencesItems, rootNav: menuNav), // Security MenuItem(title: S.MenuButton.security, icon: #imageLiteral(resourceName: "security"), subMenu: securityItems, rootNav: menuNav, faqButton: UIButton.buildFaqButton(articleId: ArticleIds.securityCenter)), // Support MenuItem(title: S.MenuButton.support, icon: MenuItem.Icon.support) { [weak self] in self?.presentFaq() }, // Rewards MenuItem(title: S.Settings.rewards, icon: MenuItem.Icon.rewards) { [weak self] in self?.presentPlatformWebViewController("/rewards") }, // About MenuItem(title: S.Settings.about, icon: MenuItem.Icon.about) { menuNav.pushViewController(AboutViewController(), animated: true) }, // Export Transfer History MenuItem(title: S.Settings.exportTransfers, icon: MenuItem.Icon.export) { [weak self] in self?.presentExportTransfers() } ] // ATM Finder if let experiment = Store.state.experimentWithName(.atmFinder), experiment.active, let meta = experiment.meta as? BrowserExperimentMetaData, let url = meta.url, !url.isEmpty, let URL = URL(string: url) { rootItems.append(MenuItem(title: S.Settings.atmMapMenuItemTitle, subTitle: S.Settings.atmMapMenuItemSubtitle, icon: MenuItem.Icon.atmMap) { [weak self] in guard let `self` = self else { return } let browser = BRBrowserViewController() browser.isNavigationBarHidden = true browser.showsBottomToolbar = false browser.statusBarStyle = .lightContent if let closeUrl = meta.closeOn { browser.closeOnURL = closeUrl } let req = URLRequest(url: URL) browser.load(req) self.topViewController?.present(browser, animated: true, completion: nil) }) } // MARK: Developer/QA Menu if E.isSimulator || E.isDebug || E.isTestFlight { var developerItems = [MenuItem]() developerItems.append(MenuItem(title: "Fast Sync", callback: { [weak self] in self?.presentConnectionModeScreen(menuNav: menuNav) })) developerItems.append(MenuItem(title: S.Settings.sendLogs) { [weak self] in self?.showEmailLogsModal() }) developerItems.append(MenuItem(title: "Lock Wallet") { Store.trigger(name: .lock) }) developerItems.append(MenuItem(title: "Unlink Wallet (no prompt)") { Store.trigger(name: .wipeWalletNoPrompt) }) if E.isDebug { // for dev/debugging use only // For test wallets with a PIN of 111111, the PIN is auto entered on startup. developerItems.append(MenuItem(title: "Auto-enter PIN", accessoryText: { UserDefaults.debugShouldAutoEnterPIN ? "ON" : "OFF" }, callback: { _ = UserDefaults.toggleAutoEnterPIN() (menuNav.topViewController as? MenuViewController)?.reloadMenu() })) developerItems.append(MenuItem(title: "Connection Settings Override", accessoryText: { UserDefaults.debugConnectionModeOverride.description }, callback: { UserDefaults.cycleConnectionModeOverride() (menuNav.topViewController as? MenuViewController)?.reloadMenu() })) } // For test wallets, suppresses the paper key prompt on the home screen. developerItems.append(MenuItem(title: "Suppress paper key prompt", accessoryText: { UserDefaults.debugShouldSuppressPaperKeyPrompt ? "ON" : "OFF" }, callback: { _ = UserDefaults.toggleSuppressPaperKeyPrompt() (menuNav.topViewController as? MenuViewController)?.reloadMenu() })) // always show the app rating when viewing transactions if 'ON' AND Suppress is 'OFF' (see below) developerItems.append(MenuItem(title: "App rating on enter wallet", accessoryText: { UserDefaults.debugShowAppRatingOnEnterWallet ? "ON" : "OFF" }, callback: { _ = UserDefaults.toggleShowAppRatingPromptOnEnterWallet() (menuNav.topViewController as? MenuViewController)?.reloadMenu() })) developerItems.append(MenuItem(title: "Suppress app rating prompt", accessoryText: { UserDefaults.debugSuppressAppRatingPrompt ? "ON" : "OFF" }, callback: { _ = UserDefaults.toggleSuppressAppRatingPrompt() (menuNav.topViewController as? MenuViewController)?.reloadMenu() })) // Shows a preview of the paper key. if UserDefaults.debugShouldAutoEnterPIN, let paperKey = keyStore.seedPhrase(pin: "111111") { let words = paperKey.components(separatedBy: " ") let timestamp = (try? keyStore.loadAccount().map { $0.timestamp }.get()) ?? Date.zeroValue() let preview = "\(words[0]) \(words[1])... (\(DateFormatter.mediumDateFormatter.string(from: timestamp))" developerItems.append(MenuItem(title: "Paper key preview", accessoryText: { UserDefaults.debugShouldShowPaperKeyPreview ? preview : "" }, callback: { _ = UserDefaults.togglePaperKeyPreview() (menuNav.topViewController as? MenuViewController)?.reloadMenu() })) } developerItems.append(MenuItem(title: "Reset User Defaults", callback: { UserDefaults.resetAll() menuNav.showAlert(title: "", message: "User defaults reset") (menuNav.topViewController as? MenuViewController)?.reloadMenu() })) developerItems.append(MenuItem(title: "Clear Core persistent storage and exit", callback: { [weak self] in guard let `self` = self else { return } self.system.shutdown { fatalError("forced exit") } })) developerItems.append( MenuItem(title: "API Host", accessoryText: { Backend.apiClient.host }, callback: { let alert = UIAlertController(title: "Set API Host", message: "Clear and save to reset", preferredStyle: .alert) alert.addTextField(configurationHandler: { textField in textField.text = Backend.apiClient.host textField.keyboardType = .URL textField.clearButtonMode = .always }) alert.addAction(UIAlertAction(title: "Save", style: .default) { (_) in guard let newHost = alert.textFields?.first?.text, !newHost.isEmpty else { UserDefaults.debugBackendHost = nil Backend.apiClient.host = C.backendHost (menuNav.topViewController as? MenuViewController)?.reloadMenu() return } let originalHost = Backend.apiClient.host Backend.apiClient.host = newHost Backend.apiClient.me { (success, _, _) in if success { UserDefaults.debugBackendHost = newHost (menuNav.topViewController as? MenuViewController)?.reloadMenu() } else { Backend.apiClient.host = originalHost } } }) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) menuNav.present(alert, animated: true, completion: nil) })) developerItems.append( MenuItem(title: "Web Platform Bundle", accessoryText: { C.webBundle }, callback: { let alert = UIAlertController(title: "Set bundle name", message: "Clear and save to reset", preferredStyle: .alert) alert.addTextField(configurationHandler: { textField in textField.text = C.webBundle textField.keyboardType = .URL textField.clearButtonMode = .always }) alert.addAction(UIAlertAction(title: "Save", style: .default) { (_) in guard let newBundleName = alert.textFields?.first?.text, !newBundleName.isEmpty else { UserDefaults.debugWebBundleName = nil (menuNav.topViewController as? MenuViewController)?.reloadMenu() return } guard let bundle = AssetArchive(name: newBundleName, apiClient: Backend.apiClient) else { return assertionFailure() } bundle.update { error in DispatchQueue.main.async { guard error == nil else { let alert = UIAlertController(title: S.Alert.error, message: "Unable to fetch bundle named \(newBundleName)", preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .default, handler: nil)) menuNav.present(alert, animated: true, completion: nil) return } UserDefaults.debugWebBundleName = newBundleName (menuNav.topViewController as? MenuViewController)?.reloadMenu() } } }) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) menuNav.present(alert, animated: true, completion: nil) })) developerItems.append( MenuItem(title: "Web Platform Debug URL", accessoryText: { UserDefaults.platformDebugURL?.absoluteString ?? "<not set>" }, callback: { let alert = UIAlertController(title: "Set debug URL", message: "Clear and save to reset", preferredStyle: .alert) alert.addTextField(configurationHandler: { textField in textField.text = UserDefaults.platformDebugURL?.absoluteString ?? "" textField.keyboardType = .URL textField.clearButtonMode = .always }) alert.addAction(UIAlertAction(title: "Save", style: .default) { (_) in guard let input = alert.textFields?.first?.text, !input.isEmpty, let debugURL = URL(string: input) else { UserDefaults.platformDebugURL = nil (menuNav.topViewController as? MenuViewController)?.reloadMenu() return } UserDefaults.platformDebugURL = debugURL (menuNav.topViewController as? MenuViewController)?.reloadMenu() }) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) menuNav.present(alert, animated: true, completion: nil) })) rootItems.append(MenuItem(title: "Developer Options", icon: nil, subMenu: developerItems, rootNav: menuNav, faqButton: nil)) } let rootMenu = MenuViewController(items: rootItems, title: S.Settings.title) rootMenu.addCloseNavigationItem(side: .right) menuNav.viewControllers = [rootMenu] self.menuNavController = menuNav self.topViewController?.present(menuNav, animated: true, completion: nil) } private func presentConnectionModeScreen(menuNav: UINavigationController) { guard let kv = Backend.kvStore, let walletInfo = WalletInfo(kvStore: kv) else { return assertionFailure() } let connectionSettings = WalletConnectionSettings(system: self.system, kvStore: kv, walletInfo: walletInfo) let connectionSettingsVC = WalletConnectionSettingsViewController(walletConnectionSettings: connectionSettings) { _ in (menuNav.viewControllers.compactMap { $0 as? MenuViewController }).last?.reloadMenu() } menuNav.pushViewController(connectionSettingsVC, animated: true) } private func presentScan(parent: UIViewController, currency: Currency?) -> PresentScan { return { [weak parent] scanCompletion in guard ScanViewController.isCameraAllowed else { self.saveEvent("scan.cameraDenied") if let parent = parent { ScanViewController.presentCameraUnavailableAlert(fromRoot: parent) } return } let vc = ScanViewController(forPaymentRequestForCurrency: currency, completion: { scanResult in scanCompletion(scanResult) parent?.view.isFrameChangeBlocked = false }) parent?.view.isFrameChangeBlocked = true parent?.present(vc, animated: true, completion: {}) } } private func presentWritePaperKey(fromViewController vc: UIViewController) { RecoveryKeyFlowController.enterRecoveryKeyFlow(pin: nil, keyMaster: self.keyStore, from: vc, context: .none, dismissAction: nil) } private func presentPlatformWebViewController(_ mountPoint: String) { let vc = BRWebViewController(bundleName: C.webBundle, mountPoint: mountPoint, walletAuthenticator: keyStore, system: system) vc.startServer() vc.preload() vc.modalPresentationStyle = .overFullScreen self.topViewController?.present(vc, animated: true, completion: nil) } private func wipeWallet() { let alert = UIAlertController.confirmationAlert(title: S.WipeWallet.alertTitle, message: S.WipeWallet.alertMessage, okButtonTitle: S.WipeWallet.wipe, cancelButtonTitle: S.Button.cancel, isDestructiveAction: true) { self.topViewController?.dismiss(animated: true, completion: { Store.trigger(name: .wipeWalletNoPrompt) }) } topViewController?.present(alert, animated: true, completion: nil) } private func presentKeyImport(wallet: Wallet, scanResult: QRCode? = nil) { let nc = ModalNavigationController() nc.setClearNavbar() nc.setWhiteStyle() let start = ImportKeyViewController(wallet: wallet, initialQRCode: scanResult) start.addCloseNavigationItem(tintColor: .white) start.navigationItem.title = S.Import.title let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.importWallet, currency: wallet.currency) faqButton.tintColor = .white start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding, UIBarButtonItem(customView: faqButton)] nc.viewControllers = [start] topViewController?.present(nc, animated: true, completion: nil) } // MARK: - Prompts func presentExportTransfers() { let alert = UIAlertController(title: S.ExportTransfers.header, message: S.ExportTransfers.body, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.ExportTransfers.confirmExport, style: .default, handler: { (_) in self.topViewController?.present(BRActivityViewController(message: ""), animated: true, completion: nil) DispatchQueue.global(qos: .background).async { guard let csvFile = CsvExporter.instance.exportTransfers(wallets: self.system.wallets) else { DispatchQueue.main.async { self.topViewController?.dismiss(animated: true) { self.topViewController?.showAlert( title: S.ExportTransfers.exportFailedTitle, message: S.ExportTransfers.exportFailedBody) } } return } DispatchQueue.main.async { self.topViewController?.dismiss(animated: true) { let activityViewController = UIActivityViewController(activityItems: [csvFile], applicationActivities: nil) self.topViewController?.present(activityViewController, animated: true, completion: nil) } } } })) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) } func presentBiometricsMenuItem() { let biometricsSettings = BiometricsSettingsViewController(self.keyStore) biometricsSettings.addCloseNavigationItem(tintColor: .white) let nc = ModalNavigationController(rootViewController: biometricsSettings) nc.setWhiteStyle() nc.isNavigationBarHidden = true nc.delegate = securityCenterNavigationDelegate topViewController?.present(nc, animated: true, completion: nil) } private func promptShareData() { let shareData = ShareDataViewController() let nc = ModalNavigationController(rootViewController: shareData) nc.setDefaultStyle() nc.isNavigationBarHidden = true nc.delegate = securityCenterNavigationDelegate shareData.addCloseNavigationItem() topViewController?.present(nc, animated: true, completion: nil) } func presentWritePaperKey() { guard let vc = topViewController else { return } presentWritePaperKey(fromViewController: vc) } func presentUpgradePin() { let updatePin = UpdatePinViewController(keyMaster: keyStore, type: .update) let nc = ModalNavigationController(rootViewController: updatePin) nc.setDefaultStyle() nc.isNavigationBarHidden = true nc.delegate = securityCenterNavigationDelegate updatePin.addCloseNavigationItem() topViewController?.present(nc, animated: true, completion: nil) } private func handleFile(_ file: Data) { //TODO:CRYPTO payment request -- what is this use case? /* if let request = PaymentProtocolRequest(data: file) { if let topVC = topViewController as? ModalViewController { let attemptConfirmRequest: () -> Bool = { if let send = topVC.childViewController as? SendViewController { send.confirmProtocolRequest(request) return true } return false } if !attemptConfirmRequest() { modalTransitionDelegate.reset() topVC.dismiss(animated: true, completion: { //TODO:BCH Store.perform(action: RootModalActions.Present(modal: .send(currency: Currencies.btc))) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { //This is a hack because present has no callback _ = attemptConfirmRequest() }) }) } } } else if let ack = PaymentProtocolACK(data: file) { if let memo = ack.memo { let alert = UIAlertController(title: "", message: memo, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) } //TODO - handle payment type } else { let alert = UIAlertController(title: S.Alert.error, message: S.PaymentProtocol.Errors.corruptedDocument, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) } */ } private func handlePaymentRequest(request: PaymentRequest) { self.currentRequest = request guard !Store.state.isLoginRequired else { presentModal(.send(currency: request.currency)); return } showAccountView(currency: request.currency, animated: false) { self.presentModal(.send(currency: request.currency)) } } private func showAccountView(currency: Currency, animated: Bool, completion: (() -> Void)?) { let pushAccountView = { guard let nc = self.topViewController?.navigationController as? RootNavigationController, nc.viewControllers.count == 1 else { return } let accountViewController = AccountViewController(currency: currency, wallet: self.system.wallet(for: currency)) nc.pushViewController(accountViewController, animated: animated) completion?() } if let accountVC = topViewController as? AccountViewController { if accountVC.currency == currency { completion?() } else { accountVC.navigationController?.popToRootViewController(animated: false) pushAccountView() } } else if topViewController is HomeScreenViewController { pushAccountView() } else if let presented = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController { if let nc = presented.presentingViewController as? RootNavigationController, nc.viewControllers.count > 1 { // modal on top of another account screen presented.dismiss(animated: false) { self.showAccountView(currency: currency, animated: animated, completion: completion) } } else { presented.dismiss(animated: true) { pushAccountView() } } } } private func handleScanQrURL() { guard !Store.state.isLoginRequired else { presentLoginScan(); return } if topViewController is AccountViewController || topViewController is LoginViewController { presentLoginScan() } else { if let presented = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController { presented.dismiss(animated: true, completion: { self.presentLoginScan() }) } } } private func authenticateForPlatform(prompt: String, allowBiometricAuth: Bool, callback: @escaping (PlatformAuthResult) -> Void) { if allowBiometricAuth && keyStore.isBiometricsEnabledForUnlocking { keyStore.authenticate(withBiometricsPrompt: prompt, completion: { result in switch result { case .success: return callback(.success(nil)) case .cancel: return callback(.cancelled) case .failure: self.verifyPinForPlatform(prompt: prompt, callback: callback) case .fallback: self.verifyPinForPlatform(prompt: prompt, callback: callback) } }) } else { self.verifyPinForPlatform(prompt: prompt, callback: callback) } } private func verifyPinForPlatform(prompt: String, callback: @escaping (PlatformAuthResult) -> Void) { let verify = VerifyPinViewController(bodyText: prompt, pinLength: Store.state.pinLength, walletAuthenticator: keyStore, pinAuthenticationType: .unlocking, success: { pin in callback(.success(pin)) }) verify.didCancel = { callback(.cancelled) } verify.transitioningDelegate = verifyPinTransitionDelegate verify.modalPresentationStyle = .overFullScreen verify.modalPresentationCapturesStatusBarAppearance = true topViewController?.present(verify, animated: true, completion: nil) } private func confirmTransaction(currency: Currency, amount: Amount, fee: Amount, displayFeeLevel: FeeLevel, address: String, callback: @escaping (Bool) -> Void) { let confirm = ConfirmationViewController(amount: amount, fee: fee, displayFeeLevel: displayFeeLevel, address: address, isUsingBiometrics: false, currency: currency, shouldShowMaskView: true) confirm.successCallback = { callback(true) } confirm.cancelCallback = { callback(false) } topViewController?.present(confirm, animated: true, completion: nil) } private var topViewController: UIViewController? { var viewController = window.rootViewController if let nc = viewController as? UINavigationController { viewController = nc.topViewController } while viewController?.presentedViewController != nil { viewController = viewController?.presentedViewController } return viewController } private func showLightWeightAlert(message: String) { let alert = LightWeightAlert(message: message) let view = UIApplication.shared.keyWindow! view.addSubview(alert) alert.constrain([ alert.centerXAnchor.constraint(equalTo: view.centerXAnchor), alert.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) alert.background.effect = nil UIView.animate(withDuration: 0.6, animations: { alert.background.effect = alert.effect }, completion: { _ in UIView.animate(withDuration: 0.6, delay: 1.0, options: [], animations: { alert.background.effect = nil }, completion: { _ in alert.removeFromSuperview() }) }) } private func showEmailLogsModal() { self.messagePresenter.presenter = self.topViewController self.messagePresenter.presentEmailLogs() } } class SecurityCenterNavigationDelegate: NSObject, UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { guard let coordinator = navigationController.topViewController?.transitionCoordinator else { return } if coordinator.isInteractive { coordinator.notifyWhenInteractionChanges { context in //We only want to style the view controller if the //pop animation wasn't cancelled if !context.isCancelled { self.setStyle(navigationController: navigationController) } } } else { setStyle(navigationController: navigationController) } } func setStyle(navigationController: UINavigationController) { navigationController.isNavigationBarHidden = false navigationController.setDefaultStyle() } }
mit
d6a4f80aeb8a0f3945c0f7d8c1be7d6b
48.800975
169
0.551652
5.847482
false
false
false
false
ajsnow/Shear
Shear/SwiftExtensions.swift
1
3925
// Copyright 2016 The Shear Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. import Foundation public extension Sequence { /// Return the array of partial results of repeatedly calling `combine` with an /// accumulated value initialized to `initial` and each element of /// `self`, in turn, i.e. return /// `[initial, combine(results[0], self[0]),...combine(results[count-1], self[count-1]]`. func scan<T>(_ initial: T, combine: (T, Self.Iterator.Element) -> T) -> [T] { var results: [T] = [initial] for (i, v) in self.enumerated() { results.append(combine(results[i], v)) } return results } } // We could have defined these on sequence types, but this definition is much nicer public extension Collection { func reduce(_ combine: (Iterator.Element, Iterator.Element) -> Iterator.Element) -> Iterator.Element { guard !isEmpty else { fatalError("CollectionType must have at least one element to be self-reduced") } return dropFirst().reduce(first!, combine) } /// Return the array of partial results of repeatedly calling `combine` with an /// accumulated value initialized to `initial` and each element of /// `self`, in turn, i.e. return /// `[self[0], combine(results[0], self[1]),...combine(results[count-2], self[count-1]]`. func scan(_ combine: (Iterator.Element, Iterator.Element) -> Iterator.Element) -> [Iterator.Element] { guard !isEmpty else { fatalError("CollectionType must have at least one element to be self-scanned.") } var results = [first!] as [Iterator.Element] for v in self.dropFirst() { results.append(combine(results.last!, v)) } return results } } extension Collection where Iterator.Element: Equatable { func allEqual() -> Bool { guard let first = self.first else { return true } // An empty array certainly has uniform contents. return !self.contains { $0 != first } } } extension Collection { func allEqual<A>(_ compare: (Iterator.Element) -> A) -> Bool where A: Equatable { guard let first = self.first else { return true } // An empty array certainly has uniform contents. let firstTransformed = compare(first) return !self.contains { compare($0) != firstTransformed } } } public extension Array { public func ravel() -> Tensor<Iterator.Element> { return Tensor(shape: [Int(count)], values: self) } public func reshape(_ shape: [Int]) -> Tensor<Iterator.Element> { return Tensor(shape: shape, values: self) } public func rotate(_ s: Int) -> [Iterator.Element] { let shift = modulo(s, base: count) let back = self[0..<shift] let front = self[shift..<count] return [Element](front) + back } } extension Collection where Index: BinaryInteger { func ravel() -> Tensor<Iterator.Element> { let array = self.map { $0 } return array.ravel() } func reshape(_ shape: [Int]) -> Tensor<Iterator.Element> { return Tensor(shape: shape, values: Array(self)) } } extension String { func leftpad(_ count: Int, padding: Character = " ") -> String { let paddingCount = count - self.characters.count switch paddingCount { case 0: return self case _ where paddingCount < 0: return String(self[self.startIndex..<self.characters.index(self.startIndex, offsetBy: count)]) default: let pad = String(repeating: String(padding), count: paddingCount) return pad + self } } } func modulo(_ count: Int, base: Int) -> Int { let m = count % base return m < 0 ? m + base : m }
mit
42d77780ce0a2b5d9ae10637badc0292
31.438017
111
0.612229
4.153439
false
false
false
false
BridgeTheGap/KRMathInputView
KRMathInputView/Classes/MathInputView.swift
1
12044
// // MathInputView.swift // TestScript // // Created by Joshua Park on 31/01/2017. // Copyright © 2017 Knowre. All rights reserved. // import UIKit @objc public protocol MathInputViewDelegate: NSObjectProtocol { func mathInputView(_ mathInputView: MathInputView, didTap node: ObjCNode?) func mathInputView(_ mathInputView: MathInputView, didLongPress node: ObjCNode?) func mathInputView(_ mathInputView: MathInputView, didRemove node: ObjCNode) func mathInputView(_ mathInputView: MathInputView, didReplace oldNode: ObjCNode, with newNode: ObjCNode) func mathInputView(_ mathInputView: MathInputView, didParse ink: [Any], latex: String) func mathInputView(_ mathInputView: MathInputView, didFailToParse ink: [Any], with error: NSError) func mathInputView(_ mathInputView: MathInputView, didChangeModeTo isWritingMode: Bool) } private typealias ProtocolCollection = MathInkRendering & KeyboardTypeDelegate & KeyboardTypeDataSource open class MathInputView: UIView, ProtocolCollection { open weak var delegate: MathInputViewDelegate? open var isWritingMode: Bool = true { willSet { tapGestureRecognizer.isEnabled = !newValue longPressGestureRecognizer.isEnabled = !newValue if !isWritingMode && newValue { manager.selectNode(at: nil) display(node: nil) delegate?.mathInputView(self, didTap: nil) } } didSet { if oldValue != isWritingMode { delegate?.mathInputView(self, didChangeModeTo: isWritingMode) } } } open var manager = MathInkManager() @IBOutlet open weak var undoButton: UIButton? @IBOutlet open weak var redoButton: UIButton? public var lineWidth: CGFloat = 3.0 public var selectionPadding: CGFloat = 8.0 public var nodePadding: CGFloat { return lineWidth + selectionPadding } public var selectionBGColor = UIColor(hex: 0x00BCD4, alpha: 0.1) public var selectionStrokeColor = UIColor(hex: 0x00BCD4) public var fontName: String? public var selectedNodeCandidates: [String]? { guard let index = manager.indexOfSelectedNode else { return nil } return manager.nodes[index].candidates.filter { $0.count == 1 } } open weak var candidatesView: KeyboardType? { didSet { candidatesView?.delegate = self candidatesView?.dataSource = self } } open weak var keyboardView: KeyboardType? { didSet { keyboardView?.delegate = self keyboardView?.dataSource = self } } public weak var selectedNodeLayer: CALayer? public let tapGestureRecognizer = UITapGestureRecognizer() public let longPressGestureRecognizer = UILongPressGestureRecognizer() override public init(frame: CGRect) { super.init(frame: frame) setUp() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUp() } private func setUp() { clipsToBounds = true tapGestureRecognizer.addTarget(self, action: #selector(tapAction(_:))) tapGestureRecognizer.isEnabled = false addGestureRecognizer(tapGestureRecognizer) longPressGestureRecognizer.addTarget(self, action: #selector(longPressAction(_:))) longPressGestureRecognizer.isEnabled = false addGestureRecognizer(longPressGestureRecognizer) manager.renderer = self } // MARK: - Public override open func draw(_ rect: CGRect) { UIColor.black.setStroke() for ink in manager.ink { if let strokeInk = ink as? StrokeInk { guard rect.intersects(strokeInk.path.bounds) else { continue } strokeInk.path.lineWidth = lineWidth strokeInk.path.lineCapStyle = .round strokeInk.path.stroke() } else { // TODO: Add error handling let charInk = ink as! CharacterInk guard rect.intersects(charInk.frame) else { continue } guard let ctx = UIGraphicsGetCurrentContext() else { return } guard let image = getImage(for: charInk, strokeColor: UIColor.black) else { return } ctx.draw(image.cgImage!, in: charInk.frame) } } if let stroke = manager.buffer { stroke.lineWidth = lineWidth stroke.lineCapStyle = .round stroke.stroke() } } // MARK: - Node @discardableResult open func selectNode(at point: NSValue?) -> Node? { return selectNode(at: point?.cgPointValue) } @discardableResult open func selectNode(at point: CGPoint?) -> Node? { let node = manager.selectNode(at: point) display(node: node) return node } private func getImage(for charInk: CharacterInk, strokeColor: UIColor) -> UIImage? { let size = charInk.frame.height - selectionPadding * 2.0 let font = (fontName != nil ? UIFont(name: fontName!, size: size) : UIFont.systemFont(ofSize: size)) ?? UIFont.systemFont(ofSize: size) let attrib = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: strokeColor] let attribString = NSAttributedString(string: String(charInk.character), attributes: attrib) let line = CTLineCreateWithAttributedString(attribString as CFAttributedString) var frame = CTLineGetImageBounds(line, nil) frame.size.width += abs(frame.origin.x) frame.size.height += abs(frame.origin.y) UIGraphicsBeginImageContextWithOptions(frame.size, false, 0.0) guard let fontCtx = UIGraphicsGetCurrentContext() else { return nil } fontCtx.textPosition = CGPoint(x: -frame.origin.x, y: -frame.origin.y) CTLineDraw(line, fontCtx) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } open func image(for node: Node) -> UIImage? { UIGraphicsBeginImageContextWithOptions(node.frame.size, false, 0.0) guard let ctx = UIGraphicsGetCurrentContext() else { return nil } ctx.saveGState() ctx.setFillColor(selectionBGColor.cgColor) ctx.setStrokeColor(selectionStrokeColor.cgColor) ctx.fill(CGRect(origin: CGPoint.zero, size: node.frame.size)) ctx.translateBy(x: -node.frame.origin.x, y: -node.frame.origin.y) ctx.setLineWidth(lineWidth) ctx.setLineCap(.round) for ink in node.ink { if let strokeInk = ink as? StrokeInk { ctx.addPath(strokeInk.path.cgPath) } else { let charInk = ink as! CharacterInk guard let image = getImage(for: charInk, strokeColor: selectionStrokeColor)?.cgImage else { return nil } ctx.draw(image, in: charInk.frame) } } ctx.strokePath() ctx.restoreGState() let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } // TODO: Add error handling open func display(node: Node?) { selectedNodeLayer?.removeFromSuperlayer() candidatesView?.hideKeyboard(nil) guard let node = node else { return } // Draw image of strokes and the bounding box // Set as layer content and assign `selectedNodeLayer` guard let image = image(for: node) else { return } let imageLayer = CALayer() imageLayer.frame = node.frame imageLayer.contents = image.cgImage // Add as sublayer layer.addSublayer(imageLayer) selectedNodeLayer = imageLayer } // MARK: - Touch private func register(touch: UITouch, isLast: Bool = false) { let rect = manager.inputStream(at: touch.location(in: self), previousPoint: touch.previousLocation(in: self), isLast: isLast) setNeedsDisplay(rect) } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard isWritingMode else { return } register(touch: touches.first!) } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if !isWritingMode { isWritingMode = true } register(touch: touches.first!) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard isWritingMode else { return } register(touch: touches.first!, isLast: true) } override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { guard isWritingMode else { return } register(touch: touches.first!, isLast: true) } // MARK: - Target action @objc open func tapAction(_ sender: UITapGestureRecognizer) { let node = manager.selectNode(at: sender.location(in: self)) display(node: node) delegate?.mathInputView(self, didTap: ObjCNode(node: node)) } @objc open func longPressAction(_ sender: UILongPressGestureRecognizer) { let node = manager.selectNode(at: sender.location(in: self)) display(node: node) delegate?.mathInputView(self, didLongPress: ObjCNode(node: node)) } @IBAction open func undoAction(_ sender: UIButton?) { if !isWritingMode { isWritingMode = true } if let rect = manager.undo() { setNeedsDisplay(rect) } } @IBAction open func redoAction(_ sender: UIButton?) { if !isWritingMode { isWritingMode = true } if let rect = manager.redo() { setNeedsDisplay(rect) } } open func removeSelection() { guard let node = manager.removeSelectedNode() else { return } display(node: nil) setNeedsDisplay(node.frame) delegate?.mathInputView(self, didRemove: ObjCNode(node: node)!) } open func replaceSelection(with character: String) { guard let node = manager.replaceSelectedNode(with: character) else { return } display(node: nil) setNeedsDisplay(node.1.frame) delegate?.mathInputView(self, didReplace: ObjCNode(node: node.0)!, with: ObjCNode(node: node.1)!) } // MARK: - Keyboard open func keyboard(_ keyboard: KeyboardType, didReceive input: String?) { if let input = input { guard input.count == 1 else { return } replaceSelection(with: input) } else { removeSelection() } } // MARK: - MathInkRendering open func manager(_ manager: MathInkManager, didExtractLaTeX string: String) { delegate?.mathInputView(self, didParse: manager.ink, latex: string) } open func manager(_ manager: MathInkManager, didFailToExtractWith error: NSError) { delegate?.mathInputView(self, didFailToParse: manager.ink, with: error) } open func manager(_ manager: MathInkManager, didUpdateHistory state: (undo: Bool, redo: Bool)) { } open func manager(_ manager: MathInkManager, didScratchOut frame: CGRect) { } open func manager(_ manager: MathInkManager, didLoad ink: [InkType]?) { selectedNodeLayer?.removeFromSuperlayer() candidatesView?.hideKeyboard(nil) setNeedsDisplay() } }
mit
d847c90f454bb74e913f18ce310787b2
32.923944
108
0.608569
5.236087
false
false
false
false
grigaci/RateMyTalkAtMobOS
RateMyTalkAtMobOS/Classes/Helpers/Extensions/UIColor+Extra.swift
1
1028
// // UIColor+Extra.swift // RateMyTalkAtMobOS // // Created by Bogdan Iusco on 10/18/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import UIKit extension UIColor { class func appBackgroundColor() -> UIColor { return UIColor(fullRed: 247.0, fullGreen: 247.0, fullBlue: 247.0) } class func allSessionsBackgroundColor() -> UIColor { let image = UIImage(named: "allSessionsBackgroundPattern") return UIColor(patternImage: image!) } class func sessionBackgroundColor() -> UIColor { let image = UIImage(named: "sessionBackgroundPattern") return UIColor(patternImage: image!) } convenience init(fullRed: Float, fullGreen: Float, fullBlue: Float) { let divider: CGFloat = 255.0 let red : CGFloat = CGFloat(fullRed) / divider let green : CGFloat = CGFloat(fullGreen) / divider let blue : CGFloat = CGFloat(fullBlue) / divider self.init(red: red, green: green, blue: blue, alpha: CGFloat(1.0)) } }
bsd-3-clause
f76ed6d4441d3f0ac842454a6e6014d2
29.235294
74
0.652724
3.908745
false
false
false
false
SWBerard/Stormpath-iOS-Demo
Stormpath Demo/ForgotPasswordViewController.swift
1
7747
// // ForgotPasswordViewController.swift // Stormpath Demo // // Created by Steven Berard on 10/12/15. // Copyright © 2015 Byteware LLC. All rights reserved. // import UIKit class ForgotPasswordViewController: UIViewController, UITextFieldDelegate, ForgotPasswordManagerDelegate { @IBOutlet weak var windowView: UIView! @IBOutlet weak var resetPasswordButton: UIButton! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var scrollView: UIScrollView! var _blurView : UIVisualEffectView? var _allowAutorotation = true var _isKeyboardOnScreen = false var _forgotPasswordManager : ForgotPasswordManager? override func viewDidLoad() { super.viewDidLoad() // WindowView setup windowView.layer.shadowRadius = 2.0 windowView.layer.shadowOpacity = 0.5 windowView.layer.shadowOffset = CGSize.init(width: 0.0, height: 0.0) windowView.layer.cornerRadius = 3 // resetPasswordButton setup resetPasswordButton.backgroundColor = UIColor.clearColor() // Top half of button let topButtonLayer = CALayer() topButtonLayer.frame = CGRect(x: resetPasswordButton.bounds.origin.x, y: resetPasswordButton.bounds.origin.y, width: resetPasswordButton.bounds.width, height: resetPasswordButton.bounds.height/2) topButtonLayer.backgroundColor = UIColor(red: 0.0, green: 0.77, blue: 0.0, alpha: 1.0).CGColor resetPasswordButton.layer.insertSublayer(topButtonLayer, atIndex: 0) // Bottom half of button let bottomButtonLayer = CALayer() bottomButtonLayer.frame = CGRect(x: resetPasswordButton.bounds.origin.x, y: resetPasswordButton.bounds.origin.y + resetPasswordButton.bounds.height/2, width: resetPasswordButton.bounds.width, height: resetPasswordButton.bounds.height/2) bottomButtonLayer.backgroundColor = UIColor(red: 0.0, green: 0.73, blue: 0.0, alpha: 1.0).CGColor resetPasswordButton.layer.insertSublayer(bottomButtonLayer, atIndex: 0) // Rounding the corners let maskButtonLayer = CAShapeLayer() maskButtonLayer.frame = resetPasswordButton.bounds maskButtonLayer.backgroundColor = UIColor.whiteColor().CGColor maskButtonLayer.cornerRadius = 5 resetPasswordButton.layer.mask = maskButtonLayer emailTextField.delegate = self } @IBAction func dismissKeyboard(sender: AnyObject?) { view.endEditing(true) } override func shouldAutorotate() -> Bool { return _allowAutorotation } @IBAction func backToLogInPage(sender: AnyObject?) { dismissKeyboard(nil) dismissViewControllerAnimated(true, completion: nil) } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { // If the keyboard is on the screen we need to make the content size of the scrollView taller, so the user // can scroll to the all textviews if fromInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft || fromInterfaceOrientation == UIInterfaceOrientation.LandscapeRight { if _isKeyboardOnScreen { scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + 216) } } else { if _isKeyboardOnScreen { scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + 162) } } } @IBAction func attemptToLogIn(sender: AnyObject?) { dismissKeyboard(nil) // Create blur view _blurView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) _blurView!.frame = view.bounds // Add the ability to cancel the login attempt let tapGesture = UITapGestureRecognizer() tapGesture.addTarget(self, action: "cancelPasswordResetAttempt") _blurView!.addGestureRecognizer(tapGesture) // Add the activity spinner let spinner = UIActivityIndicatorView() spinner.center = _blurView!.center spinner.startAnimating() spinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray _blurView?.contentView.addSubview(spinner) // Add the blur view to the main view view.addSubview(_blurView!) // Restrict autorotation since I don't want to set constraints for the blur view _allowAutorotation = false _forgotPasswordManager = ForgotPasswordManager(email: self.emailTextField.text!) _forgotPasswordManager!.delegate = self _forgotPasswordManager!.sendPasswordResetRequest() } func cancelPasswordResetAttempt() { if let bv = _blurView as UIVisualEffectView? { if let fPM = _forgotPasswordManager { fPM.cancelRequest() } bv.removeFromSuperview() _allowAutorotation = true UIViewController.attemptRotationToDeviceOrientation() } } // MARK: ForgotPasswordManagerDelegate Methods func passwordResetDidSucceed(didSucceed: Bool, message: String) { print("Received response from server: \(didSucceed)") cancelPasswordResetAttempt() if didSucceed { let alert = UIAlertController(title: "Success", message: "Your password has been reset. You should receive an email soon that will explain what to do next.", preferredStyle: UIAlertControllerStyle.Alert) let closeAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: {Void in self.backToLogInPage(nil) }) alert.addAction(closeAction) self.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert) let closeAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(closeAction) self.presentViewController(alert, animated: true, completion: nil) } } // MARK: UITextFieldDelegate Methods func textFieldDidBeginEditing(textField: UITextField) { if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft || UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight { scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + 162) } else { scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + 216) } _isKeyboardOnScreen = true } func textFieldDidEndEditing(textField: UITextField) { if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft || UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight { scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height - 162) } else { scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height - 216) } _isKeyboardOnScreen = false } }
mit
2ef1db9a664b1d0178a20157ec716072
38.319797
244
0.656855
5.695588
false
false
false
false
rajabishek/Beyond
Beyond/AuthManager.swift
1
3931
// // AuthManager.swift // Beyond // // Created by Raj Abishek on 20/03/16. // Copyright © 2016 Raj Abishek. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class AuthManager { static let defaults = NSUserDefaults.standardUserDefaults() class func getToken() -> String? { return defaults.objectForKey("token") as? String } class func setToken(token: String) { defaults.setObject(token, forKey: "token") } let baseUrl = "http://begin.dev/api/v1" func loginWithEmail(email: String, password: String, callback: (errorMessage: String?, token: String?) -> Void) { Alamofire.request(.POST, "\(baseUrl)/login", parameters: ["email": email, "password": password]).responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let success = json["success"].bool { if success { if let token = json["data"]["token"].string { callback(errorMessage: nil, token: token) } } else { for (_, errorMessage):(String, JSON) in json["errors"] { if let message = errorMessage.string { return callback(errorMessage: message, token: nil) } else { callback(errorMessage: "Please try after some time", token: nil) } } } } else { callback(errorMessage: "Please try after some time", token: nil) } } case .Failure: callback(errorMessage: "Please try after some time", token: nil) } } } func signupWithName(name: String, email: String, password: String, confirm: String, callback: (errorMessage: String?, token: String?) -> Void) { Alamofire.request(.POST, "\(baseUrl)/register", parameters: ["name": name, "email": email, "password": password, "password_confirmation": confirm]) .responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let success = json["success"].bool { if success { if let token = json["data"]["token"].string { callback(errorMessage: nil, token: token) } } else { for (_, errorMessage):(String, JSON) in json["errors"] { if let message = errorMessage.string { return callback(errorMessage: message, token: nil) } else { callback(errorMessage: "Please try after some time", token: nil) } } } } else { callback(errorMessage: "Please try after some time", token: nil) } } case .Failure: callback(errorMessage: "Please try after some time", token: nil) } } } }
mit
7c95decb8082017e5207f1904b078959
43.659091
155
0.425445
6.083591
false
false
false
false
IGRSoft/IGRFastFilterView
Demo/DemoSwift/ViewController.swift
1
5842
// // ViewController.swift // DemoSwift // // Created by Vitalii Parovishnyk on 1/8/17. // Copyright © 2017 IGR Software. All rights reserved. // import UIKit import IGRFastFilterView class ViewController: UIViewController { @IBOutlet weak fileprivate var instaFiltersView: IGRFastFilterView? static let kImageNotification = NSNotification.Name(rawValue: "WorkImageNotification") let kDemoImage = UIImage.init(named: "demo") override func viewDidLoad() { super.viewDidLoad() setupTheme() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(setupWorkImage(_:)), name: ViewController.kImageNotification, object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.once(token: "com.igrsoft.fastfilter.demo") { self.setupDemoView() } } deinit { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self, name: ViewController.kImageNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in self.instaFiltersView?.layoutSubviews() }, completion: nil) } fileprivate func setupTheme () { IGRFastFilterView.appearance().backgroundColor = UIColor(white:0.7, alpha:1.0) IGRFiltersbarCollectionView.appearance().backgroundColor = UIColor(white:0.9, alpha:1.0) } fileprivate func setupDemoView() { let notificationCenter = NotificationCenter.default notificationCenter.post(name: ViewController.kImageNotification, object: kDemoImage) } func setupWorkImage(_ notification: Notification) { assert(notification.object is UIImage, "Image only allowed!"); instaFiltersView?.setImage(notification.object as! UIImage) } func prepareImage() -> UIImage { return self.instaFiltersView!.processedImage!; } @IBAction func onTouchGetImageButton(_ sender: UIBarButtonItem) { let alert = UIAlertController.init(title: NSLocalizedString("Select image", comment: ""), message: "", preferredStyle: UIAlertControllerStyle.actionSheet) alert.popoverPresentationController?.barButtonItem = sender; func completeAlert(type: UIImagePickerControllerSourceType) { let pickerView = UIImagePickerController.init() pickerView.delegate = self pickerView.sourceType = type self.present(pickerView, animated: true, completion: nil) } let style = UIAlertActionStyle.default var action = UIAlertAction.init(title: NSLocalizedString("From Library", comment: ""), style: style) { (UIAlertAction) in completeAlert(type: UIImagePickerControllerSourceType.photoLibrary) } alert.addAction(action) action = UIAlertAction.init(title: NSLocalizedString("From Camera", comment: ""), style: style) { (UIAlertAction) in completeAlert(type: UIImagePickerControllerSourceType.camera) } alert.addAction(action) action = UIAlertAction.init(title: NSLocalizedString("Cancel", comment: ""), style: style) alert.addAction(action) self.present(alert, animated: true, completion: nil) } @IBAction func onTouchShareButton(_ sender: UIBarButtonItem) { let image = prepareImage() let avc = UIActivityViewController.init(activityItems: [image], applicationActivities: nil) avc.popoverPresentationController?.barButtonItem = sender; avc.popoverPresentationController?.permittedArrowDirections = .up; self.present(avc, animated: true, completion: nil) } } extension ViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] let notificationCenter = NotificationCenter.default notificationCenter.post(name: ViewController.kImageNotification, object: image) picker.dismiss(animated: true, completion: nil) } } public extension DispatchQueue { private static var _onceTracker = [String]() /** Executes a block of code, associated with a unique token, only once. The code is thread safe and will only execute the code once even in the presence of multithreaded calls. - parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID - parameter block: Block to execute once */ public class func once(token: String, block:(Void)->Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } if _onceTracker.contains(token) { return } _onceTracker.append(token) block() } }
mit
9a9445a8eac1fd9f24ff41aebf92f63d
35.968354
162
0.628488
5.749016
false
false
false
false
Limon-O-O/Lego
Frameworks/EggKit/EggKit/Extensions/UIColor+Egg.swift
1
3333
// // UIColor+Egg.swift // EggKit // // Created by Limon.F on 26/2/2017. // Copyright © 2017 Limon.F. All rights reserved. // import UIKit extension UIColor { /** Create non-autoreleased color with in the given hex string and alpha. - parameter hexString: The hex string, with or without the hash character. - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: A color with the given hex string and alpha. */ public convenience init?(hexString: String, alpha: Float = 1.0) { var hex = hexString // Check for hash and remove the hash if hex.hasPrefix("#") { hex = hex.substring(from: hex.characters.index(hex.startIndex, offsetBy: 1)) } if (hex.range(of: "(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .regularExpression) != nil) { // Deal with 3 character Hex strings if hex.characters.count == 3 { let redHex = hex.substring(to: hex.characters.index(hex.startIndex, offsetBy: 1)) let greenHex = hex.substring(with: Range<String.Index>(hex.characters.index(hex.startIndex, offsetBy: 1) ..< hex.characters.index(hex.startIndex, offsetBy: 2))) let blueHex = hex.substring(from: hex.characters.index(hex.startIndex, offsetBy: 2)) hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex } let redHex = hex.substring(to: hex.characters.index(hex.startIndex, offsetBy: 2)) let greenHex = hex.substring(with: Range<String.Index>(hex.characters.index(hex.startIndex, offsetBy: 2) ..< hex.characters.index(hex.startIndex, offsetBy: 4))) let blueHex = hex.substring(with: Range<String.Index>(hex.characters.index(hex.startIndex, offsetBy: 4) ..< hex.characters.index(hex.startIndex, offsetBy: 6))) var redInt: CUnsignedInt = 0 var greenInt: CUnsignedInt = 0 var blueInt: CUnsignedInt = 0 Scanner(string: redHex).scanHexInt32(&redInt) Scanner(string: greenHex).scanHexInt32(&greenInt) Scanner(string: blueHex).scanHexInt32(&blueInt) self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha)) } else { // Note: // The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases, // so it disallows formation of a situation where it would have to. We consider this a bug to be fixed // in future releases, not a feature. -- Apple Forum self.init() return nil } } /** Create non-autoreleased color with in the given hex value and alpha - parameter hex: The hex value. For example: 0xff8942 (no quotation). - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: color with the given hex value and alpha */ public convenience init?(hex: Int, alpha: Float = 1.0) { var hexString = String(format: "%2X", hex) let leadingZerosString = String(repeating: "0", count: 6 - hexString.characters.count) hexString = leadingZerosString + hexString self.init(hexString: hexString, alpha: alpha) } }
mit
637d3397494ad67ca9963897f22b6d41
42.272727
176
0.629352
4.128872
false
false
false
false
tjw/swift
test/SILGen/generic_witness.swift
1
2653
// RUN: %target-swift-frontend -module-name generic_witness -emit-silgen -enable-sil-ownership %s | %FileCheck %s // RUN: %target-swift-frontend -module-name generic_witness -emit-ir -enable-sil-ownership %s protocol Runcible { func runce<A>(_ x: A) } // CHECK-LABEL: sil hidden @$S15generic_witness3foo{{[_0-9a-zA-Z]*}}F : $@convention(thin) <B where B : Runcible> (@in_guaranteed B) -> () { func foo<B : Runcible>(_ x: B) { // CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : {{.*}} : $@convention(witness_method: Runcible) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> () // CHECK: apply [[METHOD]]<B, Int> x.runce(5) } // CHECK-LABEL: sil hidden @$S15generic_witness3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in_guaranteed Runcible) -> () func bar(_ x: Runcible) { var x = x // CHECK: [[BOX:%.*]] = alloc_box ${ var Runcible } // CHECK: [[TEMP:%.*]] = alloc_stack $Runcible // CHECK: [[EXIST:%.*]] = open_existential_addr immutable_access [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1 // CHECK: apply [[METHOD]]<[[OPENED]], Int> x.runce(5) } protocol Color {} protocol Ink { associatedtype Paint } protocol Pen {} protocol Pencil : Pen { associatedtype Stroke : Pen } protocol Medium { associatedtype Texture : Ink func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint } struct Canvas<I : Ink> where I.Paint : Pen { typealias Texture = I func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { } } extension Canvas : Medium {} // CHECK-LABEL: sil private [transparent] [thunk] @$S15generic_witness6CanvasVyxGAA6MediumA2aEP4draw5paint6pencily6StrokeQyd___qd__tAA6PencilRd__7Texture_5PaintQZAKRSlFTW : $@convention(witness_method: Medium) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in_guaranteed τ_0_0.Paint, @in_guaranteed τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () { // CHECK: [[FN:%.*]] = function_ref @$S15generic_witness6CanvasV4draw5paint6pencily5PaintQz_qd__tAA6PencilRd__6StrokeQyd__AHRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in_guaranteed τ_0_0.Paint, @in_guaranteed τ_1_0, Canvas<τ_0_0>) -> () // CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in_guaranteed τ_0_0.Paint, @in_guaranteed τ_1_0, Canvas<τ_0_0>) -> () // CHECK: }
apache-2.0
baf99c0263b7463b57e68968ed74e77d
44.947368
381
0.644139
2.865427
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Template/SimpleUserProfileExample/Service/MatrixSDK/TemplateUserProfileService.swift
1
2566
// // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Combine @available(iOS 14.0, *) class TemplateUserProfileService: TemplateUserProfileServiceProtocol { // MARK: - Properties // MARK: Private private let session: MXSession private var listenerReference: Any? // MARK: Public var userId: String { session.myUser.userId } var displayName: String? { session.myUser.displayname } var avatarUrl: String? { session.myUser.avatarUrl } private(set) var presenceSubject: CurrentValueSubject<TemplateUserProfilePresence, Never> // MARK: - Setup init(session: MXSession) { self.session = session self.presenceSubject = CurrentValueSubject(TemplateUserProfilePresence(mxPresence: session.myUser.presence)) self.listenerReference = setupPresenceListener() } deinit { guard let reference = listenerReference else { return } session.myUser.removeListener(reference) } func setupPresenceListener() -> Any? { let reference = session.myUser.listen { [weak self] event in guard let self = self, let event = event, case .presence = MXEventType(identifier: event.eventId) else { return } self.presenceSubject.send(TemplateUserProfilePresence(mxPresence: self.session.myUser.presence)) } if reference == nil { UILog.error("[TemplateUserProfileService] Did not recieve a lisenter reference.") } return reference } } fileprivate extension TemplateUserProfilePresence { init(mxPresence: MXPresence) { switch mxPresence { case MXPresenceOnline: self = .online case MXPresenceUnavailable: self = .idle case MXPresenceOffline, MXPresenceUnknown: self = .offline default: self = .offline } } }
apache-2.0
70dab67448cc014b2a1475a625be3e8b
28.159091
116
0.64887
4.887619
false
false
false
false
kylebshr/ElegantPresentations
Example/Example/ViewController.swift
1
2663
// // ViewController.swift // Example // // Created by Kyle Bashour on 2/20/16. // Copyright © 2016 Kyle Bashour. All rights reserved. // import UIKit import ElegantPresentations class ViewController: UITableViewController, UIViewControllerTransitioningDelegate { @IBOutlet weak var shrinkPresentingViewSwitch: UISwitch! @IBOutlet weak var dimPresentingViewSwitch: UISwitch! @IBOutlet weak var dismissOnTapSwitch: UISwitch! @IBOutlet weak var heightSegment: UISegmentedControl! @IBOutlet weak var heightTextField: UITextField! @IBOutlet weak var heightLabel: UILabel! var options: Set<PresentationOption> { var options = Set<PresentationOption>() if !shrinkPresentingViewSwitch.isOn { options.insert(.presentingViewKeepsSize) } if !dimPresentingViewSwitch.isOn { options.insert(.noDimmingView) } if dismissOnTapSwitch.isOn { options.insert(.dismissOnDimmingViewTap) } if let heightValue = Double(heightTextField.text!) { if heightSegment.selectedSegmentIndex == 0 { options.insert(.presentedPercentHeight(heightValue)) } else { options.insert(.presentedHeight(CGFloat(heightValue))) } } return options } @IBAction func unwind(_ segue: UIStoryboardSegue) { } @IBAction func codeButtonPressed(_ sender: UIBarButtonItem) { let destinationVC = storyboard!.instantiateViewController(withIdentifier: "Compose") destinationVC.modalPresentationStyle = .custom destinationVC.transitioningDelegate = self present(destinationVC, animated: true, completion: nil) } @IBAction func heightSegmentDidChange(_ sender: UISegmentedControl) { heightLabel.text = sender.selectedSegmentIndex == 0 ? "Percent Value:" : "Constant Value:" heightTextField.text = sender.selectedSegmentIndex == 0 ? "1.0" : "200" } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { segue.destination.modalPresentationStyle = .custom segue.destination.transitioningDelegate = self } func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return ElegantPresentations.controller(presentedViewController: presented, presentingViewController: presenting, options: options) } } extension ViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
mit
cd1ecebb8767d5631f99690a7afd2aaa
36.492958
161
0.705109
5.511387
false
false
false
false
therealcodesailor/Rvnug.HabHygLite
habhyglite/AppDelegate.swift
1
6030
// // AppDelegate.swift // habhyglite // // Created by Brian Lanham on 8/18/17. // Copyright © 2017 Brian Lanham. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.persistentContainer.viewContext 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) { // 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: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "habhyglite") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
ee952123c07d7f992c669a0177addd7b
52.830357
285
0.709736
6.177254
false
false
false
false
alexcosmin/MovingHelper
MovingHelperTests/TaskCellTests.swift
1
2963
// // TaskCellTests.swift // MovingHelper // // Created by Alexandru Vasile on 17/10/15. // Copyright © 2015 Razeware. All rights reserved. // import UIKit import XCTest import MovingHelper class TaskCellTests: XCTestCase { func testCheckingCheckboxMarksTaskDone() { var testCell: TaskTableViewCell? let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) if let navVC = mainStoryboard.instantiateInitialViewController() as? UINavigationController, listVC = navVC.topViewController as? MasterViewController { let tasks = TaskLoader.loadStockTasks() listVC.createdMovingTasks(tasks) testCell = listVC.tableView(listVC.tableView, cellForRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as? TaskTableViewCell if let cell = testCell { //1 let expectation = expectationWithDescription("Task updated") //2 struct TestDelegate: TaskUpdatedDelegate { let testExpectation: XCTestExpectation let expectedDone: Bool init(updatedExpectation: XCTestExpectation, expectedDoneStateAfterToggle: Bool) { testExpectation = updatedExpectation expectedDone = expectedDoneStateAfterToggle } func taskUpdated(task: Task) { XCTAssertEqual(expectedDone, task.done, "Task done state did not match expected!") testExpectation.fulfill() } } //3 let testTask = Task(aTitle: "TestTask", aDueDate: .OneMonthAfter) XCTAssertFalse(testTask.done, "Newly created task is already done!") cell.delegate = TestDelegate(updatedExpectation: expectation, expectedDoneStateAfterToggle: true) cell.configureForTask(testTask) //4 XCTAssertFalse(cell.checkbox.isChecked, "Checkbox checked for not-done task!") //5 cell.checkbox.sendActionsForControlEvents(.TouchUpInside) //6 XCTAssertTrue(cell.checkbox.isChecked, "Checkbox not checked after tap!") waitForExpectationsWithTimeout(1, handler: nil) } else { XCTFail("Test cell was nil!") } } else { XCTFail("Could not get reference to list VC!") } } }
mit
c4b0f8a0976ae2583337bad3db073ae7
39.575342
110
0.505064
6.731818
false
true
false
false
Acidburn0zzz/firefox-ios
Shared/UserAgent.swift
7
6207
/* 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 WebKit import UIKit open class UserAgent { public static let uaBitSafari = "Safari/605.1.15" public static let uaBitMobile = "Mobile/15E148" public static let uaBitFx = "FxiOS/\(AppInfo.appVersion)" public static let product = "Mozilla/5.0" public static let platform = "AppleWebKit/605.1.15" public static let platformDetails = "(KHTML, like Gecko)" // For iPad, we need to append this to the default UA for google.com to show correct page public static let uaBitGoogleIpad = "Version/13.0.3" private static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! private static func clientUserAgent(prefix: String) -> String { let versionStr: String if AppInfo.appVersion != "0.0.1" { versionStr = "\(AppInfo.appVersion)b\(AppInfo.buildNumber)" } else { versionStr = "dev" } return "\(prefix)/\(versionStr) (\(DeviceInfo.deviceModel()); iPhone OS \(UIDevice.current.systemVersion)) (\(AppInfo.displayName))" } public static var syncUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Sync") } public static var tokenServerClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Token") } public static var fxaUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-FxA") } public static var defaultClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS") } public static func isDesktop(ua: String) -> Bool { return ua.lowercased().contains("intel mac") } public static func desktopUserAgent() -> String { return "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15" } public static func mobileUserAgent() -> String { return UserAgentBuilder.defaultMobileUserAgent().userAgent() } public static func oppositeUserAgent(domain: String) -> String { let isDefaultUADesktop = UserAgent.isDesktop(ua: UserAgent.getUserAgent(domain: domain)) if isDefaultUADesktop { return UserAgent.getUserAgent(domain: domain, platform: .Mobile) } else { return UserAgent.getUserAgent(domain: domain, platform: .Desktop) } } public static func getUserAgent(domain: String, platform: UserAgentPlatform) -> String { switch platform { case .Desktop: return desktopUserAgent() case .Mobile: if let customUA = CustomUserAgentConstant.mobileUserAgent[domain] { return customUA } else { return mobileUserAgent() } } } public static func getUserAgent(domain: String = "") -> String { // As of iOS 13 using a hidden webview method does not return the correct UA on // iPad (it returns mobile UA). We should consider that method no longer reliable. if UIDevice.current.userInterfaceIdiom == .pad { return getUserAgent(domain: domain, platform: .Desktop) } else { return getUserAgent(domain: domain, platform: .Mobile) } } } public enum UserAgentPlatform { case Desktop case Mobile } public struct CustomUserAgentConstant { private static let defaultMobileUA = UserAgentBuilder.defaultMobileUserAgent().userAgent() private static let customDesktopUA = UserAgentBuilder.defaultDesktopUserAgent().clone(extensions: "Version/\(AppInfo.appVersion) \(UserAgent.uaBitSafari)") public static let mobileUserAgent = [ "paypal.com": defaultMobileUA, "yahoo.com": defaultMobileUA ] } public struct UserAgentBuilder { // User agent components fileprivate var product = "" fileprivate var systemInfo = "" fileprivate var platform = "" fileprivate var platformDetails = "" fileprivate var extensions = "" init(product: String, systemInfo: String, platform: String, platformDetails: String, extensions: String) { self.product = product self.systemInfo = systemInfo self.platform = platform self.platformDetails = platformDetails self.extensions = extensions } public func userAgent() -> String { let userAgentItems = [product, systemInfo, platform, platformDetails, extensions] return removeEmptyComponentsAndJoin(uaItems: userAgentItems) } public func clone(product: String? = nil, systemInfo: String? = nil, platform: String? = nil, platformDetails: String? = nil, extensions: String? = nil) -> String { let userAgentItems = [product ?? self.product, systemInfo ?? self.systemInfo, platform ?? self.platform, platformDetails ?? self.platformDetails, extensions ?? self.extensions] return removeEmptyComponentsAndJoin(uaItems: userAgentItems) } /// Helper method to remove the empty components from user agent string that contain only whitespaces or are just empty private func removeEmptyComponentsAndJoin(uaItems: [String]) -> String { return uaItems.filter{ !$0.isEmptyOrWhitespace() }.joined(separator: " ") } public static func defaultMobileUserAgent() -> UserAgentBuilder { return UserAgentBuilder(product: UserAgent.product, systemInfo: "(\(UIDevice.current.model); CPU OS \(UIDevice.current.systemVersion.replacingOccurrences(of: ".", with: "_")) like Mac OS X)", platform: UserAgent.platform, platformDetails: UserAgent.platformDetails, extensions: "FxiOS/\(AppInfo.appVersion) \(UserAgent.uaBitMobile) \(UserAgent.uaBitSafari)") } public static func defaultDesktopUserAgent() -> UserAgentBuilder { return UserAgentBuilder(product: UserAgent.product, systemInfo: "(Macintosh; Intel Mac OS X 10.15)", platform: UserAgent.platform, platformDetails: UserAgent.platformDetails, extensions: "FxiOS/\(AppInfo.appVersion) \(UserAgent.uaBitSafari)") } }
mpl-2.0
6ca5efd75127bdf0ead20fba80924010
42.104167
367
0.682133
4.723744
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/src/Network/Receiving/SSKMessageDecryptJobRecord+SDS.swift
1
2999
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import GRDB import SignalCoreKit // NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py. // Do not manually edit it, instead run `sds_codegen.sh`. // MARK: - Typed Convenience Methods @objc public extension SSKMessageDecryptJobRecord { // NOTE: This method will fail if the object has unexpected type. class func anyFetchMessageDecryptJobRecord(uniqueId: String, transaction: SDSAnyReadTransaction) -> SSKMessageDecryptJobRecord? { assert(uniqueId.count > 0) guard let object = anyFetch(uniqueId: uniqueId, transaction: transaction) else { return nil } guard let instance = object as? SSKMessageDecryptJobRecord else { owsFailDebug("Object has unexpected type: \(type(of: object))") return nil } return instance } // NOTE: This method will fail if the object has unexpected type. func anyUpdateMessageDecryptJobRecord(transaction: SDSAnyWriteTransaction, block: (SSKMessageDecryptJobRecord) -> Void) { anyUpdate(transaction: transaction) { (object) in guard let instance = object as? SSKMessageDecryptJobRecord else { owsFailDebug("Object has unexpected type: \(type(of: object))") return } block(instance) } } } // MARK: - SDSSerializer // The SDSSerializer protocol specifies how to insert and update the // row that corresponds to this model. class SSKMessageDecryptJobRecordSerializer: SDSSerializer { private let model: SSKMessageDecryptJobRecord public required init(model: SSKMessageDecryptJobRecord) { self.model = model } // MARK: - Record func asRecord() throws -> SDSRecord { let id: Int64? = model.sortId > 0 ? Int64(model.sortId) : nil let recordType: SDSRecordType = .messageDecryptJobRecord let uniqueId: String = model.uniqueId // Base class properties let failureCount: UInt = model.failureCount let label: String = model.label let status: SSKJobRecordStatus = model.status // Subclass properties let attachmentIdMap: Data? = nil let contactThreadId: String? = nil let envelopeData: Data? = model.envelopeData let invisibleMessage: Data? = nil let messageId: String? = nil let removeMessageAfterSending: Bool? = nil let threadId: String? = nil return JobRecordRecord(id: id, recordType: recordType, uniqueId: uniqueId, failureCount: failureCount, label: label, status: status, attachmentIdMap: attachmentIdMap, contactThreadId: contactThreadId, envelopeData: envelopeData, invisibleMessage: invisibleMessage, messageId: messageId, removeMessageAfterSending: removeMessageAfterSending, threadId: threadId) } }
gpl-3.0
7de2cb7d516f427f3e534b82ac3fb46c
36.962025
368
0.667889
5.289242
false
false
false
false
fabiomassimo/eidolon
Kiosk/App/BidderDetailsRetrieval.swift
1
3490
import UIKit import ReactiveCocoa import RACAlertAction import SVProgressHUD public extension UIViewController { func promptForBidderDetailsRetrievalSignal() -> RACSignal { return RACSignal.createSignal { (subscriber) -> RACDisposable! in let (alertController, command) = UIAlertController.emailPromptAlertController() subscriber.sendNext(command.executionSignals.switchToLatest()) self.presentViewController(alertController, animated: true) { } return nil }.map { (emailSignal) -> AnyObject! in self.retrieveBidderDetailsSignal(emailSignal as! RACSignal) }.switchToLatest() } func retrieveBidderDetailsSignal(emailSignal: RACSignal) -> RACSignal { return emailSignal.doNext { _ -> Void in SVProgressHUD.show() }.map { (email) -> AnyObject! in let endpoint: ArtsyAPI = ArtsyAPI.BidderDetailsNotification(auctionID: appDelegate().appViewController.sale.id, identifier: (email as! String)) return XAppRequest(endpoint, provider: Provider.sharedProvider).filterSuccessfulStatusCodes() }.switchToLatest().throttle(1).doNext { _ -> Void in SVProgressHUD.dismiss() self.presentViewController(UIAlertController.successfulBidderDetailsAlertController(), animated: true, completion: nil) }.doError { _ -> Void in SVProgressHUD.dismiss() self.presentViewController(UIAlertController.failedBidderDetailsAlertController(), animated: true, completion: nil) } } } extension UIAlertController { class func successfulBidderDetailsAlertController() -> UIAlertController { let alertController = self(title: "Your details have been sent", message: nil, preferredStyle: .Alert) alertController.addAction(RACAlertAction(title: "OK", style: .Default)) return alertController } class func failedBidderDetailsAlertController() -> UIAlertController { let alertController = self(title: "Incorrect Email", message: "Email was not recognized. You may not be registered to bid yet.", preferredStyle: .Alert) alertController.addAction(RACAlertAction(title: "Cancel", style: .Cancel)) let retryAction = RACAlertAction(title: "Retry", style: .Default) retryAction.command = appDelegate().requestBidderDetailsCommand() alertController.addAction(retryAction) return alertController } class func emailPromptAlertController() -> (UIAlertController, RACCommand) { let alertController = self(title: "Send Bidder Details", message: "Enter your email address registered with Artsy and we will send your bidder number and PIN.", preferredStyle: .Alert) let ok = RACAlertAction(title: "OK", style: .Default) ok.command = RACCommand { (_) -> RACSignal! in return RACSignal.createSignal { (subscriber) -> RACDisposable! in let text = (alertController.textFields?.first as? UITextField)?.text ?? "" subscriber.sendNext(text) return nil } } let cancel = RACAlertAction(title: "Cancel", style: .Cancel) alertController.addTextFieldWithConfigurationHandler(nil) alertController.addAction(ok) alertController.addAction(cancel) return (alertController, ok.command) } }
mit
7ca84985aa9dd1aab33656269704a069
44.337662
192
0.670487
5.665584
false
false
false
false
h-n-y/BigNerdRanch-SwiftProgramming
chapter-23/BronzeChallenge.playground/Contents.swift
1
1409
import Cocoa protocol ExerciseType: CustomStringConvertible { var name: String { get } var caloriesBurned: Double { get } var minutes: Double { get } var title: String { get } // BRONZE CHALLENGE } extension ExerciseType { var description: String { return "Exercise(\(name), burned \(caloriesBurned) calories in \(minutes) minutes)" } } /* // Default implementation for required *title* property */ extension ExerciseType { var title: String { return "\(name) - \(minutes) minutes" } } struct EllipticalTrainer: ExerciseType { let name = "Elliptical Machine" let title = "Go Fast Elliptical Machine 300" let caloriesBurned: Double let minutes: Double } struct Treadmill: ExerciseType { let name = "Treadmill" let caloriesBurned: Double let minutes: Double let distanceInMiles: Double } extension Treadmill { var description: String { return "Treadmill(\(caloriesBurned) calories and \(distanceInMiles) miles in \(minutes) minutes)" } } let runningWorkout = Treadmill(caloriesBurned: 350, minutes: 25, distanceInMiles: 4.2) let ellipticalWorkout = EllipticalTrainer(caloriesBurned: 335, minutes: 30) let mondayWorkout: [ExerciseType] = [ellipticalWorkout, runningWorkout] for exercise in mondayWorkout { print(exercise.title) } print(ellipticalWorkout.title)
mit
0b6ab8baac833b2d7d0f2245e153993a
14.831461
105
0.687012
4.231231
false
false
false
false
lukaszwas/mcommerce-api
Sources/App/Controllers/PurchaseController.swift
1
3751
import Vapor import HTTP // /purchase final class PurchaseController { // Routes func makeRoutes(routes: RouteBuilder) { let group = routes.grouped("purchase") group.get(handler: getAllPurchases) group.get(Purchase.parameter, handler: getPurchaseDetails) group.post(handler: createPurchase) group.post("addproduct", handler: addProduct) group.post("pay", Purchase.parameter, handler: pay) } // METHODS // GET / // Get all purchases for user func getAllPurchases(req: Request) throws -> ResponseRepresentable { let user = try req.auth.assertAuthenticated(User.self) return try Purchase.makeQuery().filter(Purchase.userIdKey, .equals, user.id).all().makeJSON() } // GET /:id // Get purchase details func getPurchaseDetails(req: Request) throws -> ResponseRepresentable { let user = try req.auth.assertAuthenticated(User.self) let purchase = try req.parameters.next(Purchase.self) if (user.id != purchase.userId) { return Response(status: Status.unauthorized) } return try PurchaseProduct.makeQuery().filter(PurchaseProduct.purchaseIdKey, .equals, purchase.id).all().makeJSON() } // POST / // Create purchase func createPurchase(req: Request) throws -> ResponseRepresentable { let purchase = try req.purchase() try purchase.save() return purchase } // POST /pay // Purchase payment func pay(req: Request) throws -> ResponseRepresentable { let paymentInfo = try req.payment() let purchase = try req.parameters.next(Purchase.self) let products = try purchase.products.all() var price: Float = 0 for product in products { price += product.price } price *= 100 let user = try req.auth.assertAuthenticated(User.self) let stripeClient = try StripeClient(apiKey: "sk_test_QYeVSjIJJ5HNIujPjrUALzH0") stripeClient.initializeRoutes() let createCustomer = try stripeClient.customer.create(email: user.email) let customer = try createCustomer.serializedResponse() let addCard = try stripeClient.customer.addCard(customer: customer.id!, number: paymentInfo.cardNumber, expMonth: paymentInfo.cardExpirationMonth, expYear: paymentInfo.cardExpirationYear, cvc: paymentInfo.cardExpirationCvc) let cardResponse = try addCard.serializedResponse() let charge = try stripeClient.charge.create(amount: Int(price), in: .usd, for: ChargeType.customer(customer.id!), description: "") let chargeResponse = try charge.serializedResponse() // change purchase status purchase.statusId = 2 try purchase.save() return "ok" } // POST / // Add product to purchase func addProduct(req: Request) throws -> ResponseRepresentable { let purchaseProduct = try req.purchaseProduct() try purchaseProduct.save() return purchaseProduct } } // Deserialize JSON extension Request { func purchase() throws -> Purchase { guard let json = json else { throw Abort.badRequest } return try Purchase(json: json) } func purchaseProduct() throws -> PurchaseProduct { guard let json = json else { throw Abort.badRequest } return try PurchaseProduct(json: json) } func payment() throws -> Payment { guard let json = json else { throw Abort.badRequest } return try Payment(json: json) } } extension PurchaseController: EmptyInitializable { }
mit
ec325946b0b3f164fee63ef961e3921d
32.792793
231
0.637963
4.84
false
false
false
false
kiliankoe/apodidae
Sources/SwiftLibrary/SwiftLibrary.swift
1
1328
import Foundation public enum SwiftLibrary { public static func query(_ query: String, session: URLSession = .shared, completion: @escaping (Result<[PackageData], Error>) -> Void) { let task = session.dataTask(with: urlRequest(with: query)) { data, _, error in guard let data = data, error == nil else { completion(.failure(error!)) return } let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase do { let packages = try decoder.decode([PackageData].self, from: data) completion(.success(packages)) } catch { completion(.failure(error)) } } task.resume() } private static func urlRequest(with query: String) -> URLRequest { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "api.swiftpm.co" urlComponents.path = "/packages.json" let queryItem = URLQueryItem(name: "query", value: query) urlComponents.queryItems = [queryItem] guard let url = urlComponents.url else { fatalError("Failed to create URL") } return URLRequest(url: url) } }
mit
59dc6ab70700f7001f9404956d2e3248
36.942857
92
0.563253
5.1875
false
false
false
false
kak-ios-codepath/everest
Everest/Everest/Controllers/Login/LoginViewController.swift
1
3270
// // LoginViewController.swift // Everest // // Created by Kavita Gaitonde on 10/13/17. // Copyright © 2017 Kavita Gaitonde. All rights reserved. // import UIKit import FacebookCore import FacebookLogin import FacebookShare class LoginViewController: UIViewController, LoginButtonDelegate, EmailLoginDelegate { @IBOutlet weak var fbLoginView: UIView! override func viewDidLoad() { super.viewDidLoad() //adding FB login button programmatically let fbLoginButton = LoginButton(readPermissions: [ .publicProfile, .email, .userFriends ]) fbLoginButton.frame = fbLoginView.bounds fbLoginButton.delegate = self fbLoginView.addSubview(fbLoginButton) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func userLoggedIn() { print("Transition to main app.....") let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateInitialViewController() UIApplication.shared.delegate?.window??.rootViewController = vc } func userLoggedOut() { LoginManager.shared.logoutUser { (error) in //TODO: Handle error self.dismiss(animated: true, completion: nil) } } // MARK: - Facebook Login delegates func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) { switch result { case .failed(let error): print(error) break case .cancelled: print("Cancelled") break case .success(let grantedPermissions, let declinedPermissions, let accessToken): //TODO: Create a new user on Firebase based on thise token print("Logged In via Facebook") print (grantedPermissions) print (declinedPermissions) print (accessToken) LoginManager.shared.loginUserWithFacebook(token: accessToken, completion: { (error) in if error == nil { self.userLoggedIn() } }) } self.dismiss(animated: true, completion: nil) } func loginButtonDidLogOut(_ loginButton: LoginButton) { print("Facebook logout complete.....") self.userLoggedOut() } // MARK: - Email Login delegates func didCompleteEmailLogin() { print("Logged In via Email") self.userLoggedIn() self.dismiss(animated: true, completion: nil) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if(segue.identifier == "emailLoginModalViewController") { let controller = segue.destination as! EmailLoginViewController controller.delegate = self } } }
apache-2.0
ba3893afc4a7f5ce961735c61a42774b
30.737864
106
0.61915
5.341503
false
false
false
false
tlax/GaussSquad
GaussSquad/View/Main/Parent/VParent.swift
1
9943
import UIKit class VParent:UIView { weak var viewBar:VParentBar! weak var panRecognizer:UIPanGestureRecognizer! private weak var controller:CParent! private weak var layoutBarTop:NSLayoutConstraint! private var panningX:CGFloat? private let kAnimationDuration:TimeInterval = 0.4 private let kBarHeight:CGFloat = 70 private let kMaxXPanning:CGFloat = 60 private let kMaxXDelta:CGFloat = 90 private let kMinXDelta:CGFloat = 30 convenience init(controller:CParent) { self.init() clipsToBounds = true backgroundColor = UIColor.white self.controller = controller let viewBar:VParentBar = VParentBar(controller:controller) self.viewBar = viewBar addSubview(viewBar) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) NSLayoutConstraint.topToTop( view:viewBar, toView:self) NSLayoutConstraint.width( view:viewBar, toView:self) let panRecognizer:UIPanGestureRecognizer = UIPanGestureRecognizer( target:self, action:#selector(actionPanRecognized(sender:))) panRecognizer.isEnabled = false self.panRecognizer = panRecognizer addGestureRecognizer(panRecognizer) } //MARK: actions func actionPanRecognized(sender panGesture:UIPanGestureRecognizer) { let location:CGPoint = panGesture.location( in:self) let xPos:CGFloat = location.x switch panGesture.state { case UIGestureRecognizerState.began, UIGestureRecognizerState.possible: if xPos < kMaxXPanning { self.panningX = xPos } break case UIGestureRecognizerState.changed: if let panningX:CGFloat = self.panningX { var deltaX:CGFloat = xPos - panningX if deltaX > kMaxXDelta { panRecognizer.isEnabled = false } else { if deltaX < 0 { deltaX = 0 } guard let topView:VView = subviews.last as? VView else { return } topView.layoutLeft.constant = deltaX } } break case UIGestureRecognizerState.cancelled, UIGestureRecognizerState.ended, UIGestureRecognizerState.failed: if let panningX:CGFloat = self.panningX { let deltaX:CGFloat = xPos - panningX if deltaX > kMinXDelta { gesturePop() } else { gestureRestore() } } panningX = nil break } } //MARK: private private func gesturePop() { controller.pop(horizontal:CParent.TransitionHorizontal.fromRight) } private func gestureRestore() { guard let topView:VView = subviews.last as? VView else { return } topView.layoutLeft.constant = 0 UIView.animate(withDuration:kAnimationDuration) { self.layoutIfNeeded() } } //MARK: public func scrollDidScroll(offsetY:CGFloat) { let barTopConstant:CGFloat if offsetY > 0 { barTopConstant = offsetY } else { barTopConstant = 0 } layoutBarTop.constant = -barTopConstant } func mainView(view:VView) { insertSubview(view, belowSubview:viewBar) view.layoutTop = NSLayoutConstraint.topToTop( view:view, toView:self) view.layoutBottom = NSLayoutConstraint.bottomToBottom( view:view, toView:self) view.layoutLeft = NSLayoutConstraint.leftToLeft( view:view, toView:self) view.layoutRight = NSLayoutConstraint.rightToRight( view:view, toView:self) } func slide( currentView:VView, newView:VView, left:CGFloat, completion:@escaping(() -> ())) { insertSubview(newView, belowSubview:viewBar) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:-left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:-left) layoutIfNeeded() currentView.layoutRight.constant = left currentView.layoutLeft.constant = left newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() }) { (done:Bool) in currentView.removeFromSuperview() completion() } } func push( newView:VView, left:CGFloat, top:CGFloat, background:Bool, completion:@escaping(() -> ())) { if background { let pushBackground:VParentPushBackground = VParentPushBackground() newView.pushBackground = pushBackground addSubview(pushBackground) NSLayoutConstraint.equals( view:pushBackground, toView:self) } addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self, constant:top) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self, constant:top) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:left) layoutIfNeeded() if top >= 0 { newView.layoutTop.constant = 0 newView.layoutBottom.constant = 0 } else { newView.layoutBottom.constant = 0 newView.layoutTop.constant = 0 } if left >= 0 { newView.layoutLeft.constant = 0 newView.layoutRight.constant = 0 } else { newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 } UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() newView.pushBackground?.alpha = 1 }) { (done:Bool) in completion() } } func animateOver( newView:VView, completion:@escaping(() -> ())) { newView.alpha = 0 addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self) UIView.animate( withDuration:kAnimationDuration, animations: { [weak newView] in newView?.alpha = 1 }) { (done:Bool) in completion() } } func pop( currentView:VView, left:CGFloat, top:CGFloat, completion:@escaping(() -> ())) { currentView.layoutTop.constant = top currentView.layoutBottom.constant = top currentView.layoutRight.constant = left currentView.layoutLeft.constant = left UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() currentView.pushBackground?.alpha = 0 }) { (done:Bool) in currentView.pushBackground?.removeFromSuperview() currentView.removeFromSuperview() completion() } } func dismissAnimateOver( currentView:VView, completion:@escaping(() -> ())) { UIView.animate( withDuration:kAnimationDuration, animations: { [weak currentView] in currentView?.alpha = 0 }) { [weak currentView] (done:Bool) in currentView?.removeFromSuperview() completion() } } }
mit
d819dcf29433fa1d0e7432d248072d3e
25.304233
78
0.49995
6.337157
false
false
false
false
kstaring/swift
test/DebugInfo/inlinescopes.swift
7
1306
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: echo "public var x = Int64()" \ // RUN: | %target-swift-frontend -module-name FooBar -emit-module -o %t - // RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o %t.ll // RUN: %FileCheck %s < %t.ll // RUN: %FileCheck %s -check-prefix=TRANSPARENT-CHECK < %t.ll // CHECK: define{{( protected)?( signext)?}} i32 @main // CHECK: call {{.*}}noinline{{.*}}, !dbg ![[CALL:.*]] // CHECK-DAG: ![[TOPLEVEL:.*]] = !DIFile(filename: "inlinescopes.swift" import FooBar func use<T>(_ t: T) {} @inline(never) func noinline(_ x: Int64) -> Int64 { return x } @_transparent func transparent(_ x: Int64) -> Int64 { return noinline(x) } @inline(__always) func inlined(_ x: Int64) -> Int64 { // CHECK-DAG: ![[CALL]] = !DILocation(line: [[@LINE+2]], column: {{.*}}, scope: ![[SCOPE:.*]], inlinedAt: ![[INLINED:.*]]) // CHECK-DAG: ![[SCOPE:.*]] = distinct !DILexicalBlock( let result = transparent(x) // TRANSPARENT-CHECK-NOT: !DISubprogram(name: "transparent" return result } // CHECK-DAG: !DIGlobalVariable(name: "y",{{.*}} file: ![[TOPLEVEL]],{{.*}} line: [[@LINE+1]] let y = inlined(x) use(y) // Check if the inlined and removed function still has the correct linkage name. // CHECK-DAG: !DISubprogram(name: "inlined", linkageName: "_TF4main7inlinedFVs5Int64S0_"
apache-2.0
0079fae0946daceb683f6a9ae2d2e790
34.297297
122
0.624043
3.072941
false
false
false
false
luismatute/On-The-Map
On The Map/UdacityClient.swift
1
3916
// // UdacityClient.swift // On The Map // // Created by Luis Matute on 5/26/15. // Copyright (c) 2015 Luis Matute. All rights reserved. // import Foundation import UIKit class UdacityClient: NSObject { // MARK: - Properties var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // MARK: - Class Properties override init() { super.init() } // MARK: - Convinience func getSession(username: String, passwd: String, callback: (success: Bool, error: String?) -> Void) { let jsonBody: String = "{\"\(UdacityClient.JSONBodyKeys.Udacity)\": {\"\(UdacityClient.JSONBodyKeys.Username)\": \"\(username)\", \"\(UdacityClient.JSONBodyKeys.Password)\": \"\(passwd)\"}}" $.post("\(UdacityClient.URLs.BaseURL)\(UdacityClient.Methods.Session)").json(jsonBody).parseJSONWithCompletion(5){ (result, response, error) in if let error = error { callback(success: false, error: error.localizedDescription) } else { if let errorString = result.valueForKey(UdacityClient.JSONResponseKeys.Error) as? String { callback(success: false, error: errorString) } else { var dict = result as! [String: AnyObject] var user: User = User(dict: dict) self.appDelegate.user = user callback(success: true, error: nil) } } } } func getUserInfo(userID: String, callback: (success: Bool, error: String?) -> Void) { var urlString = UdacityClient.URLs.BaseURL + $.subtituteKeyInMethod(UdacityClient.Methods.User, key: UdacityClient.URLKeys.UserID, value: self.appDelegate.user!.id)! $.get(urlString).parseJSONWithCompletion(5) { (result, response, error) in if let error = error { callback(success: false, error: error.localizedDescription) } else { if let userResponse = result["user"] as? [String: AnyObject] { var user = self.appDelegate.user user?.firstName = userResponse["first_name"] as! String user?.lastName = userResponse["last_name"] as! String self.appDelegate.user = user! callback(success: true, error: nil) } else { callback(success: false, error: "No User found") } } } } func authenticateWithViewController(username: String, password: String, callback: (success: Bool, errorString: String?) -> Void) { self.getSession(username, passwd: password) { (success, errorString) in if success { self.getUserInfo(self.appDelegate.user!.id) { success, errorString in if success { callback(success: true, errorString: nil) } else { callback(success: false, errorString: errorString) } } } else { callback(success: false, errorString: errorString) } } } func doLogout(callback: (success: Bool, error: String?) -> Void) { $.delete("\(UdacityClient.URLs.BaseURL)\(UdacityClient.Methods.Session)").cookies().parseJSONWithCompletion(5) { (result, response, error) in if let error = error { callback(success: false, error: error.localizedDescription) } else { self.appDelegate.user = nil callback(success: true, error: nil) } } } // MARK: - Shared Instance class func sharedInstance() -> UdacityClient { struct Singleton { static var sharedInstance = UdacityClient() } return Singleton.sharedInstance } }
mit
61d5508fa859cb3e32afdf277b79cb23
40.670213
198
0.564351
4.988535
false
false
false
false
ITzTravelInTime/TINU
TINU/Diskutil/DiskutilCommands.swift
1
5475
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Foundation import AppKit import Command import CommandSudo public extension Diskutil{ //TODO: multithreaded bug! class func performCommand(withArgs args: [String], useAdminPrivileges: Bool = false) -> Command.Result?{ var ret: Command.Result? = nil DispatchQueue.global(qos: .background).sync { let exec = "/usr/sbin/diskutil" ret = (useAdminPrivileges ? Command.Sudo.run(cmd: exec, args: args, shouldActuallyUseSudo: false) : Command.run(cmd: exec, args: args)) } if ret?.errorString().contains("(-128)") ?? false{ return nil } return ret } internal class func mount(bsdID: BSDID, useAdminPrivileges: Bool = false) -> Bool?{ assert(bsdID.isValid, "BSDID must be a valid device identifier") if bsdID.isDrive{ return nil } if let mount = bsdID.mountPoint() { if FileManager.default.directoryExists(atPath: mount){ log("Partition already mounted: \(bsdID) at mount point: \(mount)") return true } } guard let res = performCommand(withArgs: ["mount", bsdID.rawValue], useAdminPrivileges: useAdminPrivileges) else { return nil } let text = res.output.stringList() return res.errorString().isEmpty && ((text.contains("mounted") && (text.contains("Volume EFI on") || text.contains("Volume (null) on") || (text.contains("Volume ") && text.contains("on")))) || (text.isEmpty)) } internal class func unmount( bsdID: BSDID, useAdminPrivileges: Bool = false) -> Bool?{ assert(bsdID.isValid, "BSDID must be a valid device identifier") if bsdID.isDrive{ guard let res = performCommand(withArgs: ["unmountDisk", bsdID.rawValue], useAdminPrivileges: useAdminPrivileges) else { return nil } let text = res.outputString() return text.contains("was successful") || text.isEmpty } if let mount = bsdID.mountPoint() { if !FileManager.default.directoryExists(atPath: mount){ log("Partition already unmounted: \(bsdID)") return true } } guard let res = performCommand(withArgs: ["unmount", bsdID.rawValue], useAdminPrivileges: useAdminPrivileges) else { return nil } let text = res.outputString() return ((text.contains("unmounted") && (text.contains("Volume EFI on") || text.contains("Volume (null) on") || (text.contains("Volume ") && text.contains("on")) || (text.contains("was already")) )) || (text.isEmpty)) } internal class func eject(mountedDiskAtPath path: Path) -> Bool{ return NSWorkspace.shared.unmountAndEjectDevice(atPath: path) } internal class func eject(bsdID: BSDID, useAdminPrivileges: Bool = false) -> Bool?{ assert(bsdID.isValid, "BSDID must be a valid device identifier") guard let result = performCommand(withArgs: ["eject", bsdID.rawValue], useAdminPrivileges: useAdminPrivileges) else { return nil } var res = false let text = result.outputString() if !text.isEmpty && result.errorString().isEmpty{ let resSrc: [(Bool, [String])] = [(true, [""]), (false, ["Unmount of all volumes on", "was successful"]), (false, ["Disk", "ejected"])] for s in resSrc{ if !s.0{ var breaked = false for r in s.1 where !text.contains(r){ breaked = true break } if breaked{ continue } }else if !s.1.isEmpty{ if text != s.1.first!{ continue } } res = true } } return res } class func eraseHFS(bsdID: BSDID, newVolumeName: String , useAdminPrivileges: Bool = false) -> Bool?{ assert(bsdID.isValid, "BSDID must be a valid device identifier") guard let result = performCommand(withArgs: ["eraseDisk", "JHFS+", "\"\(newVolumeName)\"", "/dev/" + bsdID.rawValue], useAdminPrivileges: useAdminPrivileges) else { return nil } if !result.errorString().isEmpty{ log("----Volume format process fail: ") log(" Format script output: \n" + result.outputString()) log(" Format script error: \n" + result.errorString()) return false } //output separated in parts let c = result.outputString().components(separatedBy: "\n") if c.isEmpty{ log("Failed to get outut from the format process") return false } if (c.count <= 1 && c.first!.isEmpty){ //too less output from the process log("Failed to get valid output for the format process") return false } //checks if the erase has been completed with success if !c.last!.contains("Finished erase on disk"){ //the format has failed, so the boolean is false and a screen with installer creation failed will be displayed log("----Volume format process fail: ") log(" Format script output: \n" + result.outputString()) return false } return true } }
gpl-2.0
0e19e0b68be0566ca9f3da2d6b270257
31.205882
218
0.684201
3.863797
false
false
false
false
socialradar/Vacation-Tracker-Swift
Vacation-Tracker-Swift/VTVisitDetailViewController.swift
2
4638
// // VTVisitDetailViewController.swift // Vacation-Tracker-Swift // // Created by Spencer Atkin on 7/30/15. // Copyright (c) 2015 SocialRadar. All rights reserved. // import UIKit import MapKit class VTVisitDetailViewController: UIViewController { let MILE_TO_METER = 0.00062137 @IBOutlet weak var mapView: MKMapView! var visit = VTVisit() @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var address_0: UILabel! @IBOutlet weak var address_1: UILabel! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var localityLabel: UILabel! @IBOutlet weak var ratingLabel: UILabel! @IBOutlet weak var ratingStepper: UIStepper! var placeName: NSString? = NSString() var name = NSString() override func viewDidLoad() { super.viewDidLoad() self.ratingLabel.text = String(format: "Rating: %.f", self.visit.rating) self.ratingStepper.value = self.visit.rating if let place = visit.place.venue.name { self.placeName = visit.place.venue.name } else { self.placeName = nil } let address = visit.place.address // Creates an array from the street name components separated by a space let streetName = address.streetName.componentsSeparatedByString(" ") var name = address.streetNumber for var x = 0; x < streetName.count; x++ { let currentComponent: NSString = streetName[x] // If the component contains a number, ('19th' for example) it should be lowercase if currentComponent.intValue != 0 { name = name.stringByAppendingString(" \(streetName[x].lowercaseString)") } else { // If the component has length one, or is equal to NE, NW, SE, or SW it should be uppercase if currentComponent.length == 1 || currentComponent == "NE" || currentComponent == "NW" || currentComponent == "SE" || currentComponent == "SW" { name = name.stringByAppendingString(" \(currentComponent.uppercaseString)") } // Otherwise it should simply be capitalized else { name = name.stringByAppendingString(" \(streetName[x].capitalizedString)") } } } self.addAnnotation() if placeName == nil { self.navigationItem.title = "Visit to \(name)" } else { self.navigationItem.title = "Visit to \(self.placeName!)" } var dateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle self.dateLabel.text = dateFormatter.stringFromDate(visit.arrivalDate) dateFormatter.dateFormat = "h:mm a" self.timeLabel.text = dateFormatter.stringFromDate(visit.arrivalDate) self.address_0.text = name self.address_1.text = "\(address.locality.capitalizedString) \(address.region) \(address.postalCode)" if let category = self.visit.place.venue.category { self.categoryLabel.text = category } else { self.categoryLabel.text = "None" } // Do any additional setup after loading the view. } @IBAction func didTapStepper(sender: AnyObject) { self.visit.rating = self.ratingStepper.value self.ratingLabel.text = String(format: "Rating: %.f", self.visit.rating) VTTripHandler.notifyTripChange(VTTripHandler.trips) } func addAnnotation() { var annotation = MKPointAnnotation() if placeName == nil { annotation.title = "Visit to \(self.name)" } else { annotation.title = self.placeName as! String } annotation.coordinate = self.visit.place.address.coordinate self.mapView.centerCoordinate = annotation.coordinate self.mapView.mapType = MKMapType.Hybrid self.mapView.region = MKCoordinateRegionMakeWithDistance(self.mapView.centerCoordinate, 0.1 / MILE_TO_METER, 0.1 / MILE_TO_METER) self.mapView.addAnnotation(annotation) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "DetailsToCommentsSegueID" { ((segue.destinationViewController as! UINavigationController).viewControllers[0] as! VTVisitCommentsViewController).visit = self.visit } } }
mit
0e44d7ab9050c5e62d61e95c5bec0f0c
39.330435
161
0.629582
4.861635
false
false
false
false
guipanizzon/ioscreator
IOS8SwiftAirdropTutorial/IOS8SwiftAirdropTutorial/ViewController.swift
39
1285
// // ViewController.swift // IOS8SwiftAirdropTutorial // // Created by Arthur Knopper on 16/05/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { //var activityViewController: UIActivityViewController? @IBOutlet var imageView: UIImageView! @IBAction func shareImage(sender: AnyObject) { let image = imageView.image! let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil) controller.excludedActivityTypes = [UIActivityTypePostToFacebook, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypePostToFlickr, UIActivityTypePostToTencentWeibo, UIActivityTypeMail, UIActivityTypeMessage] self.presentViewController(controller, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() var image : UIImage = UIImage(named:"imac.jpg")! imageView.image = image } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
d3828cfa7ba3d7f3082673d06e06159c
33.72973
350
0.740078
5.538793
false
false
false
false
sean915213/SGYWebSession
Example/Pods/SGYSwiftUtility/SGYSwiftUtility/Classes/Logger.swift
1
4704
// // Logger.swift // // Created by Sean G Young on 2/8/15. // Copyright (c) 2015 Sean G Young. All rights reserved. // import Foundation public typealias LoggingBlock = (String) -> Void // Defaults private let defaultLogFormat = "[\(Logger.FormatPlaceholder.sourceName)] \(Logger.FormatPlaceholder.level) - \(Logger.FormatPlaceholder.value)" private let defaultLogBlock: LoggingBlock = { NSLog($0) } /** * Provides a logging interface with a predefined structure. */ public class Logger { // MARK: - Static Enums /** The log levels supported by Logger. - debug: A debugging logging. Generally considered temporary. - info: An informational log. Denotes a log that is useful to see and indicates no problems. - warning: A warning log. Denotes an issue that can be recovered from, but should be noted as it is likely not functioning properly. - error: An error log. Denotes a crtitical error that may or may not be recovered from and should be addressed immediately. */ public enum Level: String, CustomStringConvertible { case debug = "Debug", info = "Info", warning = "Warning", error = "Error" public var description: String { return rawValue } } public enum FormatPlaceholder: String, CustomStringConvertible { case sourceName = "$context", level = "$logLevel", value = "$logValue" public var description: String { return rawValue } } // MARK: - Initialization /** Initializes a SerialLogger instance. :param: source The name that all logs printed using this instance will be prefixed with. :returns: An instance of the SerialLogger class. */ public convenience init(sourceName: String) { // Use default log format self.init(sourceName: sourceName, logFormat: defaultLogFormat, logBlock: defaultLogBlock) } public convenience init(sourceName: String, logBlock: @escaping LoggingBlock) { // Use default log format self.init(sourceName: sourceName, logFormat: defaultLogFormat, logBlock: logBlock) } public init(sourceName: String, logFormat: String, logBlock: @escaping LoggingBlock) { self.logFormat = logFormat self.sourceName = sourceName self.logBlock = logBlock } // MARK: - Properties /// The description prefixed to logs. Assigned on initialization. public var sourceName: String /// The format used to create the final logging string. public let logFormat: String /// The block used to perform actual logging action. private let logBlock: LoggingBlock // MARK: - Methods /** Executes a log statement. :param: description The text to log. :param: level The log level to display. */ public func log(_ description: String, level: Level = .debug) { // Create log description by replacing placeholders w/ their respective values var log = logFormat.replacingOccurrences(of: FormatPlaceholder.sourceName.rawValue, with: sourceName) log = log.replacingOccurrences(of: FormatPlaceholder.level.rawValue, with: level.rawValue) log = log.replacingOccurrences(of: FormatPlaceholder.value.rawValue, with: description) // Log it logBlock(log) } } // MARK: Convenience Methods Extension extension Logger { public func logDebug(_ value: String) { log(value, level: .debug) } public func logInfo(_ value: String) { log(value, level: .info) } public func logWarning(_ value: String) { log(value, level: .warning) } public func logError(_ value: String) { log(value, level: .error) } } // MARK: CustomStringConvertible Extension /** extension Logger { public func logDebug(_ value: @autoclosure () -> CustomStringConvertible) { log(.debug, value: value) } public func logInfo(_ value: @autoclosure () -> CustomStringConvertible) { log(.info, value: value) } public func logWarning(_ value: @autoclosure () -> CustomStringConvertible) { log(.warning, value: value) } public func logError(_ value: @autoclosure () -> CustomStringConvertible) { log(.error, value: value) } private func log(_ level: Level, value: @autoclosure () -> CustomStringConvertible) { // Value block execution could be non-trivial, so don't even bother if not debugging #if DEBUG log(value().description, level: level) #endif } } **/
mit
32a4a0dd125d41a927d001237cdb7d04
29.947368
143
0.641794
4.765957
false
false
false
false
JoeFerrucci/Swift-Date-ISO-8601
Swift-Date-ISO-8601.swift
1
2405
/* ****************************************************** * * The MIT License (MIT) * * Copyright (c) 2016 Joe Ferrucci <http://joeferrucci.info> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ***************************************************** */ import Foundation public extension NSDate { public class func ISOStringFromDate(date: NSDate, locale: String = "en_US_POSIX", timezone: String = "UTC") -> String { let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: locale) dateFormatter.timeZone = NSTimeZone(abbreviation: timezone) dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" /* * Append Z in lieu of putting into dateFormat. * This will prevent UTC Offset +0000 from displaying. */ return dateFormatter.stringFromDate(date).stringByAppendingString("Z") } public class func dateFromISOString(string: String, locale: String = "en_US_POSIX") -> NSDate? { let dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone.localTimeZone() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" return dateFormatter.dateFromString(string) } public class func isoStringNow() -> String { return NSDate.ISOStringFromDate(NSDate()) } }
mit
f3a398d1aa41fbfcda6a685cd3298c72
42.727273
123
0.671518
4.60728
false
false
false
false
haawa799/WaniPersistance
WaniPersistance/Persistance+Fetch.swift
1
3082
// // Persistance+Fetch.swift // WaniKani // // Created by Andriy K. on 4/6/17. // Copyright © 2017 haawa. All rights reserved. // import Foundation import WaniModel public extension Persistance { var levelProgression: WaniModel.LevelProgressionInfo? { return user.levelProgression?.waniModelStruct } var studyQueue: WaniModel.StudyQueueInfo? { return user.studyQueue?.waniModelStruct } var srs: WaniModel.SRSDistributionInfo? { return user.srs?.waniModelStruct } var criticalItems: [WaniModel.ReviewItemInfo]? { return user.criticalItems?.waniModelStruct } var recentsItems: [WaniModel.ReviewItemInfo]? { return user.recentsItems?.waniModelStruct } func radicalsForLevel(level: Int) -> [WaniModel.RadicalInfo] { let predicate = NSPredicate(format: "level == \(level)") return realm.objects(WaniPersistance.RadicalInfo.self).filter(predicate).map { $0.waniModelStruct } } func kanjiForLevel(level: Int) -> [WaniModel.KanjiInfo] { let predicate = NSPredicate(format: "level == \(level)") return realm.objects(WaniPersistance.KanjiInfo.self).filter(predicate).map { $0.waniModelStruct } } func wordsForLevel(level: Int) -> [WaniModel.WordInfo] { let predicate = NSPredicate(format: "level == \(level)") return realm.objects(WaniPersistance.WordInfo.self).filter(predicate).map { $0.waniModelStruct } } func searchResults(text: String) -> ([WaniModel.RadicalInfo], [WaniModel.KanjiInfo], [WaniModel.WordInfo]) { let levelPredicatString: String if let number = Int(text) { levelPredicatString = "OR (level == \(number))" } else { levelPredicatString = "" } let radicalPredicate = NSPredicate(format: "(character contains[c] '\(text)') OR (meaning contains[c] '\(text)')\(levelPredicatString)") let radicals = realm.objects(WaniPersistance.RadicalInfo).filter(radicalPredicate) let kanjiPredicate = NSPredicate(format: "(character contains[c] '\(text)') OR (meaning contains[c] '\(text)') OR (onyomi == '\(text)') OR (kunyomi == '\(text)')\(levelPredicatString)") let kanji = realm.objects(WaniPersistance.KanjiInfo).filter(kanjiPredicate) let wordsPredicate = NSPredicate(format: "(character contains[c] '\(text)') OR (meaning contains[c] '\(text)') OR (kana contains[c] '\(text)')\(levelPredicatString)") let words = realm.objects(WaniPersistance.WordInfo).filter(wordsPredicate) return (radicals.map { $0.waniModelStruct }, kanji.map { $0.waniModelStruct }, words.map { $0.waniModelStruct }) } } extension Persistance { var allKanji: [WaniModel.KanjiInfo] { return realm.objects(WaniPersistance.KanjiInfo.self).map { $0.waniModelStruct } } var allRadicals: [WaniModel.RadicalInfo] { return realm.objects(WaniPersistance.RadicalInfo.self).map { $0.waniModelStruct } } var allWords: [WaniModel.WordInfo] { return realm.objects(WaniPersistance.WordInfo.self).map { $0.waniModelStruct } } }
mit
e4e92597f0d41e3ba85fd2a59fd99076
36.573171
193
0.686141
4.315126
false
false
false
false
wireapp/wire-ios-sync-engine
Source/UnauthenticatedSession/UnauthenticatedSession+Login.swift
1
3413
// // 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 Foundation extension ZMCredentials { var isInvalid: Bool { let noEmail = email?.isEmpty ?? true let noPassword = password?.isEmpty ?? true let noNumber = phoneNumber?.isEmpty ?? true let noVerificationCode = phoneNumberVerificationCode?.isEmpty ?? true return (noEmail || noPassword) && (noNumber || noVerificationCode) } } extension UnauthenticatedSession { @objc(continueAfterBackupImportStep) public func continueAfterBackupImportStep() { authenticationStatus.continueAfterBackupImportStep() } /// Attempt to log in with the given credentials @objc(loginWithCredentials:) public func login(with credentials: ZMCredentials) { let updatedCredentialsInUserSession = delegate?.session(session: self, updatedCredentials: credentials) ?? false guard !updatedCredentialsInUserSession else { return } if credentials.isInvalid { let error = NSError(code: .needsCredentials, userInfo: nil) authenticationStatus.notifyAuthenticationDidFail(error) } else { authenticationErrorIfNotReachable { self.authenticationStatus.prepareForLogin(with: credentials) RequestAvailableNotification.notifyNewRequestsAvailable(nil) } } } /// Requires a phone verification code for login. Returns NO if the phone number was invalid @objc(requestPhoneVerificationCodeForLogin:) @discardableResult public func requestPhoneVerificationCodeForLogin(phoneNumber: String) -> Bool { do { var phoneNumber: String? = phoneNumber _ = try ZMUser.validate(phoneNumber: &phoneNumber) } catch { return false } authenticationErrorIfNotReachable { self.authenticationStatus.prepareForRequestingPhoneVerificationCode(forLogin: phoneNumber) RequestAvailableNotification.notifyNewRequestsAvailable(nil) } return true } /// Triggers a request for an email verification code for login. /// /// Returns: false if the email address was invalid. @objc(requestEmailVerificationCodeForLogin:) @discardableResult public func requestEmailVerificationCodeForLogin(email: String) -> Bool { do { var email: String? = email _ = try ZMUser.validate(emailAddress: &email) } catch { return false } authenticationErrorIfNotReachable { self.authenticationStatus.prepareForRequestingEmailVerificationCode(forLogin: email) RequestAvailableNotification.notifyNewRequestsAvailable(nil) } return true } }
gpl-3.0
fcd1cca3abc50c2dd99d654389960e81
36.097826
120
0.691181
5.194825
false
false
false
false
firebase/firebase-ios-sdk
FirebaseSessions/Sources/SessionStartEvent.swift
1
5897
// // Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @_implementationOnly import GoogleDataTransport /// /// SessionStartEvent is responsible for: /// 1) Writing fields to the Session proto /// 2) Synthesizing itself for persisting to disk and logging to GoogleDataTransport /// class SessionStartEvent: NSObject, GDTCOREventDataObject { var proto: firebase_appquality_sessions_SessionEvent init(identifiers: IdentifierProvider, appInfo: ApplicationInfoProtocol, time: TimeProvider = Time()) { proto = firebase_appquality_sessions_SessionEvent() super.init() proto.event_type = firebase_appquality_sessions_EventType_SESSION_START proto.session_data.session_id = makeProtoString(identifiers.sessionID) proto.session_data.previous_session_id = makeProtoStringOrNil(identifiers.previousSessionID) proto.session_data.event_timestamp_us = time.timestampUS proto.application_info.app_id = makeProtoString(appInfo.appID) proto.application_info.session_sdk_version = makeProtoString(appInfo.sdkVersion) proto.application_info.log_environment = convertLogEnvironment(environment: appInfo.environment) proto.application_info.device_model = makeProtoString(appInfo.deviceModel) // proto.application_info.development_platform_name; // proto.application_info.development_platform_version; // `which_platform_info` tells nanopb which oneof we're choosing to fill in for our proto proto.application_info.which_platform_info = FIRSESGetAppleApplicationInfoTag() proto.application_info.apple_app_info.bundle_short_version = makeProtoString(appInfo.bundleID) // proto.application_info.apple_app_info.network_connection_info proto.application_info.apple_app_info.os_name = convertOSName(osName: appInfo.osName) proto.application_info.apple_app_info.mcc_mnc = makeProtoString(appInfo.mccMNC) proto.session_data.data_collection_status .crashlytics = firebase_appquality_sessions_DataCollectionState_COLLECTION_UNKNOWN proto.session_data.data_collection_status .performance = firebase_appquality_sessions_DataCollectionState_COLLECTION_UNKNOWN } func setInstallationID(identifiers: IdentifierProvider) { proto.session_data.firebase_installation_id = makeProtoString(identifiers.installationID) } // MARK: - GDTCOREventDataObject func transportBytes() -> Data { var fields = firebase_appquality_sessions_SessionEvent_fields var error: NSError? let data = FIRSESEncodeProto(&fields.0, &proto, &error) if error != nil { Logger.logError(error.debugDescription) } guard let data = data else { Logger.logError("Session event generated nil transportBytes. Returning empty data.") return Data() } return data } // MARK: - Data Conversion private func makeProtoStringOrNil(_ string: String?) -> UnsafeMutablePointer<pb_bytes_array_t>? { guard let string = string else { return nil } return FIRSESEncodeString(string) } private func makeProtoString(_ string: String) -> UnsafeMutablePointer<pb_bytes_array_t>? { return FIRSESEncodeString(string) } private func convertOSName(osName: String) -> firebase_appquality_sessions_OsName { switch osName.lowercased() { case "macos": return firebase_appquality_sessions_OsName_MACOS case "maccatalyst": return firebase_appquality_sessions_OsName_MACCATALYST case "ios_on_mac": return firebase_appquality_sessions_OsName_IOS_ON_MAC case "ios": return firebase_appquality_sessions_OsName_IOS case "tvos": return firebase_appquality_sessions_OsName_TVOS case "watchos": return firebase_appquality_sessions_OsName_WATCHOS case "ipados": return firebase_appquality_sessions_OsName_IPADOS default: Logger.logWarning("Found unknown OSName: \"\(osName)\" while converting.") return firebase_appquality_sessions_OsName_UNKNOWN_OSNAME } } /// Encodes the proto in this SessionStartEvent to Data, and then decodes the Data back into /// the proto object and returns the decoded proto. This is used for validating encoding works /// and should not be used in production code. func encodeDecodeEvent() -> firebase_appquality_sessions_SessionEvent { let transportBytes = self.transportBytes() var proto = firebase_appquality_sessions_SessionEvent() var fields = firebase_appquality_sessions_SessionEvent_fields let bytes = (transportBytes as NSData).bytes var istream: pb_istream_t = pb_istream_from_buffer(bytes, transportBytes.count) if !pb_decode(&istream, &fields.0, &proto) { let errorMessage = FIRSESPBGetError(istream) if errorMessage.count > 0 { Logger.logInfo("Failed to decode transportBytes: \(errorMessage)") } } return proto } /// Converts the provided log environment to its Proto format. private func convertLogEnvironment(environment: DevEnvironment) -> firebase_appquality_sessions_LogEnvironment { switch environment { case .prod: return firebase_appquality_sessions_LogEnvironment_LOG_ENVIRONMENT_PROD case .staging: return firebase_appquality_sessions_LogEnvironment_LOG_ENVIRONMENT_STAGING case .autopush: return firebase_appquality_sessions_LogEnvironment_LOG_ENVIRONMENT_AUTOPUSH } } }
apache-2.0
225f843fa2972707023db82efdb840a5
39.390411
100
0.744955
4.371386
false
false
false
false
sachin004/firefox-ios
Client/Frontend/Home/BookmarksPanel.swift
4
15657
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage import Shared import XCGLogger private let log = Logger.browserLogger let BookmarkStatusChangedNotification = "BookmarkStatusChangedNotification" struct BookmarksPanelUX { private static let BookmarkFolderHeaderViewChevronInset: CGFloat = 10 private static let BookmarkFolderChevronSize: CGFloat = 20 private static let BookmarkFolderChevronLineWidth: CGFloat = 4.0 private static let BookmarkFolderTextColor = UIColor(red: 92/255, green: 92/255, blue: 92/255, alpha: 1.0) private static let BookmarkFolderTextFont = UIFont.systemFontOfSize(UIConstants.DefaultMediumFontSize, weight: UIFontWeightMedium) } class BookmarksPanel: SiteTableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? = nil var source: BookmarksModel? var parentFolders = [BookmarkFolder]() var bookmarkFolder: BookmarkFolder? private let BookmarkFolderCellIdentifier = "BookmarkFolderIdentifier" private let BookmarkFolderHeaderViewIdentifier = "BookmarkFolderHeaderIdentifier" private lazy var defaultIcon: UIImage = { return UIImage(named: "defaultFavicon")! }() init() { super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: NotificationFirefoxAccountChanged, object: nil) self.tableView.registerClass(BookmarkFolderTableViewCell.self, forCellReuseIdentifier: BookmarkFolderCellIdentifier) self.tableView.registerClass(BookmarkFolderTableViewHeader.self, forHeaderFooterViewReuseIdentifier: BookmarkFolderHeaderViewIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } override func viewDidLoad() { super.viewDidLoad() // if we've not already set a source for this panel fetch a new model // otherwise just use the existing source to select a folder guard let source = self.source else { // Get all the bookmarks split by folders if let bookmarkFolder = bookmarkFolder { profile.bookmarks.modelForFolder(bookmarkFolder).upon(onModelFetched) } else { profile.bookmarks.modelForFolder(BookmarkRoots.MobileFolderGUID).upon(onModelFetched) } return } if let bookmarkFolder = bookmarkFolder { source.selectFolder(bookmarkFolder).upon(onModelFetched) } else { source.selectFolder(BookmarkRoots.MobileFolderGUID).upon(onModelFetched) } } func notificationReceived(notification: NSNotification) { switch notification.name { case NotificationFirefoxAccountChanged: self.reloadData() break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } private func onModelFetched(result: Maybe<BookmarksModel>) { guard let model = result.successValue else { self.onModelFailure(result.failureValue) return } self.onNewModel(model) } private func onNewModel(model: BookmarksModel) { dispatch_async(dispatch_get_main_queue()) { self.source = model self.tableView.reloadData() } } private func onModelFailure(e: Any) { log.error("Error: failed to get data: \(e)") } override func reloadData() { self.source?.reloadData().upon(onModelFetched) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return source?.current.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let source = source, bookmark = source.current[indexPath.row] else { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) } let cell: UITableViewCell if let _ = bookmark as? BookmarkFolder { cell = tableView.dequeueReusableCellWithIdentifier(BookmarkFolderCellIdentifier, forIndexPath: indexPath) } else { cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if let url = bookmark.favicon?.url.asURL where url.scheme == "asset" { cell.imageView?.image = UIImage(named: url.host!) } else { cell.imageView?.setIcon(bookmark.favicon, withPlaceholder: self.defaultIcon) } } switch (bookmark) { case let item as BookmarkItem: if item.title.isEmpty { cell.textLabel?.text = item.url } else { cell.textLabel?.text = item.title } default: // Bookmark folders don't have a good fallback if there's no title. :( cell.textLabel?.text = bookmark.title } return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let cell = cell as? BookmarkFolderTableViewCell { cell.textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont } } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // Don't show a header for the root if source == nil || parentFolders.isEmpty { return nil } guard let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(BookmarkFolderHeaderViewIdentifier) as? BookmarkFolderTableViewHeader else { return nil } // register as delegate to ensure we get notified when the user interacts with this header if header.delegate == nil { header.delegate = self } if parentFolders.count == 1 { header.textLabel?.text = NSLocalizedString("Bookmarks", comment: "Panel accessibility label") } else if let parentFolder = parentFolders.last { header.textLabel?.text = parentFolder.title } return header } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header. if source == nil || parentFolders.isEmpty { return 0 } return SiteTableViewControllerUX.RowHeight } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? BookmarkFolderTableViewHeader { // for some reason specifying the font in header view init is being ignored, so setting it here header.textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if let source = source { let bookmark = source.current[indexPath.row] switch (bookmark) { case let item as BookmarkItem: homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: item.url)!, visitType: VisitType.Bookmark) break case let folder as BookmarkFolder: let nextController = BookmarksPanel() nextController.parentFolders = parentFolders + [source.current] nextController.bookmarkFolder = folder nextController.source = source nextController.homePanelDelegate = self.homePanelDelegate nextController.profile = self.profile self.navigationController?.pushViewController(nextController, animated: true) break default: // Weird. break // Just here until there's another executable statement (compiler requires one). } } } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // Intentionally blank. Required to use UITableViewRowActions } func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { if source == nil { return .None } if source!.current.itemIsEditableAtIndex(indexPath.row) ?? false { return .Delete } return .None } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { if source == nil { return [AnyObject]() } let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.") let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in if let bookmark = self.source?.current[indexPath.row] { // Why the dispatches? Because we call success and failure on the DB // queue, and so calling anything else that calls through to the DB will // deadlock. This problem will go away when the bookmarks API switches to // Deferred instead of using callbacks. // TODO: it's now time for this. self.profile.bookmarks.remove(bookmark).uponQueue(dispatch_get_main_queue()) { res in if let err = res.failureValue { self.onModelFailure(err) return } dispatch_async(dispatch_get_main_queue()) { self.source?.reloadData().upon { guard let model = $0.successValue else { self.onModelFailure($0.failureValue) return } dispatch_async(dispatch_get_main_queue()) { tableView.beginUpdates() self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left) self.source = model tableView.endUpdates() NSNotificationCenter.defaultCenter().postNotificationName(BookmarkStatusChangedNotification, object: bookmark, userInfo:["added":false]) } } } } } }) return [delete] } } private protocol BookmarkFolderTableViewHeaderDelegate { func didSelectHeader() } extension BookmarksPanel: BookmarkFolderTableViewHeaderDelegate { private func didSelectHeader() { self.navigationController?.popViewControllerAnimated(true) } } class BookmarkFolderTableViewCell: TwoLineTableViewCell { private let ImageMargin: CGFloat = 12 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor textLabel?.backgroundColor = UIColor.clearColor() textLabel?.tintColor = BookmarksPanelUX.BookmarkFolderTextColor textLabel?.font = BookmarksPanelUX.BookmarkFolderTextFont imageView?.image = UIImage(named: "bookmarkFolder") let chevron = ChevronView(direction: .Right) chevron.tintColor = BookmarksPanelUX.BookmarkFolderTextColor chevron.frame = CGRectMake(0, 0, BookmarksPanelUX.BookmarkFolderChevronSize, BookmarksPanelUX.BookmarkFolderChevronSize) chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth accessoryView = chevron separatorInset = UIEdgeInsetsZero } override func layoutSubviews() { super.layoutSubviews() // doing this here as TwoLineTableViewCell changes the imageView frame in it's layoutSubviews and we have to make sure it is right if let imageSize = imageView?.image?.size { imageView?.frame = CGRectMake(ImageMargin, (frame.height - imageSize.width) / 2, imageSize.width, imageSize.height) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private class BookmarkFolderTableViewHeader : UITableViewHeaderFooterView { var delegate: BookmarkFolderTableViewHeaderDelegate? lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIConstants.HighlightBlue return label }() lazy var chevron: ChevronView = { let chevron = ChevronView(direction: .Left) chevron.tintColor = UIConstants.HighlightBlue chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth return chevron }() lazy var topBorder: UIView = { let view = UIView() view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor return view }() lazy var bottomBorder: UIView = { let view = UIView() view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor return view }() override var textLabel: UILabel? { return titleLabel } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) userInteractionEnabled = true let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "viewWasTapped:") tapGestureRecognizer.numberOfTapsRequired = 1 addGestureRecognizer(tapGestureRecognizer) addSubview(topBorder) addSubview(bottomBorder) contentView.addSubview(chevron) contentView.addSubview(titleLabel) chevron.snp_makeConstraints { make in make.left.equalTo(contentView).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset) make.centerY.equalTo(contentView) make.size.equalTo(BookmarksPanelUX.BookmarkFolderChevronSize) } titleLabel.snp_makeConstraints { make in make.left.equalTo(chevron.snp_right).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset) make.right.greaterThanOrEqualTo(contentView).offset(-BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset) make.centerY.equalTo(contentView) } topBorder.snp_makeConstraints { make in make.left.right.equalTo(self) make.top.equalTo(self).offset(-0.5) make.height.equalTo(0.5) } bottomBorder.snp_makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(0.5) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func viewWasTapped(gestureRecognizer: UITapGestureRecognizer) { delegate?.didSelectHeader() } }
mpl-2.0
3dc5e02f1a540d24af24935f71f9d2d3
38.738579
172
0.65434
5.903846
false
false
false
false