repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
aliceatlas/hexagen
refs/heads/master
Hexagen/Swift/Promise.swift
mit
1
/*****\\\\ / \\\\ Swift/Promise.swift / /\ /\ \\\\ (part of Hexagen) \ \_X_/ //// \ //// Copyright © 2015 Alice Atlas (see LICENSE.md) \*****//// public class Promiselike<T> { private var handlers: SynchronizedQueue<T -> Void>? = SynchronizedQueue() private var shouldDischargeHandlers = DispatchOnce() internal var value: T? { fatalError("not implemented") } public func map<U>(fn: T -> U) -> MappedPromise<T, U> { return MappedPromise(parent: self, mapping: fn) } public func addHandler(fn: T -> Void) { handlers?.push(fn) ?? fn(value!) } private func dischargeHandlers() { var alreadyRan = true shouldDischargeHandlers.perform { alreadyRan = false let value = self.value! let handlers = self.handlers! self.handlers = nil for handler in handlers.unroll() { handler(value) } } if alreadyRan { fatalError("promise being asked to discharge handlers for a second time") } } } public class Promise<T>: Promiselike<T> { private var shouldFulfill = DispatchOnce() private var _value: T? override internal var value: T? { return _value } internal override init() {} public init(@noescape _ fn: (T -> Void) -> Void) { super.init() fn(_fulfill) } internal func _fulfill(value: T) { var alreadyRan = true shouldFulfill.perform { alreadyRan = false printo("FULFILL \(self.sn)") self._value = value self.dischargeHandlers() } if alreadyRan { fatalError("promise was already fulfilled") } } } public class MappedPromise<T, U>: Promiselike<U> { private let parent: Promiselike<T> private let mapping: T -> U private var shouldAddParentHandler = DispatchOnce() private var cachedValue: U? override internal var value: U? { if cachedValue == nil && parent.value != nil { cachedValue = mapping(parent.value!) } return cachedValue } private init(parent: Promiselike<T>, mapping: T -> U) { self.parent = parent self.mapping = mapping } private func _parentHandler(value: T) { dischargeHandlers() } public override func addHandler(handler: U -> Void) { super.addHandler(handler) shouldAddParentHandler.perform { self.parent.addHandler(self._parentHandler) } } } }
06c5fa287fee72cde8062b43a348fa6c
26.082474
85
0.559193
false
false
false
false
demmys/treeswift
refs/heads/master
src/Parser/GrammarParser.swift
bsd-2-clause
1
import AST class GrammarParser { let integerLiteral = TokenKind.IntegerLiteral(0, decimalDigits: true) let floatingPointLiteral = TokenKind.FloatingPointLiteral(0) let booleanLiteral = TokenKind.BooleanLiteral(true) let stringLiteral = TokenKind.StringLiteral("") let identifier = TokenKind.Identifier("") let implicitParameterName = TokenKind.ImplicitParameterName(0) let prefixOperator = TokenKind.PrefixOperator("") let binaryOperator = TokenKind.BinaryOperator("") let postfixOperator = TokenKind.PostfixOperator("") let modifier = TokenKind.Modifier(.Convenience) let ts: TokenStream init(_ ts: TokenStream) { self.ts = ts } func find(candidates: [TokenKind], startIndex: Int = 0) -> (Int, TokenKind) { var i = startIndex var kind = ts.look(i, skipLineFeed: false).kind while kind != .EndOfFile { for c in candidates { if kind == c { return (i, kind) } } kind = ts.look(++i, skipLineFeed: false).kind } return (i, .EndOfFile) } func findInsideOfBrackets( candidates: [TokenKind], startIndex: Int = 0 ) -> (Int, TokenKind) { var i = startIndex var nest = 0 while true { let kind = ts.look(i).kind switch kind { case .EndOfFile: return (i, .EndOfFile) case .LeftBracket: ++nest case .RightBracket: if nest == 0 { return (i, .RightBracket) } --nest default: for c in candidates { if kind == c { return (i, kind) } } ++i } } } func findParenthesisClose(startIndex: Int = 0) -> Int? { var i = startIndex var nest = 0 while true { let kind = ts.look(i).kind switch kind { case .EndOfFile: return nil case .LeftParenthesis: ++nest case .RightParenthesis: if nest == 0 { return i } --nest default: ++i } } } func findRightParenthesisBefore( candidates: [TokenKind], startIndex: Int = 0 ) -> Int? { var i = startIndex var nest = 0 while true { let kind = ts.look(i).kind switch kind { case .EndOfFile: return nil case .LeftParenthesis: ++nest case .RightParenthesis: if nest == 0 { return i } --nest default: for c in candidates { if kind == c { return nil } } ++i } } } func disjointModifiers( var mods: [Modifier] ) throws -> (AccessLevel?, [Modifier]) { var accessLevel: AccessLevel? for var i = 0; i < mods.count; ++i { switch mods[i] { case let .AccessLevelModifier(al): if accessLevel != nil { try ts.error(.DuplicateAccessLevelModifier) } accessLevel = al mods.removeAtIndex(i--) default: break } } return (accessLevel, mods) } func isEnum(name: String) -> Bool { return true } }
c0245b02e00e874b2094806954f479f3
27.112782
81
0.457342
false
false
false
false
ManueGE/AlamofireActivityLogger
refs/heads/master
watchos Extension/InterfaceController.swift
mit
1
// // InterfaceController.swift // watchOS Extension // // Created by Manuel García-Estañ on 19/10/16. // Copyright © 2016 manuege. All rights reserved. // import WatchKit import Foundation import Alamofire import AlamofireActivityLogger class InterfaceController: WKInterfaceController { var prettyPrint = true var addSeparator = true var selectedLevel = LogLevel.all @IBOutlet var levelPicker: WKInterfacePicker! @IBOutlet var prettyPrintSwitch: WKInterfaceSwitch! @IBOutlet var separatorSwitch: WKInterfaceSwitch! override func awake(withContext context: Any?) { super.awake(withContext: context) prettyPrintSwitch.setOn(prettyPrint) separatorSwitch.setOn(addSeparator) let items: [WKPickerItem] = Constants.levelsAndNames.map { (value) in let item = WKPickerItem() item.title = value.1 return item; } levelPicker.setItems(items) levelPicker.setSelectedItemIndex(1) } override func willActivate() { super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func didChangePrettySwitch(_ value: Bool) { prettyPrint = value } @IBAction func didChangeSeparatorSwitch(_ value: Bool) { addSeparator = value } @IBAction func didChangeLevelPicker(_ value: Int) { selectedLevel = Constants.levelsAndNames[value].0 } @IBAction func didPressSuccess() { performRequest(success: true) } @IBAction func didPressFail() { performRequest(success: false) } private func performRequest(success: Bool) { // Build options var options: [LogOption] = [] if prettyPrint { options.append(.jsonPrettyPrint) } if addSeparator { options.append(.includeSeparator) } Helper.performRequest(success: success, level: selectedLevel, options: options) { } } }
2cb45feac2194f60784579585763d527
23.382979
80
0.596859
false
false
false
false
SwiftFS/Swift-FS-China
refs/heads/master
Sources/SwiftFSChina/configuration/Routes.swift
mit
1
// // Routes.swift // Perfect-App-Template // // Created by Jonathan Guthrie on 2017-02-20. // Copyright (C) 2017 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectHTTPServer import PerfectLib import PerfectHTTP import OAuth2 func mainRoutes() -> [[String: Any]] { let dic = ApplicationConfiguration() GitHubConfig.appid = dic.appid GitHubConfig.secret = dic.secret GitHubConfig.endpointAfterAuth = dic.endpointAfterAuth GitHubConfig.redirectAfterAuth = dic.redirectAfterAuth var routes: [[String: Any]] = [[String: Any]]() routes.append(["method":"get", "uri":"/**", "handler":PerfectHTTPServer.HTTPHandler.staticFiles, "documentRoot":"./webroot", "allowRequestFilter":false, "allowResponseFilters":true]) //github routes.append(["method":"get", "uri":"/to/github", "handler":OAuth.sendToProvider]) // routes.append(["method":"get", "uri":"/auth/response/github", "handler":OAuth.authResponse]) //Handler for home page routes.append(["method":"get", "uri":"/", "handler":Handlers.index]) routes.append(["method":"get", "uri":"/index", "handler":Handlers.index]) routes.append(["method":"get", "uri":"/share", "handler":Handlers.share]) routes.append(["method":"get", "uri":"/ask", "handler":Handlers.ask]) routes.append(["method":"get", "uri":"/settings", "handler":Handlers.settings]) routes.append(["method":"get", "uri":"/about", "handler":Handlers.about]) routes.append(["method":"get", "uri":"/login", "handler":Handlers.login]) routes.append(["method":"get", "uri":"/register", "handler":Handlers.register]) routes.append(["method":"get", "uri":"/notification/**", "handler":Notification.index]) //wiki routes.append(["method":"get", "uri":"/wiki/{path}", "handler":Wiki.index]) routes.append(["method":"get", "uri":"/wiki", "handler":Wiki.index]) routes.append(["method":"get", "uri":"/wiki/", "handler":Wiki.index]) //wiki-api routes.append(["method":"post", "uri":"/wiki/new", "handler":Wiki.newWiki]) //user routes.append(["method":"get", "uri":"/user/{username}/index", "handler":User.index]) routes.append(["method":"get", "uri":"/user/{username}/hot_topics", "handler":User.hotTopics]) routes.append(["method":"get", "uri":"/user/{username}/like_topics", "handler":User.likeTopics]) routes.append(["method":"get", "uri":"/user/{username}/topics", "handler":User.topics]) routes.append(["method":"get", "uri":"/user/{username}/comments", "handler":User.comments]) routes.append(["method":"get", "uri":"/user/{username}/collects", "handler":User.collects]) routes.append(["method":"get", "uri":"/user/{username}/follows", "handler":User.follows]) routes.append(["method":"post", "uri":"/user/follow", "handler":User.follow]) routes.append(["method":"post", "uri":"/user/cancel_follow", "handler":User.cancelFollow]) routes.append(["method":"get", "uri":"/user/{username}/fans", "handler":User.fans]) routes.append(["method":"post", "uri":"/user/edit", "handler":User.edit]) routes.append(["method":"post", "uri":"/user/change_pwd", "handler":User.changePwd]) //notification routes.append(["method":"get", "uri":"/notification/all", "handler":Notification.requiredDate]) //topic routes.append(["method":"get", "uri":"topic/{topic_id}/view", "handler":Topic.get]) routes.append(["method":"get", "uri":"topic/new", "handler":Topic.new]) routes.append(["method":"post", "uri":"topic/new", "handler":Topic.newTopic]) routes.append(["method":"post", "uri":"topic/edit", "handler":Topic.edit]) routes.append(["method":"get", "uri":"topic/{topic_id}/query", "handler":Topic.getQuery]) routes.append(["method":"get", "uri":"topic/{topic_id}/edit", "handler":Topic.editTopic]) routes.append(["method":"get", "uri":"topic/{topic_id}/delete", "handler":Topic.deleteTopic]) routes.append(["method":"post", "uri":"topic/collect", "handler":Topic.collect]) routes.append(["method":"post", "uri":"topic/like", "handler":Topic.like]) routes.append(["method":"get", "uri":"topic/cancel_like", "handler":Topic.cancleLike]) routes.append(["method":"post", "uri":"topic/cancel_collect", "handler":Topic.cancelCollect]) //comments routes.append(["method":"get", "uri":"comments/all", "handler":Comments.getComments]) routes.append(["method":"post", "uri":"comment/new", "handler":Comments.newComment]) routes.append(["method":"get", "uri":"comment/{comment_id}/delete", "handler":Comments.delete]) //auth routes.append(["method":"post", "uri":"/auth/sign_up", "handler":Auth.signUp]) routes.append(["method":"post", "uri":"/auth/login", "handler":Auth.login]) routes.append(["method":"get", "uri":"/auth/logout", "handler":Auth.logout]) routes.append(["method":"get", "uri":"/topics/all", "handler":Topics.topics]) //upload routes.append(["method":"post", "uri":"/upload/avatar", "handler":Upload.avatar]) routes.append(["method":"post", "uri":"/upload/file", "handler":Upload.file]) //notification routes.append(["method":"post", "uri":"notification/delete_all", "handler":Notification.deleteAll]) routes.append(["method":"post", "uri":"notification/mark", "handler":Notification.mark]) routes.append(["method":"post", "uri":"notification/{id}/delete", "handler":Notification.delete]) //search routes.append(["method":"get", "uri":"search/*", "handler":Search.query]) //email routes.append(["method":"get", "uri":"verification/{secret}", "handler":EmailAuth.verification]) routes.append(["method":"get", "uri":"email-verification", "handler":EmailAuth.emailVerification]) routes.append(["method":"post", "uri":"send-verification-mail", "handler":EmailAuth.sendVerificationMail]) return routes }
225ab839ee82fb27bdc1c97fc3dad852
47.121212
110
0.627361
false
false
false
false
LedgerHQ/ledger-wallet-ios
refs/heads/master
ledger-wallet-ios/Extensions/NSDate+Utils.swift
mit
1
// // NSDate+Utils.swift // ledger-wallet-ios // // Created by Nicolas Bigot on 20/07/15. // Copyright (c) 2015 Ledger. All rights reserved. // import Foundation extension NSDate { func firstMomentDate() -> NSDate { let calendar = NSCalendar.currentCalendar() let comps = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: self) comps.hour = 0 comps.minute = 0 comps.second = 0 return calendar.dateFromComponents(comps)! } }
75a89b37419596eea94b08119d3fc50e
22.173913
103
0.612782
false
false
false
false
inacioferrarini/glasgow
refs/heads/master
Example/Tests/UIKit/Controller/DataBasedViewControllerSpec.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2017 Inácio Ferrarini // // 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 Quick import Nimble @testable import Glasgow class DataBasedViewControllerSpec: QuickSpec { // swiftlint:disable function_body_length override func spec() { var dataBasedViewController: TestDataBasedViewController? var onPerformDataSyncBlockWasCalled: Bool? var onWillSyncDataBlockWasCalled: Bool? var onSyncDataBlockWasCalled: Bool? var onDidSyncDataBlockWasCalled: Bool? var courtainView: UIView? describe("Initialiation") { var onPerformDataSyncBlockWasCalled = false beforeEach { // Given dataBasedViewController = TestDataBasedViewController() dataBasedViewController?.onPerformDataSync = { onPerformDataSyncBlockWasCalled = true } } it("viewWillAppear must call performDataSync") { // When dataBasedViewController?.viewWillAppear(false) // Then expect(onPerformDataSyncBlockWasCalled).to(beTruthy()) } } describe("Data Synchronization") { beforeEach { // Given onPerformDataSyncBlockWasCalled = false onWillSyncDataBlockWasCalled = false onSyncDataBlockWasCalled = false onDidSyncDataBlockWasCalled = false dataBasedViewController = TestDataBasedViewController() dataBasedViewController?.onPerformDataSync = { onPerformDataSyncBlockWasCalled = true } dataBasedViewController?.onWillSyncData = { onWillSyncDataBlockWasCalled = true } dataBasedViewController?.onSyncData = { onSyncDataBlockWasCalled = true } dataBasedViewController?.onDidSyncData = { onDidSyncDataBlockWasCalled = true } } it("performDataSync, when shouldSyncData is true, must call all methods ") { // Given dataBasedViewController?.onShouldSyncData = { return true } // When dataBasedViewController?.performDataSync() // Then expect(onPerformDataSyncBlockWasCalled).to(beTruthy()) expect(onWillSyncDataBlockWasCalled).toEventually(beTruthy()) expect(onSyncDataBlockWasCalled).to(beTruthy()) expect(onDidSyncDataBlockWasCalled).to(beTruthy()) } it("performDataSync, when shouldSyncData is false, must call only didSyncData") { // Given dataBasedViewController?.onShouldSyncData = { return false } // When dataBasedViewController?.performDataSync() // Then expect(onPerformDataSyncBlockWasCalled).to(beTruthy()) expect(onWillSyncDataBlockWasCalled).to(beFalsy()) expect(onSyncDataBlockWasCalled).to(beFalsy()) expect(onDidSyncDataBlockWasCalled).to(beTruthy()) } } describe("Courtain Methods") { beforeEach { // Given courtainView = UIView() dataBasedViewController = TestDataBasedViewController() dataBasedViewController?.courtainView = courtainView } it("showCourtainView must show courtain") { // Given courtainView?.isHidden = true // When dataBasedViewController?.showCourtainView() // Then expect(courtainView?.isHidden).toEventually(beFalsy()) } it("hideCourtainView must hide courtain") { // Given courtainView?.isHidden = false // When dataBasedViewController?.hideCourtainView() // Then expect(courtainView?.isHidden).toEventually(beTruthy()) } } } // swiftlint:enable body_length }
d59e0ceddef4d51be51c46fbde0e859c
33.3625
93
0.588396
false
false
false
false
raymondshadow/SwiftDemo
refs/heads/master
SwiftApp/Pods/RxGesture/Pod/Classes/RxGestureRecognizerDelegate.swift
apache-2.0
1
// Copyright (c) RxSwiftCommunity // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif import RxSwift import RxCocoa public struct GestureRecognizerDelegatePolicy<PolicyInput> { public typealias PolicyBody = (PolicyInput) -> Bool private let policy: PolicyBody private init(policy: @escaping PolicyBody) { self.policy = policy } public static func custom(_ policy: @escaping PolicyBody) -> GestureRecognizerDelegatePolicy<PolicyInput> { return .init(policy: policy) } public static var always: GestureRecognizerDelegatePolicy<PolicyInput> { return .init { _ in true } } public static var never: GestureRecognizerDelegatePolicy<PolicyInput> { return .init { _ in false } } fileprivate func isPolicyPassing(with args: PolicyInput) -> Bool { return policy(args) } } public final class RxGestureRecognizerDelegate: NSObject, GestureRecognizerDelegate { public var beginPolicy: GestureRecognizerDelegatePolicy<GestureRecognizer> = .always public var touchReceptionPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, Touch)> = .always public var selfFailureRequirementPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, GestureRecognizer)> = .never public var otherFailureRequirementPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, GestureRecognizer)> = .never public var simultaneousRecognitionPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, GestureRecognizer)> = .always #if os(iOS) // Workaround because we can't have stored properties with @available annotation private var _pressReceptionPolicy: Any? @available(iOS 9.0, *) public var pressReceptionPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, UIPress)> { get { if let policy = _pressReceptionPolicy as? GestureRecognizerDelegatePolicy<(GestureRecognizer, UIPress)> { return policy } return GestureRecognizerDelegatePolicy<(GestureRecognizer, UIPress)>.always } set { _pressReceptionPolicy = newValue } } #endif #if os(OSX) public var eventRecognitionAttemptPolicy: GestureRecognizerDelegatePolicy<(GestureRecognizer, NSEvent)> = .always #endif public func gestureRecognizerShouldBegin( _ gestureRecognizer: GestureRecognizer ) -> Bool { return beginPolicy.isPolicyPassing(with: gestureRecognizer) } public func gestureRecognizer( _ gestureRecognizer: GestureRecognizer, shouldReceive touch: Touch ) -> Bool { return touchReceptionPolicy.isPolicyPassing( with: (gestureRecognizer, touch) ) } public func gestureRecognizer( _ gestureRecognizer: GestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: GestureRecognizer ) -> Bool { return otherFailureRequirementPolicy.isPolicyPassing( with: (gestureRecognizer, otherGestureRecognizer) ) } public func gestureRecognizer( _ gestureRecognizer: GestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: GestureRecognizer ) -> Bool { return selfFailureRequirementPolicy.isPolicyPassing( with: (gestureRecognizer, otherGestureRecognizer) ) } public func gestureRecognizer( _ gestureRecognizer: GestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: GestureRecognizer ) -> Bool { return simultaneousRecognitionPolicy.isPolicyPassing( with: (gestureRecognizer, otherGestureRecognizer) ) } #if os(iOS) @available(iOS 9.0, *) public func gestureRecognizer( _ gestureRecognizer: UIGestureRecognizer, shouldReceive press: UIPress ) -> Bool { return pressReceptionPolicy.isPolicyPassing( with: (gestureRecognizer, press) ) } #endif #if os(OSX) public func gestureRecognizer( _ gestureRecognizer: NSGestureRecognizer, shouldAttemptToRecognizeWith event: NSEvent ) -> Bool { return eventRecognitionAttemptPolicy.isPolicyPassing( with: (gestureRecognizer, event) ) } #endif }
e2f643a7796987195d3fbec98c3b0822
33.144654
127
0.708786
false
false
false
false
jshin47/swift-reactive-viper-example
refs/heads/master
swift-reactive-viper-sample/swift-reactive-viper-sample/GlobalReactiveUiKitFunctions.swift
mit
1
// // GlobalReactiveUiKitFunctions.swift // swift-reactive-viper-sample // // Created by Justin Shin on 8/21/15. // Copyright © 2015 EmergingMed. All rights reserved. // import Foundation import ObjectiveC import UIKit import ReactiveCocoa func lazyAssociatedProperty<T: AnyObject>(host: AnyObject, key: UnsafePointer<Void>, factory: ()->T) -> T { var associatedProperty = objc_getAssociatedObject(host, key) as? T if associatedProperty == nil { associatedProperty = factory() objc_setAssociatedObject(host, key, associatedProperty, .OBJC_ASSOCIATION_RETAIN) } return associatedProperty! } func lazyMutableProperty<T>(host: AnyObject, _ key: UnsafePointer<Void>, setter: T -> (), getter: () -> T) -> MutableProperty<T> { return lazyAssociatedProperty(host, key: key) { let property = MutableProperty<T>(getter()) property.producer .start(next: { newValue in setter(newValue) }) return property } }
9d01c66b613f7bac025218e51a6be3e8
29.216216
74
0.608774
false
false
false
false
geekaurora/ReactiveListViewKit
refs/heads/master
ReactiveListViewKit/Supported Files/CZUtils/Sources/CZUtils/Extensions/UIView+.swift
mit
1
// // UIView+Extension.swift // // Created by Cheng Zhang on 1/12/16. // Copyright © 2016 Cheng Zhang. All rights reserved. // import UIKit /// Constants for UIView extensions public enum UIViewConstants { public static let fadeInDuration: TimeInterval = 0.4 public static let fadeInAnimationName = "com.tony.animation.fadein" } // MARK: - Corner/Border public extension UIView { func roundToCircle() { let width = self.bounds.size.width layer.cornerRadius = width / 2 layer.masksToBounds = true } func roundCorner(_ cornerRadius: CGFloat = 2, boarderWidth: CGFloat = 0, boarderColor: UIColor = .clear, shadowColor: UIColor = .clear, shadowOffset: CGSize = .zero, shadowRadius: CGFloat = 2, shadowOpacity: Float = 1) { layer.masksToBounds = true layer.cornerRadius = cornerRadius layer.borderColor = boarderColor.cgColor layer.borderWidth = boarderWidth layer.shadowColor = shadowColor.cgColor layer.shadowOffset = shadowOffset layer.shadowRadius = shadowRadius } } // MARK: - Animations public extension UIView { func fadeIn(animationName: String = UIViewConstants.fadeInAnimationName, duration: TimeInterval = UIViewConstants.fadeInDuration) { let transition = CATransition() transition.duration = duration transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) transition.type = CATransitionType.fade layer.add(transition, forKey: animationName) } }
c7c846fbaaba7d7c4e3021b16dd0af5a
29.77193
104
0.627138
false
false
false
false
somegeekintn/SimDirs
refs/heads/main
SimDirs/Model/SimModel.swift
mit
1
// // SimModel.swift // SimDirs // // Created by Casey Fleser on 5/24/22. // import Foundation import Combine enum SimError: Error { case deviceParsingFailure case invalidApp } struct SimDevicesUpdates { let runtime : SimRuntime var additions : [SimDevice] var removals : [SimDevice] } class SimModel { var deviceTypes : [SimDeviceType] var runtimes : [SimRuntime] var monitor : Cancellable? let updateInterval = 2.0 var devices : [SimDevice] { runtimes.flatMap { $0.devices } } var apps : [SimApp] { devices.flatMap { $0.apps } } var deviceUpdates = PassthroughSubject<SimDevicesUpdates, Never>() init() { let simctl = SimCtl() do { let runtimeDevs : [String : [SimDevice]] deviceTypes = try simctl.readAllDeviceTypes() runtimes = try simctl.readAllRuntimes() runtimeDevs = try simctl.readAllRuntimeDevices() for (runtimeID, devices) in runtimeDevs { do { let runtimeIdx = try runtimes.indexOfMatchedOrCreated(identifier: runtimeID) runtimes[runtimeIdx].setDevices(devices, from: deviceTypes) } catch { print("Warning: Unable to create placeholder runtime from \(runtimeID)") } } runtimes.sort() devices.completeSetup(with: deviceTypes) if !ProcessInfo.processInfo.isPreviewing { beginMonitor() } } catch { fatalError("Failed to initialize data model:\n\(error)") } } func beginMonitor() { monitor = Timer.publish(every: updateInterval, on: .main, in: .default) .autoconnect() .receive(on: DispatchQueue.global(qos: .background)) .flatMap { _ in Just((try? SimCtl().readAllRuntimeDevices()) ?? [String : [SimDevice]]()) } .receive(on: DispatchQueue.main) .sink { [weak self] runtimeDevs in guard let this = self else { return } for (runtimeID, curDevices) in runtimeDevs { guard let runtime = this.runtimes.first(where: { $0.identifier == runtimeID }) else { print("missing runtime: \(runtimeID)"); continue } let curDevIDs = curDevices.map { $0.udid } let lastDevID = runtime.devices.map { $0.udid } let updates = SimDevicesUpdates( runtime: runtime, additions: curDevices.filter { !lastDevID.contains($0.udid) }, removals: runtime.devices.filter { !curDevIDs.contains($0.udid) }) if !updates.removals.isEmpty || !updates.additions.isEmpty { let idsToRemove = updates.removals.map { $0.udid } updates.additions.completeSetup(with: this.deviceTypes) runtime.devices.removeAll(where: { idsToRemove.contains($0.udid) }) runtime.devices.append(contentsOf: updates.additions) this.deviceUpdates.send(updates) } for srcDevice in curDevices { guard let dstDevice = runtime.devices.first(where: { $0.udid == srcDevice.udid }) else { print("missing device: \(srcDevice.udid)"); continue } if dstDevice.updateDevice(from: srcDevice) { print("\(dstDevice.udid) updated: \(dstDevice.state)") } } } } } }
cf44200a5b5c07a118f8269a969a57f6
37.442308
167
0.503002
false
false
false
false
VladasZ/iOSTools
refs/heads/master
Sources/iOS/IBDesignable/IBDesignableView.swift
mit
1
// // IBDesignableView.swift // iOSTools // // Created by Vladas Zakrevskis on 7/7/17. // Copyright © 2017 VladasZ. All rights reserved. // import UIKit fileprivate func viewWithSize<T>(_ size: CGSize) -> T where T: IBDesignableView { return T(frame: CGRect(0, 0, size.width, size.height)) } @IBDesignable open class IBDesignableView : UIView { open class var defaultSize: CGSize { return CGSize(width: 100, height: 100) } public class func fromNib() -> Self { return viewWithSize(defaultSize) } private static var identifier: String { return String(describing: self) } private var identifier: String { return type(of: self).identifier } //MARK: - Initialization public required override init(frame: CGRect) { super.init(frame: frame) addSubview(loadFromXib()) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(loadFromXib()) setup() } private func loadFromXib() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: identifier, bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView view.frame = self.bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] return view } open func setup() { } }
e7eabe562a8051ff0cc25dfd2b842eca
25.867925
81
0.630618
false
false
false
false
borisyurkevich/Wallet
refs/heads/master
Wallet/User Interface/CarouselViewController.swift
gpl-3.0
1
// // CarouselViewController.swift // Wallet // // Created by Boris Yurkevich on 30/09/2017. // Copyright © 2017 Boris Yurkevich. All rights reserved. // import UIKit enum State: Int { case first case second case third } protocol CarouselViewControllerDelegate: class { func updateState(newState: State) } class CarouselViewController: UIViewController { weak var delegate: CarouselViewControllerDelegate? private var animator: UIViewPropertyAnimator! private var state = State.first @IBOutlet weak var mainLabel: UILabel! @IBOutlet weak var leftLabel: UILabel! @IBOutlet weak var rightLabel: UILabel! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var leftView: UIView! @IBOutlet weak var rightView: UIView! @IBOutlet weak var mainView: UIView! @IBAction func pan(_ sender: UIPanGestureRecognizer) { switch sender.state { case .began: let velocity = sender.velocity(in: self.view) if velocity.x > 0 { // Moving forward. animator = UIViewPropertyAnimator(duration: 1.0, controlPoint1: mainLabel.center, controlPoint2: leftLabel.center) { switch self.state { case .first: self.mainLabel.center = self.rightView.center self.leftLabel.center = self.mainView.center self.rightLabel.center = self.leftView.center self.mainLabel.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5) self.leftLabel.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0) case .second: self.mainLabel.center = self.leftView.center self.leftLabel.center = self.rightView.center self.rightLabel.center = self.mainView.center self.rightLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.leftLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) case .third: self.mainLabel.center = self.mainView.center self.leftLabel.center = self.leftView.center self.rightLabel.center = self.rightView.center self.mainLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.rightLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) } } } else { // Moving backward animator = UIViewPropertyAnimator(duration: 1.0, controlPoint1: mainLabel.center, controlPoint2: leftLabel.center) { switch self.state { case .first: self.mainLabel.center = self.leftView.center self.leftLabel.center = self.rightView.center self.rightLabel.center = self.mainView.center self.rightLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.mainLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) case .second: self.mainLabel.center = self.mainView.center self.leftLabel.center = self.leftView.center self.rightLabel.center = self.rightView.center self.leftLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) self.mainLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) case .third: self.mainLabel.center = self.rightView.center self.leftLabel.center = self.mainView.center self.rightLabel.center = self.leftView.center self.rightLabel.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5) self.leftLabel.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0) } } } case .changed: // begam let translation = sender.translation(in: self.view) animator.fractionComplete = abs(translation.x) / 100 case .ended: animator.continueAnimation(withTimingParameters: nil, durationFactor: 0) let velocity = sender.velocity(in: self.view) if velocity.x > 0 { // Going forward switch self.state { case .first: self.state = .second self.pageControl.currentPage = 1 case .second: self.state = .third self.pageControl.currentPage = 2 case .third: self.state = .first self.pageControl.currentPage = 0 } } else { // Going backward. switch self.state { case .first: self.state = .third self.pageControl.currentPage = 2 case .second: self.state = .first self.pageControl.currentPage = 0 case .third: self.state = .second self.pageControl.currentPage = 1 } } self.delegate?.updateState(newState: self.state) default: break } } override func viewDidLoad() { super.viewDidLoad() mainLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) rightLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) leftLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) } }
f22626e3f5ba3f27d7a1af07102cb645
39.398693
95
0.508008
false
false
false
false
openboy2012/FlickerNumber
refs/heads/master
Swift/FlickerNumber-Swift/ViewController.swift
mit
1
// // ViewController.swift // FlickerNumber // // Created by DeJohn Dong on 15/10/23. // Copyright © 2015年 DDKit. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label : UILabel! @IBOutlet weak var fnSwitch : UISwitch! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // label?.fn_setNumber(1234.1234) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.valueChanged(self.fnSwitch) } @IBAction func valueChanged(_ sender : UISwitch) { if sender.isOn { if self.title == "Flicker An Integer Number" { label?.fn_setNumber(1234442218, formatter: nil) } else if self.title == "Flicker A Float Number" { label?.fn_setNumber(123456789.123456, formatter: nil) } else if self.title == "Flicker A Format Number" { label?.fn_setNumber(1234512, format:"$%@", formatter: nil) } else if self.title == "Flicker An Attribute Number" { let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red] let range = NSRange(location: 2, length: 2) let attribute = NSDictionary.fn_dictionary(colorDict, range: range) label?.fn_setNumber(12345.212, formatter: nil, attributes: attribute) } else { let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red] let colorRange = NSRange(location: 1, length: 2) let colorAttribute = NSDictionary.fn_dictionary(colorDict, range: colorRange) let fontDict = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)] let fontRange = NSRange(location: 3, length: 4) let fontAttribute = NSDictionary.fn_dictionary(fontDict, range: fontRange) let attributes = [colorAttribute, fontAttribute] let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency numberFormatter.formatterBehavior = .behavior10_4 label?.fn_setNumber(123456.789, format:"%@", formatter:numberFormatter, attributes: attributes) } } else { if self.title == "Flicker An Integer Number" { label?.fn_setNumber(1235566321) } else if self.title == "Flicker A Float Number" { label?.fn_setNumber(123456789.123456) } else if self.title == "Flicker A Format Number" { label?.fn_setNumber(91, format:"$%.2f") } else if self.title == "Flicker An Attribute Number" { let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red] let range = NSRange(location: 2, length: 2) let attribute = NSDictionary.fn_dictionary(colorDict, range: range) label?.fn_setNumber(48273.38, attributes: attribute) } else { let colorDict = [NSAttributedStringKey.foregroundColor: UIColor.red] let colorRange = NSRange(location: 1, length: 2) let colorAttribute = NSDictionary.fn_dictionary(colorDict, range: colorRange) let fontDict = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)] let fontRange = NSRange(location: 3, length: 4) let fontAttribute = NSDictionary.fn_dictionary(fontDict, range: fontRange) let attributes = [colorAttribute, fontAttribute] label?.fn_setNumber(987654.321, format:"¥%.3f", attributes: attributes) } } } }
0b5da6d15a3ad3e42a64640741bd5fee
47.525641
111
0.606341
false
false
false
false
mrommel/TreasureDungeons
refs/heads/master
TreasureDungeons/Source/OpenGL/Camera.swift
apache-2.0
1
// // Camera.swift // TreasureDungeons // // Created by Michael Rommel on 26.06.17. // Copyright © 2017 BurtK. All rights reserved. // import Foundation import GLKit protocol CameraChangeListener { func moveCameraTo(x: Float, andY y: Float, withYaw yaw: Float) } class Camera { fileprivate var pitch: Float = 0 fileprivate var yaw: Float = 0 //fileprivate var roll: Float = 0 var x: Float = -2 var y: Float = -2 fileprivate var changeListeners: [CameraChangeListener] = [] init() { } var viewMatrix: GLKMatrix4 { get { var viewMatrix: GLKMatrix4 = GLKMatrix4Identity viewMatrix = GLKMatrix4RotateX(viewMatrix, GLKMathDegreesToRadians(self.pitch)) viewMatrix = GLKMatrix4RotateY(viewMatrix, GLKMathDegreesToRadians(self.yaw)) //viewMatrix = GLKMatrix4RotateZ(viewMatrix, GLKMathDegreesToRadians(self.roll)) viewMatrix = GLKMatrix4Translate(viewMatrix, self.x, 0, self.y) return viewMatrix } } var positionOnMap: Point { get { return Point(x: -Int((self.x - 1.0) / 2.0) , y: -Int((self.y - 1.0) / 2.0)) } } var predictedPositionOnMap: Point { get { let newX = self.x - sin(GLKMathDegreesToRadians(self.yaw)) * 0.5 let newY = self.y + cos(GLKMathDegreesToRadians(self.yaw)) * 0.5 return Point(x: -Int((newX - 1.0) / 2.0) , y: -Int((newY - 1.0) / 2.0)) } } func moveForward() { self.x = self.x - sin(GLKMathDegreesToRadians(self.yaw)) * 0.5 self.y = self.y + cos(GLKMathDegreesToRadians(self.yaw)) * 0.5 for changeListener in self.changeListeners { changeListener.moveCameraTo(x: self.x, andY: self.y, withYaw: self.yaw) } } func turn(leftAndRight value: Float) { self.yaw -= value for changeListener in self.changeListeners { changeListener.moveCameraTo(x: self.x, andY: self.y, withYaw: self.yaw) } } func reset() { self.pitch = self.pitch * 0.95 } func addChangeListener(changeListener: CameraChangeListener) { self.changeListeners.append(changeListener) } }
99a24982b0579a63c41fc993fd76aee9
27.170732
92
0.591775
false
false
false
false
jkusnier/WorkoutMerge
refs/heads/master
WorkoutMerge/SyncAllTableViewController.swift
mit
1
// // SyncAllTableViewController.swift // WorkoutMerge // // Created by Jason Kusnier on 9/12/15. // Copyright (c) 2015 Jason Kusnier. All rights reserved. // import UIKit import HealthKit import CoreData class SyncAllTableViewController: UITableViewController { var workoutSyncAPI: WorkoutSyncAPI? let hkStore = HKHealthStore() typealias WorkoutRecord = (startDate: NSDate, durationLabel: String, workoutTypeLabel: String, checked: Bool, workoutDetails: WorkoutSyncAPI.WorkoutDetails?) typealias Workout = [WorkoutRecord] var workouts: Workout = [] let managedContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext! var syncButton: UIBarButtonItem? override func viewDidLoad() { super.viewDidLoad() self.syncButton = UIBarButtonItem(title: "Sync All", style: .Plain, target: self, action: "syncItems") self.syncButton?.possibleTitles = ["Sync All", "Sync Selected"]; navigationItem.rightBarButtonItem = self.syncButton if !HKHealthStore.isHealthDataAvailable() { print("HealthKit Not Available") // self.healthKitAvailable = false // self.refreshControl.removeFromSuperview() } else { let readTypes = Set(arrayLiteral: HKObjectType.workoutType(), HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)! ) hkStore.requestAuthorizationToShareTypes(nil, readTypes: readTypes, completion: { (success: Bool, err: NSError?) -> () in let actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView actInd.center = self.view.center actInd.hidesWhenStopped = true actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray self.view.addSubview(actInd) actInd.startAnimating() if success { self.readWorkOuts({(results: [AnyObject]!, error: NSError!) -> () in if let results = results as? [HKWorkout] { dispatch_async(dispatch_get_main_queue()) { self.workouts = [] var queue = results.count for workout in results { queue-- if let _ = self.managedObject(workout) { // Verify the workout hasn't already been synced // If the last item was already synced, we will stop the progress // FIXME this should be done with a timer if queue == 0 { // TODO Check the timer status, cancel if needed dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() actInd.stopAnimating() } } } else { let totalDistance: Double? = (workout.totalDistance != nil) ? workout.totalDistance!.doubleValueForUnit(HKUnit.meterUnit()) : nil let totalEnergyBurned: Double? = workout.totalEnergyBurned != nil ? workout.totalEnergyBurned!.doubleValueForUnit(HKUnit.kilocalorieUnit()) : nil let activityType = self.workoutSyncAPI?.activityType(workout.workoutActivityType) var workoutRecord = (workout.UUID, type: activityType, startTime: workout.startDate, totalDistance: totalDistance, duration: workout.duration, averageHeartRate: nil, totalCalories: totalEnergyBurned, notes: nil, otherType: nil, activityName: nil) as WorkoutSyncAPI.WorkoutDetails let queue = queue self.averageHeartRateForWorkout(workout, success: { d in if let d = d { workoutRecord.averageHeartRate = Int(d) } self.workouts.append((startDate: workout.startDate, durationLabel: self.stringFromTimeInterval(workout.duration), workoutTypeLabel: HKWorkoutActivityType.hkDescription(workout.workoutActivityType), checked: false, workoutDetails: workoutRecord) as WorkoutRecord) if queue == 0 { // TODO Check timer, cancel and reset dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() actInd.stopAnimating() } } }, tryAgain: true) } } } } }) } else { actInd.stopAnimating() } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.workouts.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier("syncAllCell") as? WorkoutTableViewCell { let workout = self.workouts[indexPath.row] let startDate = workout.startDate.relativeDateFormat() if workout.checked { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } cell.startTimeLabel?.text = startDate cell.durationLabel?.text = workout.durationLabel cell.workoutTypeLabel?.text = workout.workoutTypeLabel return cell } else { return tableView.dequeueReusableCellWithIdentifier("syncAllCell")! } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var workout = self.workouts[indexPath.row] workout.checked = !workout.checked self.workouts[indexPath.row] = workout self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) self.tableView.deselectRowAtIndexPath(indexPath, animated: true) let anyTrue = self.workouts .map { return $0.checked } .reduce(false) { (sum, next) in return sum || next } if anyTrue { self.navigationItem.rightBarButtonItem?.title = "Sync Selected" } else { self.navigationItem.rightBarButtonItem?.title = "Sync All" } } func readWorkOuts(completion: (([AnyObject]!, NSError!) -> Void)!) { let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false) let sampleQuery = HKSampleQuery(sampleType: HKWorkoutType.workoutType(), predicate: nil, limit: 0, sortDescriptors: [sortDescriptor]) { (sampleQuery, results, error ) -> Void in if let queryError = error { print( "There was an error while reading the samples: \(queryError.localizedDescription)") } completion(results, error) } hkStore.executeQuery(sampleQuery) } func managedObject(workout: HKWorkout) -> NSManagedObject? { let uuid = workout.UUID.UUIDString let servicesPredicate: String if let _ = self.workoutSyncAPI as? RunKeeperAPI { servicesPredicate = "uuid = %@ AND syncToRunKeeper != nil" } else if let _ = self.workoutSyncAPI as? StravaAPI { servicesPredicate = "uuid = %@ AND syncToStrava != nil" } else { return nil } let fetchRequest = NSFetchRequest(entityName: "SyncLog") let predicate = NSPredicate(format: servicesPredicate, uuid) fetchRequest.predicate = predicate let fetchedEntities = try? self.managedContext.executeFetchRequest(fetchRequest) if let syncLog = fetchedEntities?.first as? NSManagedObject { return syncLog } return nil } func stringFromTimeInterval(interval:NSTimeInterval) -> String { let ti = NSInteger(interval) let seconds = ti % 60 let minutes = (ti / 60) % 60 let hours = (ti / 3600) return String(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds) } func syncItems() { let workoutsToSync: Workout let anyTrue = self.workouts .map { return $0.checked } .reduce(false) { (sum, next) in return sum || next } if anyTrue { workoutsToSync = self.workouts.filter({$0.checked}) } else { workoutsToSync = self.workouts } let vcu = ViewControllerUtils() vcu.showActivityIndicator(self.view) let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! if let runKeeper = self.workoutSyncAPI as? RunKeeperAPI { // Loop over workoutsToSync workoutsToSync.forEach { workout in if let workoutDetail = workout.workoutDetails { runKeeper.postActivity(workoutDetail, failure: { (error, msg) in dispatch_async(dispatch_get_main_queue()) { vcu.hideActivityIndicator(self.view) let errorMessage: String if let error = error { errorMessage = "\(error.localizedDescription) - \(msg)" } else { errorMessage = "An error occurred while saving workout. Please verify that WorkoutMerge is still authorized through RunKeeper - \(msg)" } let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }, success: { (savedKey) in if let uuid = workout.workoutDetails?.UUID?.UUIDString { if let syncLog = self.syncLog(uuid) { syncLog.setValue(NSDate(), forKey: "syncToRunKeeper") syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper") if let workoutType = workout.workoutDetails?.type { syncLog.setValue(workoutType, forKey: "workoutType") } } else { let entity = NSEntityDescription.entityForName("SyncLog", inManagedObjectContext: managedContext) let syncLog = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) syncLog.setValue(uuid, forKey: "uuid") syncLog.setValue(NSDate(), forKey: "syncToRunKeeper") syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper") if let workoutType = workout.workoutDetails?.type { syncLog.setValue(workoutType, forKey: "workoutType") } } var error: NSError? do { try managedContext.save() } catch let error1 as NSError { error = error1 print("Could not save \(error)") } catch { fatalError() } } dispatch_async(dispatch_get_main_queue()) { // TODO reload data in table - remove workouts synced vcu.hideActivityIndicator(self.view) } }) } } } else if let strava = self.workoutSyncAPI as? StravaAPI { // Loop over workoutsToSync workoutsToSync.forEach { workout in // strava if let workoutDetail = workout.workoutDetails { strava.postActivity(workoutDetail, failure: { (error, msg) in dispatch_async(dispatch_get_main_queue()) { vcu.hideActivityIndicator(self.view) let errorMessage: String if let error = error { errorMessage = "\(error.localizedDescription) - \(msg)" } else { errorMessage = "An error occurred while saving workout. Please verify that WorkoutMerge is still authorized through Strava - \(msg)" } let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }, success: { (savedKey) in if let uuid = workout.workoutDetails?.UUID?.UUIDString { if let syncLog = self.syncLog(uuid) { syncLog.setValue(NSDate(), forKey: "syncToRunKeeper") syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper") if let workoutType = workout.workoutDetails?.type { syncLog.setValue(workoutType, forKey: "workoutType") } } else { let entity = NSEntityDescription.entityForName("SyncLog", inManagedObjectContext: managedContext) let syncLog = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) syncLog.setValue(uuid, forKey: "uuid") syncLog.setValue(NSDate(), forKey: "syncToRunKeeper") syncLog.setValue(savedKey, forKey: "savedKeyRunKeeper") if let workoutType = workout.workoutDetails?.type { syncLog.setValue(workoutType, forKey: "workoutType") } } var error: NSError? do { try managedContext.save() } catch let error1 as NSError { error = error1 print("Could not save \(error)") } catch { fatalError() } } dispatch_async(dispatch_get_main_queue()) { // TODO reload data in table - remove workouts synced vcu.hideActivityIndicator(self.view) } }) } } } } func averageHeartRateForWorkout(workout: HKWorkout, success: (Double?) -> (), tryAgain: Bool) { let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) let workoutPredicate = HKQuery.predicateForSamplesWithStartDate(workout.startDate, endDate: workout.endDate, options: .None) // let startDateSort = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true) let query = HKStatisticsQuery(quantityType: quantityType!, quantitySamplePredicate: workoutPredicate, options: .DiscreteAverage) { (query, results, error) -> Void in if error != nil { print("\(error)") if tryAgain { self.averageHeartRateForWorkout(workout, success: success, tryAgain: false) } else { print("failed to retrieve heart rate data") success(nil) } } else { if results!.averageQuantity() != nil { let avgHeartRate = results!.averageQuantity()!.doubleValueForUnit(HKUnit(fromString: "count/min")); success(avgHeartRate) } else if tryAgain { print("averageQuantity unexpectedly found nil") self.averageHeartRateForWorkout(workout, success: success, tryAgain: false) } else { print("failed to retrieve heart rate data") success(nil) } } } hkStore.executeQuery(query) } func syncLog(uuid: String) -> NSManagedObject? { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName: "SyncLog") let predicate = NSPredicate(format: "uuid = %@", uuid) fetchRequest.predicate = predicate let fetchedEntities = try? managedContext.executeFetchRequest(fetchRequest) if let syncLog = fetchedEntities?.first as? NSManagedObject { return syncLog } return nil } }
213d54243f26eabc6f718134a67b35c9
47.681704
319
0.506075
false
false
false
false
Longhanks/qlift
refs/heads/master
Sources/Qlift/QVBoxLayout.swift
mit
1
import CQlift open class QVBoxLayout: QBoxLayout { public init(parent: QWidget? = nil) { super.init(ptr: QVBoxLayout_new(parent?.ptr), parent: parent) } override init(ptr: UnsafeMutableRawPointer, parent: QWidget? = nil) { super.init(ptr: ptr, parent: parent) } deinit { if self.ptr != nil { if QObject_parent(self.ptr) == nil { QVBoxLayout_delete(self.ptr) } self.ptr = nil } } }
8021bb9bf39f7a0bce5a7de41431edfe
20.521739
73
0.551515
false
false
false
false
timpalpant/SwiftConstraint
refs/heads/master
ConstraintSolver/Solver.swift
lgpl-2.1
1
// // ConstraintSolver.swift // ConstraintSolver // // Adapted from Python source by Timothy Palpant on 7/29/14. // // Copyright (c) 2005-2014 - Gustavo Niemeyer <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation public protocol Solver { func solve<T: Hashable>(problem: Problem<T>, single:Bool) -> [[T]] } public class BacktrackingSolver : Solver { let forwardCheck: Bool public init(forwardCheck: Bool=true) { self.forwardCheck = forwardCheck } public func solve<T: Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] { problem.preprocess() var queue: [(variable: Variable<T>, values: [T], pushdomains: [Domain<T>])] = [] var variable: Variable<T>! var values: [T] = [] var pushdomains: [Domain<T>] = [] while true { // Mix the Degree and Minimum Remaining Values (MRV) heuristics var lst = problem.variables.map { variable in (-variable.constraints.count, variable.domain.count, variable) } lst.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 } variable = nil for (_, _, v) in lst { if v.assignment == nil { // Found unassigned variable variable = v values = Array(v.domain) pushdomains = [] if self.forwardCheck { for x in problem.variables { if x.assignment == nil && x !== v { pushdomains.append(x.domain) } } } break } } if variable == nil { // No unassigned variables. We have a solution // Go back to last variable, if there is one let sol = problem.variables.map { v in v.assignment! } problem.solutions.append(sol) if queue.isEmpty { // last solution return problem.solutions } let t = queue.removeLast() variable = t.variable values = t.values pushdomains = t.pushdomains for domain in pushdomains { domain.popState() } } while true { // We have a variable. Do we have any values left? if values.count == 0 { // No. Go back to the last variable, if there is one. variable.assignment = nil while !queue.isEmpty { let t = queue.removeLast() variable = t.variable values = t.values pushdomains = t.pushdomains for domain in pushdomains { domain.popState() } if !values.isEmpty { break } variable.assignment = nil } if values.isEmpty { return problem.solutions } } // Got a value; check it variable.assignment = values.removeLast() for domain in pushdomains { domain.pushState() } var good = true for constraint in variable.constraints { if !constraint.evaluate(self.forwardCheck) { good = false break // Value is not good } } if good { break } for domain in pushdomains { domain.popState() } } // Push state before looking for next variable. queue += [(variable: variable!, values: values, pushdomains: pushdomains)] } } } public class RecursiveBacktrackingSolver : Solver { let forwardCheck: Bool public init(forwardCheck: Bool) { self.forwardCheck = forwardCheck } public convenience init() { self.init(forwardCheck: true) } private func recursiveBacktracking<T: Hashable>(var problem: Problem<T>, single:Bool=false) -> [[T]] { var pushdomains = [Domain<T>]() // Mix the Degree and Minimum Remaining Values (MRV) heuristics var lst = problem.variables.map { variable in (-variable.constraints.count, variable.domain.count, variable) } lst.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 } var missing: Variable<T>? for (_, _, variable) in lst { if variable.assignment == nil { missing = variable } } if var variable = missing { pushdomains.removeAll() if forwardCheck { for v in problem.variables { if v.assignment == nil { pushdomains.append(v.domain) } } } for value in variable.domain { variable.assignment = value for domain in pushdomains { domain.pushState() } var good = true for constraint in variable.constraints { if !constraint.evaluate(forwardCheck) { good = false break // Value is not good } } if good { // Value is good. Recurse and get next variable recursiveBacktracking(problem, single: single) if !problem.solutions.isEmpty && single { return problem.solutions } } for domain in pushdomains { domain.popState() } } variable.assignment = nil return problem.solutions } // No unassigned variables. We have a solution let values = problem.variables.map { variable in variable.assignment! } problem.solutions.append(values) return problem.solutions } public func solve<T : Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] { problem.preprocess() return recursiveBacktracking(problem, single: single) } } func random_choice<T>(a: [T]) -> T { let index = Int(arc4random_uniform(UInt32(a.count))) return a[index] } func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C { let c = count(list) for i in 0..<(c - 1) { let j = Int(arc4random_uniform(UInt32(c - i))) + i swap(&list[i], &list[j]) } return list } public class MinConflictsSolver : Solver { let steps: Int public init(steps: Int=1_000) { self.steps = steps } public func solve<T : Hashable>(problem: Problem<T>, single:Bool=false) -> [[T]] { problem.preprocess() // Initial assignment for variable in problem.variables { variable.assignment = random_choice(variable.domain.elements) } for _ in 1...self.steps { var conflicted = false let lst = shuffle(problem.variables) for variable in lst { // Check if variable is not in conflict var allSatisfied = true for constraint in variable.constraints { if !constraint.evaluate(false) { allSatisfied = false break } } if allSatisfied { continue } // Variable has conflicts. Find values with less conflicts var mincount = variable.constraints.count var minvalues: [T] = [] for value in variable.domain { variable.assignment = value var count = 0 for constraint in variable.constraints { if !constraint.evaluate(false) { count += 1 } } if count == mincount { minvalues.append(value) } else if count < mincount { mincount = count minvalues.removeAll() minvalues.append(value) } } // Pick a random one from these values variable.assignment = random_choice(minvalues) conflicted = true } if !conflicted { let solution = problem.variables.map { variable in variable.assignment! } problem.solutions.append(solution) return problem.solutions } } return problem.solutions } }
27e2b84d08132e96913453bbbdc5d486
29.172185
104
0.585227
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/YesterdailiesDialogView.swift
gpl-3.0
1
// // YesterdailiesDialogView.swift // Habitica // // Created by Phillip on 08.06.17. // Copyright © 2017 HabitRPG Inc. All rights reserved. // import UIKit import PopupDialog import Habitica_Models import ReactiveSwift class YesterdailiesDialogView: UIViewController, UITableViewDelegate, UITableViewDataSource, Themeable { @IBOutlet weak var heightConstraint: NSLayoutConstraint! @IBOutlet weak var yesterdailiesHeightConstraint: NSLayoutConstraint! @IBOutlet weak var yesterdailiesTableView: UITableView! @IBOutlet weak var checkinCountView: UILabel! @IBOutlet weak var nextCheckinCountView: UILabel! @IBOutlet weak var headerWrapperView: UIView! @IBOutlet weak var tableViewWrapper: UIView! @IBOutlet weak var checkinYesterdaysDailiesLabel: UILabel! @IBOutlet weak var startDayButton: UIButton! let taskRepository = TaskRepository() private let userRepository = UserRepository() private let disposable = ScopedDisposable(CompositeDisposable()) var tasks: [TaskProtocol]? override func viewDidLoad() { super.viewDidLoad() yesterdailiesTableView.delegate = self yesterdailiesTableView.dataSource = self let nib = UINib.init(nibName: "YesterdailyTaskCell", bundle: Bundle.main) yesterdailiesTableView.register(nib, forCellReuseIdentifier: "Cell") yesterdailiesTableView.rowHeight = UITableView.automaticDimension yesterdailiesTableView.estimatedRowHeight = 60 updateTitleBanner() startDayButton.setTitle(L10n.startMyDay, for: .normal) ThemeService.shared.addThemeable(themable: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.cornerRadius = 16 view.superview?.superview?.cornerRadius = 16 startDayButton.layer.shadowRadius = 2 startDayButton.layer.shadowOffset = CGSize(width: 1, height: 1) startDayButton.layer.shadowOpacity = 0.5 startDayButton.layer.masksToBounds = false } func applyTheme(theme: Theme) { view.backgroundColor = theme.contentBackgroundColor startDayButton.setTitleColor(.white, for: .normal) startDayButton.backgroundColor = theme.fixedTintColor tableViewWrapper.backgroundColor = theme.windowBackgroundColor checkinCountView.textColor = theme.primaryTextColor nextCheckinCountView.textColor = theme.secondaryTextColor startDayButton.layer.shadowColor = ThemeService.shared.theme.buttonShadowColor.cgColor } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let window = view.window { heightConstraint.constant = window.frame.size.height - 300 } yesterdailiesHeightConstraint.constant = yesterdailiesTableView.contentSize.height } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasks?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? YesterdailyTaskCell if let tasks = tasks { cell?.configure(task: tasks[indexPath.item]) cell?.checkbox.wasTouched = {[weak self] in self?.checkedCell(indexPath) } cell?.onChecklistItemChecked = {[weak self] item in self?.checkChecklistItem(indexPath, item: item) } } return cell ?? UITableViewCell() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { checkedCell(indexPath) } private func checkedCell(_ indexPath: IndexPath) { if let tasks = tasks { tasks[indexPath.item].completed = !tasks[indexPath.item].completed yesterdailiesTableView.reloadRows(at: [indexPath], with: .fade) } } private func checkChecklistItem(_ indexPath: IndexPath, item: ChecklistItemProtocol) { item.completed = !item.completed yesterdailiesTableView.reloadRows(at: [indexPath], with: .fade) } func updateTitleBanner() { checkinCountView.text = L10n.welcomeBack nextCheckinCountView.text = L10n.checkinYesterdaysDalies } @IBAction func allDoneTapped(_ sender: Any) { handleDismiss() dismiss(animated: true) {} } func handleDismiss() { UserManager.shared.yesterdailiesDialog = nil var completedTasks = [TaskProtocol]() if let tasks = tasks { for task in tasks where task.completed { completedTasks.append(task) } } userRepository.runCron(tasks: completedTasks) } }
f4dba9e10dd0d99b755fc4406434ef37
34.934783
112
0.681589
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Decimator.xcplaygroundpage/Contents.swift
mit
1
//: ## Decimator //: Decimation is a type of digital distortion like bit crushing, //: but instead of directly stating what bit depth and sample rate you want, //: it is done through setting "decimation" and "rounding" parameters. import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true //: Next, we'll connect the audio sources to a decimator var decimator = AKDecimator(player) decimator.decimation = 0.5 // Normalized Value 0 - 1 decimator.rounding = 0.5 // Normalized Value 0 - 1 decimator.mix = 0.5 // Normalized Value 0 - 1 AudioKit.output = decimator AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Decimator") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKSlider(property: "Decimation", value: decimator.decimation) { sliderValue in decimator.decimation = sliderValue }) addView(AKSlider(property: "Rounding", value: decimator.rounding) { sliderValue in decimator.rounding = sliderValue }) addView(AKSlider(property: "Mix", value: decimator.mix) { sliderValue in decimator.mix = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
486709d40878b16fac6756413df8446a
29.58
96
0.722041
false
false
false
false
Xiomara7/cv
refs/heads/master
Xiomara-Figueroa/customMenuView.swift
mit
1
// // customMenu.swift // Xiomara-Figueroa // // Created by Xiomara on 5/6/15. // Copyright (c) 2015 UPRRP. All rights reserved. // import UIKit class customMenuView: UIView { var aboutButton: UIButton! var workButton: UIButton! var projectsButton: UIButton! var extraButton: UIButton! var workTitle: UILabel! var projectsTitle: UILabel! var extraTitle: UILabel! var aboutTitle: UILabel! var topLeft: UIImageView! var bottomRigth: UIImageView! var topRight: UIImageView! var bottomLeft: UIImageView! var shouldSetupConstraints = true init() { super.init(frame: CGRectZero) self.backgroundColor = UIColor.whiteColor() let imageWidth = UIScreen.mainScreen().bounds.width / 2 let imageHeight = UIScreen.mainScreen().bounds.height / 2 topLeft = UIImageView(frame: CGRectMake(0.0, 0.0, imageWidth, imageHeight)) bottomRigth = UIImageView(frame: CGRectMake(imageWidth, imageHeight, imageWidth, imageHeight)) topRight = UIImageView(frame: CGRectMake(imageWidth, 0.0, imageWidth, imageHeight)) bottomLeft = UIImageView(frame: CGRectMake(0.0, imageHeight, imageWidth, imageHeight)) aboutButton = button(imageName:"button_About") workButton = button(imageName: "button_Work") projectsButton = button(imageName: "button_Projects") extraButton = button(imageName:"button_Extra") workTitle = label(title:"WORK") extraTitle = label(title:"OUTREACH") projectsTitle = label(title:"PROJECTS") aboutTitle = label(title:"ABOUT") self.addSubview(aboutButton) self.addSubview(workButton) self.addSubview(projectsButton) self.addSubview(extraButton) self.addSubview(topLeft) self.addSubview(topRight) self.addSubview(bottomRigth) self.addSubview(bottomLeft) self.addSubview(workTitle) self.addSubview(aboutTitle) self.addSubview(projectsTitle) self.addSubview(extraTitle) aboutButton.setTranslatesAutoresizingMaskIntoConstraints(false) updateConstraints() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class label: UILabel { init(title: String) { super.init(frame: CGRectZero) self.font = UIFont.boldSystemFontOfSize(20.0) self.textColor = UIColor.grayColor() self.text = title } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class button: UIButton { init(imageName: String) { super.init(frame: CGRectZero) self.setImage(UIImage(named: imageName), forState: .Normal) self.backgroundColor = UIColor.whiteColor() self.sizeToFit() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } override func updateConstraints() { super.updateConstraints() if shouldSetupConstraints { // AutoLayout workButton.autoAlignAxis(.Horizontal, toSameAxisOfView: topLeft) workButton.autoAlignAxis(.Vertical, toSameAxisOfView: topLeft) workTitle.autoPinEdge(.Top, toEdge: .Bottom, ofView: workButton, withOffset: 20.0) workTitle.autoAlignAxis(.Vertical, toSameAxisOfView: workButton) aboutButton.autoAlignAxis(.Horizontal, toSameAxisOfView: bottomRigth) aboutButton.autoAlignAxis(.Vertical, toSameAxisOfView: bottomRigth) aboutTitle.autoPinEdge(.Bottom, toEdge: .Top, ofView: aboutButton, withOffset: -20.0) aboutTitle.autoAlignAxis(.Vertical, toSameAxisOfView: aboutButton) extraButton.autoAlignAxis(.Horizontal, toSameAxisOfView: bottomLeft) extraButton.autoAlignAxis(.Vertical, toSameAxisOfView: bottomLeft) extraTitle.autoPinEdge(.Bottom, toEdge: .Top, ofView: extraButton, withOffset: -20.0) extraTitle.autoAlignAxis(.Vertical, toSameAxisOfView: extraButton) projectsButton.autoAlignAxis(.Horizontal, toSameAxisOfView: topRight) projectsButton.autoAlignAxis(.Vertical, toSameAxisOfView: topRight) projectsTitle.autoPinEdge(.Top, toEdge: .Bottom, ofView: projectsButton, withOffset: 20.0) projectsTitle.autoAlignAxis(.Vertical, toSameAxisOfView: projectsButton) shouldSetupConstraints = false } } }
c789d1d65d8c83380f32a7f88c70d88e
34.141026
102
0.55892
false
false
false
false
huangboju/Moots
refs/heads/master
UICollectionViewLayout/MagazineLayout-master/MagazineLayout/LayoutCore/Types/ElementLocation.swift
mit
1
// Created by bryankeller on 8/13/18. // Copyright © 2018 Airbnb, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Represents the location of an item in a section. /// /// Initializing a `ElementLocation` is measurably faster than initializing an `IndexPath`. /// On an iPhone X, compiled with -Os optimizations, it's about 35x faster to initialize this struct /// compared to an `IndexPath`. struct ElementLocation: Hashable { // MARK: Lifecycle init(elementIndex: Int, sectionIndex: Int) { self.elementIndex = elementIndex self.sectionIndex = sectionIndex } init(indexPath: IndexPath) { if indexPath.count == 2 { elementIndex = indexPath.item sectionIndex = indexPath.section } else { // `UICollectionViewFlowLayout` is able to work with empty index paths (`IndexPath()`). Per // the `IndexPath` documntation, an index path that uses `section` or `item` must have exactly // 2 elements. If not, we default to {0, 0} to prevent crashes. elementIndex = 0 sectionIndex = 0 } } // MARK: Internal let elementIndex: Int let sectionIndex: Int var indexPath: IndexPath { return IndexPath(item: elementIndex, section: sectionIndex) } }
ade0db4bf1d6161b9d2ce3148dd5f62f
31.481481
100
0.710946
false
false
false
false
vgorloff/AUHost
refs/heads/master
Vendor/mc/mcxTypes/Sources/Sources/MinMax.swift
mit
1
// // MinMax.swift // MCA-OSS-AUH // // Created by Vlad Gorlov on 06/05/16. // Copyright © 2016 Vlad Gorlov. All rights reserved. // public struct MinMax<T: Comparable> { public var min: T public var max: T public init(min aMin: T, max aMax: T) { min = aMin max = aMax assert(min <= max) } public init(valueA: MinMax, valueB: MinMax) { min = Swift.min(valueA.min, valueB.min) max = Swift.max(valueA.max, valueB.max) } } extension MinMax where T: Numeric { public var difference: T { return max - min } } extension MinMax where T: FloatingPoint { public var difference: T { return max - min } }
4e80fd5715d3b2ee8782f6cf6a325d33
17.777778
54
0.609467
false
false
false
false
sawijaya/UIFloatPHTextField
refs/heads/master
UIFloatPHTextField/Item.swift
mit
1
// // Item.swift // // Created by Salim Wijaya // Copyright © 2017. All rights reserved. // import Foundation import UIKit public protocol ItemConvertible { associatedtype TypeData } public enum ItemImage: ItemConvertible { public typealias TypeData = ItemImage case Image(UIImage) case Data(Data) case String(String) public static func dataType(_ dataType: Any?) -> TypeData? { switch (dataType) { case let image as UIImage: return ItemImage.Image(image) case let data as Data: return ItemImage.Data(data) case let string as String: return ItemImage.String(string) default: return nil } } public var image : UIImage! { switch (self) { case .Image(let image): return image default: return nil } } public var data : Data! { switch (self) { case .Data(let data): return data default: return nil } } public var string : String! { switch (self) { case .String(let string): return string default: return nil } } } public struct Item<T: ItemConvertible> { public var text: String? public var value: String? public var image: T? public var data:[String:Any]? public init(data:[String:Any]) { self.text = data["text"] as? String self.value = data["value"] as? String let itemImage = ItemImage.dataType(data["image"]) self.image = itemImage as? T self.data = data } }
b59a394670338b5d139407495c4ffa3b
22.105263
64
0.527904
false
false
false
false
AHuaner/Gank
refs/heads/master
Gank/AHMainViewController.swift
mit
2
// // AHMainViewController.swift // Gank // // Created by CoderAhuan on 2016/12/7. // Copyright © 2016年 CoderAhuan. All rights reserved. // import UIKit class AHMainViewController: BaseViewController { lazy var tabBarVC: TabBarController = { let tabBarVC = TabBarController() tabBarVC.delegate = self return tabBarVC }() lazy var LaunchVC: AHLaunchViewController = { let LaunchVC = AHLaunchViewController(showTime: 3) LaunchVC.launchComplete = { [unowned self] in self.view.addSubview(self.tabBarVC.view) self.addChildViewController(self.tabBarVC) } return LaunchVC }() override func viewDidLoad() { super.viewDidLoad() setupLaunchVC() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setupLaunchVC() { addChildViewController(LaunchVC) view.addSubview(LaunchVC.view) } } extension AHMainViewController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { NotificationCenter.default.post(name: NSNotification.Name.AHTabBarDidSelectNotification, object: nil) } }
a762247fe044f0e85a3ead7656b600fb
26.319149
111
0.676791
false
false
false
false
NjrSea/FlickTransition
refs/heads/master
FlickTransition/DismissAnimationController.swift
mit
1
// // DismissAnimationController.swift // FlickTransition // // Created by paul on 16/9/18. // Copyright © 2016年 paul. All rights reserved. // import UIKit class DismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning { fileprivate let scaling: CGFloat = 0.95 var dismissDirection: Direction = .Left var dismissDuration = 0.2 fileprivate var dimmingView: UIView = { let view = UIView() view.backgroundColor = UIColor(white: 0, alpha: 0.4) return view }() func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return dismissDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return } let containerView = transitionContext.containerView guard let snapshot = toVC.view.snapshotView(afterScreenUpdates: true) else { return } snapshot.addSubview(dimmingView) snapshot.frame = toVC.view.bounds dimmingView.frame = snapshot.bounds dimmingView.alpha = 1.0 snapshot.layer.transform = CATransform3DScale(CATransform3DIdentity, self.scaling, self.scaling, 1) containerView.insertSubview(snapshot, at: 0) toVC.view.isHidden = true let duration = transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { snapshot.layer.transform = CATransform3DIdentity self.dimmingView.alpha = 0.0 var frame = fromVC.view.frame switch self.dismissDirection { case .Left: frame.origin.x = -frame.width fromVC.view.frame = frame case .Right: frame.origin.x = frame.width fromVC.view.frame = frame case .Up: frame.origin.y = -frame.height fromVC.view.frame = frame case .Down: frame.origin.y = frame.height fromVC.view.frame = frame } }) { _ in snapshot.removeFromSuperview() self.dimmingView.removeFromSuperview() toVC.view.isHidden = false transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
fdac12463b427ccd6f5e78c81550bd03
33.705128
111
0.623938
false
false
false
false
tachun77/todoru2
refs/heads/master
SwipeTableViewCell/CompleteViewController.swift
mit
1
// // Todoル // SwipeTableViewCell // // Created by 福島達也 on 2016/06/25. // Copyright © 2016年 福島達也. All rights reserved. // import UIKit import BubbleTransition class CompleteViewController: UIViewController ,UIViewControllerTransitioningDelegate{ let saveData = NSUserDefaults.standardUserDefaults() var monsterArray : [UIImage]! var haikeiArray : [UIImage]! @IBOutlet var kkeiken : UILabel! @IBOutlet var monsterImageView : UIImageView! @IBOutlet var haikeiImageView : UIImageView! @IBOutlet var sinkagamen : UIButton! @IBOutlet var serihu : UILabel! @IBOutlet var hukidasi : UIImageView! @IBOutlet var tolist : UIButton! @IBOutlet var tosinka : UIButton! @IBOutlet var anatano : UILabel! let transition = BubbleTransition() var startingPoint = CGPointZero var duration = 20.0 var transitionMode: BubbleTransitionMode = .Present var bubbleColor: UIColor = .yellowColor() override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let controller = segue.destinationViewController controller.transitioningDelegate = self controller.modalPresentationStyle = .Custom } func colorWithHexString (hex:String) -> UIColor { let cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString if ((cString as String).characters.count != 6) { return UIColor.grayColor() } let rString = (cString as NSString).substringWithRange(NSRange(location: 0, length: 2)) let gString = (cString as NSString).substringWithRange(NSRange(location: 2, length: 2)) let bString = (cString as NSString).substringWithRange(NSRange(location: 4, length: 2)) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; NSScanner(string: rString).scanHexInt(&r) NSScanner(string: gString).scanHexInt(&g) NSScanner(string: bString).scanHexInt(&b) return UIColor( red: CGFloat(Float(r) / 255.0), green: CGFloat(Float(g) / 255.0), blue: CGFloat(Float(b) / 255.0), alpha: CGFloat(Float(1.0)) ) } // MARK: UIViewControllerTransitioningDelegate func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.transitionMode = .Present transition.startingPoint = tolist.center transition.bubbleColor = UIColor.whiteColor() return transition } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.transitionMode = .Dismiss transition.startingPoint = tosinka.center transition.bubbleColor = UIColor.whiteColor() return transition } // @IBAction func modoru(){ // // self.presentViewController(ListTableViewController,animated:true, completion: nil) // // } override func viewDidLoad() { super.viewDidLoad() let keiken : AnyObject = saveData.integerForKey("keikenchi") let keikenchinow = String(keiken) kkeiken.text = keikenchinow let keikenchinow2 = Int(keikenchinow) monsterArray = [UIImage(named:"anpo_1.png")!,UIImage(named:"rev_1.png")!,UIImage(named:"load.png")!,UIImage(named:"anpo_11.png")!,UIImage(named:"rev_11.png")!] if keikenchinow2 == 1000{ monsterImageView.image = monsterArray[3] } else if keikenchinow2 < 1000 { monsterImageView.image = monsterArray[0] } else if keikenchinow2 < 2000 && 1000 < keikenchinow2{ monsterImageView.image = monsterArray[1] } else if keikenchinow2 == 2000 { monsterImageView.image = monsterArray[4] }else{ monsterImageView.image = monsterArray[2] } // haikeiArray = [UIImage(named:"[email protected]")!] // // if keikenchinow2 > 2000{ // haikeiImageView.image = haikeiArray[0] // } if keikenchinow2 == 1000 || keikenchinow2 == 2000 { self.sinkagamen.hidden = false serihu.hidden = true hukidasi.hidden = true tolist.hidden = true anatano.hidden = true self.view.backgroundColor = UIColor.whiteColor() kkeiken.hidden = true } else { self.sinkagamen.hidden = true serihu.hidden = false hukidasi.hidden = false tolist.hidden = false anatano.hidden = false kkeiken.hidden = false } let serihuArray = ["NICE!","Wonderful!","いいね!","...やるじゃん","Fantastic!!!","oh yeah!","経験値ありがと!"] let number = Int(rand() % 7) serihu.text = serihuArray[number] // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { // let keikenchinow : AnyObject = saveData.objectForKey("keiken") as! Int // // kkeiken.text = keikenchinow["keiken"] } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) let keiken : AnyObject = saveData.integerForKey("keikenchi") let keikenchinow = String(keiken) kkeiken.text = keikenchinow let keikenchinow2 = Int(keikenchinow) if keikenchinow2 == 1000 || keikenchinow2 == 2000{ UIImageView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.Repeat, animations: { () -> Void in self.monsterImageView.alpha = 0.0 }, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tosinkagamen(sender : UIButton){ performSegueWithIdentifier("tosinka", sender: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
9b6542161fa005d413a3563814566bc1
34.178947
217
0.62687
false
false
false
false
xxxAIRINxxx/ViewPagerController
refs/heads/master
Sources/UIColor+RGBA.swift
mit
1
// // UIColor+RGBA.swift // ViewPagerController // // Created by xxxAIRINxxx on 2016/01/05. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit public struct RGBA { var red : CGFloat = 0.0 var green : CGFloat = 0.0 var blue : CGFloat = 0.0 var alpha : CGFloat = 0.0 } public extension UIColor { public func getRGBAStruct() -> RGBA { let components = self.cgColor.components let colorSpaceModel = self.cgColor.colorSpace?.model if colorSpaceModel?.rawValue == CGColorSpaceModel.rgb.rawValue && self.cgColor.numberOfComponents == 4 { return RGBA( red: components![0], green: components![1], blue: components![2], alpha: components![3] ) } else if colorSpaceModel?.rawValue == CGColorSpaceModel.monochrome.rawValue && self.cgColor.numberOfComponents == 2 { return RGBA( red: components![0], green: components![0], blue: components![0], alpha: components![1] ) } else { return RGBA() } } }
8e96bf1caadb512c5e3c6a102aba67bc
27
126
0.559801
false
false
false
false
MFaarkrog/Apply
refs/heads/master
Example/Apply/simple/SimpleStylesheet.swift
mit
1
// // SimpleStylesheet.swift // Apply // // Created by Morten Faarkrog on 6/7/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit struct Styles { struct Colors { static let primary = UIColor.black static let secondary = UIColor.darkGray static let button = UIColor.blue static let background = UIColor.white } struct Fonts { static let h1 = UIFont.systemFont(ofSize: 22) static let h2 = UIFont.systemFont(ofSize: 17) static let body = UIFont.systemFont(ofSize: 15) static let button = UIFont.boldSystemFont(ofSize: 15) } }
233872ac804986a385eb7f4b1dfc2db2
21.111111
57
0.683417
false
false
false
false
macemmi/HBCI4Swift
refs/heads/master
HBCI4Swift/HBCI4Swift/Source/Orders/HBCITanOrder.swift
gpl-2.0
1
// // HBCITanOrder.swift // HBCI4Swift // // Created by Frank Emminghaus on 02.03.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation class HBCITanOrder : HBCIOrder { // we only support process variant 2 by now var process:String? var orderRef:String? var listIndex:String? var tanMediumName:String? // results var challenge:String? var challenge_hhd_uc:Data? // todo(?) init?(message:HBCICustomMessage) { super.init(name: "TAN", message: message); if self.segment == nil { return nil; } } func finalize(_ refOrder:HBCIOrder?) ->Bool { if let process = self.process { var values:Dictionary<String,Any> = ["process":process, "notlasttan":false]; if tanMediumName != nil { values["tanmedia"] = tanMediumName! } /* if process == "1" || process == "2" { values["notlasttan"] = false; } */ if orderRef != nil { values["orderref"] = orderRef; } if let refOrder = refOrder { values["ordersegcode"] = refOrder.segment.code; } if segment.setElementValues(values) { return true; } else { logInfo("Values could not be set for TAN order"); return false; } } else { logInfo("Could not create TAN order - missing process info"); return false; } } func enqueue() ->Bool { if finalize(nil) { return msg.addOrder(self); } return false; } override func updateResult(_ result:HBCIResultMessage) { super.updateResult(result); // get challenge information if let seg = resultSegments.first { self.challenge = seg.elementValueForPath("challenge") as? String; self.orderRef = seg.elementValueForPath("orderref") as? String; if seg.version > 3 { self.challenge_hhd_uc = seg.elementValueForPath("challenge_hhd_uc") as? Data; } } } }
ecb7419c577481390c59e56e14fe3711
26.070588
93
0.515428
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/CryptoAssets/Sources/EthereumKit/Models/Accounts/KeyPair/EthereumKeyPairDeriver.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import WalletCore public typealias AnyEthereumKeyPairDeriver = AnyKeyPairDeriver<EthereumKeyPair, EthereumKeyDerivationInput, HDWalletError> public struct EthereumKeyPairDeriver: KeyPairDeriverAPI { public func derive(input: EthereumKeyDerivationInput) -> Result<EthereumKeyPair, HDWalletError> { let ethereumCoinType = CoinType.ethereum // Hardcoding BIP39 passphrase as empty string as it is currently not supported. guard let hdWallet = HDWallet(mnemonic: input.mnemonic, passphrase: "") else { return .failure(.walletFailedToInitialise()) } let privateKey = hdWallet.getKeyForCoin(coin: ethereumCoinType) let publicKey = hdWallet.getAddressForCoin(coin: ethereumCoinType) let ethereumPrivateKey = EthereumPrivateKey( mnemonic: input.mnemonic, data: privateKey.data ) let keyPair = EthereumKeyPair( accountID: publicKey, privateKey: ethereumPrivateKey ) return .success(keyPair) } }
40d55bf071d3dc0b9d7c85f267d8aac7
39.321429
122
0.708592
false
false
false
false
inamiy/ReactiveCocoaCatalog
refs/heads/master
ReactiveCocoaCatalog/MasterViewController.swift
mit
1
// // MasterViewController.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2015-09-16. // Copyright © 2015 Yasuhiro Inami. All rights reserved. // import UIKit import ReactiveSwift class MasterViewController: UITableViewController { let catalogs = Catalog.allCatalogs() override func awakeFromNib() { super.awakeFromNib() if UIDevice.current.userInterfaceIdiom == .pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // auto-select for i in 0..<self.catalogs.count { if self.catalogs[i].selected { self.showDetailViewController(at: i) break } } } // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.catalogs.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let catalog = self.catalogs[indexPath.row] cell.textLabel?.text = catalog.title cell.detailTextLabel?.text = catalog.description return cell } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.showDetailViewController(at: indexPath.row) } func showDetailViewController(at index: Int) { let catalog = self.catalogs[index] let newVC = catalog.scene.instantiate() let newNavC = UINavigationController(rootViewController: newVC) self.splitViewController?.showDetailViewController(newNavC, sender: self) // Deinit logging. let message = deinitMessage(newVC) newVC.reactive.lifetime.ended.observeCompleted { print(message) } newVC.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem newVC.navigationItem.leftItemsSupplementBackButton = true } }
3c193a1a6062a872f7bd4c42cb652b85
26.091954
107
0.658888
false
false
false
false
chendingcd/DouYuZB
refs/heads/master
DouYuZB/DouYuZB/Classes/Tools/Common.swift
mit
1
// // Common.swift // DouYuZB // // Created by 陈鼎 on 2016/11/29. // Copyright © 2016年 apple. All rights reserved. // import UIKit let kSatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabbarH: CGFloat = 44 let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height
5ba5b0a1e3ceb79d515163bd6543f5bb
14.190476
49
0.702194
false
false
false
false
Beaconstac/iOS-SDK
refs/heads/master
BeaconstacSampleApp/Pods/EddystoneScanner/EddystoneScanner/EddystoneRFC/Models/Telemetry.swift
mit
1
// // Telemetry.swift // EddystoneScanner // // Created by Amit Prabhu on 14/01/18. // Copyright © 2018 Amit Prabhu. All rights reserved. // import Foundation /// /// Struct that handles the beacon telemtry data /// Specs https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md /// @objc public class Telemetry: NSObject { /// Telemetry data version @objc public let version: String /// Battery voltage is the current battery charge in millivolts @objc public var voltage: UInt = 0 /// Beacon temperature is the temperature in degrees Celsius sensed by the beacon. If not supported the value will be -128. @objc public var temperature: Float = 0 /// ADV_CNT is the running count of advertisement frames of all types emitted by the beacon since power-up or reboot, useful for monitoring performance metrics that scale per broadcast frame @objc public var advCount: UInt = 0 /// SEC_CNT is a 0.1 second resolution counter that represents time since beacon power-up or reboot @objc public var uptime: Float = 0 /// Calculates the advertising interval of the beacon in milliseconds /// Assumes the beacon is transmitting all 3 eddystone packets (UID, URL and TLM frames) @objc public var advInt: Float { guard uptime != 0, uptime != 0 else { return 0 } let numberOFFramesPerBeacon = 3 return Float(numberOFFramesPerBeacon * 1000) / (Float(advCount) / uptime) } /// Battery percentage /// Assume the chip requires a 3V battery. Most of the beacons have Nordic chips which support 3V /// We aaume here that the lower bound is 2000 and upper bound is 3000 /// If the milliVolt is less than 2000, we assume 0% and if it is greater than 3000 we consider it as 100% charged. /// The formula is % = (read milliVolt - LowerBound) / (UpperBound - LowerBound) * 100 @objc public var batteryPercentage: UInt { guard voltage > 2000 else { return 0 } guard voltage < 3000 else { return 100 } let percentage: UInt = UInt(((Float(voltage) - 2000.0) / 1000.0) * 100.0) return percentage > 100 ? 100 : percentage } internal init?(tlmFrameData: Data) { guard let frameBytes = Telemetry.validateTLMFrameData(tlmFrameData: tlmFrameData) else { debugPrint("Failed to iniatialize the telemtry object") return nil } self.version = String(format: "%02X", frameBytes[1]) super.init() self.parseTLMFrameData(frameBytes: frameBytes) } /** Update the telemetry object for the new telemtry frame data - Parameter tlmFrameData: The raw TLM frame data */ internal func update(tlmFrameData: Data) { guard let frameBytes = Telemetry.validateTLMFrameData(tlmFrameData: tlmFrameData) else { debugPrint("Failed to update telemetry data") return } self.parseTLMFrameData(frameBytes: frameBytes) } /** Validate the TLM frame data - Parameter tlmFrameData: The raw TLM frame data */ private static func validateTLMFrameData(tlmFrameData: Data) -> [UInt8]? { let frameBytes = Array(tlmFrameData) as [UInt8] // The length of the frame should be 14 guard frameBytes.count == 14 else { debugPrint("Corrupted telemetry frame") return nil } return frameBytes } /** Parse the TLM frame data - Parameter frameBytes: The `UInt8` byte array */ private func parseTLMFrameData(frameBytes: [UInt8]) { self.voltage = bytesToUInt(byteArray: frameBytes[2..<4])! self.temperature = Float(frameBytes[4]) + Float(frameBytes[5])/256 self.advCount = bytesToUInt(byteArray: frameBytes[6..<10])! self.uptime = Float(bytesToUInt(byteArray: frameBytes[10..<14])!) / 10.0 } }
1ecbe6e08727dfa31a6c0a09267ed2f3
34.929204
194
0.637685
false
false
false
false
ngominhtrint/Twittient
refs/heads/master
Twittient/TweetDetailViewController.swift
apache-2.0
1
// // TweetDetailViewController.swift // Twittient // // Created by TriNgo on 3/26/16. // Copyright © 2016 TriNgo. All rights reserved. // import UIKit class TweetDetailViewController: UIViewController { @IBOutlet weak var retweetUserLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var tagLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var timeStampLabel: UILabel! @IBOutlet weak var numberRetweetLabel: UILabel! @IBOutlet weak var numberFavoritesLabel: UILabel! @IBOutlet weak var likeButton: UIButton! @IBOutlet weak var avatarImage: UIImageView! @IBOutlet weak var retweetButton: UIButton! var tweet: Tweet? override func viewDidLoad() { super.viewDidLoad() avatarImage.layer.cornerRadius = 3.0 showData() // Do any additional setup after loading the view. } func showData(){ nameLabel.text = tweet!.name as? String tagLabel.text = tweet!.screenName as? String descriptionLabel.text = tweet!.text as? String numberRetweetLabel.text = "\(tweet!.retweetCount)" numberFavoritesLabel.text = "\(tweet!.favoritesCount)" avatarImage.setImageWithURL((tweet!.profileImageUrl)!) let timeStamp = dateFromString((tweet?.timeStamp)!, format: "dd/MM/yy HH:mm a") timeStampLabel.text = "\(timeStamp)" let isFavorited = tweet!.favorited if isFavorited { let image = UIImage(named: "like.png")! as UIImage likeButton.setImage(image, forState: .Normal) } else { let image = UIImage(named: "unlike.png")! as UIImage likeButton.setImage(image, forState: .Normal) } let isRetweeted = tweet!.retweeted if isRetweeted { let image = UIImage(named: "retweeted.png")! as UIImage retweetButton.setImage(image, forState: .Normal) } else { let image = UIImage(named: "retweet.png")! as UIImage retweetButton.setImage(image, forState: .Normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onReplyClicked(sender: UIButton) { } @IBAction func onRetweetClicked(sender: UIButton) { let id = tweet?.id as! String let isRetweeted = (tweet?.retweeted)! as Bool let retweetEnum: TwitterClient.Retweet if isRetweeted { retweetEnum = TwitterClient.Retweet.Unretweet } else { retweetEnum = TwitterClient.Retweet.Retweet } TwitterClient.shareInstance.retweet(id, retweet: retweetEnum, success: { (tweet: Tweet) -> () in self.tweet = tweet self.showData() }) { (error: NSError) -> () in print("\(error)") } } @IBAction func onLikeClicked(sender: UIButton) { let id = tweet?.id as! String let isFavorite = (tweet?.favorited)! as Bool let favoriteEnum: TwitterClient.Favorite if isFavorite { favoriteEnum = TwitterClient.Favorite.Unlike } else { favoriteEnum = TwitterClient.Favorite.Like } TwitterClient.shareInstance.favorite(id, favorite: favoriteEnum, success: { (tweet: Tweet) -> () in self.tweet = tweet self.showData() }) { (error: NSError) -> () in print("\(error)") } } func dateFromString(date: NSDate, format: String) -> String { let formatter = NSDateFormatter() let locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.locale = locale formatter.dateFormat = format return formatter.stringFromDate(date) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let replyViewController = segue.destinationViewController as! ReplyViewController replyViewController.tweet = self.tweet replyViewController.isReplyMessage = true print("Reply Tweet") } }
7288b2dfca309f8fe8da2a7392f06799
31.659259
107
0.615786
false
false
false
false
mmisesin/particle
refs/heads/master
Particle/ArticleCellTableViewCell.swift
mit
1
// // ArticleCellTableViewCell.swift // Particle // // Created by Artem Misesin on 6/25/17. // Copyright © 2017 Artem Misesin. All rights reserved. // import UIKit final class ArticleCellTableViewCell: UITableViewCell { @IBOutlet weak var mainImage: UIImageView! @IBOutlet weak var mainLabel: UILabel! @IBOutlet weak var secondaryLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() setupViews() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func configure(with article: ParticleReading, at indexRow: Int, searchStatus: SearchStatus) { if let articleTitle = article.title { mainLabel.text = articleTitle } else { mainLabel.text = Constants.unknownTitle } if let articleURL = article.url { secondaryLabel.text = crop(url: articleURL) } else { secondaryLabel.text = Constants.unknownLink } if let imgData = article.thumbnail { mainImage.image = UIImage(data: imgData as Data) } else { mainImage.image = UIImage() } if indexRow == 0 { let height = 1 / UIScreen.main.scale let line = UIView(frame: CGRect(x: 15, y: 0, width: bounds.width - 30, height: height)) line.backgroundColor = Colors.separatorColor addSubview(line) } setupColors(for: searchStatus) } private func setupViews() { backgroundColor = .white separatorInset.right = 16 separatorInset.left = 16 //mainImage.layer.cornerRadius = 4 mainImage.contentMode = .scaleAspectFill mainImage.clipsToBounds = true mainLabel.textAlignment = .left secondaryLabel.textAlignment = .left } private func setupColors(for searchStatus: SearchStatus) { switch searchStatus { case .active(let range): mainLabel.textColor = Colors.desaturatedHeaderColor guard let text = mainLabel.text else { return } let attributedString = NSMutableAttributedString(string: text, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.bold)]) attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: Colors.headerColor, range: range) mainLabel.attributedText = attributedString case .nonActive: mainLabel.textColor = Colors.headerColor } secondaryLabel.textColor = Colors.subHeaderColor } private func crop(url: String) -> String { if let startRange = url.range(of: "://") { let tempString = String(url[startRange.upperBound..<url.endIndex]) if let endRange = tempString.range(of: "/") { let shortURL = String(tempString[tempString.startIndex..<endRange.lowerBound]) return shortURL } } return url } }
e34f1faad045f64b9779d0a6a5c8dc9b
33.477778
121
0.620045
false
false
false
false
kishikawakatsumi/TextKitExamples
refs/heads/master
BulletPoint/BulletPoint/ViewController.swift
mit
1
// // ViewController.swift // BulletPoint // // Created by Kishikawa Katsumi on 9/2/16. // Copyright © 2016 Kishikawa Katsumi. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let textView = UITextView(frame: CGRectInset(view.bounds, 10, 10)) textView.editable = false textView.textContainerInset = UIEdgeInsetsZero textView.textContainer.lineFragmentPadding = 0 textView.layoutManager.usesFontLeading = false view.addSubview(textView) let headFont = UIFont.boldSystemFontOfSize(20) let subheadFont = UIFont.boldSystemFontOfSize(16) let bodyFont = UIFont.systemFontOfSize(12) let text = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("List", ofType: "txt")!) let attributedText = NSMutableAttributedString(string: text) let image = UIImage(named: "bullet") let attachment = NSTextAttachment(data: nil, ofType: nil) attachment.image = image attachment.bounds = CGRect(x: 0, y: -2, width: bodyFont.pointSize, height: bodyFont.pointSize) let bulletText = NSAttributedString(attachment: attachment) attributedText.replaceCharactersInRange(NSRange(location: 350, length: 1), withAttributedString: bulletText) attributedText.replaceCharactersInRange(NSRange(location: 502, length: 1), withAttributedString: bulletText) attributedText.replaceCharactersInRange(NSRange(location: 617, length: 1), withAttributedString: bulletText) attributedText.replaceCharactersInRange(NSRange(location: 650, length: 1), withAttributedString: bulletText) do { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(headFont.lineHeight) paragraphStyle.maximumLineHeight = ceil(headFont.lineHeight) paragraphStyle.paragraphSpacing = ceil(headFont.pointSize / 2) let attributes = [ NSFontAttributeName: headFont, NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0), NSParagraphStyleAttributeName: paragraphStyle, ] attributedText.addAttributes(attributes, range: NSRange(location: 0, length: 33)) } do { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(subheadFont.lineHeight) paragraphStyle.maximumLineHeight = ceil(subheadFont.lineHeight) paragraphStyle.paragraphSpacing = ceil(subheadFont.lineHeight / 2) let attributes = [ NSFontAttributeName: subheadFont, NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0), NSParagraphStyleAttributeName: paragraphStyle, ] attributedText.addAttributes(attributes, range: NSRange(location: 34, length: 20)) } do { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight) paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight) paragraphStyle.lineSpacing = 2 paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2) paragraphStyle.alignment = .Justified let attributes = [ NSFontAttributeName: bodyFont, NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0), NSParagraphStyleAttributeName: paragraphStyle, ] attributedText.addAttributes(attributes, range: NSRange(location: 55, length: 275)) } do { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(subheadFont.lineHeight) paragraphStyle.maximumLineHeight = ceil(subheadFont.lineHeight) paragraphStyle.paragraphSpacing = ceil(subheadFont.lineHeight / 2) let attributes = [ NSFontAttributeName: subheadFont, NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0), NSParagraphStyleAttributeName: paragraphStyle, ] attributedText.addAttributes(attributes, range: NSRange(location: 330, length: 19)) } do { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight) paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight) paragraphStyle.lineSpacing = 2 paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2) paragraphStyle.headIndent = bodyFont.pointSize * 2 paragraphStyle.alignment = .Justified paragraphStyle.tabStops = [] paragraphStyle.defaultTabInterval = bodyFont.pointSize * 2 let attributes = [ NSFontAttributeName: bodyFont, NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0), NSParagraphStyleAttributeName: paragraphStyle, ] attributedText.addAttributes(attributes, range: NSRange(location: 350, length: 472)) } do { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight) paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight) paragraphStyle.lineSpacing = 2 paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2) paragraphStyle.alignment = .Justified let attributes = [ NSFontAttributeName: bodyFont, NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0), NSParagraphStyleAttributeName: paragraphStyle, ] attributedText.addAttributes(attributes, range: NSRange(location: 822, length: 126)) } textView.attributedText = attributedText } override func prefersStatusBarHidden() -> Bool { return true } }
ede5b227282d87cc06423c511dba1fd7
40.149351
116
0.652517
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
Objects/struct tables/Battles.swift
gpl-2.0
1
// // Battles.swift // GoD Tool // // Created by Stars Momodu on 23/03/2021. // import Foundation #if GAME_XD let battleTrainerStruct = GoDStruct(name: "Battle CD Trainer", format: [ .short(name: "Deck ID", description: "", type: .deckID), .short(name: "Trainer ID", description: "", type: .uintHex) ]) let BattleCDStruct = GoDStruct(name: "Battle CD", format: [ .byte(name: "Unknown", description: "", type: .uintHex), .byte(name: "Turn Limit", description: "Set to 0 for no limit", type: .uint), .byte(name: "Battle Style", description: "Single or Double", type: .battleStyle), .short(name: "Battle Field", description: "", type: .battleFieldID), .short(name: "Padding", description: "", type: .null), .subStruct(name: "Player Deck", description: "", property: battleTrainerStruct), .subStruct(name: "Opponent Deck", description: "", property: battleTrainerStruct), .word(name: "Name ID", description: "", type: .msgID(file: .dol)), .word(name: "Description ID", description: "", type: .msgID(file: .dol)), .word(name: "Condition Text ID", description: "", type: .msgID(file: .dol)), .word(name: "Unknown 4", description: "", type: .uintHex), .array(name: "Unknowns", description: "", property: .byte(name: "Unknown", description: "", type: .uintHex), count: 0x1c), ]) let battleCDsTable = CommonStructTable(index: .BattleCDs, properties: BattleCDStruct) let battleLayoutsStruct = GoDStruct(name: "Battle Layout", format: [ .byte(name: "Active pokemon per player", description: "", type: .uint), .byte(name: "Unknown 1", description: "", type: .uintHex), .byte(name: "Unknown 2", description: "", type: .uintHex), .word(name: "Unknown", description: "", type: .uintHex) ]) let battleLayoutsTable = CommonStructTable(index: .BattleLayouts, properties: battleLayoutsStruct) #endif let battlefieldsStruct = GoDStruct(name: "Battlefield", format: [ .byte(name: "Unknown 1", description: "", type: .uintHex), .short(name: "Unknown 2", description: "", type: .uintHex), .word(name: "Name ID", description: "", type: .msgID(file: .common_rel)), .word(name: "Unknown 4", description: "", type: .uintHex), .word(name: "Unknown 5", description: "", type: .uintHex), .word(name: "Unknown 6", description: "", type: .uintHex), .short(name: "Unknown 7", description: "", type: .uintHex), .short(name: "Unknown 8", description: "", type: .uintHex) ]) let battlefieldsTable = CommonStructTable(index: .BattleFields, properties: battlefieldsStruct) #if GAME_XD var battleStruct: GoDStruct { return GoDStruct(name: "Battle", format: [ .byte(name: "Battle Type", description: "", type: .battleType), .byte(name: "Trainers per side", description: "", type: .uint), .byte(name: "Battle Style", description: "", type: .battleStyle), .byte(name: "Pokemon Per Player", description: "", type: .uint), .byte(name: "Is Story Battle", description: "", type: .bool), .short(name: "Battle Field ID", description: "", type: .battleFieldID), .short(name: "Battle CD ID", description: "Set programmatically at run time so is always set to 0 in the game files", type: .uint), .word(name: "Battle Identifier String", description: "", type: .msgID(file: .dol)), .word(name: "BGM ID", description: "", type: .uintHex), .word(name: "Unknown 2", description: "", type: .uintHex) ] + (region == .EU ? [.array(name: "Unknown Values", description: "Only exist in the PAL version", property: .word(name: "", description: "", type: .uintHex), count: 4)] : []) + [ .word(name: "Colosseum Round", description: "wzx id for intro text", type: .colosseumRound), .array(name: "Players", description: "", property: .subStruct(name: "Battle Player", description: "", property: GoDStruct(name: "Battle Player", format: [ .short(name: "Deck ID", description: "", type: .deckID), .short(name: "Trainer ID", description: "Use deck 0, id 5000 for the player's team", type: .uint), .word(name: "Controller Index", description: "0 for AI", type: .playerController), ] )), count: 4) ]) } #else let battleStruct = GoDStruct(name: "Battle", format: [ .byte(name: "Battle Type", description: "", type: .battleType), .byte(name: "Battle Style", description: "", type: .battleStyle), .byte(name: "Unknown Flag", description: "", type: .bool), .short(name: "Battle Field ID", description: "", type: .battleFieldID), .word(name: "Name ID", description: "", type: .msgID(file: .common_rel)), .word(name: "BGM ID", description: "", type: .uintHex), .word(name: "Unknown 3", description: "", type: .uintHex), .word(name: "Colosseum Round", description: "", type: .colosseumRound), .array(name: "Players", description: "", property: .subStruct(name: "Battle Player", description: "", property: GoDStruct(name: "Battle Player", format: [ .short(name: "Trainer ID", description: "id 1 is the player", type: .indexOfEntryInTable(table: trainersTable, nameProperty: nil)), .word(name: "Controller Index", description: "0 for AI", type: .playerController), ])), count: 4) ]) #endif var battlesTable: CommonStructTable { return CommonStructTable(index: .Battles, properties: battleStruct) } #if GAME_COLO let battleStyleStruct = GoDStruct(name: "Battle Styles", format: [ .byte(name: "Trainers per side", description: "", type: .uint), .byte(name: "Pokemon per trainer", description: "", type: .uint), .byte(name: "Active pokemon per trainer", description: "", type: .uint), .word(name: "Name ID", description: "", type: .msgID(file: .common_rel)) ]) let battleStylesTable = CommonStructTable(index: .BattleStyles, properties: battleStyleStruct) { (index, data) -> String? in if let trainersPerSide: Int = data.get("Trainers per side"), let pokemonPerTrainer: Int = data.get("Pokemon per trainer"), let activePokemonPerTrainer: Int = data.get("Active pokemon per trainer") { let battleTypeName: String if trainersPerSide > 1 { battleTypeName = "Multi" } else { battleTypeName = activePokemonPerTrainer == 1 ? "Single" : "Double" } return "\(battleTypeName) Battle - \(pokemonPerTrainer) Pokemon Each" } return "Battle Style \(index)" } let battleTypesStruct = GoDStruct(name: "Battle Types", format: [ .byte(name: "Flag 1", description: "", type: .bool), .byte(name: "Flag 2", description: "", type: .bool), .byte(name: "Flag 3", description: "", type: .bool), .byte(name: "Flag 4", description: "", type: .bool), .byte(name: "Can Use Items", description: "", type: .bool), .byte(name: "Flag 6", description: "", type: .bool), .byte(name: "Flag 7", description: "", type: .bool), .byte(name: "Flag 8", description: "", type: .bool), .byte(name: "Flag 9", description: "", type: .bool), .byte(name: "Flag 10", description: "", type: .bool), .byte(name: "Flag 11", description: "", type: .bool), .byte(name: "Flag 12", description: "", type: .bool), .byte(name: "Flag 13", description: "", type: .bool), .byte(name: "Flag 14", description: "", type: .bool), .byte(name: "Flag 15", description: "", type: .bool), .byte(name: "Flag 16", description: "", type: .bool), .byte(name: "Flag 17", description: "", type: .bool), .byte(name: "Flag 18", description: "", type: .bool), .byte(name: "Flag 19", description: "", type: .bool), .byte(name: "Flag 20", description: "", type: .bool), .byte(name: "Flag 21", description: "", type: .bool), .byte(name: "Flag 22", description: "", type: .bool), .byte(name: "Flag 23", description: "", type: .bool), .byte(name: "Flag 24", description: "", type: .bool), .byte(name: "Flag 25", description: "", type: .bool), .word(name: "Name ID", description: "", type: .msgID(file: .common_rel)) ]) let battleTypesTable = CommonStructTable(index: .BattleTypes, properties: battleTypesStruct) { (index, data) -> String? in if let type = XGBattleTypes(rawValue: index) { return type.name } return "Battle Type \(index)" } #endif private let aiRolesEnd: [GoDStructProperties] = game == .Colosseum ? [] : [ .byte(name: "Misc 3", description: "", type: .byteRange), .byte(name: "Misc 4", description: "", type: .byteRange), ] let pokemonAIRolesStruct = GoDStruct(name: "Pokemon AI Roles", format: [ .word(name: "Name ID", description: "", type: .msgID(file: nil)), .word(name: "Unknown 1", description: "", type: .uint), .subStruct(name: "Move Type Weights", description: "How much more/less likely this role is to use a certain type of move", property: GoDStruct(name: "AI Role Weights", format: [ .byte(name: "No Effect", description: "", type: .byteRange), .byte(name: "Attack", description: "", type: .byteRange), .byte(name: "Healing", description: "", type: .byteRange), .byte(name: "Stat Decrease", description: "", type: .byteRange), .byte(name: "Stat Increase", description: "", type: .byteRange), .byte(name: "Status", description: "", type: .byteRange), .byte(name: "Field", description: "", type: .byteRange), .byte(name: "Affect Opponent's Move", description: "", type: .byteRange), .byte(name: "OHKO", description: "", type: .byteRange), .byte(name: "Multi-turn", description: "", type: .byteRange), .byte(name: "Misc", description: "", type: .byteRange), .byte(name: "Misc 2", description: "", type: .byteRange) ] + aiRolesEnd)) ]) let pokemonAIRolesTable = CommonStructTable(index: .AIPokemonRoles, properties: pokemonAIRolesStruct)
7177f762c9fa016c3fed16ac27aee930
48.930108
178
0.667708
false
false
false
false
sorenmortensen/SymondsTimetable
refs/heads/master
Sources/Lesson.swift
mit
1
// // Lesson.swift // SymondsAPI // // Created by Søren Mortensen on 20/01/2017. // Copyright © 2017 Soren Mortensen. All rights reserved. // import Foundation /// A `Lesson` includes all the information provided by the Peter Symonds /// College Data Service about a single event in a student's timetable. public class Lesson { // MARK: - Properties /// The ID of the lesson. /// /// - note: Unique among other items of the same type. public let id: String /// The title of the lesson. public let title: String /// The subtitle of the lesson. public let subtitle: String? /// The staff member(s) in charge of the lesson. public let staff: String? /// The room in which the lesson takes place. public let room: String? /// The start time of the lesson. public let start: Date /// The end time of the lesson. public let end: Date /// The date at the beginning of the day on which this lesson occurs. public var dayDate: Date { let calendar = Calendar.current return calendar.startOfDay(for: start) } /// The type of timetable item this instance represents (such as a lesson, /// study period, exam, etc.). public let type: LessonType /// Whether this lesson is a blank lesson (e.g. a study period or a college /// holiday). public let isBlank: Bool /// Whether this lesson has been marked as cancelled. /// /// - note: If this property is true, this information should be displayed /// clearly to the user. public let isCancelled: Bool /// Whether this lesson has been marked as taking place in a different room /// than usual. /// /// - note: If this property is true, this information should be displayed /// clearly to the user. public let isRoomChange: Bool /// The time range of this lesson, in the format `HH:mm-HH:mm`. public var timeRange: String { let startTime = self.timeFormatter.string(from: self.start) let endTime = self.timeFormatter.string(from: self.end) return "\(startTime)-\(endTime)" } /// The start time of this lesson, in the format `HH:mm`. public var startTime: String { return self.timeFormatter.string(from: self.start) } /// The end time of this lesson, in the format `HH:mm`. public var endTime: String { return self.timeFormatter.string(from: self.end) } /// The date on which the lesson occurs, in the user's .long date format. public var dateString: String { get { return dateFormatter.string(from: start) } } /// The length of the lesson (i.e. the length of time between `start` and /// `end`). public var length: TimeInterval { get { return end.timeIntervalSince(start) } } /// A formatter that can create a date in the format `HH:mm` from a `Date` /// instance, or vice versa. private let timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "HH:mm" return formatter }() /// A formatter that can create a date in the localised long date format for /// the user. private let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .long return formatter }() // MARK: - Types /// The various types of lessons. public enum LessonType: String { /// An extra curricular activity or sports team. case activity = "activity" /// A booking made by a student for their art exam. case artExamBooking = "artexambooking" /// A national bank holiday. case bankHoliday = "bankholiday" /// A period during which a boarding student is on leave from one of the /// boarding houses. case boardingLeave = "boardingleave" /// The morning break period, which occurs from 10:20 to 10:40 each /// morning for all students. case morningBreak = "break" /// An appointment with a Careers adviser. case careersAppointment = "careersappointment" /// A careers week talk. case careersWeek = "careersweek" /// An exam. case exam = "exam" /// One of the college holidays. case holiday = "holiday" /// A normal college lesson. case lesson = "lesson" /// A blank lunchtime period, which occurs from 13:00 to 13:50 for /// students who do not have a scheduled lesson during that time. /// /// - note: This lesson type does not exist in the Symonds Data Service /// and is manually added to blank events starting at 13:00 and /// ending at 13:50. case lunch = "lunch" /// A period of spare time between lessons. case study = "studyperiod" /// A Study Skills appointment. case studySkills = "studyskills" /// A Study Support appointment. case studySupport = "studysupport" /// A college trip. case trip = "trip" /// Tutor time. case tutorGroup = "tutorgroup" } // MARK: - Initialisers /// Creates a new instance of `Lesson`. /// /// - Parameters: /// - id: The lesson's ID. /// - title: The lesson's title. /// - subtitle: The lesson's subtitle. /// - staff: The lesson's staff member. /// - room: The lesson's room. /// - start: The lesson's start time. /// - end: The lesson's end time. /// - type: The lesson's type. /// - isBlank: The lesson's blank status. /// - isCancelled: The lesson's cancelled status. /// - isRoomChange: The lesson's room change status. public init( id: String, title: String, subtitle: String, staff: String?, room: String?, start: Date, end: Date, type: LessonType, isBlank: Bool = false, isCancelled: Bool = false, isRoomChange: Bool = false ) { if isBlank { self.id = "blank" } else { self.id = id } self.subtitle = subtitle self.staff = staff self.room = room self.start = start self.end = end let startTime = self.timeFormatter.string(from: self.start) let endTime = self.timeFormatter.string(from: self.end) let timeRange = "\(startTime)-\(endTime)" if isBlank && timeRange == "13:00-13:50" { self.type = .lunch self.title = "Lunch" } else { self.type = type self.title = title } self.isBlank = isBlank self.isCancelled = isCancelled self.isRoomChange = isRoomChange } }
10b43086690b4f51d81b761b7d92a85f
30.854545
80
0.581336
false
false
false
false
wilfreddekok/Antidote
refs/heads/master
Antidote/ChangePasswordController.swift
mpl-2.0
1
// 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 SnapKit private struct Constants { static let HorizontalOffset = 40.0 static let ButtonVerticalOffset = 20.0 static let FieldsOffset = 10.0 static let MaxFormWidth = 350.0 } protocol ChangePasswordControllerDelegate: class { func changePasswordControllerDidFinishPresenting(controller: ChangePasswordController) } class ChangePasswordController: KeyboardNotificationController { weak var delegate: ChangePasswordControllerDelegate? private let theme: Theme private weak var toxManager: OCTManager! private var scrollView: UIScrollView! private var containerView: IncompressibleView! private var oldPasswordField: ExtendedTextField! private var newPasswordField: ExtendedTextField! private var repeatPasswordField: ExtendedTextField! private var button: RoundedButton! init(theme: Theme, toxManager: OCTManager) { self.theme = theme self.toxManager = toxManager super.init() edgesForExtendedLayout = .None addNavigationButtons() title = String(localized: "change_password") } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { loadViewWithBackgroundColor(theme.colorForType(.NormalBackground)) createViews() installConstraints() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let old = oldPasswordField { old.becomeFirstResponder() } else if let new = newPasswordField { new.becomeFirstResponder() } } override func keyboardWillShowAnimated(keyboardFrame frame: CGRect) { scrollView.contentInset.bottom = frame.size.height scrollView.scrollIndicatorInsets.bottom = frame.size.height } override func keyboardWillHideAnimated(keyboardFrame frame: CGRect) { scrollView.contentInset.bottom = 0.0 scrollView.scrollIndicatorInsets.bottom = 0.0 } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.contentSize.width = scrollView.frame.size.width scrollView.contentSize.height = CGRectGetMaxY(containerView.frame) } } // MARK: Actions extension ChangePasswordController { func cancelButtonPressed() { delegate?.changePasswordControllerDidFinishPresenting(self) } func buttonPressed() { guard validatePasswordFields() else { return } let oldPassword = oldPasswordField.text! let newPassword = newPasswordField.text! let hud = JGProgressHUD(style: .Dark) hud.showInView(view) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [unowned self] in let result = self.toxManager.changeEncryptPassword(newPassword, oldPassword: oldPassword) if result { let keychainManager = KeychainManager() if keychainManager.toxPasswordForActiveAccount != nil { keychainManager.toxPasswordForActiveAccount = newPassword } } dispatch_async(dispatch_get_main_queue()) { [unowned self] in hud.dismiss() if result { self.delegate?.changePasswordControllerDidFinishPresenting(self) } else { handleErrorWithType(.WrongOldPassword) } } } } } extension ChangePasswordController: ExtendedTextFieldDelegate { func loginExtendedTextFieldReturnKeyPressed(field: ExtendedTextField) { if field === oldPasswordField { newPasswordField!.becomeFirstResponder() } else if field === newPasswordField { repeatPasswordField!.becomeFirstResponder() } else if field === repeatPasswordField { buttonPressed() } } } private extension ChangePasswordController { func addNavigationButtons() { navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .Cancel, target: self, action: #selector(ChangePasswordController.cancelButtonPressed)) } func createViews() { scrollView = UIScrollView() view.addSubview(scrollView) containerView = IncompressibleView() containerView.backgroundColor = .clearColor() scrollView.addSubview(containerView) button = RoundedButton(theme: theme, type: .RunningPositive) button.setTitle(String(localized: "change_password_done"), forState: .Normal) button.addTarget(self, action: #selector(ChangePasswordController.buttonPressed), forControlEvents: .TouchUpInside) containerView.addSubview(button) oldPasswordField = createPasswordFieldWithTitle(String(localized: "old_password")) newPasswordField = createPasswordFieldWithTitle(String(localized: "new_password")) repeatPasswordField = createPasswordFieldWithTitle(String(localized: "repeat_password")) oldPasswordField.returnKeyType = .Next newPasswordField.returnKeyType = .Next repeatPasswordField.returnKeyType = .Done } func createPasswordFieldWithTitle(title: String) -> ExtendedTextField { let field = ExtendedTextField(theme: theme, type: .Normal) field.delegate = self field.title = title field.secureTextEntry = true containerView.addSubview(field) return field } func installConstraints() { scrollView.snp_makeConstraints { $0.edges.equalTo(view) } containerView.customIntrinsicContentSize.width = CGFloat(Constants.MaxFormWidth) containerView.snp_makeConstraints { $0.top.equalTo(scrollView) $0.centerX.equalTo(scrollView) $0.width.lessThanOrEqualTo(Constants.MaxFormWidth) $0.width.lessThanOrEqualTo(scrollView).offset(-2 * Constants.HorizontalOffset) } var topConstraint = containerView.snp_top if installConstraintsForField(oldPasswordField, topConstraint: topConstraint) { topConstraint = oldPasswordField!.snp_bottom } if installConstraintsForField(newPasswordField, topConstraint: topConstraint) { topConstraint = newPasswordField!.snp_bottom } if installConstraintsForField(repeatPasswordField, topConstraint: topConstraint) { topConstraint = repeatPasswordField!.snp_bottom } button.snp_makeConstraints { $0.top.equalTo(topConstraint).offset(Constants.ButtonVerticalOffset) $0.leading.trailing.equalTo(containerView) $0.bottom.equalTo(containerView) } } /** Returns true if field exists, no otherwise. */ func installConstraintsForField(field: ExtendedTextField?, topConstraint: ConstraintItem) -> Bool { guard let field = field else { return false } field.snp_makeConstraints { $0.top.equalTo(topConstraint).offset(Constants.FieldsOffset) $0.leading.trailing.equalTo(containerView) } return true } func validatePasswordFields() -> Bool { guard let oldText = oldPasswordField.text where !oldText.isEmpty else { handleErrorWithType(.PasswordIsEmpty) return false } guard let newText = newPasswordField.text where !newText.isEmpty else { handleErrorWithType(.PasswordIsEmpty) return false } guard let repeatText = repeatPasswordField.text where !repeatText.isEmpty else { handleErrorWithType(.PasswordIsEmpty) return false } guard newText == repeatText else { handleErrorWithType(.PasswordsDoNotMatch) return false } return true } }
01d0c3156ab825ab578df813c0b45779
31.559055
123
0.662999
false
false
false
false
jarocht/iOS-AlarmDJ
refs/heads/master
AlarmDJ/AlarmDJ/SettingsTableViewController.swift
mit
1
// // SettingsTableViewController.swift // AlarmDJ // // Created by X Code User on 7/22/15. // Copyright (c) 2015 Tim Jaroch, Morgan Heyboer, Andreas Plüss (TEAM E). All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var snoozeTimeTextField: UITextField! @IBOutlet weak var zipcodeTextField: UITextField! @IBOutlet weak var twentyFourHourSwitch: UISwitch! @IBOutlet weak var newsQueryTextField: UITextField! @IBOutlet weak var musicGenreDataPicker: UIPickerView! let ldm = LocalDataManager() var settings = SettingsContainer() var genres: [String] = ["Alternative","Blues","Country","Dance","Electronic","Hip-Hop/Rap","Jazz","Klassik","Pop","Rock", "Soundtracks"] override func viewDidLoad() { super.viewDidLoad() snoozeTimeTextField.delegate = self snoozeTimeTextField.tag = 0 zipcodeTextField.delegate = self zipcodeTextField.tag = 1 newsQueryTextField.delegate = self newsQueryTextField.tag = 2 musicGenreDataPicker.dataSource = self musicGenreDataPicker.delegate = self } override func viewWillAppear(animated: Bool) { settings = ldm.loadSettings() snoozeTimeTextField.text! = "\(settings.snoozeInterval)" zipcodeTextField.text! = settings.weatherZip twentyFourHourSwitch.on = settings.twentyFourHour newsQueryTextField.text! = settings.newsQuery var index = 0 for var i = 0; i < genres.count; i++ { if genres[i] == settings.musicGenre{ index = i } } musicGenreDataPicker.selectRow(index, inComponent: 0, animated: true) } override func viewWillDisappear(animated: Bool) { if count(zipcodeTextField.text!) == 5 { settings.weatherZip = zipcodeTextField.text! } if count(snoozeTimeTextField.text!) > 0 { var timeVal: Int = (snoozeTimeTextField.text!).toInt()! if timeVal > 0 { settings.snoozeInterval = timeVal //ldm.saveSettings(settingsContainer: settings) } } if count (newsQueryTextField.text!) > 0 { settings.newsQuery = newsQueryTextField.text! } ldm.saveSettings(settingsContainer: settings) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func twentyFourHourSwitchClicked(sender: AnyObject) { settings.twentyFourHour = twentyFourHourSwitch.on } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if textField.tag < 2 { if count(textField.text!) + count(string) <= 5 { return true; } return false } else { if count(textField.text!) + count(string) <= 25 { return true; } return false } } func textFieldDidBeginEditing(textField: UITextField) { } func textFieldShouldEndEditing(textField: UITextField) -> Bool { return true } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return genres.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return genres[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { settings.musicGenre = genres[row] } }
d207e8ac6ca5ea9328b8425b5d580525
32.809917
140
0.632274
false
false
false
false
nomothetis/SemverKit
refs/heads/master
Common/Increment.swift
mit
1
// // VersionBump.swift // SemverKit // // Created by Salazar, Alexandros on 9/15/14. // Copyright (c) 2014 nomothetis. All rights reserved. // import Foundation /** An extension to allow semantic incrementation of versions, including support for alpha and beta versions. */ extension Version { /** Bumps the major number by one; zeros and nils out the rest. :return: a new version with a bumped major version. */ public func nextMajorVersion() -> Version { return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: PreReleaseInfo.None) } /** Bumps the minor number by one; zeros and nils out all less-significant values. :return: a new version with a bumped minor version. */ public func nextMinorVersion() -> Version { return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease: nil, metadata: nil) } /** Bumps the patch number by one; zeros and nils out all less-significant values. :return: a new version with a bumped patch version. */ public func nextPatchVersion() -> Version { return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease: nil) } /** Returns the next major alpha version. The next major alpha version of version `v1` is defined as the smallest version `v2 > v1` with - A patch number of 0 - A minor number of 0 - A pre-release of alpha.X, where X is an integer Examples: - 2.3.5 -> 3.0.0-alpha.0 - 2.0.5 -> 3.0.0-alpha.0 - 3.0.0 -> 4.0.0-alpha.0 - 3.0.0-alpha.0 -> 3.0.0-alpha.1 - 3.0.0-beta.1 -> 4.0.0-alpha.0 - 3.0.0-alpha -> 3.0.0-alpha.0 - 3.0.0-234 -> 3.0.0-alpha.0 - 3.0.0-tim -> 4.0.0-alpha.0 :return: a new version with bumped major version, and an alpha prerelease of 0. */ public func nextMajorAlphaVersion() -> Version { switch self.preRelease { case PreReleaseInfo.None: return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Alpha(0)) case PreReleaseInfo.Alpha(let alpha): if (self.patch == 0) && (self.minor == 0) { return Version(major: self.major, minor: 0, patch: 0, preRelease:.Alpha(alpha + 1)) } else { return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Alpha(0)) } case PreReleaseInfo.Beta(_): return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Alpha(0)) case .Arbitrary(let info): if (self.preRelease < PreReleaseInfo.Alpha(0)) { return Version(major: self.major, minor: 0, patch: 0, preRelease: .Alpha(0)) } else { return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: .Alpha(0)) } } } /** Returns the next minor alpha version. The next minor alpha version of a version `v1` is defined as the smallest version `v2 > v1` with - A patch number of 0. - An pre-release of alpha.X, where X is an integer. Examples: - 2.3.5 -> 2.4.0-alpha.0 - 2.3.0 -> 2.4.0-alpha.0 - 2.3.5-alpha.3 -> 2.4.0-alpha.0 - 2.3.0-alpha.3 -> 2.3.0-alpha.4 - 2.3.0-alpha.a -> 2.4.0-alpha.0 (digits have lower priority than strings) - 2.3.0-12 -> 2.3.0-alpha.0 - 2.3.0-beta.3 -> 2.4.0-alpha.0 - 2.3.0-alpha -> 2.3.0-alpha.0 :return: the next minor alpha version. */ public func nextMinorAlphaVersion() -> Version { switch self.preRelease { case PreReleaseInfo.None: return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Alpha(0)) case PreReleaseInfo.Alpha(let alpha): if (self.patch == 0) { return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Alpha(alpha + 1)) } else { return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Alpha(0)) } case PreReleaseInfo.Beta(_): return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Alpha(0)) case .Arbitrary(let info): if (self.patch != 0) { return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Alpha(0)) } else if (self.preRelease < PreReleaseInfo.Alpha(0)) { return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: .Alpha(0)) } else { return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease: .Alpha(0)) } } } /** Returns the next patch alpha version. The next patch alpha version of a version `v1` is defined as the smallest version `v2 > v1` with: - A pre-release in the form alpha.X where X is an integer Examples: - 2.0.0 -> 2.0.1-alpha.0 - 2.0.1-alpha.0 -> 2.0.1-alpha.2 - 2.0.1-beta.3 -> 2.0.2-alpha.0 - 2.0.1-alpha -> 2.0.2-alpha.0 :return: the next patch alpha version. */ public func nextPatchAlphaVersion() -> Version { switch self.preRelease { case PreReleaseInfo.None: return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Alpha(0)) case PreReleaseInfo.Alpha(let alpha): return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Alpha(alpha + 1)) case PreReleaseInfo.Beta(_): return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Alpha(0)) case .Arbitrary(let info): if (self.preRelease < PreReleaseInfo.Alpha(0)) { return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: .Alpha(0)) } else { return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease: .Alpha(0)) } } } /** Returns the next major beta version. The next major beta version of a version `v1` is defined as the smallest version `v2 > v1` with: - A minor number of 0 - A patch number of 0 - A pre-release of beta.X, where X is an integer Examples: 2.3.5 -> 3.0.0-beta.0 2.3.5-alpha.0 -> 3.0.0-beta.0 3.0.0-alpha.7 -> 3.0.0-beta.0 3.0.0-beta.7 -> 3.0.0-beta.8 3.0.0-tim -> 4.0.0-beta.0 3.0.0-123 -> 3.0.0-beta0 :return: the next major beta version. */ public func nextMajorBetaVersion() -> Version { switch self.preRelease { case .None: return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: .Beta(0)) case .Alpha(_): if self.minor == 0 && self.patch == 0 { return Version(major: self.major, minor: 0, patch: 0, preRelease:.Beta(0)) } else { return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Beta(0)) } case .Beta(let int): if (self.minor == 0 && self.patch == 0) { return Version(major: self.major, minor: 0, patch: 0, preRelease:.Beta(int + 1)) } else { return Version(major: self.major + 1, minor: 0, patch: 0, preRelease:.Beta(0)) } case .Arbitrary(let arr): if (self.preRelease < .Beta(0)) { return Version(major: self.major, minor: 0, patch: 0, preRelease: .Beta(0)) } else { return Version(major: self.major + 1, minor: 0, patch: 0, preRelease: .Beta(0)) } } } /** Returns the next minor beta version. The next minor beta version of a version `v1` is defined as the smallest version `v2 > v1` with: - A patch number of 0 - A pre-release of beta.X, where X is an integer Examples: - 2.3.5 -> 2.4.0-beta.0 - 2.2.0 -> 2.3.0-beta.0 - 2.5.0-alpha.3 -> 2.5.0-beta.0 - 2.7.0-beta.3 -> 2.7.0-beta.4 - 8.3.0-final -> 8.4.0-beta.0 - 8.4.0-45 -> 8.4.0-beta.0 :return: the next minor beta version. */ public func nextMinorBetaVersion() -> Version { switch self.preRelease { case .None: return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0)) case .Alpha(_): if self.patch == 0 { return Version(major: self.major, minor: self.minor, patch: 0, preRelease:.Beta(0)) } else { return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0)) } case .Beta(let int): if self.patch == 0 { return Version(major: self.major, minor: self.minor, patch: 0, preRelease:.Beta(int + 1)) } else { return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0)) } case .Arbitrary(let info): if self.preRelease < PreReleaseInfo.Beta(0) { return Version(major: self.major, minor: self.minor, patch: 0, preRelease:.Beta(0)) } else { return Version(major: self.major, minor: self.minor + 1, patch: 0, preRelease:.Beta(0)) } } } /** Returns the next patch beta version. The next patch beta version of a version `v1` is defined as the smallest version `v2 > v1` where: - A pre-release in the form beta.X where X is an integer Examples: - 2.3.5 -> 2.3.6-beta.0 - 3.4.0-alpha.0 -> 3.4.0-beta.0 - 3.0.0 -> 3.0.1-beta.0 - 3.1.0 -> 3.1.1-beta.0 - 3.1.0-beta.1 -> 3.1.1-beta.2 - 3.1.0-123 -> 3.1.0-beta.0 :return: the next patch beta version. */ public func nextPatchBetaVersion() -> Version { switch self.preRelease { case .None: return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Beta(0)) case .Alpha(_): return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Beta(0)) case .Beta(let num): return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: .Beta(num + 1)) case .Arbitrary(let info): if self.preRelease < .Beta(0) { return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease:.Beta(0)) } else { return Version(major: self.major, minor: self.minor, patch: self.patch + 1, preRelease:.Beta(0)) } } } /** Gets the stable version. A stabilized version `v1` is the smallest version `v2 > v1` such that there is no prerelease or metadata info. Examples: - 3.0.0-alpha.2 -> 3.0.0 - 3.4.3-beta.0 -> 3.4.3 :return: the stabilized version. */ public func nextStableVersion() -> Version { return Version(major: self.major, minor: self.minor, patch: self.patch, preRelease: PreReleaseInfo.None) } }
8a550ab9f3b901cc64b0ce628ab5b559
37.753425
117
0.563588
false
false
false
false
CoolCodeFactory/ViperWeather
refs/heads/master
ViperWeather/RootContainer.swift
apache-2.0
1
// // RootContainer.swift // Architecture // // Created Dmitri Utmanov on 20/02/16. // Copyright © 2016 Dmitriy Utmanov. All rights reserved. // // Generated by Swift-Viper templates. Find latest version at https://github.com/Nikita2k/SwiftViper // import UIKit import Swinject class RootContainer: AssemblyType { func assemble(container: Container) { container.registerForStoryboard(RootViewController.self) { (r, c) -> () in container.register(RootPresenterProtocol.self) { [weak c] r in guard let c = c else { fatalError("Contoller is nil") } let interface = c let interactor = r.resolve(RootInteractorInputProtocol.self)! let router = r.resolve(RootRouterInputProtocol.self)! let presenter = RootPresenter(interface: interface, interactor: interactor, router: router) interactor.presenter = presenter return presenter } c.presenter = r.resolve(RootPresenterProtocol.self) } container.register(RootInteractorInputProtocol.self) { r in return RootInteractor() } container.register(RootRouterInputProtocol.self) { r in let router = RootRouter() router.listAssembler = r.resolve(ListAssembler.self)! return router } container.register(ListAssembler.self) { r in let parentAssembler = r.resolve(RootAssembler.self)! return ListAssembler(parentAssembler: parentAssembler) } } }
72477183fde18dc28f6d4d4a246781fa
32.44898
107
0.612569
false
false
false
false
BoltApp/bolt-ios
refs/heads/master
BoltExample/BoltExample/BoltAPI/Model/BLTShippingAddress.swift
mit
1
// // BLTShippingAddress.swift // BoltAPI // // Created by Bolt. // Copyright © 2018 Bolt. All rights reserved. // import Foundation public enum BLTShippingAddressError: Error { case wrongCountryCode(_ countryCode: String) } struct BLTShippingAddressConstants { static let countryCodeCharactersCount = 2 } /// Shipping address object within shipment public class BLTShippingAddress: Decodable { // MARK: Required /// First name public var firstName: String /// Last Name public var lastName: String /// Street address line 1 public var streetAddress1: String /// Refers to a city or something similar public var locality: String /// Refers to a state or something similar public var region: String /// Postal or ZIP code public var postalCode: String /// 2 letter ISO country code public private(set) var countryCode: String /// Full name of the country public var country: String // MARK: Optional /// Company public var company: String? /// Phone number public var phone: String? /// Email address public var email: String? /// Street address line 2 public var streetAddress2: String? /// Street address line 3 public var streetAddress3: String? /// Street address line 4 public var streetAddress4: String? // MARK: Initialization /** Initializes a Shipping address object within shipment. - Parameter firstName: First name. - Parameter lastName: Last name. - Parameter streetAddress1: Street address line 1. - Parameter locality: Refers to a city or something similar. - Parameter region: Refers to a state or something similar. - Parameter postalCode: Postal or ZIP code. - Parameter countryCode: 2 letter ISO country code. - Parameter country: Full name of the country. - Returns: A new shipping address instance. */ public init(firstName: String, lastName: String, streetAddress1: String, locality: String, region: String, postalCode: String, countryCode: String, country: String) throws { self.firstName = firstName self.lastName = lastName self.streetAddress1 = streetAddress1 self.locality = locality self.region = region self.postalCode = postalCode if countryCode.count == BLTShippingAddressConstants.countryCodeCharactersCount { self.countryCode = countryCode } else { throw BLTShippingAddressError.wrongCountryCode(countryCode) } self.country = country } // MARK: Additional public func change(countryCode: String) throws { if countryCode.count == BLTShippingAddressConstants.countryCodeCharactersCount { self.countryCode = countryCode } else { throw BLTShippingAddressError.wrongCountryCode(countryCode) } } // MARK: Codable enum CodingKeys: String, CodingKey { case firstName = "first_name" case lastName = "last_name" case streetAddress1 = "street_address1" case streetAddress2 = "street_address2" case streetAddress3 = "street_address3" case streetAddress4 = "street_address4" case locality case region case postalCode = "postal_code" case countryCode = "country_code" case country case company case phone case email } required public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) firstName = try values.decode(String.self, forKey: .firstName) lastName = try values.decode(String.self, forKey: .lastName) streetAddress1 = try values.decode(String.self, forKey: .streetAddress1) locality = try values.decode(String.self, forKey: .locality) region = try values.decode(String.self, forKey: .region) postalCode = try values.decode(String.self, forKey: .postalCode) countryCode = try values.decode(String.self, forKey: .countryCode) country = try values.decode(String.self, forKey: .country) if let value = try? values.decode(String.self, forKey: .company) { company = value } if let value = try? values.decode(String.self, forKey: .phone) { phone = value } if let value = try? values.decode(String.self, forKey: .email) { email = value } if let value = try? values.decode(String.self, forKey: .streetAddress2) { streetAddress2 = value } if let value = try? values.decode(String.self, forKey: .streetAddress3) { streetAddress3 = value } if let value = try? values.decode(String.self, forKey: .streetAddress4) { streetAddress4 = value } } } // MARK: Encode extension BLTShippingAddress: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(firstName, forKey: .firstName) try container.encode(lastName, forKey: .lastName) try container.encode(streetAddress1, forKey: .streetAddress1) try container.encode(locality, forKey: .locality) try container.encode(region, forKey: .region) try container.encode(postalCode, forKey: .postalCode) try container.encode(countryCode, forKey: .countryCode) try container.encode(country, forKey: .country) if let value = company { try container.encode(value, forKey: .company) } if let value = phone { try container.encode(value, forKey: .phone) } if let value = email { try container.encode(value, forKey: .email) } if let value = streetAddress2 { try container.encode(value, forKey: .streetAddress2) } if let value = streetAddress3 { try container.encode(value, forKey: .streetAddress3) } if let value = streetAddress4 { try container.encode(value, forKey: .streetAddress4) } } }
57644556860454580c3db5ab2f60842f
31.179104
88
0.618429
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureAuthentication/Sources/FeatureAuthenticationData/WalletAuthentication/Repositories/WalletRecovery/AccountRecoveryRepository.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import Errors import FeatureAuthenticationDomain final class AccountRecoveryRepository: AccountRecoveryRepositoryAPI { // MARK: - Properties private let userCreationClient: NabuUserCreationClientAPI private let userResetClient: NabuResetUserClientAPI private let userRecoveryClient: NabuUserRecoveryClientAPI // MARK: - Setup init( userCreationClient: NabuUserCreationClientAPI = resolve(), userResetClient: NabuResetUserClientAPI = resolve(), userRecoveryClient: NabuUserRecoveryClientAPI = resolve() ) { self.userCreationClient = userCreationClient self.userResetClient = userResetClient self.userRecoveryClient = userRecoveryClient } // MARK: - API func createOrGetNabuUser( jwtToken: String ) -> AnyPublisher<(NabuOfflineToken, jwtToken: String), AccountRecoveryServiceError> { userCreationClient .createUser(for: jwtToken) .map(NabuOfflineToken.init) .map { ($0, jwtToken) } .mapError(AccountRecoveryServiceError.network) .eraseToAnyPublisher() } func resetUser( offlineToken: NabuOfflineToken, jwtToken: String ) -> AnyPublisher<Void, AccountRecoveryServiceError> { let response = NabuOfflineTokenResponse(from: offlineToken) return userResetClient .resetUser(offlineToken: response, jwt: jwtToken) .mapError(AccountRecoveryServiceError.network) .eraseToAnyPublisher() } func recoverUser( jwtToken: String, userId: String, recoveryToken: String ) -> AnyPublisher<NabuOfflineToken, AccountRecoveryServiceError> { userRecoveryClient .recoverUser( jwt: jwtToken, userId: userId, recoveryToken: recoveryToken ) .map(NabuOfflineToken.init) .mapError(AccountRecoveryServiceError.network) .eraseToAnyPublisher() } }
21034b80b8be35136a93d1843e41719f
30.641791
90
0.666981
false
false
false
false
argent-os/argent-ios
refs/heads/master
app-ios/ProfileMenuViewController.swift
mit
1
// // ProfileMenuViewController.swift // argent-ios // // Created by Sinan Ulkuatam on 3/19/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import UIKit import Foundation import SafariServices import CWStatusBarNotification import StoreKit import Crashlytics import Whisper import MZFormSheetPresentationController import KeychainSwift class ProfileMenuViewController: UITableViewController, SKStoreProductViewControllerDelegate { @IBOutlet weak var shareCell: UITableViewCell! @IBOutlet weak var rateCell: UITableViewCell! @IBOutlet weak var inviteCell: UITableViewCell! private var menuSegmentBar: UISegmentedControl = UISegmentedControl(items: ["Account", "More"]) private var shouldShowSection1: Bool? = true private var shouldShowSection2: Bool? = false private var maskHeaderView = UIView() private var verifiedLabel = UILabel() private var verifiedImage = UIImageView() private var verifiedButton:UIButton = UIButton() private var userImageView: UIImageView = UIImageView() private var scrollView: UIScrollView! private var notification = CWStatusBarNotification() private var locationLabel = UILabel() private let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 40, width: UIScreen.mainScreen().bounds.size.width, height: 50)) private let refreshControlView = UIRefreshControl() private var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) override func viewDidLoad() { super.viewDidLoad() configureView() configureHeader() validateAccount() } func validateAccount() { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let app: UIApplication = UIApplication.sharedApplication() let statusBarHeight: CGFloat = app.statusBarFrame.size.height let statusBarView: UIView = UIView(frame: CGRectMake(0, -statusBarHeight, UIScreen.mainScreen().bounds.size.width, statusBarHeight)) statusBarView.backgroundColor = UIColor.clearColor() self.navigationController?.navigationBar.addSubview(statusBarView) self.verifiedLabel.contentMode = .Center self.verifiedLabel.textAlignment = .Center self.verifiedLabel.textColor = UIColor.darkBlue() self.verifiedLabel.font = UIFont(name: "SFUIText-Regular", size: 14) self.verifiedLabel.layer.cornerRadius = 5 self.verifiedLabel.layer.borderColor = UIColor.darkBlue().CGColor self.verifiedLabel.layer.borderWidth = 0 let verifyTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.showTutorialModal(_:))) self.verifiedLabel.addGestureRecognizer(verifyTap) self.verifiedLabel.userInteractionEnabled = true self.view.addSubview(self.verifiedLabel) self.view.bringSubviewToFront(self.verifiedLabel) Account.getStripeAccount { (acct, err) in let fields = acct?.verification_fields_needed let _ = fields.map { (unwrappedOptionalArray) -> Void in // if array has values if !unwrappedOptionalArray.isEmpty { self.verifiedLabel.text = "How to Verify?" self.verifiedLabel.textColor = UIColor.iosBlue() self.verifiedLabel.frame = CGRect(x: 110, y: 82, width: screenWidth-220, height: 30) self.locationLabel.textAlignment = NSTextAlignment.Center var fields_required: [String] = unwrappedOptionalArray if let indexOfExternalAccount = fields_required.indexOf("external_account") { fields_required[indexOfExternalAccount] = "Bank" } if let indexOfFirstName = fields_required.indexOf("legal_entity.first_name") { fields_required[indexOfFirstName] = "First Name" } if let indexOfLastName = fields_required.indexOf("legal_entity.last_name") { fields_required[indexOfLastName] = "Last Name" } if let indexOfBusinessName = fields_required.indexOf("legal_entity.business_name") { fields_required[indexOfBusinessName] = "Business Name" } if let indexOfAddressCity = fields_required.indexOf("legal_entity.address.city") { fields_required[indexOfAddressCity] = "City" } if let indexOfAddressState = fields_required.indexOf("legal_entity.address.state") { fields_required[indexOfAddressState] = "State" } if let indexOfAddressZip = fields_required.indexOf("legal_entity.address.postal_code") { fields_required[indexOfAddressZip] = "ZIP" } if let indexOfAddressLine1 = fields_required.indexOf("legal_entity.address.line1") { fields_required[indexOfAddressLine1] = "Address" } if let indexOfPIN = fields_required.indexOf("legal_entity.personal_id_number") { fields_required[indexOfPIN] = "SSN or Personal ID Number" } if let indexOfSSNLast4 = fields_required.indexOf("legal_entity.ssn_last_4") { fields_required[indexOfSSNLast4] = "SSN Information" } if let indexOfEIN = fields_required.indexOf("legal_entity.business_tax_id") { fields_required[indexOfEIN] = "Business Tax ID (EIN)" } if let indexOfVerificationDocument = fields_required.indexOf("legal_entity.verification.document") { fields_required[indexOfVerificationDocument] = "Verification Document" } let fields_list = fields_required.dropLast().reduce("") { $0 + $1 + ", " } + fields_required.last! // regex to replace legal.entity in the future var announcement = Announcement(title: "Identity verification incomplete", subtitle: fields_list, image: UIImage(named: "IconAlertCalm")) announcement.duration = 7 // Shout(announcement, to: self) let _ = Timeout(10) { if acct?.transfers_enabled == false { //showGlobalNotification("Transfers disabled until more account information is provided", duration: 10.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.oceanBlue()) } } } else if let disabled_reason = acct?.verification_disabled_reason where acct?.verification_disabled_reason != "" { self.locationLabel.removeFromSuperview() self.verifiedLabel.layer.borderWidth = 0 self.verifiedLabel.frame = CGRect(x: 30, y: 100, width: screenWidth-60, height: 30) self.view.addSubview(self.verifiedLabel) if disabled_reason == "rejected.fraud" { self.verifiedButton.removeFromSuperview() self.verifiedLabel.text = "Account rejected: Fraud detected" } else if disabled_reason == "rejected.terms_of_service" { self.verifiedButton.removeFromSuperview() self.verifiedLabel.text = "Account rejected: Terms of Service" } else if disabled_reason == "rejected.other" { self.verifiedButton.removeFromSuperview() self.verifiedLabel.text = "Account rejected | Reason: Other" } else if disabled_reason == "other" { self.verifiedButton.removeFromSuperview() self.verifiedLabel.text = "System maintenance, transfers disabled" } } } } } func checkIfVerified(completionHandler: (Bool, NSError?) -> ()){ Account.getStripeAccount { (acct, err) in let fields = acct?.verification_fields_needed let _ = fields.map { (unwrappedOptionalArray) -> Void in // if array has values if !unwrappedOptionalArray.isEmpty { // print("checking if empty... false") completionHandler(false, nil) } else { // print("checking if empty... true") completionHandler(true, nil) } } } } func refresh(sender:AnyObject) { self.configureView() self.validateAccount() self.loadProfile() self.configureHeader() // self.tableView.tableHeaderView = ParallaxHeaderView.init(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 220)); let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 180)) self.view.sendSubviewToBack(self.tableView.tableHeaderView!) let _ = Timeout(0.3) { self.refreshControlView.endRefreshing() } } func configureView() { self.view.backgroundColor = UIColor.clearColor() let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height self.view.bringSubviewToFront(tableView) // self.tableView.tableHeaderView = ParallaxHeaderView.init(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 220)); self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 180)) refreshControlView.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControlView.addTarget(self, action: #selector(ProfileMenuViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged) self.tableView.addSubview(refreshControlView) // not required when using UITableViewController configureHeader() loadProfile() // Add action to share cell to return to activity menu shareCell.targetForAction(Selector("share:"), withSender: self) // Add action to rate cell to return to activity menu let rateGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.openStoreProductWithiTunesItemIdentifier(_:))) rateCell.addGestureRecognizer(rateGesture) // Add action to invite user let inviteGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.inviteUser(_:))) inviteCell.addGestureRecognizer(inviteGesture) maskHeaderView.frame = CGRect(x: 0, y: 90, width: screenWidth, height: 60) maskHeaderView.backgroundColor = UIColor.whiteColor() self.view.addSubview(maskHeaderView) menuSegmentBar.addTarget(self, action: #selector(self.toggleSegment(_:)), forControlEvents: .ValueChanged) menuSegmentBar.selectedSegmentIndex = 0 menuSegmentBar.frame = CGRect(x: 30, y: 120, width: screenWidth-60, height: 30) self.view.addSubview(menuSegmentBar) self.view.bringSubviewToFront(menuSegmentBar) } func inviteUser(sender: AnyObject) { self.presentViewController(AddCustomerViewController(), animated: true, completion: nil) } func openStoreProductWithiTunesItemIdentifier(sender: AnyObject) { showGlobalNotification("Loading App Store", duration: 1, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.NavigationBarNotification, color: UIColor.pastelBlue()) let storeViewController = SKStoreProductViewController() storeViewController.delegate = self let parameters = [ SKStoreProductParameterITunesItemIdentifier : APP_ID] storeViewController.loadProductWithParameters(parameters) { [weak self] (loaded, error) -> Void in if loaded { // Parent class of self is UIViewController self?.presentViewController(storeViewController, animated: true, completion: nil) } } } func productViewControllerDidFinish(viewController: SKStoreProductViewController) { viewController.dismissViewControllerAnimated(true, completion: nil) } func configureHeader() { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let attachment: NSTextAttachment = NSTextAttachment() attachment.image = UIImage(named: "IconPinWhiteTiny") let attachmentString: NSAttributedString = NSAttributedString(attachment: attachment) Account.getStripeAccount { (acct, err) in self.checkIfVerified({ (bool, err) in if bool == true { // the account does not require information, display location if let address_city = acct?.address_city where address_city != "", let address_country = acct?.address_country { let locationStr = adjustAttributedStringNoLineSpacing(address_city.uppercaseString + ", " + address_country.uppercaseString, spacing: 0.5, fontName: "SFUIText-Regular", fontSize: 11, fontColor: UIColor.darkBlue()) // locationStr.appendAttributedString(attachmentString) self.locationLabel.attributedText = locationStr } else { let locationStr: NSMutableAttributedString = NSMutableAttributedString(string: "") locationStr.appendAttributedString(attachmentString) self.locationLabel.attributedText = locationStr } self.view.addSubview(self.locationLabel) } else { // profile information is required, show tutorial button } }) } self.locationLabel.frame = CGRectMake(0, 62, screenWidth, 70) self.locationLabel.textAlignment = NSTextAlignment.Center self.locationLabel.font = UIFont(name: "SFUIText-Regular", size: 12) self.locationLabel.numberOfLines = 0 self.locationLabel.textColor = UIColor.darkBlue() } // Sets up nav func configureNav(user: User) { let navItem = UINavigationItem() // TODO: do a check for first name, and business name let f_name = user.first_name let l_name = user.last_name let u_name = user.username let b_name = user.business_name if b_name != "" { navItem.title = b_name } else if f_name != "" { navItem.title = f_name + " " + l_name } else { navItem.title = u_name } self.navBar.titleTextAttributes = [ NSForegroundColorAttributeName : UIColor.darkBlue(), NSFontAttributeName : UIFont(name: "SFUIText-Regular", size: 17.0)! ] self.navBar.setItems([navItem], animated: false) let _ = Timeout(0.1) { self.view.addSubview(self.navBar) } } //Changing Status Bar override func prefersStatusBarHidden() -> Bool { return false } //Changing Status Bar override func preferredStatusBarStyle() -> UIStatusBarStyle { return .Default } // Handles share and logout action controller override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if(tableView.cellForRowAtIndexPath(indexPath)!.tag == 865) { // share action controller let activityViewController = UIActivityViewController( activityItems: ["Check out this app! https://www.argentapp.com/home" as NSString], applicationActivities: nil) if activityViewController.userActivity?.activityType == UIActivityTypePostToFacebook { let uuid = NSUUID().UUIDString Answers.logShareWithMethod("FaceBook", contentName: "User sharing to Facebook", contentType: "facebook", contentId: uuid, customAttributes: nil) } else if activityViewController.userActivity?.activityType == UIActivityTypePostToTwitter { let uuid = NSUUID().UUIDString Answers.logShareWithMethod("Twitter", contentName: "User sharing to Twitter", contentType: "twitter", contentId: uuid, customAttributes: nil) } else if activityViewController.userActivity?.activityType == UIActivityTypeMessage { let uuid = NSUUID().UUIDString Answers.logShareWithMethod("Message", contentName: "User sharing through message", contentType: "message", contentId: uuid, customAttributes: nil) } else if activityViewController.userActivity?.activityType == UIActivityTypeMail { let uuid = NSUUID().UUIDString Answers.logShareWithMethod("Mail", contentName: "User sharing through mail", contentType: "mail", contentId: uuid, customAttributes: nil) } activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList] presentViewController(activityViewController, animated: true, completion: nil) activityViewController.popoverPresentationController?.sourceView = UIView() activityViewController.popoverPresentationController?.sourceRect = UIView().bounds } if(tableView.cellForRowAtIndexPath(indexPath)!.tag == 534) { // 1 let optionMenu = UIAlertController(title: nil, message: "Are you sure you want to logout?", preferredStyle: .ActionSheet) optionMenu.popoverPresentationController?.sourceView = UIView() optionMenu.popoverPresentationController?.sourceRect = UIView().bounds // 2 let logoutAction = UIAlertAction(title: "Logout", style: .Destructive, handler: { (alert: UIAlertAction!) -> Void in NSUserDefaults.standardUserDefaults().setValue("", forKey: "userAccessToken") NSUserDefaults.standardUserDefaults().synchronize(); Answers.logCustomEventWithName("User logged out from profile", customAttributes: [:]) // go to login view // let sb = UIStoryboard(name: "Main", bundle: nil) // let loginVC = sb.instantiateViewControllerWithIdentifier("LoginViewController") // loginVC.modalTransitionStyle = .CrossDissolve // let root = UIApplication.sharedApplication().keyWindow?.rootViewController // root!.presentViewController(loginVC, animated: true, completion: { () -> Void in }) self.performSegueWithIdentifier("loginView", sender: self) }) // let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in }) // 4 optionMenu.addAction(logoutAction) optionMenu.addAction(cancelAction) // 5 self.presentViewController(optionMenu, animated: true, completion: nil) } } // Loads profile and sets picture func loadProfile() { let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(ProfileMenuViewController.goToEditPicture(_:))) userImageView.frame = CGRectMake(screenWidth / 2, -64, 60, 60) userImageView.layer.cornerRadius = 30 userImageView.userInteractionEnabled = true userImageView.addGestureRecognizer(tapGestureRecognizer) userImageView.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin] // centers user profile image userImageView.center = CGPointMake(self.view.bounds.size.width / 2, 10) userImageView.backgroundColor = UIColor.groupTableViewBackgroundColor() userImageView.layer.masksToBounds = true userImageView.clipsToBounds = true userImageView.layer.borderWidth = 3 userImageView.layer.borderColor = UIColor(rgba: "#fff").colorWithAlphaComponent(0.3).CGColor User.getProfile({ (user, error) in let acv = UIActivityIndicatorView(activityIndicatorStyle: .White) acv.frame = CGRect(x: 0, y: 0, width: 30, height: 30) acv.startAnimating() self.activityIndicator.center = self.userImageView.center self.userImageView.addSubview(acv) addActivityIndicatorView(acv, view: self.userImageView, color: .White) self.userImageView.bringSubviewToFront(acv) if error != nil { let alert = UIAlertController(title: "Error", message: "Could not load profile \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } self.configureNav(user!) if user!.picture != "" { let img = UIImage(data: NSData(contentsOfURL: NSURL(string: (user!.picture))!)!)! self.userImageView.image = img addSubviewWithFade(self.userImageView, parentView: self, duration: 0.8) } else { let img = UIImage(named: "IconAnonymous") self.userImageView.image = img addSubviewWithFade(self.userImageView, parentView: self, duration: 0.8) } }) } // Opens edit picture func goToEditPicture(sender: AnyObject) { self.performSegueWithIdentifier("profilePictureView", sender: sender) } // Opens edit picture func goToEdit(sender: AnyObject) { self.performSegueWithIdentifier("editProfileView", sender: sender) } } extension ProfileMenuViewController { // MARK: Tutorial modal func showTutorialModal(sender: AnyObject) { let navigationController = self.storyboard!.instantiateViewControllerWithIdentifier("accountVerificationModalNavigationController") as! UINavigationController let formSheetController = MZFormSheetPresentationViewController(contentViewController: navigationController) // Initialize and style the terms and conditions modal formSheetController.presentationController?.contentViewSize = CGSizeMake(300, UIScreen.mainScreen().bounds.height-130) formSheetController.presentationController?.shouldUseMotionEffect = true formSheetController.presentationController?.containerView?.backgroundColor = UIColor.blackColor() formSheetController.presentationController?.containerView?.sizeToFit() formSheetController.presentationController?.shouldApplyBackgroundBlurEffect = true formSheetController.presentationController?.blurEffectStyle = UIBlurEffectStyle.Dark formSheetController.presentationController?.shouldDismissOnBackgroundViewTap = true formSheetController.presentationController?.movementActionWhenKeyboardAppears = MZFormSheetActionWhenKeyboardAppears.CenterVertically formSheetController.presentationController?.shouldCenterVertically = true formSheetController.presentationController?.shouldCenterHorizontally = true formSheetController.contentViewControllerTransitionStyle = MZFormSheetPresentationTransitionStyle.SlideFromBottom formSheetController.contentViewCornerRadius = 15 formSheetController.allowDismissByPanningPresentedView = true formSheetController.interactivePanGestureDismissalDirection = .All; // Blur will be applied to all MZFormSheetPresentationControllers by default MZFormSheetPresentationController.appearance().shouldApplyBackgroundBlurEffect = true let presentedViewController = navigationController.viewControllers.first as! AccountVerificationTutorialViewController // keep passing along user data to modal presentedViewController.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem() presentedViewController.navigationItem.leftItemsSupplementBackButton = true // Be sure to update current module on storyboard self.presentViewController(formSheetController, animated: true, completion: nil) } } extension ProfileMenuViewController { func toggleSegment(sender: UISegmentedControl) { self.tableView.beginUpdates() // change boolean conditions for what to show/hide if menuSegmentBar.selectedSegmentIndex == 0 { self.view.bringSubviewToFront(menuSegmentBar) self.view.bringSubviewToFront(verifiedLabel) self.shouldShowSection1 = true self.shouldShowSection2 = false } else if menuSegmentBar.selectedSegmentIndex == 1 { self.view.bringSubviewToFront(menuSegmentBar) self.view.bringSubviewToFront(verifiedLabel) self.shouldShowSection1 = false self.shouldShowSection2 = true } self.tableView.endUpdates() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { if self.shouldShowSection1 == true { return 44.0 } else { return 0.0 } } else if indexPath.section == 1 { if self.shouldShowSection2 == true { return 44.0 } else { return 0.0 } } else { return 44.0 } } } extension ProfileMenuViewController { override func scrollViewDidScroll(scrollView: UIScrollView) { if self.tableView.contentOffset.y > 90 { self.view.bringSubviewToFront(menuSegmentBar) self.menuSegmentBar.frame.origin.y = self.tableView.contentOffset.y+30 self.maskHeaderView.frame.origin.y = self.tableView.contentOffset.y+20 } } }
3dc60beb65ea3a4f2567ce71572987ec
48.691358
310
0.619556
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/NCNPCPickerGroupsViewController.swift
lgpl-2.1
2
// // NCNPCPickerGroupsViewController.swift // Neocom // // Created by Artem Shimanski on 21.07.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import CoreData import EVEAPI import Futures class NCNPCPickerGroupsViewController: NCTreeViewController, NCSearchableViewController { var parentGroup: NCDBNpcGroup? override func viewDidLoad() { super.viewDidLoad() tableView.register([Prototype.NCHeaderTableViewCell.default, Prototype.NCDefaultTableViewCell.compact]) setupSearchController(searchResultsController: self.storyboard!.instantiateViewController(withIdentifier: "NCNPCPickerTypesViewController")) title = parentGroup?.npcGroupName ?? NSLocalizedString("NPC", comment: "") } override func didReceiveMemoryWarning() { if !isViewLoaded || view.window == nil { treeController?.content = nil } } override func content() -> Future<TreeNode?> { let request = NSFetchRequest<NCDBNpcGroup>(entityName: "NpcGroup") request.sortDescriptors = [NSSortDescriptor(key: "npcGroupName", ascending: true)] if let parent = parentGroup { request.predicate = NSPredicate(format: "parentNpcGroup == %@", parent) } else { request.predicate = NSPredicate(format: "parentNpcGroup == NULL") } let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: NCDatabase.sharedDatabase!.viewContext, sectionNameKeyPath: nil, cacheName: nil) try? results.performFetch() return .init(FetchedResultsNode(resultsController: results, sectionNode: nil, objectNode: NCNPCGroupRow.self)) } //MARK: - TreeControllerDelegate override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) { super.treeController(treeController, didSelectCellWithNode: node) guard let row = node as? NCNPCGroupRow else {return} if row.object.group != nil { Router.Database.NPCPickerTypes(npcGroup: row.object).perform(source: self, sender: treeController.cell(for: node)) } else { Router.Database.NPCPickerGroups(parentGroup: row.object).perform(source: self, sender: treeController.cell(for: node)) } } //MARK: UISearchResultsUpdating var searchController: UISearchController? func updateSearchResults(for searchController: UISearchController) { let predicate: NSPredicate guard let controller = searchController.searchResultsController as? NCNPCPickerTypesViewController else {return} if let text = searchController.searchBar.text, text.count > 2 { predicate = NSPredicate(format: "group.category.categoryID == 11 AND typeName CONTAINS[C] %@", text) } else { predicate = NSPredicate(value: false) } controller.predicate = predicate controller.reloadData() } }
213495c2985ef793bb7220a3d0424eba
32.240964
168
0.757521
false
false
false
false
danwatco/mega-liker
refs/heads/master
MegaLiker/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // MegaLiker // // Created by Dan Watkinson on 27/11/2015. // Copyright © 2015 Dan Watkinson. All rights reserved. // import UIKit class SettingsViewController: UIViewController { var clientID = "[INSTAGRAM_CLIENT_ID]" var defaults = NSUserDefaults.standardUserDefaults() @IBOutlet weak var statusLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { let accessCode = defaults.objectForKey("accessCode") if(accessCode != nil){ statusLabel.text = "You are now signed in." } } @IBAction func signInBtn(sender: UIButton) { let userScope = "&scope=likes" let instagramURL = "https://instagram.com/oauth/authorize/?client_id=" + clientID + "&redirect_uri=megaliker://callback&response_type=token" + userScope UIApplication.sharedApplication().openURL(NSURL(string: instagramURL)!) } @IBAction func signOutBtn(sender: UIButton) { defaults.removeObjectForKey("accessCode") statusLabel.textColor = UIColor.redColor() statusLabel.text = "You are now signed out." let navController:CustomNavigationController = self.parentViewController as! CustomNavigationController let viewController:ViewController = navController.viewControllers.first as! ViewController viewController.userStatus = false viewController.accessCode = nil } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0d313230912efdd6ce04e547934067de
32.587302
160
0.681474
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/ContextMenu/RoomContextPreviewViewController.swift
apache-2.0
1
// File created from ScreenTemplate // $ createScreen.sh Spaces/SpaceRoomList/SpaceChildRoomDetail ShowSpaceChildRoomDetail /* 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 UIKit import MatrixSDK /// `RoomContextPreviewViewController` is used to dsplay room preview data within a `UIContextMenuContentPreviewProvider` final class RoomContextPreviewViewController: UIViewController { // MARK: - Constants private enum Constants { static let popoverWidth: CGFloat = 300 } // MARK: Outlets @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var avatarView: RoomAvatarView! @IBOutlet private weak var spaceAvatarView: SpaceAvatarView! @IBOutlet private weak var userIconView: UIImageView! @IBOutlet private weak var membersLabel: UILabel! @IBOutlet private weak var roomsIconView: UIImageView! @IBOutlet private weak var roomsLabel: UILabel! @IBOutlet private weak var topicLabel: UILabel! @IBOutlet private weak var topicLabelBottomMargin: NSLayoutConstraint! @IBOutlet private weak var spaceTagView: UIView! @IBOutlet private weak var spaceTagLabel: UILabel! @IBOutlet private weak var stackView: UIStackView! @IBOutlet private weak var inviteHeaderView: UIView! @IBOutlet private weak var inviterAvatarView: UserAvatarView! @IBOutlet private weak var inviteTitleLabel: UILabel! @IBOutlet private weak var inviteDetailLabel: UILabel! @IBOutlet private weak var inviteSeparatorView: UIView! // MARK: Private private var theme: Theme! private var viewModel: RoomContextPreviewViewModelProtocol! private var mediaManager: MXMediaManager? // MARK: - Setup class func instantiate(with viewModel: RoomContextPreviewViewModelProtocol, mediaManager: MXMediaManager?) -> RoomContextPreviewViewController { let viewController = StoryboardScene.RoomContextPreviewViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.mediaManager = mediaManager viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. viewModel.viewDelegate = self setupView() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.process(viewAction: .loadData) } override var preferredContentSize: CGSize { get { return CGSize(width: Constants.popoverWidth, height: self.intrisicHeight(with: Constants.popoverWidth)) } set { super.preferredContentSize = newValue } } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleLabel.textColor = theme.textPrimaryColor self.titleLabel.font = theme.fonts.title3SB self.membersLabel.font = theme.fonts.caption1 self.membersLabel.textColor = theme.colors.tertiaryContent self.topicLabel.font = theme.fonts.caption1 self.topicLabel.textColor = theme.colors.tertiaryContent self.userIconView.tintColor = theme.colors.tertiaryContent self.roomsIconView.tintColor = theme.colors.tertiaryContent self.roomsLabel.font = theme.fonts.caption1 self.roomsLabel.textColor = theme.colors.tertiaryContent self.spaceTagView.backgroundColor = theme.colors.quinaryContent self.spaceTagLabel.font = theme.fonts.caption1 self.spaceTagLabel.textColor = theme.colors.tertiaryContent self.inviteTitleLabel.textColor = theme.colors.tertiaryContent self.inviteTitleLabel.font = theme.fonts.calloutSB self.inviteDetailLabel.textColor = theme.colors.tertiaryContent self.inviteDetailLabel.font = theme.fonts.caption1 self.inviteSeparatorView.backgroundColor = theme.colors.quinaryContent self.inviterAvatarView.alpha = 0.7 } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func renderLoaded(with parameters: RoomContextPreviewLoadedParameters) { self.titleLabel.text = parameters.displayName self.spaceTagView.isHidden = parameters.roomType != .space self.avatarView.isHidden = parameters.roomType == .space self.spaceAvatarView.isHidden = parameters.roomType != .space let avatarViewData = AvatarViewData(matrixItemId: parameters.roomId, displayName: parameters.displayName, avatarUrl: parameters.avatarUrl, mediaManager: mediaManager, fallbackImage: .matrixItem(parameters.roomId, parameters.displayName)) if !self.avatarView.isHidden { self.avatarView.fill(with: avatarViewData) } if !self.spaceAvatarView.isHidden { self.spaceAvatarView.fill(with: avatarViewData) } if parameters.membership != .invite { self.stackView.removeArrangedSubview(self.inviteHeaderView) self.inviteHeaderView.isHidden = true } self.membersLabel.text = parameters.membersCount == 1 ? VectorL10n.roomTitleOneMember : VectorL10n.roomTitleMembers("\(parameters.membersCount)") if let inviterId = parameters.inviterId { if let inviter = parameters.inviter { let avatarData = AvatarViewData(matrixItemId: inviterId, displayName: inviter.displayname, avatarUrl: inviter.avatarUrl, mediaManager: mediaManager, fallbackImage: .matrixItem(inviterId, inviter.displayname)) self.inviterAvatarView.fill(with: avatarData) if let inviterName = inviter.displayname { self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterName) self.inviteDetailLabel.text = inviterId } else { self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterId) } } else { self.inviteTitleLabel.text = VectorL10n.noticeRoomInviteYou(inviterId) } } self.topicLabel.text = parameters.topic topicLabelBottomMargin.constant = self.topicLabel.text.isEmptyOrNil ? 0 : 16 self.roomsIconView.isHidden = parameters.roomType != .space self.roomsLabel.isHidden = parameters.roomType != .space self.view.layoutIfNeeded() } private func setupView() { self.spaceTagView.layer.masksToBounds = true self.spaceTagView.layer.cornerRadius = 2 self.spaceTagLabel.text = VectorL10n.spaceTag } private func intrisicHeight(with width: CGFloat) -> CGFloat { if self.topicLabel.text.isEmptyOrNil { return self.topicLabel.frame.minY } let topicHeight = self.topicLabel.sizeThatFits(CGSize(width: width - self.topicLabel.frame.minX * 2, height: 0)).height return self.topicLabel.frame.minY + topicHeight + 16 } } // MARK: - RoomContextPreviewViewModelViewDelegate extension RoomContextPreviewViewController: RoomContextPreviewViewModelViewDelegate { func roomContextPreviewViewModel(_ viewModel: RoomContextPreviewViewModelProtocol, didUpdateViewState viewSate: RoomContextPreviewViewState) { switch viewSate { case .loaded(let parameters): self.renderLoaded(with: parameters) } } }
c386e7ef56e9edb214c2a72bc4dcc680
40.031963
153
0.670376
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/Serialization/serialize_attr.swift
apache-2.0
2
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -parse-as-library -o %t %s // RUN: llvm-bcanalyzer %t/serialize_attr.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER // RUN: %target-sil-opt -enable-sil-verify-all -disable-sil-linking %t/serialize_attr.swiftmodule | %FileCheck %s // BCANALYZER-NOT: UnknownCode // @_semantics // ----------------------------------------------------------------------------- //CHECK-DAG: @_semantics("crazy") func foo() @_inlineable @_versioned @_semantics("crazy") func foo() -> Int { return 5} // @_specialize // ----------------------------------------------------------------------------- // These lines should be contiguous. // CHECK-DAG: @_specialize(exported: false, kind: full, where T == Int, U == Float) // CHECK-DAG: func specializeThis<T, U>(_ t: T, u: U) @_inlineable @_versioned @_specialize(where T == Int, U == Float) func specializeThis<T, U>(_ t: T, u: U) {} public protocol PP { associatedtype PElt } public protocol QQ { associatedtype QElt } public struct RR : PP { public typealias PElt = Float } public struct SS : QQ { public typealias QElt = Int } public struct GG<T : PP> {} // These three lines should be contiguous, however, there is no way to // sequence FileCheck directives while using CHECK-DAG as the outer // label, and the declaration order is unpredictable. // // CHECK-DAG: class CC<T> where T : PP { // CHECK-DAG: @_specialize(exported: false, kind: full, where T == RR, U == SS) // CHECK-DAG: @inline(never) func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ public class CC<T : PP> { @_inlineable @_versioned @inline(never) @_specialize(where T==RR, U==SS) func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-DAG: sil [serialized] [_specialize exported: false, kind: full, where T == Int, U == Float] @_T014serialize_attr14specializeThisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () { // CHECK-DAG: sil [serialized] [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T014serialize_attr2CCC3fooqd___AA2GGVyxGtqd___AG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
0478ea7b257b8b4df210ed8eb755a651
35.370968
283
0.608869
false
false
false
false
nuclearace/SwiftDiscord
refs/heads/master
Sources/SwiftDiscord/Rest/DiscordEndpointGateway.swift
mit
1
// The MIT License (MIT) // Copyright (c) 2016 Erik Little // 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 Dispatch struct DiscordEndpointGateway { static var gatewayURL = getURL() private static var gatewaySemaphore = DispatchSemaphore(value: 0) static func getURL() -> String { // Linux's urlsession is busted #if os(Linux) return "wss://gateway.discord.gg" #else var request = URLRequest(url: URL(string: "https://discordapp.com/api/gateway")!) request.httpMethod = "GET" var url = "wss://gateway.discord.gg" URLSession.shared.dataTask(with: request) {data, response, error in guard let data = data, let stringData = String(data: data, encoding: .utf8), case let .object(info)? = JSON.decodeJSON(stringData), let gateway = info["url"] as? String else { gatewaySemaphore.signal() return } url = gateway gatewaySemaphore.signal() }.resume() gatewaySemaphore.wait() return url #endif } }
65910564b19d3dd06ef164f7e9cc14a8
39
119
0.681481
false
false
false
false
rudkx/swift
refs/heads/main
test/Interop/Cxx/class/inheritance/type-aliases-module-interface.swift
apache-2.0
1
// RUN: %target-swift-ide-test -print-module -module-to-print=TypeAliases -I %S/Inputs -source-filename=x -enable-cxx-interop | %FileCheck %s // CHECK: struct Base { // CHECK-NEXT: init() // CHECK-NEXT: struct Struct { // CHECK-NEXT: init() // CHECK-NEXT: } // CHECK-NEXT: typealias T = Int32 // CHECK-NEXT: typealias U = Base.Struct // CHECK-NEXT: } // CHECK-NEXT: struct Derived { // CHECK-NEXT: init() // CHECK-NEXT: typealias Struct = Base.Struct.Type // CHECK-NEXT: typealias T = Int32 // CHECK-NEXT: typealias U = Base.Struct // CHECK-NEXT: }
44d171780a403af808e84aa62121fb1c
33
141
0.645329
false
true
false
false
lp1994428/TextKitch
refs/heads/master
TextKitchen/TextKitchen/classes/Common/MainTabBarViewController.swift
mit
1
// // MainTabBarViewController.swift // TextKitchen // // Created by 罗平 on 16/10/21. // Copyright © 2016年 罗平. All rights reserved. // import UIKit import SnapKit class MainTabBarViewController: UITabBarController { var bgView:UIView? override func viewDidLoad() { super.viewDidLoad() tabBar.hidden = true createViewController() // myTabBar() } func createViewController(){ //10.24从文件里面读取数据 let path = NSBundle.mainBundle().pathForResource("Controllers", ofType: "json") let data = NSData(contentsOfFile: path!) //视图控制器名字的数组 var ctrNameArray = [String]() var images = [String]() var titles = [String]() do { // 可能抛异常 let array = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) if array.isKindOfClass(NSArray){ let tmp = array as![[String:String]] for dic in tmp{ let name = dic["ctrname"] let imageName = dic["image"] let title = dic["title"] ctrNameArray.append(name!) images.append(imageName!) titles.append(title!) } } }catch(let error){ //捕获错误信息 print(error) } // 如果获取的数组为空 if ctrNameArray.count == 0{ ctrNameArray = ["TextKitchen.IngredientsViewController","TextKitchen.CommunityViewController","TextKitchen.MallViewController","TextKitchen.FoodViewController","TextKitchen.ProfileViewController"] titles = ["食材","社区","商城","食客","我的"] images = ["home","community","shop","shike","mine"] } var ctrlArray = [UINavigationController]() for i in 0..<ctrNameArray.count{ let ctrl = NSClassFromString(ctrNameArray[i]) as! UIViewController.Type let vc = ctrl.init() let navCtrl = UINavigationController(rootViewController: vc) ctrlArray.append(navCtrl) } viewControllers = ctrlArray myTabBar(images, titles: titles) } func myTabBar(imagesName:[String],titles:[String]) { bgView = UIView.createView() bgView?.backgroundColor = UIColor.whiteColor() bgView?.layer.borderColor = UIColor.orangeColor().CGColor bgView?.layer.borderWidth = 1 view.addSubview(bgView!) bgView?.snp_makeConstraints(closure: { [weak self](make) in make.left.right.bottom.equalTo(self!.view) make.height.equalTo(49) }) let width = lpScreenWd/CGFloat(imagesName.count) for i in 0..<imagesName.count{ let btn = UIButton.createButton(nil, bgImageName: "\(imagesName[i])_normal", highLightImageName: "\(imagesName[i])_select" , selectImageName: "\(imagesName[i])_select", target: self, action: #selector(btnClick(_:))) btn.tag = 300 + i bgView?.addSubview(btn) btn.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(self.bgView!) make.width.equalTo(width) make.left.equalTo(width*CGFloat(i)) }) if btn.tag == 300{ btn.selected = true } let textLabel = UILabel.createLabel(titles[i], textAlignment: NSTextAlignment.Center, font: UIFont.systemFontOfSize(10)) //10.24 textLabel.textColor = UIColor.lightGrayColor() textLabel.tag = 400 btn.addSubview(textLabel) textLabel.snp_makeConstraints(closure: { (make) in make.left.right.bottom.equalTo(btn) make.height.equalTo(20) }) if i == 0{ btn.selected = true textLabel.textColor = UIColor.brownColor() } } } func btnClick(btn:UIButton) { let index = btn.tag - 300 //选中当前的按钮,取消选中之前的,切换视图控制器 if selectedIndex != index{ let lastBtn = bgView?.viewWithTag(300+selectedIndex) as! UIButton lastBtn.selected = false lastBtn.userInteractionEnabled = true let lastlabel = lastBtn.viewWithTag(400) as! UILabel lastlabel.textColor = UIColor.lightGrayColor() btn.selected = true btn.userInteractionEnabled = false selectedIndex = index let curLabel = btn.viewWithTag(400) as! UILabel curLabel.textColor = UIColor.brownColor() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
8715331bc074efa0e144e137e0dd6b0b
36.413043
227
0.574085
false
false
false
false
broccolii/SingleBarNavigationController
refs/heads/master
SingleBarNavigationController/SingleBarNavigationController/Resouce/ExclusiveNavigationController.swift
mit
1
// // ExclusiveNavigationController.swift // SingleBarNavigationController // // Created by Broccoli on 2016/10/27. // Copyright © 2016年 broccoliii. All rights reserved. // import Foundation import UIKit fileprivate func SafeWrapViewController(_ viewController: UIViewController, navigationBarClass: AnyClass? = nil, useSystemBackBarButtonItem: Bool = false, backBarButtonItem: UIBarButtonItem? = nil, backTitle: String? = nil) -> UIViewController { if !(viewController is WrapperViewController) { return WrapperViewController(viewController, navigationBarClass: navigationBarClass, backBarButtonItem: backBarButtonItem, useSystemBackBarButtonItem: useSystemBackBarButtonItem, backTitle: backTitle) } return viewController } fileprivate func SafeUnwrapViewController(_ viewController: UIViewController) -> UIViewController { if (viewController is WrapperViewController) { return (viewController as! WrapperViewController).contentViewController } return viewController } open class ExclusiveNavigationController: UINavigationController, UINavigationControllerDelegate { fileprivate weak var exclusiveDelegate: UINavigationControllerDelegate? fileprivate var animationBlock: ((Bool) -> Void)? @IBInspectable var isUseSystemBackBarButtonItem = false @IBInspectable var isTransferNavigationBarAttributes = true var exclusiveTopViewController: UIViewController { return SafeUnwrapViewController(super.topViewController!) } var exclusiveVisibleViewController: UIViewController { return SafeUnwrapViewController(super.visibleViewController!) } var exclusiveViewControllers: [UIViewController] { return super.viewControllers.map{ (viewController) -> UIViewController in return SafeUnwrapViewController(viewController) } } func onBack(_ sender: Any) { _ = popViewController(animated: true) } // MARK: - Overrides override open func awakeFromNib() { viewControllers = super.viewControllers } required public init() { super.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(rootViewController: UIViewController) { super.init(rootViewController: SafeWrapViewController(rootViewController, navigationBarClass: rootViewController.navigationBarClass)) } convenience init(rootViewControllerNoWrapping rootViewController: UIViewController) { self.init() super.pushViewController(rootViewController, animated: false) } override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white super.delegate = self super.setNavigationBarHidden(true, animated: false) } @available(iOS, introduced: 6.0, deprecated: 9.0) func forUnwindSegueAction(_ action: Selector, from fromViewController: UIViewController, withSender sender: Any) -> UIViewController? { var viewController = super.forUnwindSegueAction(action, from: fromViewController, withSender: sender) if viewController == nil { if let index = viewControllers.index(of: fromViewController) { for i in 0..<index { if let _ = viewControllers[i].forUnwindSegueAction(action, from: fromViewController, withSender: sender) { viewController = viewControllers[i].forUnwindSegueAction(action, from: fromViewController, withSender: sender) break } } } } return viewController } override open func setNavigationBarHidden(_ hidden: Bool, animated: Bool) {} override open func pushViewController(_ viewController: UIViewController, animated: Bool) { if viewControllers.count > 0 { let currentLast = SafeUnwrapViewController(viewControllers.last!) super.pushViewController(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass, useSystemBackBarButtonItem: isUseSystemBackBarButtonItem, backBarButtonItem: currentLast.navigationItem.backBarButtonItem, backTitle: currentLast.title), animated: animated) } else { super.pushViewController(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass), animated: animated) } } override open func popViewController(animated: Bool) -> UIViewController { return SafeUnwrapViewController(super.popViewController(animated: animated)!) } override open func popToRootViewController(animated: Bool) -> [UIViewController]? { if let viewControllers = super.popToRootViewController(animated: animated) { return viewControllers.map{ (viewController) -> UIViewController in SafeUnwrapViewController(viewController) } } else { return nil } } override open func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? { var controllerToPop: UIViewController? = nil for item in super.viewControllers { if SafeUnwrapViewController(item) == viewController { controllerToPop = item break } } if controllerToPop != nil { if let viewControllers = super.popToRootViewController(animated: animated) { return viewControllers.map{ (viewController) -> UIViewController in return SafeUnwrapViewController(viewController) } } return nil } return nil } override open func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) { var wrapViewControllers = [UIViewController]() for (index, viewController) in viewControllers.enumerated() { if isUseSystemBackBarButtonItem && index > 0 { wrapViewControllers.append(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass, useSystemBackBarButtonItem: isUseSystemBackBarButtonItem, backBarButtonItem: viewControllers[index - 1].navigationItem.backBarButtonItem, backTitle: viewControllers[index - 1].title)) } else { wrapViewControllers.append(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass)) } } super.setViewControllers(wrapViewControllers, animated: animated) } open override var viewControllers: [UIViewController] { set { var wrapViewControllers = [UIViewController]() for (index, viewController) in newValue.enumerated() { if isUseSystemBackBarButtonItem && index > 0 { wrapViewControllers.append(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass, useSystemBackBarButtonItem: isUseSystemBackBarButtonItem, backBarButtonItem: newValue[index - 1].navigationItem.backBarButtonItem, backTitle: newValue[index - 1].title)) } else { wrapViewControllers.append(SafeWrapViewController(viewController, navigationBarClass: viewController.navigationBarClass)) } } super.viewControllers = wrapViewControllers } get { let unwrapViewControllers = super.viewControllers.map { (viewController) -> UIViewController in return SafeUnwrapViewController(viewController) } return unwrapViewControllers } } open override var childViewControllers: [UIViewController] { let unwrapViewControllers = super.childViewControllers.map { (viewController) -> UIViewController in return SafeUnwrapViewController(viewController) } return unwrapViewControllers } override open var delegate: UINavigationControllerDelegate? { set { exclusiveDelegate = newValue } get { return super.delegate } } override open var shouldAutorotate: Bool { return topViewController?.shouldAutorotate ?? false } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return topViewController?.supportedInterfaceOrientations ?? .portrait } override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return topViewController?.preferredInterfaceOrientationForPresentation ?? .unknown } @available(iOS, introduced: 2.0, deprecated: 8.0, message: "Header views are animated along with the rest of the view hierarchy") override open func rotatingHeaderView() -> UIView? { return topViewController?.rotatingHeaderView() } @available(iOS, introduced: 2.0, deprecated: 8.0, message: "Footer views are animated along with the rest of the view hierarchy") override open func rotatingFooterView() -> UIView? { return topViewController?.rotatingFooterView() } override open func responds(to aSelector: Selector) -> Bool { if super.responds(to: aSelector) { return true } return exclusiveDelegate?.responds(to: aSelector) ?? false } override open func forwardingTarget(for aSelector: Selector) -> Any? { return exclusiveDelegate } public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { var viewController = viewController let isRootVC = SafeUnwrapViewController(viewController) == navigationController.viewControllers.first! if !isRootVC { viewController = SafeUnwrapViewController(viewController) if !isUseSystemBackBarButtonItem && viewController.navigationItem.leftBarButtonItem == nil { viewController.navigationItem.leftBarButtonItem = viewController.customBackItem(withTarget: self, action: #selector(onBack)) } } if let _ = exclusiveDelegate, exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:willShow:animated:))){ exclusiveDelegate!.navigationController!(navigationController, willShow: viewController, animated: animated) } } public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { let isRootVC = viewController == navigationController.viewControllers.first! let unwrappedViewController = SafeUnwrapViewController(viewController) if unwrappedViewController.disableInteractivePopGesture { interactivePopGestureRecognizer?.delegate = nil interactivePopGestureRecognizer?.isEnabled = false } else { interactivePopGestureRecognizer?.delaysTouchesBegan = true interactivePopGestureRecognizer?.delegate = self interactivePopGestureRecognizer?.isEnabled = !isRootVC } ExclusiveNavigationController.attemptRotationToDeviceOrientation() if (animationBlock != nil) { animationBlock!(true) animationBlock = nil } if let _ = exclusiveDelegate, exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:))){ exclusiveDelegate?.navigationController!(navigationController, didShow: unwrappedViewController, animated: animated) } } public func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask { if let _ = exclusiveDelegate, exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationControllerSupportedInterfaceOrientations(_:))){ return exclusiveDelegate!.navigationControllerSupportedInterfaceOrientations!(navigationController) } return .all } public func navigationControllerPreferredInterfaceOrientationForPresentation(_ navigationController: UINavigationController) -> UIInterfaceOrientation { if let _ = exclusiveDelegate, exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationControllerPreferredInterfaceOrientationForPresentation(_:))){ return exclusiveDelegate!.navigationControllerPreferredInterfaceOrientationForPresentation!(navigationController) } return .portrait } public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if let _ = exclusiveDelegate, exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:interactionControllerFor:))){ return exclusiveDelegate!.navigationController!(navigationController, interactionControllerFor: animationController)! } return nil } public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if let _ = exclusiveDelegate, exclusiveDelegate!.responds(to: #selector(UINavigationControllerDelegate.navigationController(_:animationControllerFor:from:to:))){ return exclusiveDelegate!.navigationController!(navigationController, animationControllerFor: operation, from: fromVC, to: toVC) } return nil } } public extension ExclusiveNavigationController { // MARK: - Methods func remove(_ controller: UIViewController) { remove(controller, animated: false) } func remove(_ controller: UIViewController, animated flag: Bool) { var controllers = viewControllers var controllerToRemove: UIViewController? = nil controllers.forEach { (viewController) in if SafeUnwrapViewController(viewController) == controller { controllerToRemove = viewController } } if controllerToRemove != nil { controllers.remove(at: controllers.index(of: controllerToRemove!)!) super.setViewControllers(controllers, animated: flag) } } func push(_ viewController: UIViewController, animated: Bool, complete block: @escaping (Bool) -> Void) { if (animationBlock != nil) { animationBlock!(false) } animationBlock = block pushViewController(viewController, animated: animated) } func popToViewController(viewController: UIViewController, animated: Bool, complete block: @escaping (Bool) -> Void) -> [UIViewController]? { if (animationBlock != nil) { animationBlock!(false) } animationBlock = block let array = popToViewController(viewController, animated: animated) if let _ = array, array!.count > 0 { if (animationBlock != nil) { animationBlock = nil } } return array } func popToRootViewController(animated: Bool, complete block: @escaping (Bool) -> Void) -> [UIViewController]? { if (animationBlock != nil) { animationBlock!(false) } animationBlock = block let array = popToRootViewController(animated: animated) if let _ = array, array!.count > 0 { if (animationBlock != nil) { animationBlock = nil } } return array } } extension ExclusiveNavigationController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return (gestureRecognizer == interactivePopGestureRecognizer) } }
aa784a2060ece4d9be80837461b1c306
44.468193
253
0.652247
false
false
false
false
blakemerryman/Swift-Scripts
refs/heads/master
Intro Examples/6-AppleScriptExample.swift
mit
1
#!/usr/bin/env xcrun swift import Foundation enum Options: String { case ShutDown = "--off" case Restart = "--restart" case Sleep = "--sleep" case Lock = "--lock" } if Process.arguments.count > 1 { let flag = Process.arguments[1] let userInput = Options(rawValue: flag) var scriptToPerform: NSAppleScript? // WARNING - Needs much better error handling here ( non-Options from user == CRASH!!! ) // Also, switch userInput! { case .ShutDown: let shutDownSource = "tell app \"loginwindow\" to «event aevtrsdn»" scriptToPerform = NSAppleScript(source:shutDownSource) case .Restart: let restartSource = "tell app \"loginwindow\" to «event aevtrrst»" scriptToPerform = NSAppleScript(source:restartSource) case .Sleep: let sleepSource = "tell app \"System Events\" to sleep" scriptToPerform = NSAppleScript(source: sleepSource) case .Lock: let lockSource = "tell application \"System Events\" to tell process \"SystemUIServer\" to click (first menu item of menu 1 of ((click (first menu bar item whose description is \"Keychain menu extra\")) of menu bar 1) whose title is \"Lock Screen\")" scriptToPerform = NSAppleScript(source:lockSource) } if let script = scriptToPerform { var possibleError: NSDictionary? print("Performing some script... \(userInput!.rawValue)") //script.executeAndReturnError(&possibleError) if let error = possibleError { print("ERROR: \(error)") } } }
238f1301b15a3ebe4073790e56b82898
29.921569
258
0.6487
false
false
false
false
dabainihao/MapProject
refs/heads/master
MapProject/MapProject/ViewController.swift
apache-2.0
1
// // ViewController.swift // MapProject // // Created by 杨少锋 on 16/4/13. // Copyright © 2016年 杨少锋. All rights reserved. // 地图定位, 编码, 插大头针 import UIKit class ViewController: UIViewController,BMKMapViewDelegate,UITextFieldDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKRouteSearchDelegate { lazy var map : BMKMapView? = { BMKMapView() }() lazy var locService : BMKLocationService? = { BMKLocationService() }() lazy var geo: BMKGeoCodeSearch? = { BMKGeoCodeSearch() }() lazy var expectAddress: UITextField! = { UITextField() }() // route搜索服务 lazy var routeSearch: BMKRouteSearch! = { BMKRouteSearch() }() lazy var titleView : UIView! = { UIView() }() var loginButton : UIButton! var sureButton: UIButton! var routePlannButton : UIButton! var userLocation :CLLocation? var expectLocation : String? var label : UILabel! override func viewDidLoad() { super.viewDidLoad() self.title = "路线规划" if (!CLLocationManager.locationServicesEnabled()) { print("定位服务当前可能尚未打开,请设置打开!") return; } self.locService?.allowsBackgroundLocationUpdates = false; self.locService?.distanceFilter = 100 self.locService?.desiredAccuracy = 100 self.locService?.startUserLocationService(); self.map?.frame = CGRectMake(0, 0, self.view.bounds.size.width,self.view.bounds.size.height) self.map?.delegate = self self.map?.showsUserLocation = true self.map?.mapType = 1; // 地图比例尺级别,在手机上当前可使用的级别为3-21级 self.map?.zoomLevel = 19; self.map?.userTrackingMode = BMKUserTrackingModeNone; // 设置定位状态 self.view.addSubview(self.map!) self.titleView.frame = CGRectMake(20, 40, self.view.frame.size.width - 40, 50) self.titleView.backgroundColor = UIColor.whiteColor() self.titleView.layer.cornerRadius = 2; self.titleView.layer.masksToBounds = true self.view.addSubview(self.titleView) self.loginButton = UIButton(type: UIButtonType.System) self.loginButton.frame = CGRectMake(5, 10, 30, 30) self.loginButton.addTarget(self, action: "loginOrregist", forControlEvents: UIControlEvents.TouchUpInside) self.titleView.addSubview(self.loginButton) self.label = UILabel(frame: CGRectMake(39, 10, 1, 30)) self.label?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.15) self.titleView.addSubview(self.label!) self.expectAddress.frame = CGRectMake(50, 0, 170, 50) NSNotificationCenter.defaultCenter().addObserver(self, selector: "expectAddressChang", name: UITextFieldTextDidChangeNotification, object: nil) self.expectAddress.borderStyle = UITextBorderStyle.None self.expectAddress.placeholder = "请输入详细的地址" self.expectAddress.delegate = self self.titleView.addSubview(self.expectAddress) self.sureButton = UIButton(type: UIButtonType.System) self.sureButton.enabled = false self.sureButton.setTitle("确定", forState: UIControlState.Normal) self.sureButton.frame = CGRectMake(225, 10, 30, 30) self.sureButton .addTarget(self, action: "sureButtonAction", forControlEvents: UIControlEvents.TouchUpInside) self.sureButton.enabled = false self.titleView.addSubview(self.sureButton) self.routePlannButton = UIButton(type: UIButtonType.System) self.routePlannButton.setTitle("路线规划", forState: UIControlState.Normal) self.routePlannButton.frame = CGRectMake(260, 10, 70, 30) self.routePlannButton .addTarget(self, action: "routePlannButtonAction", forControlEvents: UIControlEvents.TouchUpInside) self.routePlannButton.enabled = false; self.titleView.addSubview(self.routePlannButton) } func loginOrregist() { if (LO_loginHelper().isLogin()) { let alter = UIAlertView(title: "提示", message: "已登录", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定") alter.show() // } else { let nav : UINavigationController = UINavigationController(rootViewController: LO_LoginController()) self.presentViewController(nav, animated: true) { () -> Void in } } } //BMKMapView新增viewWillAppear、viewWillDisappear方法来控制BMKMapView的生命周期,并且在一个时刻只能有一个BMKMapView接受回调消息,因此在使用BMKMapView的viewController中需要在viewWillAppear、viewWillDisappear方法中调用BMKMapView的对应的方法,并处理delegat override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); if (!LO_loginHelper().isLogin()) { self.loginButton.setImage(UIImage(named:"person") , forState:UIControlState.Normal) self.loginButton.setImage(UIImage(named:"person") , forState:UIControlState.Selected) } else { self.loginButton.setImage(UIImage(named:"person_all") , forState:UIControlState.Normal) self.loginButton.setImage(UIImage(named:"person_all") , forState:UIControlState.Selected) } self.locService?.delegate = self self.map?.delegate = self self.geo?.delegate = self self.routeSearch.delegate = self } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.locService?.delegate = nil self.map?.delegate = nil self.geo?.delegate = nil self.routeSearch.delegate = nil } func expectAddressChang() { if self.expectAddress.text == "" { self.sureButton.enabled = false } else { self.sureButton.enabled = true } } // 确定按钮的事件 func sureButtonAction() { self.sureButton.enabled = false; self.expectAddress.resignFirstResponder() if (self.expectAddress.text == nil) { print("您输入的位置为空") return } let addressInformation: BMKGeoCodeSearchOption = BMKGeoCodeSearchOption() addressInformation.address = self.expectAddress.text self.geo?.geoCode(addressInformation) } // 路线规划的事件 func routePlannButtonAction() { if (self.userLocation == nil || self.expectAddress.text == nil) { return } let reverseGeoCodeOption : BMKReverseGeoCodeOption = BMKReverseGeoCodeOption(); reverseGeoCodeOption.reverseGeoPoint = (self.userLocation?.coordinate)! self.geo?.reverseGeoCode(reverseGeoCodeOption) } //*返回地址信息搜索结果(用户输入转化坐标) func onGetGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKGeoCodeResult!, errorCode error: BMKSearchErrorCode) { if result.address == nil { let alter = UIAlertView(title: "提示", message: "没有这个位置", delegate: nil, cancelButtonTitle: "确定", otherButtonTitles: "取消") alter .show() return; } self.expectLocation = result.address self.sureButton.enabled = true; if (error != BMK_SEARCH_NO_ERROR || searcher != self.geo || result == nil) { // 如果没有正常返回结果直接返回 print("编码错误") return; } self.map?.setCenterCoordinate(result.location, animated: true) // 移除地图上添加的标注 self.map?.removeAnnotations(self.map?.annotations) let annotation = LO_Annotation() annotation.coordinate = result.location annotation.pointImage = UIImage(named: "exAddress") annotation.title = result.address self.map?.addAnnotation(annotation) } /*返回反地理编码搜索结果*/ func onGetReverseGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) { let from = BMKPlanNode() from.name = result.addressDetail.district + result.addressDetail.streetName; from.name = "上地三街" from.cityName = result.addressDetail.city let to = BMKPlanNode() // 终点 to.name = self.expectAddress.text!; to.name = "清河中街" to.cityName = result.addressDetail.city let transitRouteSearchOption = BMKTransitRoutePlanOption() transitRouteSearchOption.city = result.addressDetail.city transitRouteSearchOption.from = from transitRouteSearchOption.to = to print("frame = \(from.name) to = \(to.name)") // 发起公交检索 let flag = routeSearch.transitSearch(transitRouteSearchOption) if flag { print("公交检索发送成功") }else { print("公交检索发送失败") } } // /***返回公交搜索结果*/ func onGetTransitRouteResult(searcher: BMKRouteSearch!, result: BMKTransitRouteResult!, errorCode error: BMKSearchErrorCode) { print("onGetTransitRouteResult: \(error)") if error != BMK_SEARCH_NO_ERROR { print("%d",error) let alter = UIAlertView(title: "提示", message: "\(error)", delegate: nil, cancelButtonTitle: "确定", otherButtonTitles: "取消") alter .show() } self.map!.removeAnnotations(self.map!.annotations) self.map!.removeOverlays(self.map!.overlays) if error == BMK_SEARCH_NO_ERROR { let plan = result.routes[0] as! BMKTransitRouteLine let size = plan.steps.count var planPointCounts = 0 for i in 0..<size { let transitStep = plan.steps[i] as! BMKTransitStep if i == 0 { let item = LO_RouteAnnotation() item.coordinate = plan.starting.location item.title = "起点" item.type = 0 self.map!.addAnnotation(item) // 添加起点标注 }else if i == size - 1 { let item = LO_RouteAnnotation() item.coordinate = plan.terminal.location item.title = "终点" item.type = 1 self.map!.addAnnotation(item) // 添加终点标注 } let item = LO_RouteAnnotation() item.coordinate = transitStep.entrace.location item.title = transitStep.instruction item.type = 3 self.map!.addAnnotation(item) // 轨迹点总数累计 planPointCounts = Int(transitStep.pointsCount) + planPointCounts } // 轨迹点 var tempPoints = Array(count: planPointCounts, repeatedValue: BMKMapPoint(x: 0, y: 0)) var i = 0 for j in 0..<size { let transitStep = plan.steps[j] as! BMKTransitStep for k in 0..<Int(transitStep.pointsCount) { tempPoints[i].x = transitStep.points[k].x tempPoints[i].y = transitStep.points[k].y i++ } } // 通过 points 构建 BMKPolyline let polyLine = BMKPolyline(points: &tempPoints, count: UInt(planPointCounts)) // 添加路线 overlay self.map!.addOverlay(polyLine) mapViewFitPolyLine(polyLine) } } // 添加覆盖物 func mapView(mapView: BMKMapView!, viewForOverlay overlay: BMKOverlay!) -> BMKOverlayView! { if overlay as! BMKPolyline? != nil { let polylineView = BMKPolylineView(overlay: overlay as! BMKPolyline) polylineView.strokeColor = UIColor(red: 0, green: 0, blue: 1, alpha: 0.7) polylineView.lineWidth = 3 return polylineView } return nil } //根据polyline设置地图范围 func mapViewFitPolyLine(polyline: BMKPolyline!) { if polyline.pointCount < 1 { return } let pt = polyline.points[0] var ltX = pt.x var rbX = pt.x var ltY = pt.y var rbY = pt.y for i in 1..<polyline.pointCount { let pt = polyline.points[Int(i)] if pt.x < ltX { ltX = pt.x } if pt.x > rbX { rbX = pt.x } if pt.y > ltY { ltY = pt.y } if pt.y < rbY { rbY = pt.y } } let rect = BMKMapRectMake(ltX, ltY, rbX - ltX, rbY - ltY) self.map!.visibleMapRect = rect self.map!.zoomLevel = self.map!.zoomLevel - 0.3 } // 添加大头针的代理 func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! { if annotation is LO_RouteAnnotation { if let routeAnnotation = annotation as! LO_RouteAnnotation? { return getViewForRouteAnnotation(routeAnnotation) } } if annotation is BMKUserLocation { self.routePlannButton.enabled = false return nil; } let AnnotationViewID = "renameMark" var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(AnnotationViewID) as! BMKPinAnnotationView? if annotationView == nil { annotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID) } annotationView?.annotation = annotation let lo_annotation = annotation as! LO_Annotation annotationView?.image = lo_annotation.pointImage annotationView?.canShowCallout = true self.routePlannButton.enabled = true; return annotationView } // func getViewForRouteAnnotation(routeAnnotation: LO_RouteAnnotation!) -> BMKAnnotationView? { var view: BMKAnnotationView? let imageName = "nav_bus" let identifier = "\(imageName)_annotation" view = self.map!.dequeueReusableAnnotationViewWithIdentifier(identifier) if view == nil { view = BMKAnnotationView(annotation: routeAnnotation, reuseIdentifier: identifier) view?.centerOffset = CGPointMake(0, -(view!.frame.size.height * 0.5)) view?.canShowCallout = true } view?.annotation = routeAnnotation let bundlePath = NSBundle.mainBundle().resourcePath?.stringByAppendingString("/mapapi.bundle/") let bundle = NSBundle(path: bundlePath!) if let imagePath = bundle?.resourcePath?.stringByAppendingString("/images/icon_\(imageName).png") { let image = UIImage(contentsOfFile: imagePath) if image != nil { view?.image = image } } return view } // 用户位置更新 func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) { print("didUpdateUserLocation lat:\(userLocation.location.coordinate.latitude) lon:\(userLocation.location.coordinate.longitude)") self.userLocation = userLocation.location; self.map?.updateLocationData(userLocation) // 设置用户位置为地图的中心点 self.map?.setCenterCoordinate(userLocation.location.coordinate, animated: true) } // 定位失败 func didFailToLocateUserWithError(error: NSError!) { print("定位失败") } // 大头针的点击事件 func mapView(mapView: BMKMapView!, didSelectAnnotationView view: BMKAnnotationView!) { self.map?.setCenterCoordinate(view.annotation.coordinate, animated: true); } // 控制键盘回收 func mapView(mapView: BMKMapView!, regionWillChangeAnimated animated: Bool) { self.expectAddress.resignFirstResponder() } func mapView(mapView: BMKMapView!, onClickedBMKOverlayView overlayView: BMKOverlayView!) { self.expectAddress.resignFirstResponder() } func mapview(mapView: BMKMapView!, onDoubleClick coordinate: CLLocationCoordinate2D) { self.expectAddress.resignFirstResponder() } func mapview(mapView: BMKMapView!, onLongClick coordinate: CLLocationCoordinate2D) { self.expectAddress.resignFirstResponder() } func mapView(mapView: BMKMapView!, onClickedMapBlank coordinate: CLLocationCoordinate2D) { self.expectAddress.resignFirstResponder() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.expectAddress.resignFirstResponder() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string == "\n" { self.expectAddress.resignFirstResponder() return false } return true } func textFieldShouldReturn(textField: UITextField) -> Bool { self.expectAddress.resignFirstResponder() return true } }
15646c0c6f90ddfe5d66b754d02bc30d
38.725537
198
0.622049
false
false
false
false
carping/Postal
refs/heads/master
PostalDemo/PostalDemo/LoginTableViewController.swift
mit
1
// // LoginTableViewController.swift // PostalDemo // // Created by Kevin Lefevre on 24/05/2016. // Copyright © 2017 Snips. All rights reserved. // import UIKit import Postal enum LoginError: Error { case badEmail case badPassword case badHostname case badPort } extension LoginError: CustomStringConvertible { var description: String { switch self { case .badEmail: return "Bad mail" case .badPassword: return "Bad password" case .badHostname: return "Bad hostname" case .badPort: return "Bad port" } } } final class LoginTableViewController: UITableViewController { fileprivate let mailsSegueIdentifier = "mailsSegue" @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var hostnameTextField: UITextField! @IBOutlet weak var portTextField: UITextField! var provider: MailProvider? } // MARK: - View lifecycle extension LoginTableViewController { override func viewDidLoad() { super.viewDidLoad() if let provider = provider, let configuration = provider.preConfiguration { emailTextField.placeholder = "exemple@\(provider.hostname)" hostnameTextField.isUserInteractionEnabled = false hostnameTextField.text = configuration.hostname portTextField.isUserInteractionEnabled = false portTextField.text = "\(configuration.port)" } } } // MARK: - Navigation management extension LoginTableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch (segue.identifier, segue.destination) { case (.some(mailsSegueIdentifier), let vc as MailsTableViewController): do { vc.configuration = try createConfiguration() } catch let error as LoginError { showAlertError("Error login", message: (error as NSError).localizedDescription) } catch { fatalError() } break default: break } } } // MARK: - Helpers private extension LoginTableViewController { func createConfiguration() throws -> Configuration { guard let email = emailTextField.text , !email.isEmpty else { throw LoginError.badEmail } guard let password = passwordTextField.text , !password.isEmpty else { throw LoginError.badPassword } if let configuration = provider?.preConfiguration { return Configuration(hostname: configuration.hostname, port: configuration.port, login: email, password: .plain(password), connectionType: configuration.connectionType, checkCertificateEnabled: configuration.checkCertificateEnabled) } else { guard let hostname = hostnameTextField.text , !hostname.isEmpty else { throw LoginError.badHostname } guard let portText = portTextField.text , !portText.isEmpty else { throw LoginError.badPort } guard let port = UInt16(portText) else { throw LoginError.badPort } return Configuration(hostname: hostname, port: port, login: email, password: .plain(""), connectionType: .tls, checkCertificateEnabled: true) } } }
c0fc2fa852cd3a965980486c678e2f13
33.291667
244
0.671324
false
true
false
false
joalbright/Gameboard
refs/heads/master
Gameboards.playground/Pages/Minesweeper.xcplaygroundpage/Contents.swift
apache-2.0
1
import UIKit enum MoveType { case Guess, Mark } var minesweeper = Gameboard(.Minesweeper, testing: true) // setup colors var colors = BoardColors() colors.background = UIColor(red:0.5, green:0.5, blue:0.5, alpha:1) colors.foreground = UIColor(red:0.6, green:0.6, blue:0.6, alpha:1) colors.player1 = UIColor.yellowColor() colors.player2 = UIColor.blackColor() colors.highlight = UIColor.blueColor() colors.selected = UIColor.redColor() minesweeper.boardColors = colors // collection of guesses let guesses: [(Square,MoveType)] = [ ((4,3),.Guess), // guess ((9,0),.Mark), // mark ((7,4),.Mark), // mark ((4,1),.Mark), // mark ((4,0),.Guess), // guess ((0,9),.Guess), // guess ((2,7),.Mark), // guess ((6,9),.Guess), // guess ((1,0),.Guess), // game over ] // loop guesses for guess in guesses { do { switch guess.1 { case .Guess: try minesweeper.guess(toSquare: guess.0) case .Mark: try minesweeper.mark(toSquare: guess.0) } } catch { print(error) } } minesweeper.visualize(CGRect(x: 0, y: 0, width: 199, height: 199))
27df155cfda7bd3d1d179406827c1b19
19.389831
66
0.571904
false
false
false
false
Jpadilla1/react-native-ios-charts
refs/heads/master
RNiOSCharts/PieRadarChartViewBaseExtension.swift
mit
1
// // PieRadarChartViewBase.swift // PoliRank // // Created by Jose Padilla on 2/8/16. // Copyright © 2016 Facebook. All rights reserved. // import Charts import SwiftyJSON extension PieRadarChartViewBase { func setPieRadarChartViewBaseProps(_ config: String!) { setChartViewBaseProps(config); var json: JSON = nil; if let data = config.data(using: String.Encoding.utf8) { json = JSON(data: data); }; if json["rotationEnabled"].exists() { self.rotationEnabled = json["rotationEnabled"].boolValue; } if json["rotationAngle"].exists() { self.rotationAngle = CGFloat(json["rotationAngle"].floatValue); } if json["rotationWithTwoFingers"].exists() { self.rotationWithTwoFingers = json["rotationWithTwoFingers"].boolValue; } if json["minOffset"].exists() { self.minOffset = CGFloat(json["minOffset"].floatValue); } } }
de46b7610510b3e355fb1484055beaea
22.923077
77
0.652733
false
true
false
false
crsmithdev/hint
refs/heads/master
HintLauncher/AppDelegate.swift
mit
1
// // AppDelegate.swift // HintLauncher // // Created by Christopher Smith on 12/31/16. // Copyright © 2016 Chris Smith. All rights reserved. // import Cocoa import Foundation @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { let applications = NSWorkspace.shared().runningApplications let running = applications.filter({$0.bundleIdentifier == "com.crsmithdev.Hint"}).count > 0 if !running { let launcherPath = Bundle.main.bundlePath as NSString var components = launcherPath.pathComponents components.removeLast() components.removeLast() components.removeLast() components.append("MacOS") components.append("Hint") let appPath = NSString.path(withComponents: components) NSWorkspace.shared().launchApplication(appPath) } NSApp.terminate(nil) } }
535d4041450496c484b45d0decaad366
28.027778
99
0.636364
false
false
false
false
inamiy/ReactiveCocoaCatalog
refs/heads/master
ReactiveCocoaCatalog/Samples/BadgeManager.swift
mit
1
// // BadgeManager.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2016-04-09. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import Foundation import Result import ReactiveSwift /// Singleton class for on-memory badge persistence. final class BadgeManager { // Singleton. static let badges = BadgeManager() private var _badges: [MenuId : MutableProperty<Badge>] = [:] subscript(menuId: MenuId) -> MutableProperty<Badge> { if let property = self._badges[menuId] { return property } else { let property = MutableProperty<Badge>(.none) self._badges[menuId] = property return property } } /// - FIXME: This should be created NOT from current `_badges`-dictionary but from combined MutableProperties of badges. var mergedSignal: Signal<(MenuId, Badge), NoError> { let signals = self._badges.map { menuId, property in return property.signal.map { (menuId, $0) } } return Signal.merge(signals) } private init() {} } // MARK: Badge enum Badge: RawRepresentable { case none case new // "N" mark case number(Int) case string(Swift.String) var rawValue: Swift.String? { switch self { case .none: return nil case .new: return "N" case .number(let int): return int > 999 ? "999+" : int > 0 ? "\(int)" : nil case .string(let str): return str } } var number: Int? { guard case .number(let int) = self else { return nil } return int } init(_ intValue: Int) { self = .number(intValue) } init(rawValue: Swift.String?) { switch rawValue { case .none, .some("0"), .some(""): self = .none case .some("N"): self = .new case let .some(str): self = Int(str).map { .number($0) } ?? .string(str) } } }
5cff30114cfdb9a071712ab2e0261504
23.05814
124
0.545191
false
false
false
false
RMizin/PigeonMessenger-project
refs/heads/main
FalconMessenger/ChatsControllers/InputContainerView.swift
gpl-3.0
1
// // InputContainerView.swift // Avalon-print // // Created by Roman Mizin on 3/25/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit import AVFoundation final class InputContainerView: UIControl { var audioPlayer: AVAudioPlayer! weak var mediaPickerController: MediaPickerControllerNew? weak var trayDelegate: ImagePickerTrayControllerDelegate? var attachedMedia = [MediaObject]() fileprivate var tap = UITapGestureRecognizer() static let commentOrSendPlaceholder = "Comment or Send" static let messagePlaceholder = "Message" weak var chatLogController: ChatLogViewController? { didSet { sendButton.addTarget(chatLogController, action: #selector(ChatLogViewController.sendMessage), for: .touchUpInside) } } lazy var inputTextView: InputTextView = { let textView = InputTextView() textView.translatesAutoresizingMaskIntoConstraints = false textView.delegate = self return textView }() lazy var attachCollectionView: AttachCollectionView = { let attachCollectionView = AttachCollectionView() return attachCollectionView }() let placeholderLabel: UILabel = { let placeholderLabel = UILabel() placeholderLabel.text = messagePlaceholder placeholderLabel.sizeToFit() placeholderLabel.textColor = ThemeManager.currentTheme().generalSubtitleColor placeholderLabel.translatesAutoresizingMaskIntoConstraints = false return placeholderLabel }() var attachButton: MediaPickerRespondingButton = { var attachButton = MediaPickerRespondingButton() attachButton.addTarget(self, action: #selector(togglePhoto), for: .touchDown) return attachButton }() var recordVoiceButton: VoiceRecorderRespondingButton = { var recordVoiceButton = VoiceRecorderRespondingButton() recordVoiceButton.addTarget(self, action: #selector(toggleVoiceRecording), for: .touchDown) return recordVoiceButton }() let sendButton: UIButton = { let sendButton = UIButton(type: .custom) sendButton.setImage(UIImage(named: "send"), for: .normal) sendButton.translatesAutoresizingMaskIntoConstraints = false sendButton.isEnabled = false sendButton.backgroundColor = .white return sendButton }() private var heightConstraint: NSLayoutConstraint! private func addHeightConstraints() { heightConstraint = heightAnchor.constraint(equalToConstant: InputTextViewLayout.minHeight) heightConstraint.isActive = true } func confirugeHeightConstraint() { let size = inputTextView.sizeThatFits(CGSize(width: inputTextView.bounds.size.width, height: .infinity)) let height = size.height + 12 heightConstraint.constant = height < InputTextViewLayout.maxHeight() ? height : InputTextViewLayout.maxHeight() let maxHeight: CGFloat = InputTextViewLayout.maxHeight() guard height >= maxHeight else { inputTextView.isScrollEnabled = false; return } inputTextView.isScrollEnabled = true } func handleRotation() { attachCollectionView.collectionViewLayout.invalidateLayout() DispatchQueue.main.async { [weak self] in guard let width = self?.inputTextView.frame.width else { return } self?.attachCollectionView.frame.size.width = width//self?.inputTextView.frame.width self?.attachCollectionView.reloadData() self?.confirugeHeightConstraint() } } override init(frame: CGRect) { super.init(frame: frame) NotificationCenter.default.addObserver(self, selector: #selector(changeTheme), name: .themeUpdated, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(inputViewResigned), name: .inputViewResigned, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(inputViewResponded), name: .inputViewResponded, object: nil) addHeightConstraints() backgroundColor = ThemeManager.currentTheme().barBackgroundColor // sendButton.tintColor = ThemeManager.generalTintColor addSubview(attachButton) addSubview(recordVoiceButton) addSubview(inputTextView) addSubview(sendButton) addSubview(placeholderLabel) inputTextView.addSubview(attachCollectionView) sendButton.layer.cornerRadius = 15 sendButton.clipsToBounds = true tap = UITapGestureRecognizer(target: self, action: #selector(toggleTextView)) tap.delegate = self if #available(iOS 11.0, *) { attachButton.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 5).isActive = true inputTextView.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true } else { attachButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true inputTextView.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true } attachButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true attachButton.heightAnchor.constraint(equalToConstant: 50).isActive = true attachButton.widthAnchor.constraint(equalToConstant: 35).isActive = true recordVoiceButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true recordVoiceButton.heightAnchor.constraint(equalToConstant: 50).isActive = true recordVoiceButton.widthAnchor.constraint(equalToConstant: 35).isActive = true recordVoiceButton.leftAnchor.constraint(equalTo: attachButton.rightAnchor, constant: 0).isActive = true inputTextView.topAnchor.constraint(equalTo: topAnchor, constant: 6).isActive = true inputTextView.leftAnchor.constraint(equalTo: recordVoiceButton.rightAnchor, constant: 3).isActive = true inputTextView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -6).isActive = true placeholderLabel.font = UIFont.systemFont(ofSize: (inputTextView.font!.pointSize)) placeholderLabel.isHidden = !inputTextView.text.isEmpty placeholderLabel.leftAnchor.constraint(equalTo: inputTextView.leftAnchor, constant: 12).isActive = true placeholderLabel.rightAnchor.constraint(equalTo: inputTextView.rightAnchor).isActive = true placeholderLabel.topAnchor.constraint(equalTo: attachCollectionView.bottomAnchor, constant: inputTextView.font!.pointSize / 2.3).isActive = true placeholderLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true sendButton.rightAnchor.constraint(equalTo: inputTextView.rightAnchor, constant: -4).isActive = true sendButton.bottomAnchor.constraint(equalTo: inputTextView.bottomAnchor, constant: -4).isActive = true sendButton.widthAnchor.constraint(equalToConstant: 30).isActive = true sendButton.heightAnchor.constraint(equalToConstant: 30).isActive = true configureAttachCollectionView() } deinit { NotificationCenter.default.removeObserver(self) } @objc func changeTheme() { backgroundColor = ThemeManager.currentTheme().barBackgroundColor inputTextView.changeTheme() attachButton.changeTheme() recordVoiceButton.changeTheme() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } @objc func toggleTextView () { print("toggling") inputTextView.inputView = nil inputTextView.reloadInputViews() UIView.performWithoutAnimation { inputTextView.resignFirstResponder() inputTextView.becomeFirstResponder() } } @objc fileprivate func inputViewResigned() { inputTextView.removeGestureRecognizer(tap) } @objc fileprivate func inputViewResponded() { guard let recognizers = inputTextView.gestureRecognizers else { return } guard !recognizers.contains(tap) else { return } inputTextView.addGestureRecognizer(tap) } @objc func togglePhoto () { checkAuthorisationStatus() UIView.performWithoutAnimation { _ = recordVoiceButton.resignFirstResponder() } if attachButton.isFirstResponder { _ = attachButton.resignFirstResponder() } else { if attachButton.controller == nil { attachButton.controller = MediaPickerControllerNew() mediaPickerController = attachButton.controller mediaPickerController?.mediaPickerDelegate = self } _ = attachButton.becomeFirstResponder() // inputTextView.addGestureRecognizer(tap) } } @objc func toggleVoiceRecording () { UIView.performWithoutAnimation { _ = attachButton.resignFirstResponder() } if recordVoiceButton.isFirstResponder { _ = recordVoiceButton.resignFirstResponder() } else { if recordVoiceButton.controller == nil { recordVoiceButton.controller = VoiceRecordingViewController() recordVoiceButton.controller?.mediaPickerDelegate = self } _ = recordVoiceButton.becomeFirstResponder() // inputTextView.addGestureRecognizer(tap) } } func resignAllResponders() { inputTextView.resignFirstResponder() _ = attachButton.resignFirstResponder() _ = recordVoiceButton.resignFirstResponder() } } extension InputContainerView { func prepareForSend() { inputTextView.text = "" sendButton.isEnabled = false placeholderLabel.isHidden = false inputTextView.isScrollEnabled = false attachedMedia.removeAll() attachCollectionView.reloadData() resetChatInputConntainerViewSettings() } func resetChatInputConntainerViewSettings() { guard attachedMedia.isEmpty else { return } attachCollectionView.frame = CGRect(x: 0, y: 0, width: inputTextView.frame.width, height: 0) inputTextView.textContainerInset = InputTextViewLayout.defaultInsets placeholderLabel.text = InputContainerView.messagePlaceholder sendButton.isEnabled = !inputTextView.text.isEmpty confirugeHeightConstraint() } func expandCollection() { sendButton.isEnabled = (!inputTextView.text.isEmpty || !attachedMedia.isEmpty) placeholderLabel.text = InputContainerView.commentOrSendPlaceholder attachCollectionView.frame = CGRect(x: 0, y: 3, width: inputTextView.frame.width, height: AttachCollectionView.height) inputTextView.textContainerInset = InputTextViewLayout.extendedInsets confirugeHeightConstraint() } } extension InputContainerView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard attachCollectionView.bounds.contains(touch.location(in: attachCollectionView)) else { return true } return false } } extension InputContainerView: UITextViewDelegate { private func handleSendButtonState() { let whiteSpaceIsEmpty = inputTextView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty if (attachedMedia.count > 0 && !whiteSpaceIsEmpty) || (inputTextView.text != "" && !whiteSpaceIsEmpty) { sendButton.isEnabled = true } else { sendButton.isEnabled = false } } func textViewDidChange(_ textView: UITextView) { confirugeHeightConstraint() placeholderLabel.isHidden = !textView.text.isEmpty chatLogController?.isTyping = !textView.text.isEmpty handleSendButtonState() } func textViewDidEndEditing(_ textView: UITextView) { if chatLogController?.chatLogAudioPlayer != nil { chatLogController?.chatLogAudioPlayer.stop() chatLogController?.chatLogAudioPlayer = nil } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard text == "\n", let chatLogController = self.chatLogController else { return true } if chatLogController.isScrollViewAtTheBottom() { chatLogController.collectionView.scrollToBottom(animated: false) } return true } }
9b53abe0b1b07909fd066557aaed5a11
36.548287
155
0.743466
false
false
false
false
rockbruno/swiftshield
refs/heads/master
Tests/SwiftShieldTests/FeatureTestUtils.swift
gpl-3.0
1
import Foundation @testable import SwiftShieldCore var modifiableFilePath: String { path(forResource: "FeatureTestProject/FeatureTestProject/File.swift").relativePath } func modifiableFileContents() throws -> String { try File(path: modifiableFilePath).read() } var modifiablePlistPath: String { path(forResource: "FeatureTestProject/FeatureTestProject/CustomPlist.plist").relativePath } func modifiablePlistContents() throws -> String { try File(path: modifiablePlistPath).read() } func testModule( withContents contents: String = "", withPlist plistContents: String = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> </dict> </plist> """ ) throws -> Module { let projectPath = path(forResource: "FeatureTestProject/FeatureTestProject.xcodeproj").relativePath let projectFile = File(path: projectPath) let provider = SchemeInfoProvider( projectFile: projectFile, schemeName: "FeatureTestProject", taskRunner: TaskRunner(), logger: DummyLogger(), modulesToIgnore: [] ) try File(path: modifiableFilePath).write(contents: contents) try File(path: modifiablePlistPath).write(contents: plistContents) return try provider.getModulesFromProject().first! } func baseTestData(ignorePublic: Bool = false, namesToIgnore: Set<String> = []) -> (SourceKitObfuscator, SourceKitObfuscatorDataStore, ObfuscatorDelegateSpy) { let logger = Logger() let sourceKit = SourceKit(logger: logger) let dataStore = SourceKitObfuscatorDataStore() let obfuscator = SourceKitObfuscator( sourceKit: sourceKit, logger: logger, dataStore: dataStore, namesToIgnore: namesToIgnore, ignorePublic: ignorePublic ) let delegateSpy = ObfuscatorDelegateSpy() obfuscator.delegate = delegateSpy return (obfuscator, dataStore, delegateSpy) }
f41eee9c12a7ee248ed4c6316584e412
32
130
0.693122
false
true
false
false
delannoyk/SoundcloudSDK
refs/heads/master
sources/SoundcloudSDK/model/APIResponse.swift
mit
1
// // APIResponse.swift // Soundcloud // // Created by Kevin DELANNOY on 21/10/15. // Copyright © 2015 Kevin Delannoy. All rights reserved. // import Foundation public protocol APIResponse { associatedtype U var response: Result<U, SoundcloudError> { get } } public struct SimpleAPIResponse<T>: APIResponse { public typealias U = T public let response: Result<T, SoundcloudError> // MARK: Initialization init(result: Result<T, SoundcloudError>) { response = result } init(error: SoundcloudError) { response = .failure(error) } init(value: T) { response = .success(value) } } public struct PaginatedAPIResponse<T>: APIResponse { public typealias U = [T] public let response: Result<[T], SoundcloudError> private let nextPageURL: URL? private let parse: (JSONObject) -> Result<[T], SoundcloudError> // MARK: Initialization init(response: Result<[T], SoundcloudError>, nextPageURL: URL?, parse: @escaping (JSONObject) -> Result<[T], SoundcloudError>) { self.response = response self.nextPageURL = nextPageURL self.parse = parse } // MARK: Next page public var hasNextPage: Bool { return (nextPageURL != nil) } @discardableResult public func fetchNextPage(completion: @escaping (PaginatedAPIResponse<T>) -> Void) -> CancelableOperation? { if let nextPageURL = nextPageURL { let request = Request( url: nextPageURL, method: .get, parameters: nil, headers: SoundcloudClient.accessToken.map { ["Authorization": "OAuth \($0)" ] }, parse: { JSON -> Result<PaginatedAPIResponse, SoundcloudError> in return .success(PaginatedAPIResponse(JSON: JSON, parse: self.parse)) }) { result in completion(result.recover { PaginatedAPIResponse(error: $0) }) } request.start() return request } return nil } }
bf93ea6da64ad0fa147815a60c23589d
26.077922
112
0.604317
false
false
false
false
AliSoftware/SwiftGen
refs/heads/develop
Tests/SwiftGenKitTests/ColorsTests.swift
mit
1
// // SwiftGenKit UnitTests // Copyright © 2020 SwiftGen // MIT Licence // import PathKit @testable import SwiftGenKit import TestUtils import XCTest private final class TestFileParser1: ColorsFileTypeParser { init(options: ParserOptionValues) {} static let extensions = ["test1"] func parseFile(at path: Path) throws -> Colors.Palette { Colors.Palette(name: "test1", colors: [:]) } } private final class TestFileParser2: ColorsFileTypeParser { init(options: ParserOptionValues) {} static let extensions = ["test2"] func parseFile(at path: Path) throws -> Colors.Palette { Colors.Palette(name: "test2", colors: [:]) } } private final class TestFileParser3: ColorsFileTypeParser { init(options: ParserOptionValues) {} static let extensions = ["test1"] func parseFile(at path: Path) throws -> Colors.Palette { Colors.Palette(name: "test3", colors: [:]) } } final class ColorParserTests: XCTestCase { func testEmpty() throws { let parser = try Colors.Parser() let result = parser.stencilContext() XCTDiffContexts(result, expected: "empty", sub: .colors) } // MARK: - Dispatch func testDispatchKnowExtension() throws { let parser = try Colors.Parser() parser.register(parser: TestFileParser1.self) parser.register(parser: TestFileParser2.self) let filter = try Filter(pattern: ".*\\.(test1|test2)$") try parser.searchAndParse(path: "someFile.test1", filter: filter) XCTAssertEqual(parser.palettes.first?.name, "test1") } func testDispatchUnknownExtension() throws { let parser = try Colors.Parser() parser.register(parser: TestFileParser1.self) parser.register(parser: TestFileParser2.self) do { let filter = try Filter(pattern: ".*\\.unknown$") try parser.searchAndParse(path: "someFile.unknown", filter: filter) XCTFail("Code did succeed while it was expected to fail for unknown extension") } catch Colors.ParserError.unsupportedFileType { // That's the expected exception we want to happen } catch let error { XCTFail("Unexpected error occured while parsing: \(error)") } } func testDuplicateExtensionWarning() throws { var warned = false let parser = try Colors.Parser() parser.warningHandler = { _, _, _ in warned = true } parser.register(parser: TestFileParser1.self) XCTAssert(!warned, "No warning should have been triggered") parser.register(parser: TestFileParser3.self) XCTAssert(warned, "Warning should have been triggered for duplicate extension") } // MARK: - Multiple palettes func testParseMultipleFiles() throws { let parser = try Colors.Parser() try parser.searchAndParse(path: Fixtures.resource(for: "colors.clr", sub: .colors)) try parser.searchAndParse(path: Fixtures.resource(for: "extra.txt", sub: .colors)) let result = parser.stencilContext() XCTDiffContexts(result, expected: "multiple", sub: .colors) } // MARK: - String parsing func testStringNoPrefix() throws { let color = try Colors.parse(hex: "FFFFFF", path: #file) XCTAssertEqual(color, 0xFFFFFFFF) } func testStringWithHash() throws { let color = try Colors.parse(hex: "#FFFFFF", path: #file) XCTAssertEqual(color, 0xFFFFFFFF) } func testStringWith0x() throws { let color = try Colors.parse(hex: "0xFFFFFF", path: #file) XCTAssertEqual(color, 0xFFFFFFFF) } func testStringWithAlpha() throws { let color = try Colors.parse(hex: "FFFFFFCC", path: #file) XCTAssertEqual(color, 0xFFFFFFCC) } func testStringWithAlphaArgb() throws { let color = try Colors.parse(hex: "CCFFFFFF", path: #file, format: .argb) XCTAssertEqual(color, 0xFFFFFFCC) } // MARK: - Hex Value func testHexValues() { let colors: [NSColor: UInt32] = [ NSColor(red: 0, green: 0, blue: 0, alpha: 0): 0x00000000, NSColor(red: 1, green: 1, blue: 1, alpha: 1): 0xFFFFFFFF, NSColor(red: 0.973, green: 0.973, blue: 0.973, alpha: 1): 0xF8F8F8FF, NSColor(red: 0.969, green: 0.969, blue: 0.969, alpha: 1): 0xF7F7F7FF ] for (color, value) in colors { XCTAssertEqual(color.hexValue, value) } } // MARK: - Custom options func testUnknownOption() throws { do { _ = try Colors.Parser(options: ["SomeOptionThatDoesntExist": "foo"]) XCTFail("Parser successfully created with an invalid option") } catch ParserOptionList.Error.unknownOption(let key, _) { // That's the expected exception we want to happen XCTAssertEqual(key, "SomeOptionThatDoesntExist", "Failed for unexpected option \(key)") } catch let error { XCTFail("Unexpected error occured: \(error)") } } }
1929b76ea941678460b0c36d7a79dcb4
29.907895
93
0.684972
false
true
false
false
Majki92/SwiftEmu
refs/heads/master
SwiftBoy/GameBoyJoypad.swift
gpl-2.0
2
// // GameBoyJoypad.swift // SwiftBoy // // Created by Michal Majczak on 27.09.2015. // Copyright © 2015 Michal Majczak. All rights reserved. // import Foundation class GameBoyJoypad { static let BTN_UP: UInt8 = 0x40 static let BTN_DOWN: UInt8 = 0x80 static let BTN_LEFT: UInt8 = 0x20 static let BTN_RIGHT: UInt8 = 0x10 static let BTN_A: UInt8 = 0x01 static let BTN_B: UInt8 = 0x02 static let BTN_START: UInt8 = 0x08 static let BTN_SELECT: UInt8 = 0x04 var state: UInt8 var memory: GameBoyRAM? init() { state = 0xFF } func registerRAM(_ ram: GameBoyRAM) { memory = ram } func getKeyValue(_ mask: UInt8) -> UInt8 { switch mask & 0x30 { case 0x10: return 0xD0 | (state & 0x0F) case 0x20: return 0xE0 | ((state >> 4) & 0x0F) default: return 0xFF } } func pressButton(_ flag: UInt8) { if(state & flag != 0) { state &= ~flag memory?.requestInterrupt(GameBoyRAM.I_P10P13) } } func releaseButton(_ flag: UInt8) { state |= flag } }
28fa9cd61f135f11e41fefdecb3e3f97
20.636364
57
0.543697
false
false
false
false
mogstad/Delta
refs/heads/master
tests/processor_spec.swift
mit
1
import Foundation import Quick import Nimble @testable import Delta struct Model: DeltaItem, Equatable { var identifier: Int var count: Int var deltaIdentifier: Int { return self.identifier } init(identifier: Int, count: Int = 0) { self.identifier = identifier self.count = count } } func ==(lhs: Model, rhs: Model) -> Bool { return lhs.identifier == rhs.identifier && lhs.count == rhs.count } class DeltaProcessorSpec: QuickSpec { override func spec() { describe("changes(from, to)") { var records: [DeltaChange]! describe("Adding nodes") { beforeEach { let from = [Model(identifier: 1)] let to = [Model(identifier: 1), Model(identifier: 2)] records = self.records(from, to: to) expect(records.count).to(equal(1)) } it("creates “add” record") { let record = DeltaChange.add(index: 1) expect(records[0]).to(equal(record)) } } describe("Removing nodes") { beforeEach { let from = [Model(identifier: 1), Model(identifier: 2)] let to = [Model(identifier: 1)] records = self.records(from, to: to) expect(records.count).to(equal(1)) } it("creates “remove” record") { let record = DeltaChange.remove(index: 1) expect(records[0]).to(equal(record)) } } describe("Changing nodes") { beforeEach { let from = [Model(identifier: 1, count: 10)] let to = [Model(identifier: 1, count: 5)] records = self.records(from, to: to) expect(records.count).to(equal(1)) } it("creates “change” record") { let record = DeltaChange.change(index: 0, from: 0) expect(records[0]).to(equal(record)) } } describe("Changing a node and removing a node") { beforeEach { let from = [ Model(identifier: 0), Model(identifier: 1, count: 10) ] let to = [ Model(identifier: 1, count: 5) ] records = self.records(from, to: to) expect(records.count).to(equal(2)) } it("creates “remove” record") { let record = DeltaChange.remove(index: 0) expect(records[0]).to(equal(record)) } it("creates “change” record") { let record = DeltaChange.change(index: 0, from: 1) expect(records[1]).to(equal(record)) } } describe("Removing and adding") { beforeEach { let from = [Model(identifier: 16) ,Model(identifier: 64), Model(identifier: 32)] let to = [Model(identifier: 16), Model(identifier: 256), Model(identifier: 32)] records = self.records(from, to: to) expect(records.count).to(equal(2)) } it("creates “remove” record") { let record = DeltaChange.remove(index: 1) expect(records[0]).to(equal(record)) } it("creates “add” record") { let record = DeltaChange.add(index: 1) expect(records[1]).to(equal(record)) } } describe("Moving a record in a set") { beforeEach { let from = [Model(identifier: 1), Model(identifier: 3), Model(identifier: 2)] let to = [Model(identifier: 1), Model(identifier: 2), Model(identifier: 3)] records = self.records(from, to: to) expect(records.count).to(equal(1)) } it("creates “move” record") { let record = DeltaChange.move(index: 2, from: 1) expect(records[0]).to(equal(record)) } } describe("Moving multiple items in a set set") { beforeEach { let from = [ Model(identifier: 1), Model(identifier: 3), Model(identifier: 6), Model(identifier: 2), Model(identifier: 5), Model(identifier: 4) ] let to = [ Model(identifier: 1), Model(identifier: 2), Model(identifier: 3), Model(identifier: 4), Model(identifier: 5), Model(identifier: 6) ] records = self.records(from, to: to) expect(records.count).to(equal(3)) } it("moves the record") { let record = DeltaChange.move(index: 2, from: 1) let record1 = DeltaChange.move(index: 5, from: 2) let record2 = DeltaChange.move(index: 4, from: 4) expect(records[0]).to(equal(record)) expect(records[1]).to(equal(record1)) expect(records[2]).to(equal(record2)) } } describe("Moving an item and appending an item") { beforeEach { let from = [ Model(identifier: 1), Model(identifier: 3), Model(identifier: 6) ] let to = [ Model(identifier: 4), Model(identifier: 1), Model(identifier: 6), Model(identifier: 3) ] records = self.records(from, to: to) expect(records.count).to(equal(2)) } it("moves the record") { let record = DeltaChange.move(index: 3, from: 1) expect(records[1]).to(equal(record)) } } describe("Removing an item and appending another item") { beforeEach { let from = [ Model(identifier: 4), Model(identifier: 1), Model(identifier: 3), Model(identifier: 6) ] let to = [ Model(identifier: 1), Model(identifier: 6), Model(identifier: 3) ] records = self.records(from, to: to) expect(records.count).to(equal(2)) } it("moves the record") { let record = DeltaChange.move(index: 2, from: 2) expect(records[1]).to(equal(record)) } } describe("Removing an item while moving another") { beforeEach { let from = [ Model(identifier: 0), Model(identifier: 1), Model(identifier: 2), ] let to = [ Model(identifier: 2), Model(identifier: 1), ] records = self.records(from, to: to) expect(records.count).to(equal(2)) } it("moves the record") { let removeRecord = DeltaChange.remove(index: 0) expect(records[0]).to(equal(removeRecord)) let moveRecord = DeltaChange.move(index: 0, from: 2) expect(records[1]).to(equal(moveRecord)) } } } } fileprivate func records(_ from: [Model], to: [Model]) -> [DeltaChange] { return changes(from: from, to: to) } }
0e6289dc420cbfabad5f78cbc5c81753
27.214876
90
0.521236
false
false
false
false
icylydia/PlayWithLeetCode
refs/heads/master
67. Add Binary/solution.swift
mit
1
class Solution { func addBinary(a: String, _ b: String) -> String { let x = String(a.characters.reverse()) let y = String(b.characters.reverse()) let maxLength = max(x.characters.count, y.characters.count) var carry = false var sum = false var r_ans = "" var idx = x.startIndex, idy = y.startIndex for _ in 0..<maxLength { sum = carry carry = false if idx < x.endIndex { carry = (sum && (x[idx] == "1")) sum = (sum != (x[idx] == "1")) idx = idx.advancedBy(1) } if idy < y.endIndex { carry = carry || (sum && y[idy] == "1") sum = (sum != (y[idy] == "1")) idy = idy.advancedBy(1) } r_ans += sum ? "1" : "0" } if carry { r_ans += "1" } return String(r_ans.characters.reverse()) } }
7ca4cdf358f0238b5ef31d1135e95d2a
29.5
67
0.45186
false
false
false
false
leizh007/HiPDA
refs/heads/master
HiPDA/HiPDA/General/Protocols/StoryboardLoadable.swift
mit
1
// // StoryboardLoadable.swift // HiPDA // // Created by leizh007 on 16/9/3. // Copyright © 2016年 HiPDA. All rights reserved. // import Foundation enum StoryBoard: String { case main = "Main" case login = "Login" case views = "Views" case me = "Me" case home = "Home" case message = "Message" case search = "Search" } /// 可以从storyboard中加载 protocol StoryboardLoadable { } extension StoryboardLoadable where Self: UIViewController { static var identifier: String { return "\(self)" } static func load(from storyboard: StoryBoard) -> Self { return UIStoryboard(name: storyboard.rawValue, bundle: nil) .instantiateViewController(withIdentifier: Self.identifier) as! Self } }
0c1e69ad0ff887f2b8caa47fdded3bc4
20.742857
80
0.651774
false
false
false
false
marcusellison/lil-twitter
refs/heads/master
lil-twitter/ReplyViewController.swift
mit
1
// // ReplyViewController.swift // lil-twitter // // Created by Marcus J. Ellison on 5/24/15. // Copyright (c) 2015 Marcus J. Ellison. All rights reserved. // import UIKit class ReplyViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screennameLabel: UILabel! @IBOutlet weak var thumbLabel: UIImageView! @IBOutlet weak var tweetField: UITextField! var tweet: Tweet! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. var imageURL = NSURL(string: User.currentUser!.profileImageURL!) nameLabel.text = User.currentUser?.name screennameLabel.text = User.currentUser?.screenname thumbLabel.setImageWithURL(imageURL) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onReply(sender: AnyObject) { println("replying now") var tweetID = tweet.tweetIDString var text = "@" + tweet.user!.screenname! + " " + tweetField.text TwitterClient.sharedInstance.replyTweet(tweetField.text, tweetID: tweetID) { (tweet, error) -> () in self.navigationController?.popViewControllerAnimated(true) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
7ff2da969db25f9f4c6e61884415729e
25.859375
108
0.678301
false
false
false
false
bsmith11/ScoreReporter
refs/heads/master
ScoreReporter/Teams/TeamsViewModel.swift
mit
1
// // TeamsViewModel.swift // ScoreReporter // // Created by Bradley Smith on 11/22/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation import ScoreReporterCore class TeamsViewModel: NSObject { fileprivate let teamService = TeamService(client: APIClient.sharedInstance) fileprivate(set) dynamic var loading = false fileprivate(set) dynamic var error: NSError? = nil } // MARK: - Public extension TeamsViewModel { func downloadTeams() { loading = true teamService.downloadTeamList { [weak self] result in self?.loading = false self?.error = result.error } } }
53e44d805fe24f9ed4ac59b449811b2a
21.1
79
0.6727
false
false
false
false
PayNoMind/iostags
refs/heads/master
Tags/Models/TagContainer.swift
mit
2
import Foundation public class TagContainer { private var saveTag: Tag = Tag.tag("") var set: ((_ tags: OrderedSet<Tag>) -> Void)? { didSet { self.set?(self.tags) } } public var tags: OrderedSet<Tag> = [] { didSet { self.set?(self.tags) } } var currentTag: Tag = Tag.tag("") init(tags: [Tag]) { let final: [Tag] = [Tag.addTag] + (tags.contains(Tag.addTag) ? [] : tags) self.tags = OrderedSet<Tag>(final) } func startEditing(AtIndex index: Int) { saveTag = tags[index] currentTag = tags[index] // if saveTag == .addTag { // tags.insert(Tag.tag(""), atIndex: index) // } } func doneEditing(AtIndex index: Int) { if currentTag.value.isEmpty { // do nothing // reload } if saveTag.value != currentTag.value { // self.tags = self.removeAddTag() //todo handle this safer // tags.insert(currentTag, at: 0) tags.insert(currentTag, atIndex: index) // tags[index] = currentTag let final: [Tag] = [Tag.addTag] + tags //(tags.contains(Tag.addTag) ? [] : tags) let orderedSet = OrderedSet<Tag>(final) self.set?(orderedSet) } } func remove(AtIndex index: Int) { _ = tags.remove(At: index) self.set?(self.tags) } func removeAddTag() -> [Tag] { return self.tags.filter { $0 != Tag.addTag } } func insert(Tag tag: Tag) { tags.insert(tag, atIndex: 0) tags.insert(Tag.addTag, atIndex: 0) self.set?(self.tags) } }
7edc549f69ecb9b6c2da658a5bc860c7
21.636364
86
0.584337
false
false
false
false
coppercash/Anna
refs/heads/master
CoreJS/CoreJS.swift
mit
1
// // CoreJS.swift // Anna_iOS // // Created by William on 2018/4/19. // import Foundation import JavaScriptCore public struct CoreJS { public typealias Context = JSContext public typealias FileManaging = Anna.FileManaging public typealias FileHandling = Anna.FileHandling @objc(CJSDependency) @objcMembers public class Dependency : NSObject { public typealias ExceptionHandler = (JSContext?, Error?) -> Void public var moduleURL :URL? = nil, fileManager :FileManaging? = nil, standardOutput :FileHandling? = nil, exceptionHandler :ExceptionHandler? = nil, nodePathURLs :Set<URL>? = nil } } @objc(CJSFileManaging) public protocol FileManaging { @objc(contentsAtPath:) func contents(atPath path: String) -> Data? @objc(fileExistsAtPath:) func fileExists(atPath path: String) -> Bool @objc(fileExistsAtPath:isDirectory:) func fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool } extension FileManager : CoreJS.FileManaging {} @objc(CJSFileHandling) public protocol FileHandling { @objc(writeData:) func write(_ data: Data) -> Void } extension FileHandle : CoreJS.FileHandling {} class Native : NSObject, NativeJSExport { weak var context :JSContext? let module :Module, fileManager :FileManaging, standardOutput :FileHandling init( context :JSContext, fileManager :FileManaging, standardOutput :FileHandling, paths :Set<URL> ) { self.module = Module( fileManager: fileManager, core: [], global: paths ) self.context = context self.fileManager = fileManager self.standardOutput = standardOutput } func contains( _ id :JSValue ) -> NSNumber { return (false as NSNumber) } func moduleExports( _ id :JSValue ) -> JSExport! { return nil } func resolvedPath( _ id :JSValue, _ parent :JSValue, _ main :JSValue ) -> String! { guard let id = id.string() else { return nil } let module = (parent.url() ?? main.url())?.deletingLastPathComponent() return try? self.module.resolve( x: id, from: module ) } func load( _ jspath :JSValue, _ exports :JSValue, _ require :JSValue, _ module :JSValue ) { guard let context = self.context, let url = jspath.url() else { return } self.module.loadScript( at: url, to: context, exports: exports, require: require, module: module ) } func log( _ string :String ) { guard let data = (string + "\n").data(using: .utf8) else { return } self.standardOutput.write(data) } } @objc protocol NativeJSExport : JSExport { func contains( _ id :JSValue ) -> NSNumber func moduleExports( _ id :JSValue ) -> JSExport! func resolvedPath( _ id :JSValue, _ parent :JSValue, _ main :JSValue ) -> String! func load( _ path :JSValue, _ exports :JSValue, _ require :JSValue, _ module :JSValue ) func log( _ string :String ) } extension JSContext { func setup( with dependency :CoreJS.Dependency? = nil ) throws { let context = self context.name = "CoreJS" if let handle = dependency?.exceptionHandler { context.exceptionHandler = { handle( $0, $1?.error()) } } context.globalObject.setValue( context.globalObject, forProperty: "global" ) let fileManager = dependency?.fileManager ?? FileManager.default, standardOutput = dependency?.standardOutput ?? FileHandle.standardOutput, moduleURL = dependency?.moduleURL ?? Bundle.main .bundleURL .appendingPathComponent("corejs") .appendingPathExtension("bundle"), paths = dependency?.nodePathURLs ?? Set(), native = Native( context: context, fileManager: fileManager, standardOutput: standardOutput, paths: paths ) let mainScriptPath = try native.module.resolve( x: moduleURL.path, from: nil ), require = context.evaluateScript(""" (function() { return function () {}; })(); """) as JSValue, module = context.evaluateScript(""" (function() { return { exports: {} }; })(); """) as JSValue, exports = module.forProperty("exports") as JSValue native.module.loadScript( at: URL(fileURLWithPath: mainScriptPath), to: context, exports: exports, require: require, module: module ) exports .forProperty("setup") .call(withArguments: [native]) } func require( _ identifier :String ) -> JSValue! { return self .globalObject .forProperty("require") .call(withArguments: [identifier]) } } extension JSValue { func error() -> Error? { let jsValue = self guard let name = jsValue.forProperty("name").toString(), let message = jsValue.forProperty("message").toString(), let stack = jsValue.forProperty("stack").toString() else { return nil } return NSError( domain: name, code: -1, userInfo: [ NSLocalizedDescriptionKey: message, NSLocalizedFailureReasonErrorKey: stack, ] ) } func string() -> String? { let value = self guard value.isString else { return nil } return value.toString() } func url() -> URL? { let value = self guard value.isString else { return nil } return URL(fileURLWithPath: value.toString()) } }
d198a0adc2a4c99b73b770ad31d014a8
22.606498
93
0.528215
false
false
false
false
LeeWongSnail/Swift
refs/heads/master
DesignBox/DesignBox/App/Publish/ViewController/View/ArtPublishMenuViewController.swift
mit
1
// // ArtPublishMenuViewController.swift // DesignBox // // Created by LeeWong on 2017/9/11. // Copyright © 2017年 LeeWong. All rights reserved. // import UIKit class ArtPublishMenuViewController: UIViewController { var rootNaviController:UINavigationController? var topAlphaView: UIView? var menuView: ArtPublishChoiceView? //MARK: - ADD TAP Gesture func publishWorkDidClick() -> Void { dismissMenu() let vc = ArtPublishWorkViewController() vc.hidesBottomBarWhenPushed = true let nav = UINavigationController(rootViewController: vc) self.navigationController?.present(nav, animated: true, completion: nil) } func publishRequirementDidClick() -> Void { dismissMenu() let vc = ArtPublishWorkViewController() vc.hidesBottomBarWhenPushed = true let nav = UINavigationController(rootViewController: vc) self.navigationController?.present(nav, animated: true, completion: nil) } func dismissMenu() -> Void { dismissMenuAnimated(animated: true) } func dismissMenuAnimated(animated:Bool) -> Void { if animated { UIView.animate(withDuration: 0.2, animations: { self.menuView?.center = CGPoint(x: self.view.frame.size.width/2, y: -((self.menuView?.frame.size.height)!/2)) self.view.backgroundColor = UIColor.init(white: 0, alpha: 0) }, completion: { (finish) in self.view.removeFromSuperview() self.removeTopAlphaView() self.removeFromParentViewController() }) } else { self.view.removeFromSuperview() self.removeFromParentViewController() removeTopAlphaView() } } func showInViewController(viewController:UIViewController) -> Void { if viewController.isKind(of: UITabBarController.self) { self.rootNaviController = (viewController as! UITabBarController).selectedViewController as? UINavigationController } else if (viewController.isKind(of: UINavigationController.self)) { self.rootNaviController = viewController as? UINavigationController } else { self.rootNaviController = viewController.navigationController } AppDelegate.getRootWindow()?.addSubview(self.view) self.rootNaviController?.addChildViewController(self) self.view.snp.makeConstraints { (make) in make.edges.equalTo(AppDelegate.getRootWindow()!) } self.rootNaviController?.topViewController?.navigationItem.rightBarButtonItem?.title = nil self.rootNaviController?.topViewController?.navigationItem.rightBarButtonItem?.image = UIImage.init(named: "publish_menu_close") DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.showTopAlphaView() self.showMenuView() } } func addTapGesture() -> Void { self.view.backgroundColor = UIColor.init(white: 0, alpha: 0.8) self.view.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(ArtPublishMenuViewController.dismissMenu)) self.view.addGestureRecognizer(tap) } //MARK: - LOAD VIEW func buildUI() -> Void { } func showTopAlphaView() -> Void { self.topAlphaView = self.rootNaviController?.view.resizableSnapshotView(from: CGRect.init(x: 0, y: 0, width: SCREEN_W, height: 64), afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero) let tap = UITapGestureRecognizer(target: self, action: #selector(ArtPublishMenuViewController.dismissMenu)) self.topAlphaView?.addGestureRecognizer(tap) AppDelegate.getRootWindow()?.addSubview(self.topAlphaView!) self.topAlphaView?.snp.makeConstraints({ (make) in make.top.left.right.equalTo(AppDelegate.getRootWindow()!) make.bottom.equalTo((AppDelegate.getRootWindow()?.snp.top)!).offset(64) }) } func removeTopAlphaView() -> Void { self.topAlphaView?.removeFromSuperview() self.rootNaviController?.topViewController?.navigationItem.rightBarButtonItem?.image = UIImage.init(named: "icon_publish") } func showMenuView() -> Void { let menuView = UINib(nibName: "ArtPublishChoiceView", bundle: nil).instantiate(withOwner: self, options: nil)[0] as! ArtPublishChoiceView menuView.frame = CGRect.init(x: 0, y: 64, width: SCREEN_W, height: 260) self.view.addSubview(menuView) self.view.insertSubview(menuView, belowSubview: self.topAlphaView!) menuView.center = CGPoint.init(x: SCREEN_W/2, y: -menuView.frame.size.height/2) UIView.animate(withDuration: 0.2) { self.view.backgroundColor = UIColor(white: 0, alpha: 0.5) menuView.center = CGPoint.init(x: SCREEN_W/2, y: menuView.frame.size.height/2 + 64) } self.menuView = menuView self.menuView?.publishRequirement.addTarget(self, action: #selector(ArtPublishMenuViewController.publishRequirementDidClick), for: UIControlEvents.touchUpInside) self.menuView?.publishWork.addTarget(self, action: #selector(ArtPublishMenuViewController.publishWorkDidClick), for: UIControlEvents.touchUpInside) } //MARK:- LIFE CYCLE override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. addTapGesture() buildUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
630680d752bb1238a091492369efc23c
36.202532
200
0.649711
false
false
false
false
gejingguo/NavMesh2D
refs/heads/master
Sources/Triangle.swift
apache-2.0
1
// // Triangle.swift // NavMesh2D // // Created by andyge on 16/6/25. // // import Foundation /// 三角形 public class Triangle { public var id = -1 public var groupId = -1 public var points = [Vector2D](repeating: Vector2D(), count: 3) public var neighbors = [Int](repeating: -1, count: 3) var center = Vector2D() var box = Rect() var wallDistances = [Double](repeating: 0.0, count: 3) public init() { } public init(id: Int, groupId: Int, point1: Vector2D, point2: Vector2D, point3: Vector2D) { self.id = id self.groupId = groupId self.points[0] = point1 self.points[1] = point2 self.points[2] = point3 // 计算中心点 center.x = (points[0].x + points[1].x + points[2].x)/3 center.y = (points[0].y + points[1].y + points[2].y)/3 // 计算相邻俩点中点距离 var wallMidPoints = [Vector2D](repeating: Vector2D(), count: 3) wallMidPoints[0] = Vector2D(x: (points[0].x + points[1].x)/2, y: (points[0].y + points[1].y)/2) wallMidPoints[1] = Vector2D(x: (points[1].x + points[2].x)/2, y: (points[1].y + points[2].y)/2) wallMidPoints[2] = Vector2D(x: (points[2].x + points[0].x)/2, y: (points[2].y + points[0].y)/2) wallDistances[0] = (wallMidPoints[0] - wallMidPoints[1]).length wallDistances[1] = (wallMidPoints[1] - wallMidPoints[2]).length wallDistances[2] = (wallMidPoints[2] - wallMidPoints[0]).length // 计算包围盒 calcBoxCollider() } /// 计算包围盒 func calcBoxCollider() { if points[0] == points[1] || points[1] == points[2] || points[2] == points[0] { fatalError("triangle not valid.") //return } var xMin = points[0].x var xMax = xMin var yMin = points[0].y var yMax = yMin for i in 1..<3 { if points[i].x < xMin { xMin = points[i].x } else if points[i].x > xMax { xMax = points[i].x } else if points[i].y < yMin { yMin = points[i].y } else if points[i].y > yMax { yMax = points[i].y } } self.box.origin = Vector2D(x: xMin, y: yMin) self.box.size.width = xMax - xMin self.box.size.height = yMax - yMin } /// 获取索引对应的边 public func getSide(index: Int) -> Line? { switch index { case 0: return Line(start: points[0], end: points[1]) case 1: return Line(start: points[1], end: points[2]) case 2: return Line(start: points[2], end: points[0]) default: return nil } } /// 检查点是否在三角形中(边上也算) public func contains(point: Vector2D) -> Bool { if !self.box.contains(point: point) { return false; } guard let resultA = getSide(index: 0)?.classifyPoint(point: point) else { return false } guard let resultB = getSide(index: 1)?.classifyPoint(point: point) else { return false } guard let resultC = getSide(index: 2)?.classifyPoint(point: point) else { return false } if resultA == PointSide.Online || resultB == PointSide.Online || resultC == PointSide.Online { return true } else if resultA == PointSide.Right && resultB == PointSide.Right && resultC == PointSide.Right { return true } else { return false } } /// 检查是否是邻居三角形 public func isNeighbor(triangle: Triangle) -> Bool { for i in 0..<3 { if neighbors[i] == triangle.id { return true; } } return false; } /// 获取邻居三角形边索引 public func getWallIndex(neighborId: Int) -> Int { for i in 0..<3 { if neighbors[i] == neighborId { return i } } return -1 } }
180769f80c177993a4558af81e7835ff
27.985915
104
0.500243
false
false
false
false
LYM-mg/MGDS_Swift
refs/heads/master
MGDS_Swift/MGDS_Swift/Class/Home/Miao/ViewModel/MGNewViewModel.swift
mit
1
// // MGNewViewModel.swift // MGDS_Swift // // Created by i-Techsys.com on 17/1/19. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit class MGNewViewModel: NSObject { /** 当前页 */ var currentPage: Int = 1 /** 用户 */ var anchors = [MGAnchor]() } extension MGNewViewModel { func getHotData(finishedCallBack: @escaping (_ err: Error?) -> ()) { NetWorkTools.requestData(type: .get, urlString: "http://live.9158.com/Room/GetNewRoomOnline?page=\(self.currentPage)", succeed: { [unowned self] (result, err) in guard let result = result as? [String: Any] else { return } guard let data = result["data"] as? [String: Any] else { return } guard let dictArr = data["list"] as? [[String: Any]] else { return } for anchorDict in dictArr { let anchor = MGAnchor(dict: anchorDict) self.anchors.append(anchor) } finishedCallBack(nil) }) { (err) in finishedCallBack(err) } } }
409da9fb897eff9c4e5472f6d6d6946e
29.685714
169
0.568901
false
false
false
false
KinoAndWorld/Meizhi-Swift
refs/heads/master
Meizhi-Swift/Scene/CoverController.swift
apache-2.0
1
// // CoverController.swift // Meizhi-Swift // // Created by kino on 14/11/26. // Copyright (c) 2014年 kino. All rights reserved. // import UIKit extension Array { func find(includedElement: T -> Bool) -> Int? { for (idx, element) in enumerate(self) { if includedElement(element) { return idx } } return nil } } class CoverController: BaseController , UITableViewDelegate , UITableViewDataSource{ var coverID = "" var covers:Array<Cover> = [] var loadingView:LoadingView? = nil @IBOutlet weak var coverTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() prepareData() } func prepareData(){ loadingView = LoadingView() loadingView!.showMe() if coverID != ""{ CoverManager.fetchCovers(coverID: coverID, andComplete:{ [weak self] covers in if let strongSelf = self{ strongSelf.loadingView?.hideMe() if covers.count != 0{ strongSelf.covers = covers strongSelf.observerCoverSize() strongSelf.reloadCoversData() }else{ //handle blank data } } }) } } func observerCoverSize(){ for cover in covers{ cover.obseverImageSize = { [weak self] newSizeCover in if let sgSelf = self{ let index = sgSelf.covers.find{ $0 == newSizeCover} if index != nil { sgSelf.reloadTableByRow(index!) } } } } } func reloadTableByRow(row:Int){ dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in let indexPath = NSIndexPath(forRow: row, inSection: 0) if let sgSelf = self{ sgSelf.coverTableView.beginUpdates() sgSelf.coverTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) sgSelf.coverTableView.endUpdates() } }) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return heightForIndexPath(indexPath) } func heightForIndexPath(indexPath:NSIndexPath) -> CGFloat{ let model = self.covers[indexPath.row] as Cover if model.imageSize.height != 0 { return model.imageSize.height }else{ return 500 } } func reloadCoversData(){ coverTableView.reloadData() } //MARK: TableView func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.covers.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let coverCell = tableView.dequeueReusableCellWithIdentifier("CoverTableCell", forIndexPath: indexPath) as CoverTableCell let model = self.covers[indexPath.row] as Cover coverCell.configureCellWithCover(model) coverCell.touchCellCall = {[weak self] covCell in if let sSelf = self{ let model = covCell.model! as Cover let imageInfo = JTSImageInfo() imageInfo.image = covCell.coverImageView.image imageInfo.imageURL = NSURL(string: model.imageUrl) imageInfo.referenceRect = covCell.coverImageView.frame; imageInfo.referenceView = covCell.coverImageView.superview; let imageViewer = JTSImageViewController(imageInfo: imageInfo, mode: JTSImageViewControllerMode.Image, backgroundStyle: JTSImageViewControllerBackgroundOptions.Blurred) imageViewer.showFromViewController(self, transition: JTSImageViewControllerTransition._FromOriginalPosition) } } return coverCell } }
238a7d7aaa7b3264911776b96519d2a5
31.511278
128
0.555273
false
false
false
false
CPRTeam/CCIP-iOS
refs/heads/master
Pods/Nuke/Sources/ImageProcessing.swift
gpl-3.0
1
// The MIT License (MIT) // // Copyright (c) 2015-2020 Alexander Grebenyuk (github.com/kean). import Foundation #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #endif #if os(watchOS) import WatchKit #endif #if os(macOS) import Cocoa #endif // MARK: - ImageProcessing /// Performs image processing. /// /// For basic processing needs, implement the following method: /// /// ``` /// func process(image: PlatformImage) -> PlatformImage? /// ``` /// /// If your processor needs to manipulate image metadata (`ImageContainer`), or /// get access to more information via the context (`ImageProcessingContext`), /// there is an additional method that allows you to do that: /// /// ``` /// func process(image container: ImageContainer, context: ImageProcessingContext) -> ImageContainer? /// ``` /// /// You must implement either one of those methods. public protocol ImageProcessing { /// Returns a processed image. By default, returns `nil`. /// /// - note: Gets called a background queue managed by the pipeline. func process(_ image: PlatformImage) -> PlatformImage? /// Returns a processed image. By default, this calls the basic `process(image:)` method. /// /// - note: Gets called a background queue managed by the pipeline. func process(_ container: ImageContainer, context: ImageProcessingContext) -> ImageContainer? /// Returns a string that uniquely identifies the processor. /// /// Consider using the reverse DNS notation. var identifier: String { get } /// Returns a unique processor identifier. /// /// The default implementation simply returns `var identifier: String` but /// can be overridden as a performance optimization - creating and comparing /// strings is _expensive_ so you can opt-in to return something which is /// fast to create and to compare. See `ImageProcessors.Resize` for an example. /// /// - note: A common approach is to make your processor `Hashable` and return `self` /// from `hashableIdentifier`. var hashableIdentifier: AnyHashable { get } } public extension ImageProcessing { /// The default implementation simply calls the basic /// `process(_ image: PlatformImage) -> PlatformImage?` method. func process(_ container: ImageContainer, context: ImageProcessingContext) -> ImageContainer? { container.map(process) } /// The default impleemntation simply returns `var identifier: String`. var hashableIdentifier: AnyHashable { identifier } } /// Image processing context used when selecting which processor to use. public struct ImageProcessingContext { public let request: ImageRequest public let response: ImageResponse public let isFinal: Bool public init(request: ImageRequest, response: ImageResponse, isFinal: Bool) { self.request = request self.response = response self.isFinal = isFinal } } // MARK: - ImageProcessors /// A namespace for all processors that implement `ImageProcessing` protocol. public enum ImageProcessors {} // MARK: - ImageProcessors.Resize extension ImageProcessors { /// Scales an image to a specified size. public struct Resize: ImageProcessing, Hashable, CustomStringConvertible { private let size: CGSize private let contentMode: ContentMode private let crop: Bool private let upscale: Bool /// An option for how to resize the image. public enum ContentMode: CustomStringConvertible { /// Scales the image so that it completely fills the target area. /// Maintains the aspect ratio of the original image. case aspectFill /// Scales the image so that it fits the target size. Maintains the /// aspect ratio of the original image. case aspectFit public var description: String { switch self { case .aspectFill: return ".aspectFill" case .aspectFit: return ".aspectFit" } } } /// Initializes the processor with the given size. /// /// - parameter size: The target size. /// - parameter unit: Unit of the target size, `.points` by default. /// - parameter contentMode: `.aspectFill` by default. /// - parameter crop: If `true` will crop the image to match the target size. /// Does nothing with content mode .aspectFill. `false` by default. /// - parameter upscale: `false` by default. public init(size: CGSize, unit: ImageProcessingOptions.Unit = .points, contentMode: ContentMode = .aspectFill, crop: Bool = false, upscale: Bool = false) { self.size = CGSize(size: size, unit: unit) self.contentMode = contentMode self.crop = crop self.upscale = upscale } /// Resizes the image to the given width preserving aspect ratio. /// /// - parameter unit: Unit of the target size, `.points` by default. public init(width: CGFloat, unit: ImageProcessingOptions.Unit = .points, crop: Bool = false, upscale: Bool = false) { self.init(size: CGSize(width: width, height: 4096), unit: unit, contentMode: .aspectFit, crop: crop, upscale: upscale) } /// Resizes the image to the given height preserving aspect ratio. /// /// - parameter unit: Unit of the target size, `.points` by default. public init(height: CGFloat, unit: ImageProcessingOptions.Unit = .points, crop: Bool = false, upscale: Bool = false) { self.init(size: CGSize(width: 4096, height: height), unit: unit, contentMode: .aspectFit, crop: crop, upscale: upscale) } public func process(_ image: PlatformImage) -> PlatformImage? { if crop && contentMode == .aspectFill { return image.processed.byResizingAndCropping(to: size) } else { return image.processed.byResizing(to: size, contentMode: contentMode, upscale: upscale) } } public var identifier: String { "com.github.kean/nuke/resize?s=\(size),cm=\(contentMode),crop=\(crop),upscale=\(upscale)" } public var hashableIdentifier: AnyHashable { self } public var description: String { "Resize(size: \(size) pixels, contentMode: \(contentMode), crop: \(crop), upscale: \(upscale))" } } } #if os(iOS) || os(tvOS) || os(watchOS) // MARK: - ImageProcessors.Circle extension ImageProcessors { /// Rounds the corners of an image into a circle. If the image is not a square, /// crops it to a square first. public struct Circle: ImageProcessing, Hashable, CustomStringConvertible { private let border: ImageProcessingOptions.Border? public init(border: ImageProcessingOptions.Border? = nil) { self.border = border } public func process(_ image: PlatformImage) -> PlatformImage? { image.processed.byDrawingInCircle(border: border) } public var identifier: String { if let border = self.border { return "com.github.kean/nuke/circle?border=\(border)" } else { return "com.github.kean/nuke/circle" } } public var hashableIdentifier: AnyHashable { self } public var description: String { "Circle(border: \(border?.description ?? "nil"))" } } } // MARK: - ImageProcessors.RoundedCorners extension ImageProcessors { /// Rounds the corners of an image to the specified radius. /// /// - warning: In order for the corners to be displayed correctly, the image must exactly match the size /// of the image view in which it will be displayed. See `ImageProcessor.Resize` for more info. public struct RoundedCorners: ImageProcessing, Hashable, CustomStringConvertible { private let radius: CGFloat private let border: ImageProcessingOptions.Border? /// Initializes the processor with the given radius. /// /// - parameter radius: The radius of the corners. /// - parameter unit: Unit of the radius, `.points` by default. /// - parameter border: An optional border drawn around the image. public init(radius: CGFloat, unit: ImageProcessingOptions.Unit = .points, border: ImageProcessingOptions.Border? = nil) { self.radius = radius.converted(to: unit) self.border = border } public func process(_ image: PlatformImage) -> PlatformImage? { image.processed.byAddingRoundedCorners(radius: radius, border: border) } public var identifier: String { if let border = self.border { return "com.github.kean/nuke/rounded_corners?radius=\(radius),border=\(border)" } else { return "com.github.kean/nuke/rounded_corners?radius=\(radius)" } } public var hashableIdentifier: AnyHashable { self } public var description: String { "RoundedCorners(radius: \(radius) pixels, border: \(border?.description ?? "nil"))" } } } #if os(iOS) || os(tvOS) // MARK: - ImageProcessors.CoreImageFilter import CoreImage extension ImageProcessors { /// Applies Core Image filter (`CIFilter`) to the image. /// /// # Performance Considerations. /// /// Prefer chaining multiple `CIFilter` objects using `Core Image` facilities /// instead of using multiple instances of `ImageProcessors.CoreImageFilter`. /// /// # References /// /// - [Core Image Programming Guide](https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_intro/ci_intro.html) /// - [Core Image Filter Reference](https://developer.apple.com/library/prerelease/ios/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html) public struct CoreImageFilter: ImageProcessing, CustomStringConvertible { private let name: String private let parameters: [String: Any] public let identifier: String /// - parameter identifier: Uniquely identifies the processor. public init(name: String, parameters: [String: Any], identifier: String) { self.name = name self.parameters = parameters self.identifier = identifier } public init(name: String) { self.name = name self.parameters = [:] self.identifier = "com.github.kean/nuke/core_image?name=\(name))" } public func process(_ image: PlatformImage) -> PlatformImage? { let filter = CIFilter(name: name, parameters: parameters) return CoreImageFilter.apply(filter: filter, to: image) } // MARK: - Apply Filter /// A default context shared between all Core Image filters. The context /// has `.priorityRequestLow` option set to `true`. public static var context = CIContext(options: [.priorityRequestLow: true]) public static func apply(filter: CIFilter?, to image: UIImage) -> UIImage? { guard let filter = filter else { return nil } return applyFilter(to: image) { filter.setValue($0, forKey: kCIInputImageKey) return filter.outputImage } } static func applyFilter(to image: UIImage, context: CIContext = context, closure: (CoreImage.CIImage) -> CoreImage.CIImage?) -> UIImage? { let ciImage: CoreImage.CIImage? = { if let image = image.ciImage { return image } if let image = image.cgImage { return CoreImage.CIImage(cgImage: image) } return nil }() guard let inputImage = ciImage, let outputImage = closure(inputImage) else { return nil } guard let imageRef = context.createCGImage(outputImage, from: outputImage.extent) else { return nil } return UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation) } public var description: String { "CoreImageFilter(name: \(name), parameters: \(parameters))" } } } // MARK: - ImageProcessors.GaussianBlur extension ImageProcessors { /// Blurs an image using `CIGaussianBlur` filter. public struct GaussianBlur: ImageProcessing, Hashable, CustomStringConvertible { private let radius: Int /// Initializes the receiver with a blur radius. public init(radius: Int = 8) { self.radius = radius } /// Applies `CIGaussianBlur` filter to the image. public func process(_ image: PlatformImage) -> PlatformImage? { let filter = CIFilter(name: "CIGaussianBlur", parameters: ["inputRadius": radius]) return CoreImageFilter.apply(filter: filter, to: image) } public var identifier: String { "com.github.kean/nuke/gaussian_blur?radius=\(radius)" } public var hashableIdentifier: AnyHashable { self } public var description: String { "GaussianBlur(radius: \(radius))" } } } #endif // MARK: - ImageDecompression (Internal) struct ImageDecompression { func decompress(image: UIImage) -> UIImage { let output = image.decompressed() ?? image ImageDecompression.setDecompressionNeeded(false, for: output) return output } // MARK: Managing Decompression State static var isDecompressionNeededAK = "ImageDecompressor.isDecompressionNeeded.AssociatedKey" static func setDecompressionNeeded(_ isDecompressionNeeded: Bool, for image: UIImage) { objc_setAssociatedObject(image, &isDecompressionNeededAK, isDecompressionNeeded, .OBJC_ASSOCIATION_RETAIN) } static func isDecompressionNeeded(for image: UIImage) -> Bool? { objc_getAssociatedObject(image, &isDecompressionNeededAK) as? Bool } } #endif // MARK: - ImageProcessors.Composition extension ImageProcessors { /// Composes multiple processors. public struct Composition: ImageProcessing, Hashable, CustomStringConvertible { let processors: [ImageProcessing] /// Composes multiple processors. public init(_ processors: [ImageProcessing]) { // note: multiple compositions are not flatten by default. self.processors = processors } public func process(_ image: PlatformImage) -> PlatformImage? { processors.reduce(image) { image, processor in autoreleasepool { image.flatMap { processor.process($0) } } } } /// Processes the given image by applying each processor in an order in /// which they were added. If one of the processors fails to produce /// an image the processing stops and `nil` is returned. public func process(_ container: ImageContainer, context: ImageProcessingContext) -> ImageContainer? { processors.reduce(container) { container, processor in autoreleasepool { container.flatMap { processor.process($0, context: context) } } } } public var identifier: String { processors.map({ $0.identifier }).joined() } public var hashableIdentifier: AnyHashable { self } public func hash(into hasher: inout Hasher) { for processor in processors { hasher.combine(processor.hashableIdentifier) } } public static func == (lhs: Composition, rhs: Composition) -> Bool { lhs.processors == rhs.processors } public var description: String { "Composition(processors: \(processors))" } } } // MARK: - ImageProcessors.Anonymous extension ImageProcessors { /// Processed an image using a specified closure. public struct Anonymous: ImageProcessing, CustomStringConvertible { public let identifier: String private let closure: (PlatformImage) -> PlatformImage? public init(id: String, _ closure: @escaping (PlatformImage) -> PlatformImage?) { self.identifier = id self.closure = closure } public func process(_ image: PlatformImage) -> PlatformImage? { self.closure(image) } public var description: String { "AnonymousProcessor(identifier: \(identifier)" } } } // MARK: - Image Processing (Internal) extension PlatformImage { /// Draws the image in a `CGContext` in a canvas with the given size using /// the specified draw rect. /// /// For example, if the canvas size is `CGSize(width: 10, height: 10)` and /// the draw rect is `CGRect(x: -5, y: 0, width: 20, height: 10)` it would /// draw the input image (which is horizontal based on the known draw rect) /// in a square by centering it in the canvas. /// /// - parameter drawRect: `nil` by default. If `nil` will use the canvas rect. func draw(inCanvasWithSize canvasSize: CGSize, drawRect: CGRect? = nil) -> PlatformImage? { guard let cgImage = cgImage else { return nil } // For more info see: // - Quartz 2D Programming Guide // - https://github.com/kean/Nuke/issues/35 // - https://github.com/kean/Nuke/issues/57 let alphaInfo: CGImageAlphaInfo = cgImage.isOpaque ? .noneSkipLast : .premultipliedLast guard let ctx = CGContext( data: nil, width: Int(canvasSize.width), height: Int(canvasSize.height), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue) else { return nil } ctx.draw(cgImage, in: drawRect ?? CGRect(origin: .zero, size: canvasSize)) guard let outputCGImage = ctx.makeImage() else { return nil } return PlatformImage.make(cgImage: outputCGImage, source: self) } /// Decompresses the input image by drawing in the the `CGContext`. func decompressed() -> PlatformImage? { guard let cgImage = cgImage else { return nil } return draw(inCanvasWithSize: cgImage.size, drawRect: CGRect(origin: .zero, size: cgImage.size)) } } // MARK: - ImageProcessingExtensions extension PlatformImage { var processed: ImageProcessingExtensions { ImageProcessingExtensions(image: self) } } struct ImageProcessingExtensions { let image: PlatformImage func byResizing(to targetSize: CGSize, contentMode: ImageProcessors.Resize.ContentMode, upscale: Bool) -> PlatformImage? { guard let cgImage = image.cgImage else { return nil } let scale = contentMode == .aspectFill ? cgImage.size.scaleToFill(targetSize) : cgImage.size.scaleToFit(targetSize) guard scale < 1 || upscale else { return image // The image doesn't require scaling } let size = cgImage.size.scaled(by: scale).rounded() return image.draw(inCanvasWithSize: size) } /// Crops the input image to the given size and resizes it if needed. /// - note: this method will always upscale. func byResizingAndCropping(to targetSize: CGSize) -> PlatformImage? { guard let cgImage = image.cgImage else { return nil } let imageSize = cgImage.size let scaledSize = imageSize.scaled(by: cgImage.size.scaleToFill(targetSize)) let drawRect = scaledSize.centeredInRectWithSize(targetSize) return image.draw(inCanvasWithSize: targetSize, drawRect: drawRect) } #if os(iOS) || os(tvOS) || os(watchOS) func byDrawingInCircle(border: ImageProcessingOptions.Border?) -> UIImage? { guard let squared = byCroppingToSquare(), let cgImage = squared.cgImage else { return nil } let radius = CGFloat(cgImage.width) / 2.0 // Can use any dimension since image is a square return squared.processed.byAddingRoundedCorners(radius: radius, border: border) } /// Draws an image in square by preserving an aspect ratio and filling the /// square if needed. If the image is already a square, returns an original image. func byCroppingToSquare() -> UIImage? { guard let cgImage = image.cgImage else { return nil } guard cgImage.width != cgImage.height else { return image // Already a square } let imageSize = cgImage.size let side = min(cgImage.width, cgImage.height) let targetSize = CGSize(width: side, height: side) let cropRect = CGRect(origin: .zero, size: targetSize).offsetBy( dx: max(0, (imageSize.width - targetSize.width) / 2), dy: max(0, (imageSize.height - targetSize.height) / 2) ) guard let cropped = cgImage.cropping(to: cropRect) else { return nil } return UIImage(cgImage: cropped, scale: image.scale, orientation: image.imageOrientation) } /// Adds rounded corners with the given radius to the image. /// - parameter radius: Radius in pixels. /// - parameter border: Optional stroke border. func byAddingRoundedCorners(radius: CGFloat, border: ImageProcessingOptions.Border? = nil) -> UIImage? { guard let cgImage = image.cgImage else { return nil } let imageSize = cgImage.size UIGraphicsBeginImageContextWithOptions(imageSize, false, 1.0) defer { UIGraphicsEndImageContext() } let rect = CGRect(origin: CGPoint.zero, size: imageSize) let clippingPath = UIBezierPath(roundedRect: rect, cornerRadius: radius) clippingPath.addClip() image.draw(in: CGRect(origin: CGPoint.zero, size: imageSize)) if let border = border, let context = UIGraphicsGetCurrentContext() { context.setStrokeColor(border.color.cgColor) let path = UIBezierPath(roundedRect: rect, cornerRadius: radius) path.lineWidth = border.width path.stroke() } guard let roundedImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } return UIImage(cgImage: roundedImage, scale: image.scale, orientation: image.imageOrientation) } #endif } // MARK: - CoreGraphics Helpers (Internal) #if os(macOS) extension NSImage { var cgImage: CGImage? { cgImage(forProposedRect: nil, context: nil, hints: nil) } static func make(cgImage: CGImage, source: NSImage) -> NSImage { NSImage(cgImage: cgImage, size: .zero) } } #else extension UIImage { static func make(cgImage: CGImage, source: UIImage) -> UIImage { UIImage(cgImage: cgImage, scale: source.scale, orientation: source.imageOrientation) } } #endif extension CGImage { /// Returns `true` if the image doesn't contain alpha channel. var isOpaque: Bool { let alpha = alphaInfo return alpha == .none || alpha == .noneSkipFirst || alpha == .noneSkipLast } var size: CGSize { CGSize(width: width, height: height) } } extension CGFloat { func converted(to unit: ImageProcessingOptions.Unit) -> CGFloat { switch unit { case .pixels: return self case .points: return self * Screen.scale } } } extension CGSize: Hashable { // For some reason `CGSize` isn't `Hashable` public func hash(into hasher: inout Hasher) { hasher.combine(width) hasher.combine(height) } } extension CGSize { /// Creates the size in pixels by scaling to the input size to the screen scale /// if needed. init(size: CGSize, unit: ImageProcessingOptions.Unit) { switch unit { case .pixels: self = size // The size is already in pixels case .points: self = size.scaled(by: Screen.scale) } } func scaled(by scale: CGFloat) -> CGSize { CGSize(width: width * scale, height: height * scale) } func rounded() -> CGSize { CGSize(width: CGFloat(round(width)), height: CGFloat(round(height))) } } extension CGSize { func scaleToFill(_ targetSize: CGSize) -> CGFloat { let scaleHor = targetSize.width / width let scaleVert = targetSize.height / height return max(scaleHor, scaleVert) } func scaleToFit(_ targetSize: CGSize) -> CGFloat { let scaleHor = targetSize.width / width let scaleVert = targetSize.height / height return min(scaleHor, scaleVert) } /// Calculates a rect such that the output rect will be in the center of /// the rect of the input size (assuming origin: .zero) func centeredInRectWithSize(_ targetSize: CGSize) -> CGRect { // First, resize the original size to fill the target size. CGRect(origin: .zero, size: self).offsetBy( dx: -(width - targetSize.width) / 2, dy: -(height - targetSize.height) / 2 ) } } // MARK: - ImageProcessing Extensions (Internal) func == (lhs: [ImageProcessing], rhs: [ImageProcessing]) -> Bool { guard lhs.count == rhs.count else { return false } // Lazily creates `hashableIdentifiers` because for some processors the // identifiers might be expensive to compute. return zip(lhs, rhs).allSatisfy { $0.hashableIdentifier == $1.hashableIdentifier } } // MARK: - ImageProcessingOptions public enum ImageProcessingOptions { public enum Unit: CustomStringConvertible { case points case pixels public var description: String { switch self { case .points: return "points" case .pixels: return "pixels" } } } #if os(iOS) || os(tvOS) || os(watchOS) /// Draws a border. /// /// - warning: To make sure that the border looks the way you expect, /// make sure that the images you display exactly match the size of the /// views in which they get displayed. If you can't guarantee that, pleasee /// consider adding border to a view layer. This should be your primary /// option regardless. public struct Border: Hashable, CustomStringConvertible { public let color: UIColor public let width: CGFloat /// - parameter color: Border color. /// - parameter width: Border width. 1 points by default. /// - parameter unit: Unit of the width, `.points` by default. public init(color: UIColor, width: CGFloat = 1, unit: Unit = .points) { self.color = color self.width = width.converted(to: unit) } public var description: String { "Border(color: \(color.hex), width: \(width) pixels)" } } #endif } // MARK: - Misc (Internal) struct Screen { #if os(iOS) || os(tvOS) /// Returns the current screen scale. static var scale: CGFloat { UIScreen.main.scale } #elseif os(watchOS) /// Returns the current screen scale. static var scale: CGFloat { WKInterfaceDevice.current().screenScale } #elseif os(macOS) /// Always returns 1. static var scale: CGFloat { 1 } #endif } #if os(iOS) || os(tvOS) || os(watchOS) extension UIColor { /// Returns a hex representation of the color, e.g. "#FFFFAA". var hex: String { var (r, g, b, a) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0)) getRed(&r, green: &g, blue: &b, alpha: &a) let components = [r, g, b, a < 1 ? a : nil] return "#" + components .compactMap { $0 } .map { String(format: "%02lX", lroundf(Float($0) * 255)) } .joined() } } #endif
0cd82e29b8257c32888ba4faac1fd3cf
34.21
167
0.627734
false
false
false
false
SugarRecord/SugarRecord
refs/heads/master
Example/SugarRecord/Source/Main/ViewController.swift
mit
6
import UIKit import SnapKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Attributes lazy var tableView: UITableView = { let _tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain) _tableView.translatesAutoresizingMaskIntoConstraints = false _tableView.delegate = self _tableView.dataSource = self _tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "default-cell") return _tableView }() // MARK: - Init init() { super.init(nibName: nil, bundle: nil) self.title = "SugarRecord Examples" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK - Lifecycle override func viewDidLoad() { super.viewDidLoad() setup() } // MARK: - Setup fileprivate func setup() { setupView() setupTableView() } fileprivate func setupView() { self.view.backgroundColor = UIColor.white } fileprivate func setupTableView() { self.view.addSubview(tableView) self.tableView.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self.view) } } // MARK: - UITableViewDataSource / UITableViewDelegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "default-cell")! switch (indexPath as NSIndexPath).row { case 0: cell.textLabel?.text = "CoreData Basic" default: cell.textLabel?.text = "" } cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch (indexPath as NSIndexPath).row { case 0: self.navigationController?.pushViewController(CoreDataBasicView(), animated: true) default: break } } }
a6c2017158e2e0e0b3923f965253462d
27.345238
100
0.624528
false
false
false
false
nearfri/Strix
refs/heads/main
Sources/Strix/Error/RunError.swift
mit
1
import Foundation public struct RunError: LocalizedError, CustomStringConvertible { public var input: String public var position: String.Index public var underlyingErrors: [ParseError] public init(input: String, position: String.Index, underlyingErrors: [ParseError]) { self.input = input self.position = position self.underlyingErrors = underlyingErrors } public var errorDescription: String? { var buffer = ErrorOutputBuffer() ErrorMessageWriter(input: input, position: position, errors: underlyingErrors) .write(to: &buffer) return buffer.text.trimmingCharacters(in: .newlines) } public var failureReason: String? { var buffer = ErrorOutputBuffer() ErrorMessageWriter(errors: underlyingErrors).write(to: &buffer) return buffer.text.trimmingCharacters(in: .newlines) } public var description: String { return "line: \(textPosition.line), column: \(textPosition.column), " + "underlyingErrors: \(underlyingErrors)" } public var textPosition: TextPosition { return TextPosition(string: input, index: position) } }
f8099b82515240d8418a1b580089493b
30.794872
88
0.65
false
false
false
false
macc704/iKF
refs/heads/master
iKF/KFLabelNoteRefView.swift
gpl-2.0
1
// // KFLabelNoteRefView.swift // iKF // // Created by Yoshiaki Matsuzawa on 2014-08-01. // Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved. // import UIKit class KFLabelNoteRefView: UIView { var model:KFReference!; var icon: KFPostRefIconView!; var titleLabel: UILabel!; var authorLabel: UILabel!; required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(ref: KFReference) { self.model = ref; icon = KFPostRefIconView(frame: CGRectMake(5, 5, 25, 25)); titleLabel = UILabel(frame: CGRectMake(40, 7, 200, 20)); authorLabel = UILabel(frame: CGRectMake(50, 23, 120, 10)); super.init(frame: KFAppUtils.DEFAULT_RECT()); self.layer.cornerRadius = 5; self.layer.masksToBounds = true; self.backgroundColor = UIColor.clearColor(); self.frame = CGRectMake(0, 0, 230, 40); self.addSubview(icon); titleLabel.font = UIFont.systemFontOfSize(13); self.addSubview(titleLabel); authorLabel.font = UIFont.systemFontOfSize(10); self.addSubview(authorLabel); self.layer.cornerRadius = 5; self.layer.masksToBounds = true; self.updateFromModel(); } func updateFromModel(){ icon.beenRead = (self.model.post as KFNote).beenRead; icon.update(); titleLabel.text = (self.model.post as KFNote).title; titleLabel.sizeToFit(); authorLabel.text = (self.model.post as KFNote).primaryAuthor?.getFullName(); authorLabel.sizeToFit(); //self.sizeToFit(); //does not work let titleRight = 45+titleLabel.frame.size.width; let authorRight = 55+authorLabel.frame.size.width; let tmp = titleRight > authorRight; let newWidth = tmp ? titleRight : authorRight; let r = self.frame; self.frame = CGRectMake(0, 0, newWidth, r.size.height); } func getRelativeReference() -> CGPoint{ return icon.center; } }
cc8951a6617441ee5b3c117b35a9d5a9
28.402778
84
0.601323
false
false
false
false
dekatotoro/FluxWithRxSwiftSample
refs/heads/master
FluxWithRxSwiftSample/Models/GitHub/GitHubLinkHeader.swift
mit
1
// // GitHubLinkHeader.swift // FluxWithRxSwiftSample // // Created by Yuji Hato on 2016/10/13. // Copyright © 2016年 dekatotoro. All rights reserved. // import Foundation // https://developer.github.com/v3/#pagination struct GitHubLinkHeader { let first: Element? let prev: Element? let next: Element? let last: Element? var hasFirstPage: Bool { return first != nil } var hasPrevPage: Bool { return prev != nil } var hasNextPage: Bool { return next != nil } var hasLastPage: Bool { return last != nil } init?(string: String) { let elements = string.components(separatedBy: ", ").flatMap { Element(string: $0) } first = elements.filter { $0.rel == "first" }.first prev = elements.filter { $0.rel == "prev" }.first next = elements.filter { $0.rel == "next" }.first last = elements.filter { $0.rel == "last" }.first if first == nil && prev == nil && next == nil && last == nil { return nil } } } extension GitHubLinkHeader { public struct Element { let uri: URL let rel: String let page: Int init?(string: String) { let attributes = string.components(separatedBy: "; ") guard attributes.count == 2 else { return nil } func trimString(_ string: String) -> String { guard string.characters.count > 2 else { return "" } return string[string.characters.index(after: string.startIndex)..<string.characters.index(before: string.endIndex)] } func value(_ field: String) -> String? { let pair = field.components(separatedBy: "=") guard pair.count == 2 else { return nil } return trimString(pair.last!) } let uriString = attributes[0] guard let uri = URL(string: trimString(uriString)) else { return nil } self.uri = uri guard let rel = value(attributes[1]) else { return nil } self.rel = rel guard let queryItems = NSURLComponents(url: uri, resolvingAgainstBaseURL: true)?.queryItems else { return nil } guard queryItems.count > 0 else { return nil } let pageQueryItem = queryItems.filter({ $0.name == "page" }).first guard let value = pageQueryItem?.value, let page = Int(value) else { return nil } self.page = page } } }
d61cca8c45ee215a58fd9ea6fef2eae3
28.142857
131
0.497899
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/UI/UserFlowViewController.swift
apache-2.0
1
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // swiftlint:disable file_length import UIKit import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs import third_party_objective_c_material_components_ios_components_Dialogs_ColorThemer protocol UserFlowViewControllerDelegate: class { /// Tells the delegate to present the account selector so a user can change or remove accounts. func presentAccountSelector() } // swiftlint:disable type_body_length // TODO: Consider breaking this class into multiple classes for each delegate. /// Manages the navigation of the user flow which begins after a user has signed in and includes /// all management of data such as viewing, creating, and adding to experiments. class UserFlowViewController: UIViewController, ExperimentsListViewControllerDelegate, ExperimentCoordinatorViewControllerDelegate, PermissionsGuideDelegate, SidebarDelegate, UINavigationControllerDelegate, ExperimentItemDelegate { /// The user flow view controller delegate. weak var delegate: UserFlowViewControllerDelegate? /// The experiment coordinator view controller. Exposed for testing. weak var experimentCoordinatorVC: ExperimentCoordinatorViewController? /// The experiments list view controller. weak var experimentsListVC: ExperimentsListViewController? /// The settings view controller. weak var settingsVC: SettingsViewController? private let accountsManager: AccountsManager private lazy var _actionAreaController = ActionArea.Controller() override var actionAreaController: ActionArea.Controller? { return _actionAreaController } private let analyticsReporter: AnalyticsReporter private let commonUIComponents: CommonUIComponents private let documentManager: DocumentManager private let drawerConfig: DrawerConfig private var existingDataMigrationManager: ExistingDataMigrationManager? private let experimentDataDeleter: ExperimentDataDeleter private let feedbackReporter: FeedbackReporter private let metadataManager: MetadataManager private lazy var _navController = UINavigationController() private var navController: UINavigationController { return FeatureFlags.isActionAreaEnabled ? _actionAreaController.navController : _navController } private let networkAvailability: NetworkAvailability private let devicePreferenceManager: DevicePreferenceManager private let preferenceManager: PreferenceManager private let queue = GSJOperationQueue() private let sensorController: SensorController private let sensorDataManager: SensorDataManager private let sidebar: SidebarViewController private let userManager: UserManager private weak var trialDetailVC: TrialDetailViewController? private weak var noteDetailController: NoteDetailController? private var importSpinnerVC: SpinnerViewController? private var importBeganOperation: GSJBlockOperation? private let userAssetManager: UserAssetManager private let operationQueue = GSJOperationQueue() private var shouldShowPreferenceMigrationMessage: Bool private let exportCoordinator: ExportCoordinator // Whether to show the experiment list pull to refresh animation. It should show once for a fresh // launch per user. private var shouldShowExperimentListPullToRefreshAnimation = true // The experiment update manager for the displayed experiment. This is populated when an // experiment is shown. Callbacks received from detail view controllers will route updates to // this manager. private var openExperimentUpdateManager: ExperimentUpdateManager? // Handles state updates to any experiment. private lazy var experimentStateManager: ExperimentStateManager = { let stateManager = ExperimentStateManager(experimentDataDeleter: experimentDataDeleter, metadataManager: metadataManager, sensorDataManager: sensorDataManager) stateManager.addListener(self) return stateManager }() // Drawer view controller is created lazily to avoid loading drawer contents until needed. private lazy var drawerVC: DrawerViewController? = { if FeatureFlags.isActionAreaEnabled { return nil } else { return DrawerViewController(analyticsReporter: analyticsReporter, drawerConfig: drawerConfig, preferenceManager: preferenceManager, sensorController: sensorController, sensorDataManager: sensorDataManager) } }() /// Designated initializer. /// /// - Parameters: /// - accountsManager: The accounts manager. /// - analyticsReporter: The analytics reporter. /// - commonUIComponents: Common UI components. /// - devicePreferenceManager: The device preference manager. /// - drawerConfig: The drawer config. /// - existingDataMigrationManager: The existing data migration manager. /// - feedbackReporter: The feedback reporter. /// - networkAvailability: Network availability. /// - sensorController: The sensor controller. /// - shouldShowPreferenceMigrationMessage: Whether to show the preference migration message. /// - userManager: The user manager. init(accountsManager: AccountsManager, analyticsReporter: AnalyticsReporter, commonUIComponents: CommonUIComponents, devicePreferenceManager: DevicePreferenceManager, drawerConfig: DrawerConfig, existingDataMigrationManager: ExistingDataMigrationManager?, feedbackReporter: FeedbackReporter, networkAvailability: NetworkAvailability, sensorController: SensorController, shouldShowPreferenceMigrationMessage: Bool, userManager: UserManager) { self.accountsManager = accountsManager self.analyticsReporter = analyticsReporter self.commonUIComponents = commonUIComponents self.devicePreferenceManager = devicePreferenceManager self.drawerConfig = drawerConfig self.existingDataMigrationManager = existingDataMigrationManager self.feedbackReporter = feedbackReporter self.networkAvailability = networkAvailability self.sensorController = sensorController self.shouldShowPreferenceMigrationMessage = shouldShowPreferenceMigrationMessage self.userManager = userManager self.documentManager = userManager.documentManager self.metadataManager = userManager.metadataManager self.preferenceManager = userManager.preferenceManager self.sensorDataManager = userManager.sensorDataManager self.userAssetManager = userManager.assetManager self.experimentDataDeleter = userManager.experimentDataDeleter sidebar = SidebarViewController(accountsManager: accountsManager, analyticsReporter: analyticsReporter) exportCoordinator = ExportCoordinator(exportType: userManager.exportType) super.init(nibName: nil, bundle: nil) // Set user tracking opt-out. analyticsReporter.setOptOut(preferenceManager.hasUserOptedOutOfUsageTracking) // Register user-specific sensors. metadataManager.registerBluetoothSensors() // Get updates for changes based on Drive sync. userManager.driveSyncManager?.delegate = self exportCoordinator.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override open func viewDidLoad() { super.viewDidLoad() if FeatureFlags.isActionAreaEnabled { addChild(_actionAreaController) view.addSubview(_actionAreaController.view) _actionAreaController.didMove(toParent: self) } else { addChild(navController) view.addSubview(navController.view) navController.didMove(toParent: self) navController.isNavigationBarHidden = true navController.delegate = self } sidebar.delegate = self if !devicePreferenceManager.hasAUserCompletedPermissionsGuide { let permissionsVC = PermissionsGuideViewController(delegate: self, analyticsReporter: analyticsReporter, devicePreferenceManager: devicePreferenceManager, showWelcomeView: !accountsManager.supportsAccounts) navController.setViewControllers([permissionsVC], animated: false) } else { // Don't need the permissions guide, just show the experiments list. showExperimentsList(animated: false) } // Listen to application notifications. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate), name: UIApplication.willTerminateNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) // Listen to notifications of newly imported experiments. NotificationCenter.default.addObserver(self, selector: #selector(experimentImportBegan), name: .documentManagerDidBeginImportExperiment, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(experimentImported), name: .documentManagerDidImportExperiment, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(experimentImportFailed), name: .documentManagerImportExperimentFailed, object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Generate the default experiment if necessary. createDefaultExperimentIfNecessary() } override var prefersStatusBarHidden: Bool { return false } override var preferredStatusBarStyle: UIStatusBarStyle { return navController.topViewController?.preferredStatusBarStyle ?? .lightContent } /// Handles a file import URL if possible. /// /// - Parameter url: A file URL. /// - Returns: True if the URL can be handled, otherwise false. func handleImportURL(_ url: URL) -> Bool { return documentManager.handleImportURL(url) } // MARK: - Notifications @objc private func applicationWillTerminate() { sensorDataManager.saveAllContexts() } @objc private func applicationWillResignActive() { sensorDataManager.saveAllContexts() } @objc private func applicationDidEnterBackground() { sensorDataManager.saveAllContexts() } @objc private func experimentImportBegan() { // Wrap the UI work of beginning an import in an operation so we can ensure it finishes before // handling success or failure. let operation = GSJBlockOperation(mainQueueBlock: { (continuation) in let showSpinnerBlock = { if let experimentsListVC = self.experimentsListVC { // Dismiss the feature highlight if necessary first. experimentsListVC.dismissFeatureHighlightIfNecessary() self.navController.popToViewController(experimentsListVC, animated: false) } guard let topViewController = self.navController.topViewController else { self.importBeganOperation = nil continuation() return } self.importSpinnerVC = SpinnerViewController() self.importSpinnerVC?.present(fromViewController: topViewController) self.importBeganOperation = nil continuation() } // Dismiss any VCs presented on the top view controller. if self.navController.topViewController?.presentedViewController != nil { self.navController.topViewController?.dismiss(animated: true, completion: showSpinnerBlock) } else { showSpinnerBlock() } }) importBeganOperation = operation queue.addOperation(operation) } @objc private func experimentImported(_ notification: Notification) { let finishedOperation = GSJBlockOperation(mainQueueBlock: { (continuation) in self.dismissExperimentImportSpinner { if let experimentID = notification.userInfo?[DocumentManager.importedExperimentIDKey] as? String { self.experimentsListShowExperiment(withID: experimentID) } continuation() } }) // Add began operation as a dependency so we don't show the experiment while the UI is still // preparing to begin. if let importBeganOperation = importBeganOperation { finishedOperation.addDependency(importBeganOperation) } queue.addOperation(finishedOperation) } @objc private func experimentImportFailed(_ notification: Notification) { let errorOperation = GSJBlockOperation(mainQueueBlock: { (continuation) in // Check for an importing while recording error, otherwise the default generic error will // be used. var errorMessage = String.importFailedFile if let errors = notification.userInfo?[DocumentManager.importFailedErrorsKey] as? [Error] { forLoop: for error in errors { switch error { case DocumentManagerError.importingDocumentWhileRecording: errorMessage = String.importFailedRecording break forLoop default: break } } } self.dismissExperimentImportSpinner { MDCAlertColorThemer.apply(ViewConstants.alertColorScheme) let alert = MDCAlertController(title: nil, message: errorMessage) let cancelAction = MDCAlertAction(title: String.actionOk) alert.addAction(cancelAction) guard var topViewController = self.navController.topViewController else { return } if let presentedViewController = topViewController.presentedViewController { // On iPad, the welcome flow is in a presented view controller, so the alert must be // presented on that. topViewController = presentedViewController } topViewController.present(alert, animated: true) continuation() } }) // Add began operation as a dependency so we don't show the error while the UI is still // preparing to begin. if let importBeganOperation = importBeganOperation { errorOperation.addDependency(importBeganOperation) } queue.addOperation(errorOperation) } // MARK: - PermissionsGuideDelegate func permissionsGuideDidComplete(_ viewController: PermissionsGuideViewController) { showExperimentsList(animated: true) } // MARK: - SidebarDelegate func sidebarShouldShow(_ item: SidebarRow) { switch item { case .about: let aboutVC = AboutViewController(analyticsReporter: analyticsReporter) guard UIDevice.current.userInterfaceIdiom == .pad else { navController.pushViewController(aboutVC, animated: true) return } // iPad should present modally in a navigation controller of its own since About has // sub-navigation items. let aboutNavController = UINavigationController() aboutNavController.viewControllers = [ aboutVC ] aboutNavController.isNavigationBarHidden = true aboutNavController.modalPresentationStyle = .formSheet present(aboutNavController, animated: true) case .settings: let settingsVC = SettingsViewController(analyticsReporter: analyticsReporter, driveSyncManager: userManager.driveSyncManager, preferenceManager: preferenceManager) if UIDevice.current.userInterfaceIdiom == .pad { // iPad should present modally. settingsVC.modalPresentationStyle = .formSheet present(settingsVC, animated: true) } else { navController.pushViewController(settingsVC, animated: true) } self.settingsVC = settingsVC case .feedback: guard let feedbackViewController = feedbackReporter.feedbackViewController( withStyleMatching: navController.topViewController) else { return } navController.pushViewController(feedbackViewController, animated: true) default: break } } func sidebarShouldShowSignIn() { delegate?.presentAccountSelector() } func sidebarDidOpen() { analyticsReporter.track(.sidebarOpened) } func sidebarDidClose() { analyticsReporter.track(.sidebarClosed) } // MARK: - ExperimentsListViewControllerDelegate func experimentsListShowSidebar() { showSidebar() } func experimentsListManualSync() { userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: true) } func experimentsListShowExperiment(withID experimentID: String) { guard let experiment = metadataManager.experiment(withID: experimentID) else { experimentsListVC?.handleExperimentLoadingFailure() return } showExperiment(experiment) } func experimentsListShowNewExperiment() { let (experiment, overview) = metadataManager.createExperiment() experimentsListVC?.insertOverview(overview, atBeginning: true) showExperiment(experiment) } func experimentsListToggleArchiveStateForExperiment(withID experimentID: String) { experimentStateManager.toggleArchiveStateForExperiment(withID: experimentID) } func experimentsListDeleteExperiment(withID experimentID: String) { experimentStateManager.deleteExperiment(withID: experimentID) } func experimentsListDeleteExperimentCompleted(_ deletedExperiment: DeletedExperiment) { experimentStateManager.confirmDeletion(for: deletedExperiment) userManager.driveSyncManager?.deleteExperiment(withID: deletedExperiment.experimentID) } func experimentsListDidAppear() { userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false) showPreferenceMigrationMessageIfNeeded() } func experimentsListDidSetTitle(_ title: String?, forExperimentID experimentID: String) { if openExperimentUpdateManager?.experiment.ID == experimentID { openExperimentUpdateManager?.setTitle(title) } else { metadataManager.setExperimentTitle(title, forID: experimentID) userManager.driveSyncManager?.syncExperiment(withID: experimentID, condition: .onlyIfDirty) } } func experimentsListDidSetCoverImageData(_ imageData: Data?, metadata: NSDictionary?, forExperimentID experimentID: String) { if openExperimentUpdateManager?.experiment.ID == experimentID { openExperimentUpdateManager?.setCoverImageData(imageData, metadata: metadata) } else { let experimentUpdateManager = ExperimentUpdateManager(experimentID: experimentID, experimentDataDeleter: experimentDataDeleter, metadataManager: metadataManager, sensorDataManager: sensorDataManager) experimentUpdateManager?.setCoverImageData(imageData, metadata: metadata) } } func experimentsListExportExperimentPDF( _ experiment: Experiment, completionHandler: @escaping PDFExportController.CompletionHandler ) { presentPDFExportFlow(experiment, completionHandler: completionHandler) } func experimentsListExportFlowAction(for experiment: Experiment, from presentingViewController: UIViewController, sourceView: UIView) -> PopUpMenuAction { return PopUpMenuAction.exportFlow(for: experiment, from: self, documentManager: documentManager, sourceView: sourceView, exportCoordinator: exportCoordinator) } // MARK: - ExperimentCoordinatorViewControllerDelegate func experimentViewControllerToggleArchiveStateForExperiment(withID experimentID: String) { experimentStateManager.toggleArchiveStateForExperiment(withID: experimentID) } func experimentViewControllerDidRequestDeleteExperiment(_ experiment: Experiment) { experimentStateManager.deleteExperiment(withID: experiment.ID) if let experimentsListVC = experimentsListVC { navController.popToViewController(experimentsListVC, animated: true) } } func experimentViewControllerToggleArchiveStateForTrial(withID trialID: String) { openExperimentUpdateManager?.toggleArchivedState(forTrialID: trialID) } func experimentViewControllerDeleteExperimentNote(withID noteID: String) { openExperimentUpdateManager?.deleteExperimentNote(withID: noteID) } func experimentViewControllerShowTrial(withID trialID: String, jumpToCaption: Bool) { guard let experiment = openExperimentUpdateManager?.experiment, let trialIndex = experiment.trials.firstIndex(where: { $0.ID == trialID }) else { return } let trial = experiment.trials[trialIndex] let experimentInteractionOptions = interactionOptions(forExperiment: experiment) let experimentDataParser = ExperimentDataParser(experimentID: experiment.ID, metadataManager: metadataManager, sensorController: sensorController) let trialDetailVC = TrialDetailViewController(trial: trial, experiment: experiment, experimentInteractionOptions: experimentInteractionOptions, exportType: userManager.exportType, delegate: self, itemDelegate: self, analyticsReporter: analyticsReporter, experimentDataParser: experimentDataParser, metadataManager: metadataManager, preferenceManager: preferenceManager, sensorDataManager: sensorDataManager) self.trialDetailVC = trialDetailVC openExperimentUpdateManager?.addListener(trialDetailVC) if FeatureFlags.isActionAreaEnabled { if let experimentCoordinator = experimentCoordinatorVC { let content = configure(trialDetailViewController: trialDetailVC, experimentCoordinator: experimentCoordinator) actionAreaController?.show(content, sender: self) } else { fatalError("Experiment coordinator not available.") } } else { navController.pushViewController(trialDetailVC, animated: true) } } func experimentViewControllerShowNote(_ displayNote: DisplayNote, jumpToCaption: Bool) { showNote(displayNote, jumpToCaption: jumpToCaption) } func experimentViewControllerAddTrial(_ trial: Trial, recording isRecording: Bool) { openExperimentUpdateManager?.addTrial(trial, recording: isRecording) } func experimentViewControllerDeleteTrialCompleted(_ trial: Trial, fromExperiment experiment: Experiment) { // Delete trial data locally. openExperimentUpdateManager?.confirmTrialDeletion(for: trial) userAssetManager.deleteSensorData(forTrialID: trial.ID, experimentID: experiment.ID) // Delete trial data from Drive. let recordingURL = metadataManager.recordingURL(forTrialID: trial.ID, experimentID: experiment.ID) userManager.driveSyncManager?.deleteSensorDataAsset(atURL: recordingURL, experimentID: experiment.ID) // Delete trial image assets from Drive. let imageURLs = trial.allImagePaths.map { return URL(fileURLWithPath: $0) } userManager.driveSyncManager?.deleteImageAssets(atURLs: imageURLs, experimentID: experiment.ID) } func experimentViewControllerShouldPermanentlyDeleteTrial(_ trial: Trial, fromExperiment experiment: Experiment) { guard experiment.ID == openExperimentUpdateManager?.experiment.ID else { return } openExperimentUpdateManager?.permanentlyDeleteTrial(withID: trial.ID) } func experimentsListShowClaimExperiments() { guard let existingDataMigrationManager = existingDataMigrationManager, let authAccount = accountsManager.currentAccount else { return } let claimExperimentsVC = ClaimExperimentsFlowController(authAccount: authAccount, analyticsReporter: analyticsReporter, existingDataMigrationManager: existingDataMigrationManager, sensorController: sensorController) present(claimExperimentsVC, animated: true) } func experimentViewControllerDidFinishRecordingTrial(_ trial: Trial, forExperiment experiment: Experiment) { userAssetManager.storeSensorData(forTrial: trial, experiment: experiment) } // No-op in non-claim flow. func experimentViewControllerRemoveCoverImageForExperiment(_ experiment: Experiment) -> Bool { return false } func experimentViewControllerDidSetTitle(_ title: String?, forExperiment experiment: Experiment) { guard openExperimentUpdateManager?.experiment.ID == experiment.ID else { return } openExperimentUpdateManager?.setTitle(title) } func experimentViewControllerDidSetCoverImageData(_ imageData: Data?, metadata: NSDictionary?, forExperiment experiment: Experiment) { guard openExperimentUpdateManager?.experiment.ID == experiment.ID else { return } openExperimentUpdateManager?.setCoverImageData(imageData, metadata: metadata) } func experimentViewControllerDidChangeRecordingTrial(_ recordingTrial: Trial, experiment: Experiment) { guard openExperimentUpdateManager?.experiment.ID == experiment.ID else { return } openExperimentUpdateManager?.recordingTrialChangedExternally(recordingTrial) } func experimentViewControllerExportExperimentPDF( _ experiment: Experiment, completionHandler: @escaping PDFExportController.CompletionHandler) { presentPDFExportFlow(experiment, completionHandler: completionHandler) } func experimentViewControllerExportFlowAction(for experiment: Experiment, from presentingViewController: UIViewController, sourceView: UIView) -> PopUpMenuAction? { return PopUpMenuAction.exportFlow(for: experiment, from: self, documentManager: documentManager, sourceView: sourceView, exportCoordinator: exportCoordinator) } // MARK: - ExperimentItemDelegate func detailViewControllerDidAddNote(_ note: Note, forTrialID trialID: String?) { if let trialID = trialID { openExperimentUpdateManager?.addTrialNote(note, trialID: trialID) } else { openExperimentUpdateManager?.addExperimentNote(note) } guard FeatureFlags.isActionAreaEnabled, actionAreaController?.isMasterVisible == false else { return } showSnackbar( withMessage: String.actionAreaRecordingNoteSavedMessage, category: nil, actionTitle: String.actionAreaRecordingNoteSavedViewButton, actionHandler: { self.actionAreaController?.revealMaster() }) } func detailViewControllerDidDeleteNote(_ deletedDisplayNote: DisplayNote) { if let trialID = deletedDisplayNote.trialID { // Trial note. openExperimentUpdateManager?.deleteTrialNote(withID: deletedDisplayNote.ID, trialID: trialID) } else { // Experiment note. openExperimentUpdateManager?.deleteExperimentNote(withID: deletedDisplayNote.ID) } } func detailViewControllerDidUpdateCaptionForNote(_ updatedDisplayNote: CaptionableNote) { openExperimentUpdateManager?.updateNoteCaption(updatedDisplayNote.caption, forNoteWithID: updatedDisplayNote.ID, trialID: updatedDisplayNote.trialID) } func detailViewControllerDidUpdateTextForNote(_ updatedDisplayTextNote: DisplayTextNote) { openExperimentUpdateManager?.updateText(updatedDisplayTextNote.text, forNoteWithID: updatedDisplayTextNote.ID, trialID: updatedDisplayTextNote.trialID) } func trialDetailViewControllerDidUpdateTrial(cropRange: ChartAxis<Int64>?, name trialName: String?, caption: String?, withID trialID: String) { openExperimentUpdateManager?.updateTrial(cropRange: cropRange, name: trialName, captionString: caption, forTrialID: trialID) } func trialDetailViewControllerDidRequestDeleteTrial(withID trialID: String) { openExperimentUpdateManager?.deleteTrial(withID: trialID) } func trialDetailViewController(_ trialDetailViewController: TrialDetailViewController, trialArchiveStateChanged trial: Trial) { openExperimentUpdateManager?.toggleArchivedState(forTrialID: trial.ID) } func trialDetailViewController(_ trialDetailViewController: TrialDetailViewController, trialArchiveStateToggledForTrialID trialID: String) { openExperimentUpdateManager?.toggleArchivedState(forTrialID: trialID) } func experimentViewControllerDeletePictureNoteCompleted(_ pictureNote: PictureNote, forExperiment experiment: Experiment) { guard let pictureNoteFilePath = pictureNote.filePath else { return } userManager.driveSyncManager?.deleteImageAssets( atURLs: [URL(fileURLWithPath: pictureNoteFilePath)], experimentID: experiment.ID) } // MARK: - Private /// Shows the sidebar. private func showSidebar() { present(sidebar, animated: false) { self.sidebar.show() } } /// Shows the experiments list view controller. /// /// - Parameter animated: Whether to animate the showing of the view controller. func showExperimentsList(animated: Bool) { // Force the drawer to be created here, to avoid it being created when the first experiment is // shown as it is a performance issue. // TODO: Avoid lazy loading drawer by making drawer contents load on demand. http://b/72745126 _ = drawerVC let experimentsListVC = ExperimentsListViewController(accountsManager: accountsManager, analyticsReporter: analyticsReporter, commonUIComponents: commonUIComponents, existingDataMigrationManager: existingDataMigrationManager, metadataManager: metadataManager, networkAvailability: networkAvailability, preferenceManager: preferenceManager, sensorDataManager: sensorDataManager, documentManager: documentManager, exportType: userManager.exportType, shouldAllowManualSync: userManager.isDriveSyncEnabled) experimentsListVC.delegate = self // Add as listeners for experiment state changes. experimentStateManager.addListener(experimentsListVC) self.experimentsListVC = experimentsListVC navController.setViewControllers([experimentsListVC], animated: animated) } /// Presents the PDF export flow. /// /// - Parameter experiment: An experiment. func presentPDFExportFlow(_ experiment: Experiment, completionHandler: @escaping PDFExportController.CompletionHandler) { let experimentCoordinatorVC = ExperimentCoordinatorViewController( experiment: experiment, experimentInteractionOptions: .readOnly, exportType: userManager.exportType, drawerViewController: nil, analyticsReporter: analyticsReporter, metadataManager: metadataManager, preferenceManager: preferenceManager, sensorController: sensorController, sensorDataManager: sensorDataManager, documentManager: documentManager) experimentCoordinatorVC.experimentDisplay = .pdfExport let container = PDFExportController(contentViewController: experimentCoordinatorVC, analyticsReporter: analyticsReporter) container.completionHandler = completionHandler let readyForPDFExport = { let headerInfo = PDFExportController.HeaderInfo( title: experiment.titleOrDefault, subtitle: experiment.notesAndTrialsString, image: self.metadataManager.imageForExperiment(experiment) ) let documentFilename = experiment.titleOrDefault.validFilename(withExtension: "pdf") let pdfURL: URL = FileManager.default.temporaryDirectory .appendingPathComponent(documentFilename) container.exportPDF(with: headerInfo, to: pdfURL) } experimentCoordinatorVC.readyForPDFExport = readyForPDFExport let navController = UINavigationController(rootViewController: container) present(navController, animated: true) } /// Shows an experiment. Exposed for testing. /// /// - Parameter experiment: An experiment. func showExperiment(_ experiment: Experiment) { openExperimentUpdateManager = ExperimentUpdateManager(experiment: experiment, experimentDataDeleter: experimentDataDeleter, metadataManager: metadataManager, sensorDataManager: sensorDataManager) openExperimentUpdateManager?.delegate = self let experimentInteractionOptions = interactionOptions(forExperiment: experiment) let experimentCoordinatorVC = ExperimentCoordinatorViewController( experiment: experiment, experimentInteractionOptions: experimentInteractionOptions, exportType: userManager.exportType, drawerViewController: drawerVC, analyticsReporter: analyticsReporter, metadataManager: metadataManager, preferenceManager: preferenceManager, sensorController: sensorController, sensorDataManager: sensorDataManager, documentManager: documentManager) experimentCoordinatorVC.delegate = self experimentCoordinatorVC.itemDelegate = self self.experimentCoordinatorVC = experimentCoordinatorVC // Add as listeners for all experiment changes. openExperimentUpdateManager?.addListener(experimentCoordinatorVC) experimentStateManager.addListener(experimentCoordinatorVC) if FeatureFlags.isActionAreaEnabled { let content = configure(experimentCoordinator: experimentCoordinatorVC) actionAreaController?.show(content, sender: self) } else { navController.pushViewController(experimentCoordinatorVC, animated: true) } if isExperimentTooNewToEdit(experiment) { let alertController = MDCAlertController(title: nil, message: String.experimentVersionTooNewToEdit) alertController.addAction(MDCAlertAction(title: String.actionOk)) alertController.accessibilityViewIsModal = true experimentCoordinatorVC.present(alertController, animated: true) } // Mark opened in experiment library. metadataManager.markExperimentOpened(withID: experiment.ID) // Tell drive manager to sync the experiment. userManager.driveSyncManager?.syncExperiment(withID: experiment.ID, condition: .always) // This is a good time to generate any missing recording protos. userAssetManager.writeMissingSensorDataProtos(forExperiment: experiment) } private func configure(trialDetailViewController: TrialDetailViewController, experimentCoordinator: ExperimentCoordinatorViewController) -> ActionArea.MasterContent { let recordingDetailEmptyState = RecordingDetailEmptyStateViewController() trialDetailViewController.subscribeToTimestampUpdate { (timestamp) in recordingDetailEmptyState.timestampString = timestamp } let textItem = ActionArea.BarButtonItem( title: String.actionAreaButtonText, accessibilityHint: String.actionAreaButtonTextContentDescription, image: UIImage(named: "ic_action_area_text") ) { let notesVC = trialDetailViewController.notesViewController trialDetailViewController.prepareToAddNote() self.actionAreaController?.showDetailViewController(notesVC, sender: self) } let galleryItem = ActionArea.BarButtonItem( title: String.actionAreaButtonGallery, accessibilityHint: String.actionAreaButtonGalleryContentDescription, image: UIImage(named: "ic_action_area_gallery") ) { let photoLibraryVC = trialDetailViewController.photoLibraryViewController self.actionAreaController?.showDetailViewController(photoLibraryVC, sender: self) } let cameraItem = ActionArea.BarButtonItem( title: String.actionAreaButtonCamera, accessibilityHint: String.actionAreaButtonCameraContentDescription, image: UIImage(named: "ic_action_area_camera") ) { trialDetailViewController.cameraButtonPressed() } let content = ActionArea.MasterContentContainerViewController( content: trialDetailViewController, emptyState: recordingDetailEmptyState, actionEnablingKeyPath: \.isEditable, outsideOfSafeAreaKeyPath: \.scrollViewContentObserver.isContentOutsideOfSafeArea, mode: .stateless(actionItem: ActionArea.ActionItem( items: [textItem, cameraItem, galleryItem] )) ) return content } private func configure( experimentCoordinator: ExperimentCoordinatorViewController ) -> ActionArea.MasterContent { let textItem = ActionArea.BarButtonItem( title: String.actionAreaButtonText, accessibilityHint: String.actionAreaButtonTextContentDescription, image: UIImage(named: "ic_action_area_text") ) { let textTitle = experimentCoordinator.observeViewController.isRecording ? String.actionAreaRecordingTitleAddTextNote : String.actionAreaTitleAddTextNote experimentCoordinator.notesViewController.title = textTitle self.actionAreaController?.showDetailViewController( experimentCoordinator.notesViewController, sender: self) } let cameraItem = ActionArea.BarButtonItem( title: String.actionAreaButtonCamera, accessibilityHint: String.actionAreaButtonCameraContentDescription, image: UIImage(named: "ic_action_area_camera") ) { experimentCoordinator.cameraButtonPressed() } let galleryItem = ActionArea.BarButtonItem( title: String.actionAreaButtonGallery, accessibilityHint: String.actionAreaButtonGalleryContentDescription, image: UIImage(named: "ic_action_area_gallery") ) { self.actionAreaController?.showDetailViewController( experimentCoordinator.photoLibraryViewController, sender: self) } let detail = ActionArea.DetailContentContainerViewController( content: experimentCoordinator.observeViewController, outsideOfSafeAreaKeyPath: \.scrollViewContentObserver.isContentOutsideOfSafeArea ) { let addSensorItem = ActionArea.BarButtonItem( title: String.actionAreaButtonAddSensor, accessibilityHint: String.actionAreaButtonAddSensorContentDescription, image: UIImage(named: "ic_action_area_add_sensor") ) { experimentCoordinator.observeViewController.observeFooterAddButtonPressed() } let snapshotItem = ActionArea.BarButtonItem( title: String.actionAreaButtonSnapshot, accessibilityHint: String.actionAreaButtonSnapshotContentDescription, image: UIImage(named: "ic_action_area_snapshot") ) { experimentCoordinator.observeViewController.snapshotButtonPressed() } let recordItem = ActionArea.BarButtonItem( title: String.actionAreaFabRecord, accessibilityHint: String.actionAreaFabRecordContentDescription, image: UIImage(named: "record_button") ) { experimentCoordinator.observeViewController.recordButtonPressed() } let stopItem = ActionArea.BarButtonItem( title: String.actionAreaFabStop, accessibilityHint: String.actionAreaFabStopContentDescription, image: UIImage(named: "stop_button") ) { experimentCoordinator.observeViewController.recordButtonPressed() } return .stateful( nonModal: ActionArea.ActionItem(primary: recordItem, items: [addSensorItem, snapshotItem]), modal: ActionArea.ActionItem( primary: stopItem, items: [textItem, snapshotItem, cameraItem, galleryItem] ) ) } let sensorsItem = ActionArea.BarButtonItem( title: String.actionAreaButtonSensors, accessibilityHint: String.actionAreaButtonSensorsContentDescription, image: UIImage(named: "ic_action_area_sensors") ) { self.actionAreaController?.showDetailViewController(detail, sender: self) } let emptyState = ExperimentDetailEmptyStateViewController() let content = ActionArea.MasterContentContainerViewController( content: experimentCoordinator, emptyState: emptyState, actionEnablingKeyPath: \.shouldAllowAdditions, outsideOfSafeAreaKeyPath: \.scrollViewContentObserver.isContentOutsideOfSafeArea, mode: .stateless(actionItem: ActionArea.ActionItem( items: [textItem, sensorsItem, cameraItem, galleryItem] )) ) return content } /// Shows a note. /// /// - Parameters: /// - displayNote: A display note. /// - jumpToCaption: Whether to jump to the caption input when showing the note. private func showNote(_ displayNote: DisplayNote, jumpToCaption: Bool) { guard let experiment = openExperimentUpdateManager?.experiment else { return } let experimentInteractionOptions = interactionOptions(forExperiment: experiment) var viewController: UIViewController? switch displayNote { case let displayTextNote as DisplayTextNote: viewController = TextNoteDetailViewController(displayTextNote: displayTextNote, delegate: self, experimentInteractionOptions: experimentInteractionOptions, analyticsReporter: analyticsReporter) case let displayPicture as DisplayPictureNote: viewController = PictureDetailViewController(displayPicture: displayPicture, experimentInteractionOptions: experimentInteractionOptions, exportType: userManager.exportType, delegate: self, jumpToCaption: jumpToCaption, analyticsReporter: analyticsReporter, metadataManager: metadataManager, preferenceManager: preferenceManager) case let displaySnapshot as DisplaySnapshotNote: viewController = SnapshotDetailViewController(displaySnapshot: displaySnapshot, experimentInteractionOptions: experimentInteractionOptions, delegate: self, jumpToCaption: jumpToCaption, analyticsReporter: analyticsReporter) case let displayTrigger as DisplayTriggerNote: viewController = TriggerDetailViewController(displayTrigger: displayTrigger, experimentInteractionOptions: experimentInteractionOptions, delegate: self, jumpToCaption: jumpToCaption, analyticsReporter: analyticsReporter) default: return } noteDetailController = viewController as? NoteDetailController if let viewController = viewController { navController.pushViewController(viewController, animated: true) } } private func dismissExperimentImportSpinner(completion: (() -> Void)? = nil) { if importSpinnerVC != nil { importSpinnerVC?.dismissSpinner(completion: completion) importSpinnerVC = nil } else { completion?() } } /// Whether an experiment is too new to allow editing. /// /// - Parameter experiment: An experiment. /// - Returns: True if the experiment is too new to allow editing, otherwise false. private func isExperimentTooNewToEdit(_ experiment: Experiment) -> Bool { let isMajorVersionNewer = experiment.fileVersion.version > Experiment.Version.major let isMinorVersionNewer = experiment.fileVersion.version == Experiment.Version.major && experiment.fileVersion.minorVersion > Experiment.Version.minor return isMajorVersionNewer || isMinorVersionNewer } /// The experiment interaction options to use for an experiment. /// /// - Parameter experiment: An experiment. /// - Returns: The experiment interaction options to use. private func interactionOptions(forExperiment experiment: Experiment) -> ExperimentInteractionOptions { let experimentInteractionOptions: ExperimentInteractionOptions if isExperimentTooNewToEdit(experiment) { experimentInteractionOptions = .readOnly } else { let isExperimentArchived = metadataManager.isExperimentArchived(withID: experiment.ID) experimentInteractionOptions = isExperimentArchived ? .archived : .normal } return experimentInteractionOptions } private func createDefaultExperimentIfNecessary() { guard !self.preferenceManager.defaultExperimentWasCreated else { return } guard let driveSyncManager = userManager.driveSyncManager else { // If there is no Drive sync manager, create the default experiment if it has not been // created yet. metadataManager.createDefaultExperimentIfNecessary() experimentsListVC?.reloadExperiments() return } let createDefaultOp = GSJBlockOperation(mainQueueBlock: { finished in guard !self.preferenceManager.defaultExperimentWasCreated else { finished() return } // A spinner will be shown if the experiments list is visible. var spinnerVC: SpinnerViewController? let createDefaultExperiment = { driveSyncManager.experimentLibraryExists { (libraryExists) in // If existence is unknown, perhaps due to a fetch error or lack of network, don't create // the default experiment. if libraryExists == false { self.metadataManager.createDefaultExperimentIfNecessary() self.userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: false, userInitiated: false) DispatchQueue.main.async { if let spinnerVC = spinnerVC { spinnerVC.dismissSpinner { self.experimentsListVC?.reloadExperiments() finished() } } else { finished() } } } else { // If library exists or the state is unknown, mark the default experiment as created // to avoid attempting to create it again in the future. self.preferenceManager.defaultExperimentWasCreated = true DispatchQueue.main.async { if let spinnerVC = spinnerVC { spinnerVC.dismissSpinner { finished() } } else { finished() } } if libraryExists == true { self.analyticsReporter.track(.signInSyncExistingAccount) } } } } if let experimentsListVC = self.experimentsListVC, experimentsListVC.presentedViewController == nil { spinnerVC = SpinnerViewController() spinnerVC?.present(fromViewController: experimentsListVC) { createDefaultExperiment() } } else { createDefaultExperiment() } }) createDefaultOp.addCondition(MutuallyExclusive(primaryCategory: "CreateDefaultExperiment")) createDefaultOp.addCondition(MutuallyExclusive.modalUI) operationQueue.addOperation(createDefaultOp) } private func showPreferenceMigrationMessageIfNeeded() { guard shouldShowPreferenceMigrationMessage else { return } let showPreferenceMigrationMessageOp = GSJBlockOperation(mainQueueBlock: { finished in // If signing in and immediately showing experiments list, the sign in view controller needs a // brief delay to finish dismissing before showing a snackbar. DispatchQueue.main.asyncAfter(deadline: .now() + 1) { showSnackbar(withMessage: String.preferenceMigrationMessage) self.shouldShowPreferenceMigrationMessage = false finished() } }) showPreferenceMigrationMessageOp.addCondition(MutuallyExclusive.modalUI) operationQueue.addOperation(showPreferenceMigrationMessageOp) } // MARK: - UINavigationControllerDelegate func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { setNeedsStatusBarAppearanceUpdate() if viewController is ExperimentsListViewController { // Reset open experiment update manager and observe state in the drawer when the list appears. openExperimentUpdateManager = nil experimentCoordinatorVC?.observeViewController.prepareForReuse() } } } // MARK: - TrialDetailViewControllerDelegate extension UserFlowViewController: TrialDetailViewControllerDelegate { func trialDetailViewControllerShowNote(_ displayNote: DisplayNote, jumpToCaption: Bool) { showNote(displayNote, jumpToCaption: jumpToCaption) } func trialDetailViewControllerDeletePictureNoteCompleted(_ pictureNote: PictureNote, forExperiment experiment: Experiment) { guard let pictureNoteFilePath = pictureNote.filePath else { return } userManager.driveSyncManager?.deleteImageAssets( atURLs: [URL(fileURLWithPath: pictureNoteFilePath)], experimentID: experiment.ID) } } // MARK: - DriveSyncManagerDelegate extension UserFlowViewController: DriveSyncManagerDelegate { func driveSyncWillUpdateExperimentLibrary() { if shouldShowExperimentListPullToRefreshAnimation { experimentsListVC?.startPullToRefreshAnimation() shouldShowExperimentListPullToRefreshAnimation = false } } func driveSyncDidUpdateExperimentLibrary() { experimentsListVC?.reloadExperiments() experimentsListVC?.endPullToRefreshAnimation() } func driveSyncDidDeleteTrial(withID trialID: String, experimentID: String) { openExperimentUpdateManager?.experimentTrialDeletedExternally(trialID: trialID, experimentID: experimentID) } func driveSyncDidUpdateExperiment(_ experiment: Experiment) { // Reload experiments list in case cover image, title, or sort changed. experimentsListVC?.reloadExperiments() // If the experiment ID matches the open experiment, refresh views as needed. if let experimentCoordinatorVC = experimentCoordinatorVC, experimentCoordinatorVC.experiment.ID == experiment.ID { // Replace instance handled by the update manager as well as experiment view. openExperimentUpdateManager?.experiment = experiment experimentCoordinatorVC.reloadWithNewExperiment(experiment) // Check if trial detail exists and reload or pop as needed. if let trialDetailVC = trialDetailVC { let trialID = trialDetailVC.trialDetailDataSource.trial.ID if let trial = experiment.trial(withID: trialID) { trialDetailVC.reloadTrial(trial) } else { trialDetailVC.dismissPresentedVCIfNeeded(animated: true) { self.navController.popToViewController(experimentCoordinatorVC, animated: true) } // If we pop back to the experiment view there is no need to continue. return } } // Check if a detail view exists and reload or pop as needed. if let detailNoteID = noteDetailController?.displayNote.ID { // Make a parser for this experiment. let parser = ExperimentDataParser(experimentID: experiment.ID, metadataManager: metadataManager, sensorController: sensorController) // Find the note in the experiment. let (note, trial) = experiment.findNote(withID: detailNoteID) if let note = note, let displayNote = parser.parseNote(note) { // The note being displayed still exists, reload the view with a new display model in // case there are changes. noteDetailController?.displayNote = displayNote } else if trial != nil, let trialDetailVC = trialDetailVC { // It's a trial note, has been deleted and the trial view exists, pop back to that. navController.popToViewController(trialDetailVC, animated: true) } else { // The note has been deleted and there is no trial view, pop back to the experiment view. navController.popToViewController(experimentCoordinatorVC, animated: true) } } } } func driveSyncDidDeleteExperiment(withID experimentID: String) { experimentsListVC?.reloadExperiments() // If an experiment was deleted and is currently being displayed, cancel its recording if needed // and pop back to the experiments list. guard let experimentsListVC = experimentsListVC, experimentCoordinatorVC?.experiment.ID == experimentID else { return } experimentCoordinatorVC?.cancelRecordingIfNeeded() navController.popToViewController(experimentsListVC, animated: true) } } // MARK: - ExperimentUpdateManagerDelegate extension UserFlowViewController: ExperimentUpdateManagerDelegate { func experimentUpdateManagerDidSaveExperiment(withID experimentID: String) { userManager.driveSyncManager?.syncExperiment(withID: experimentID, condition: .onlyIfDirty) } func experimentUpdateManagerDidDeleteCoverImageAsset(withPath assetPath: String, experimentID: String) { userManager.driveSyncManager?.deleteImageAssets(atURLs: [URL(fileURLWithPath: assetPath)], experimentID: experimentID) } } // MARK: - ExperimentStateListener extension UserFlowViewController: ExperimentStateListener { func experimentStateArchiveStateChanged(forExperiment experiment: Experiment, overview: ExperimentOverview, undoBlock: @escaping () -> Void) { userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false) } func experimentStateDeleted(_ deletedExperiment: DeletedExperiment, undoBlock: (() -> Void)?) { userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false) } func experimentStateRestored(_ experiment: Experiment, overview: ExperimentOverview) { userManager.driveSyncManager?.syncExperimentLibrary(andReconcile: true, userInitiated: false) } } extension UserFlowViewController: ExportCoordinatorDelegate { func showPDFExportFlow(for experiment: Experiment, completionHandler: @escaping PDFExportController.CompletionHandler) { presentPDFExportFlow(experiment, completionHandler: completionHandler) } } // swiftlint:enable file_length, type_body_length
168cf6dd2af59047c5999197396ee800
41.509489
100
0.689327
false
false
false
false
ACChe/eidolon
refs/heads/master
KioskTests/Bid Fulfillment/LoadingViewControllerTests.swift
mit
1
import Quick import Nimble @testable import Kiosk import Moya import ReactiveCocoa import Nimble_Snapshots import Forgeries class LoadingViewControllerTests: QuickSpec { override func spec() { var subject: LoadingViewController! beforeEach { subject = testLoadingViewController() subject.animate = false } describe("default") { it("placing a bid") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.completes = false subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } it("registering a user") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.completes = false subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } } describe("errors") { it("correctly placing a bid") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.errors = true subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } it("correctly registering a user") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.errors = true subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } } describe("ending") { it("placing bid success highest") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.bidIsResolved = true stubViewModel.isHighestBidder = true subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } it("dismisses by tapping green checkmark when bidding was a success") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.bidIsResolved = true stubViewModel.isHighestBidder = true subject.viewModel = stubViewModel var closed = false subject.closeSelf = { closed = true } let testingRecognizer = ForgeryTapGestureRecognizer() subject.recognizer = testingRecognizer subject.loadViewProgrammatically() testingRecognizer.invoke() expect(closed).to( beTrue() ) } it("placing bid success not highest") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.bidIsResolved = true stubViewModel.isHighestBidder = false subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } it("placing bid error due to outbid") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) subject.viewModel = stubViewModel subject.loadViewProgrammatically() let error = NSError(domain: OutbidDomain, code: 0, userInfo: nil) subject.bidderError(error) expect(subject).to(haveValidSnapshot()) } it("placing bid succeeded but not resolved") { subject.placingBid = true let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.bidIsResolved = false subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } it("registering user success") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.createdNewBidder = true stubViewModel.bidIsResolved = true subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } it("registering user not resolved") { subject.placingBid = false let fulfillmentController = StubFulfillmentController() let stubViewModel = StubLoadingViewModel(bidNetworkModel: BidderNetworkModel(fulfillmentController: fulfillmentController), placingBid: subject.placingBid) stubViewModel.bidIsResolved = true subject.viewModel = stubViewModel expect(subject).to(haveValidSnapshot()) } } } } let loadingViewControllerTestImage = UIImage.testImage(named: "artwork", ofType: "jpg") func testLoadingViewController() -> LoadingViewController { let controller = UIStoryboard.fulfillment().viewControllerWithID(.LoadingBidsorRegistering).wrapInFulfillmentNav() as! LoadingViewController return controller } class StubLoadingViewModel: LoadingViewModel { var errors = false var completes = true init(bidNetworkModel: BidderNetworkModel, placingBid: Bool) { super.init(bidNetworkModel: bidNetworkModel, placingBid: placingBid, actionsCompleteSignal: RACSignal.never()) } override func performActions() -> RACSignal { if completes { if errors { return RACSignal.error(NSError(domain: "", code: 0, userInfo: nil)) } else { return RACSignal.empty() } } else { return RACSignal.never() } } }
ff093fd26507d09368e3c4cc5d6a0e71
40.370968
171
0.632878
false
false
false
false
gtrabanco/JSQDataSourcesKit
refs/heads/develop
Example/Example/FetchedTableViewController.swift
mit
2
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://jessesquires.com/JSQDataSourcesKit // // // GitHub // https://github.com/jessesquires/JSQDataSourcesKit // // // License // Copyright (c) 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import UIKit import CoreData import JSQDataSourcesKit class FetchedTableViewController: UIViewController { // MARK: outlets @IBOutlet weak var tableView: UITableView! // MARK: properties let stack = CoreDataStack() typealias CellFactory = TableViewCellFactory<TableViewCell, Thing> var dataSourceProvider: TableViewFetchedResultsDataSourceProvider<Thing, CellFactory>? var delegateProvider: TableViewFetchedResultsDelegateProvider<Thing, CellFactory>? // MARK: view lifecycle override func viewDidLoad() { super.viewDidLoad() // register cells tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: tableCellId) // create factory let factory = TableViewCellFactory(reuseIdentifier: tableCellId) { (cell: TableViewCell, model: Thing, tableView: UITableView, indexPath: NSIndexPath) -> TableViewCell in cell.textLabel?.text = model.displayName cell.textLabel?.textColor = model.displayColor cell.detailTextLabel?.text = "\(indexPath.section), \(indexPath.row)" return cell } // create fetched results controller let frc: NSFetchedResultsController = NSFetchedResultsController(fetchRequest: Thing.fetchRequest(), managedObjectContext: stack.context, sectionNameKeyPath: "category", cacheName: nil) // create delegate provider // by passing `frc` the provider automatically sets `frc.delegate = self.delegateProvider.delegate` self.delegateProvider = TableViewFetchedResultsDelegateProvider(tableView: tableView, cellFactory: factory, controller: frc) // create data source provider // by passing `self.tableView`, the provider automatically sets `self.tableView.dataSource = self.dataSourceProvider.dataSource` self.dataSourceProvider = TableViewFetchedResultsDataSourceProvider(fetchedResultsController: frc, cellFactory: factory, tableView: tableView) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.dataSourceProvider?.performFetch() } // MARK: actions @IBAction func didTapAddButton(sender: UIBarButtonItem) { tableView.deselectAllRows() let newThing = Thing.newThing(stack.context) stack.saveAndWait() dataSourceProvider?.performFetch() if let indexPath = dataSourceProvider?.fetchedResultsController.indexPathForObject(newThing) { tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Middle) } println("Added new thing: \(newThing)") } @IBAction func didTapDeleteButton(sender: UIBarButtonItem) { if let indexPaths = tableView.indexPathsForSelectedRows() as? [NSIndexPath] { println("Deleting things at indexPaths: \(indexPaths)") for i in indexPaths { let thingToDelete = dataSourceProvider?.fetchedResultsController.objectAtIndexPath(i) as! Thing stack.context.deleteObject(thingToDelete) } stack.saveAndWait() dataSourceProvider?.performFetch() } } @IBAction func didTapHelpButton(sender: UIBarButtonItem) { UIAlertController.showHelpAlert(self) } } // MARK: extensions extension UITableView { func deselectAllRows() { if let indexPaths = indexPathsForSelectedRows() as? [NSIndexPath] { for i in indexPaths { deselectRowAtIndexPath(i, animated: true) } } } }
9737ff3e87a9f1fa0ecc07f00f103b08
29.4
193
0.689777
false
false
false
false
simonkim/AVCapture
refs/heads/master
AVCapture/AVEncoderVideoToolbox/NALUtil.swift
apache-2.0
1
// // NALUtil.swift // AVCapture // // Created by Simon Kim on 2016. 9. 11.. // Copyright © 2016 DZPub.com. All rights reserved. // import Foundation import CoreMedia enum NALUnitType: Int8 { case IDR = 5 case SPS = 7 case PPS = 8 } class NALUtil { static func readNALUnitLength(at pointer: UnsafePointer<UInt8>, headerLength: Int) -> Int { var result: Int = 0 for i in 0...(headerLength - 1) { result |= Int(pointer[i]) << (((headerLength - 1) - i) * 8) } return result } } extension CMBlockBuffer { /* * List of NAL Units without NALUnitHeader */ public func NALUnits(headerLength: Int) -> [Data] { var totalLength: Int = 0 var pointer:UnsafeMutablePointer<Int8>? = nil var dataArray: [Data] = [] if noErr == CMBlockBufferGetDataPointer(self, 0, &totalLength, nil, &pointer) { while totalLength > Int(headerLength) { let unitLength = pointer!.withMemoryRebound(to: UInt8.self, capacity: totalLength) { NALUtil.readNALUnitLength(at: $0, headerLength: Int(headerLength)) } dataArray.append(Data(bytesNoCopy: pointer!.advanced(by: Int(headerLength)), count: unitLength, deallocator: .none)) let nextOffset = headerLength + unitLength pointer = pointer!.advanced(by: nextOffset) totalLength -= Int(nextOffset) } } return dataArray } }
115544c742e1edf4af601ee5a24d8354
27.237288
100
0.537815
false
false
false
false
jeevanRao7/Swift_Playgrounds
refs/heads/master
Swift Playgrounds/Challenges/Famous Color.playground/Contents.swift
mit
1
/************************ Problem Statement: Print Most repeated Colors in a given colors array. ************************/ import Foundation //Input Array of colors let inputArray = ["green", "red" , "green", "blue", "green", "black", "red", "blue", "blue", "gray", "purple", "white", "green", "red", "yellow", "red", "blue", "green"] func getTopItemsArray(_ array:[String]) -> [String] { var topArray = [String]() var colorDictionary = [String:Int]() //Step 1 : Form dictionary of items with its count for color in array { if let count = colorDictionary[color] { colorDictionary[color] = count + 1 } else{ //First time encoured a color, initialize value to '1' colorDictionary[color] = 1 } } //Step 2 : Find the max value in the colors count dictionary let highest = colorDictionary.values.max() //Step 3 : Get the 'color' key having 'height' value for (color, count) in colorDictionary { if count == highest { topArray.append(color) } } return topArray } //Print array of colors most repeated. print(getTopItemsArray(inputArray))
008d7b60bfa7d5ac14b6d266ac750cca
23.509804
169
0.5552
false
false
false
false
levantAJ/ResearchKit
refs/heads/master
TestVoiceActions/UIImage.swift
mit
1
// // UIImage.swift // TestVoiceActions // // Created by Le Tai on 8/30/16. // Copyright © 2016 Snowball. All rights reserved. // import UIKit extension UIImage { class func imageFromColor(color: UIColor, size: CGSize) -> UIImage { let rect = CGRectMake(0.0, 0.0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func resizeImage(newWidth newWidth: CGFloat) -> UIImage { let scale = newWidth / size.width let newHeight = size.height * scale let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale) drawInRect(CGRectMake(0, 0, newWidth, newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func resizeImage(newHeight newHeight: CGFloat) -> UIImage { let scale = newHeight / size.height let newWidth = size.width * scale let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale) drawInRect(CGRectMake(0, 0, newWidth, newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
2199b5b2d0216c5ace06485d0dcf3a3e
37.295455
91
0.691395
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
Habitica Database/Habitica Database/Models/Content/RealmCustomization.swift
gpl-3.0
1
// // RealmCustomization.swift // Habitica Database // // Created by Phillip Thelen on 20.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import RealmSwift class RealmCustomization: Object, CustomizationProtocol { @objc dynamic var combinedKey: String? @objc dynamic var key: String? @objc dynamic var type: String? @objc dynamic var group: String? @objc dynamic var price: Float = 0 var set: CustomizationSetProtocol? { get { return realmSet } set { if let newSet = newValue as? RealmCustomizationSet { realmSet = newSet } else if let newSet = newValue { realmSet = RealmCustomizationSet(newSet) } } } @objc dynamic var realmSet: RealmCustomizationSet? override static func primaryKey() -> String { return "combinedKey" } convenience init(_ customizationProtocol: CustomizationProtocol) { self.init() key = customizationProtocol.key type = customizationProtocol.type group = customizationProtocol.group combinedKey = (key ?? "") + (type ?? "") + (group ?? "") price = customizationProtocol.price set = customizationProtocol.set } }
c2416b7e7740e1b80f88ed3cfbe936af
27.934783
70
0.624343
false
false
false
false
hughbe/phone-number-picker
refs/heads/master
src/View/PNPMenuDisabledTextField.swift
mit
1
// // PNPMenuDisabledTextField.swift // UIComponents // // Created by Hugh Bellamy on 05/09/2015. // Copyright (c) 2015 Hugh Bellamy. All rights reserved. // import UIKit @IBDesignable internal class PNPMenuDisabledTextField: UITextField { @IBInspectable private var menuEnabled: Bool = false @IBInspectable private var canPositionCaretAtStart: Bool = true @IBInspectable private var editingRectDeltaY: CGFloat = 0 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return menuEnabled } override func caretRect(for position: UITextPosition) -> CGRect { if position == beginningOfDocument && !canPositionCaretAtStart { return super.caretRect(for: self.position(from: position, offset: 1)!) } return super.caretRect(for: position) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: 0, dy: editingRectDeltaY) } }
c9643fb3d3a8aa343b7f08946d11cad1
31.096774
89
0.694472
false
false
false
false
seguemodev/Meducated-Ninja
refs/heads/master
iOS/Zippy/CabinetPickerViewController.swift
cc0-1.0
1
// // CabinetPickerViewController.swift // Zippy // // Created by Geoffrey Bender on 6/19/15. // Copyright (c) 2015 Segue Technologies, Inc. All rights reserved. // import UIKit class CabinetPickerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Interface Outlets @IBOutlet weak var tableView: UITableView! // MARK: - Variables let userDefaults = NSUserDefaults.standardUserDefaults() var cabinetArray = [String]() var medication: Medication! var selectedCabinet = "" // MARK: - Lifecycle Methods // Each time view appears override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // For dynamic table row height self.tableView.estimatedRowHeight = 80 self.tableView.rowHeight = UITableViewAutomaticDimension var leftBarButton = UIBarButtonItem(title:"Cancel", style:UIBarButtonItemStyle.Plain, target:self, action:"cancel") self.navigationItem.leftBarButtonItem = leftBarButton var rightBarButton = UIBarButtonItem(title:"Save", style:UIBarButtonItemStyle.Plain, target:self, action:"saveMedicationToCabinet:") self.navigationItem.rightBarButtonItem = rightBarButton var normalButtonBackground = UIImage(named:"BlueButtonBackground")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 10, 0, 10)) self.navigationItem.leftBarButtonItem!.setBackgroundImage(normalButtonBackground, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default) self.navigationItem.rightBarButtonItem!.setBackgroundImage(normalButtonBackground, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default) var pressedButtonBackground = UIImage(named:"GreenButtonBackground")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 10, 0, 10)) self.navigationItem.leftBarButtonItem!.setBackgroundImage(pressedButtonBackground, forState: UIControlState.Highlighted, barMetrics: UIBarMetrics.Default) self.navigationItem.rightBarButtonItem!.setBackgroundImage(pressedButtonBackground, forState: UIControlState.Highlighted, barMetrics: UIBarMetrics.Default) if let font = UIFont(name:"RobotoSlab-Bold", size:14.0) { self.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal) self.navigationItem.rightBarButtonItem!.setTitleTextAttributes([NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal) } // If we have saved medicine cabinets if self.userDefaults.valueForKey("cabinetArray") != nil { // Set saved cabinets to local array self.cabinetArray = self.userDefaults.valueForKey("cabinetArray") as! [String] } } // MARK: - Table View Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.cabinetArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cabinetCell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.text = self.cabinetArray[indexPath.row].capitalizedString if self.cabinetArray[indexPath.row] == self.selectedCabinet { cell.accessoryView = UIImageView(image:UIImage(named:"CheckedButton")) } else { cell.accessoryView = UIImageView(image:UIImage(named:"UncheckedButton")) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Set selected cabinet self.selectedCabinet = self.cabinetArray[indexPath.row] // Reload the table with the new cabinet (using this method for proper autoheight calculation on table cells) self.tableView.reloadSections(NSIndexSet(indexesInRange:NSMakeRange(0, self.tableView.numberOfSections())), withRowAnimation:.None) self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Middle, animated:true) } // MARK: - My Methods // Dismiss view when cancel button is clicked func cancel() { self.navigationController?.popViewControllerAnimated(true) } // Show prompt for user to create new medicine cabinet @IBAction func createNewCabinet(sender: AnyObject) { // Create the alert controller var alert = UIAlertController(title:"Create Medicine Cabinet", message:nil, preferredStyle:.Alert) // Add the text field alert.addTextFieldWithConfigurationHandler({(textField) -> Void in textField.autocapitalizationType = UITextAutocapitalizationType.Words textField.keyboardAppearance = UIKeyboardAppearance.Dark textField.text = "" }) // Add a cancel button alert.addAction(UIAlertAction(title:"Cancel", style:.Default, handler:nil)) // Add a create button with callback alert.addAction(UIAlertAction(title:"Create", style:.Default, handler:{(action) -> Void in // Get text field from alert controller let textField = alert.textFields![0] as! UITextField // Complete creating the tag self.completeCreateNewCabinet(textField.text) })) // Present the alert view so user can enter the category name self.presentViewController(alert, animated:true, completion:nil) } // Completion handler for new cabinet creation func completeCreateNewCabinet(fieldText:String) { // Make sure user entered text if fieldText.isEmpty { // Alert user that the cabinet name is required var foundAlert = UIAlertController(title:"Attention Required", message:"Please enter a cabinet name.", preferredStyle:UIAlertControllerStyle.Alert) foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil)) self.presentViewController(foundAlert, animated:true, completion:nil) } else { // Trim string var cabinet = fieldText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) // Set variable to track number of duplicates encountered var duplicates = 0 // Set variable to track highest duplicate label var highestNumber = 0 // Loop our cabinet array to check for duplicates for item in self.cabinetArray { // Get the cabinet name without the parentheses let rawStringArray = item.componentsSeparatedByString("(") // Trim the string to eliminate whitespace let trimmedRawString = rawStringArray[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) // If our entered text matches a cabinet in our array if cabinet.lowercaseString == trimmedRawString { // Increase duplicate count duplicates++ // If our raw string array has more then one item, then it had parentheses if rawStringArray.count > 1 { // Get its number let labelNumber = rawStringArray[1].componentsSeparatedByString(")")[0].toInt() // Track the highest label number if labelNumber > highestNumber { highestNumber = labelNumber! } } if highestNumber >= duplicates { duplicates = highestNumber + 1 } } } // If we found duplicates if duplicates > 0 { // Modify cabinet string let modifiedCabinet = "\(cabinet.lowercaseString) (\(duplicates))" // Append the modified string to our array self.cabinetArray.insert(modifiedCabinet, atIndex:0) } else { // Append the string to our array self.cabinetArray.insert(cabinet.lowercaseString, atIndex:0) } // Set selected cabinet to newly created cabinet self.selectedCabinet = self.cabinetArray.first! // Scroll to first row self.tableView.setContentOffset(CGPointZero, animated:true) // Reload the table with the new cabinet (using this method for proper autoheight calculation on table cells) self.tableView.reloadSections(NSIndexSet(indexesInRange:NSMakeRange(0, self.tableView.numberOfSections())), withRowAnimation:.None) let medToMove = self.cabinetArray.first self.cabinetArray.removeAtIndex(0) self.cabinetArray.append(medToMove!) // Save medicine cabinet array to persistent store self.userDefaults.setValue(self.cabinetArray, forKey: "cabinetArray") // Automatically save the medication to the new cabinet self.saveMedicationToCabinet(self) } } // Save the medication to the selected medicine cabinet @IBAction func saveMedicationToCabinet(sender: AnyObject) { // Make sure user selected a cabinet if self.selectedCabinet.isEmpty { // Alert user that the cabinet name is required var foundAlert = UIAlertController(title:"Attention Required", message:"Please choose a cabinet to save to.", preferredStyle:UIAlertControllerStyle.Alert) foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil)) self.presentViewController(foundAlert, animated:true, completion:nil) } else { // Set the medication object's medicine cabinet to selected picker row value self.medication.medicineCabinet = self.selectedCabinet // Create empty saved medication array var savedMedications = [Medication]() // If we have a stored medication array, then load the contents into our empty array if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey("medicationArray") as? NSData { savedMedications = NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as! [Medication] } // Add saved medication to our array savedMedications.append(self.medication) // Save the modified medication array let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(savedMedications as NSArray) self.userDefaults.setObject(archivedObject, forKey:"medicationArray") self.userDefaults.synchronize() // Alert user that the medication has been saved let indexPath = self.tableView.indexPathForSelectedRow() // Create confirmation var foundAlert = UIAlertController(title:"Success", message:"You have successfully saved this medication to \(self.selectedCabinet.capitalizedString).", preferredStyle:UIAlertControllerStyle.Alert) // Create handler for OK button foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:{(action) -> Void in // Dismiss the view self.navigationController?.popViewControllerAnimated(true) })) // Show confirmation self.presentViewController(foundAlert, animated:true, completion:nil) } } }
98d908c828b6db8daf462bb09226ae94
43.227273
209
0.63167
false
false
false
false
dmitrykurochka/CLTokenInputView-Swift
refs/heads/master
CLTokenInputView-Swift/Classes/CLToken.swift
mit
1
// // CLToken.swift // CLTokenInputView // // Created by Dmitry Kurochka on 23.08.17. // Copyright © 2017 Prezentor. All rights reserved. // import Foundation struct CLToken { let displayText: String let context: AnyObject? } extension CLToken: Equatable { static func == (lhs: CLToken, rhs: CLToken) -> Bool { if lhs.displayText == rhs.displayText, lhs.context?.isEqual(rhs.context) == true { return true } return false } }
13a19b403a095642402cf48268d4634b
18.913043
86
0.670306
false
false
false
false
jisudong555/swift
refs/heads/master
weibo/weibo/Classes/Main/BaseViewController.swift
mit
1
// // BaseViewController.swift // weibo // // Created by jisudong on 16/4/12. // Copyright © 2016年 jisudong. All rights reserved. // import UIKit class BaseViewController: UITableViewController, VisitorViewDelegate { let userLogin = UserAccount.userLogin() var visitorView: VisitorView? override func loadView() { userLogin ? super.loadView() : setupVisitorView() } func setupVisitorView() { let customView = VisitorView() view = customView customView.delegate = self visitorView = customView navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(registerButtonClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(loginButtonClick)) } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } // MARK: - VisitorViewDelegate func loginButtonClick() { print(#function) let oauth = OAuthViewController() let nav = UINavigationController(rootViewController: oauth) presentViewController(nav, animated: true, completion: nil) } func registerButtonClick() { print(#function) } }
abddac6409ad12d1893b0dbc6fb2ce61
28
160
0.661601
false
false
false
false
automationWisdri/WISData.JunZheng
refs/heads/master
WISData.JunZheng/View/Operation/OperationView.swift
mit
1
// // OperationView.swift // WISData.JunZheng // // Created by Allen on 16/9/6. // Copyright © 2016 Wisdri. All rights reserved. // import UIKit import SwiftyJSON class OperationView: UIView { @IBOutlet weak var viewTitleLabel: UILabel! @IBOutlet weak var dataView: UIView! private var firstColumnView: UIView! private var scrollView: UIScrollView! private var firstColumnTableView: DataTableView! private var columnTableView = [DataTableView]() private var switchRowCount = [Int]() private var totalRowCount = 0 private var tableTitleJSON = JSON.null var tableContentJSON = [JSON]() var switchContentJSON = [[JSON]]() var viewHeight: CGFloat = CGFloat(35.0) override func awakeFromNib() { super.awakeFromNib() // Basic setup self.backgroundColor = UIColor.whiteColor() self.viewTitleLabel.backgroundColor = UIColor.wisGrayColor().colorWithAlphaComponent(0.3) } func initialDrawTable(switchRowCount: [Int], viewHeight: CGFloat) { self.dataView.removeAllSubviews() self.switchRowCount = switchRowCount self.totalRowCount = switchRowCount.reduce(0, combine: + ) // Get table column title if let path = NSBundle.mainBundle().pathForResource("OperationTitle", ofType: "json") { let data = NSData(contentsOfFile: path) tableTitleJSON = JSON(data: data!) } else { tableTitleJSON = JSON.null } // Define the table dimensions let dataViewWidth = CURRENT_SCREEN_WIDTH let dataViewHeight = viewHeight - WISCommon.viewHeaderTitleHeight // let firstColumnViewWidth: CGFloat = 90 // -2 是因为 KEY "No" 和 "SwitchTimes" 不作为表格列名 let opColumnCount = Operation().propertyNames().count - 2 let switchColumnCount = SwitchTime().propertyNames().count let totalColumnCount = opColumnCount + switchColumnCount // Draw view for first column firstColumnView = UIView(frame: CGRectMake(0, 0, WISCommon.firstColumnViewWidth, dataViewHeight)) firstColumnView.backgroundColor = UIColor.whiteColor() // headerView.userInteractionEnabled = true self.dataView.addSubview(firstColumnView) // Draw first column table firstColumnTableView = DataTableView(frame: firstColumnView.bounds, style: .Plain, rowInfo: switchRowCount) firstColumnTableView.dataTableDelegate = self firstColumnView.addSubview(firstColumnTableView) // Draw view for data table scrollView = UIScrollView(frame: CGRectMake (WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, dataViewHeight)) scrollView.contentSize = CGSizeMake(CGFloat(totalColumnCount) * WISCommon.DataTableColumnWidth, DataTableHeaderRowHeight + CGFloat(totalRowCount) * DataTableBaseRowHeight) scrollView.showsHorizontalScrollIndicator = true scrollView.showsVerticalScrollIndicator = true scrollView.bounces = true scrollView.delegate = self scrollView.backgroundColor = UIColor.whiteColor() self.dataView.addSubview(scrollView) // Draw data table self.columnTableView.removeAll() var tableColumnsCount = 0 for p in Operation().propertyNames() { if p == "No" || p == "SwitchTimes" { continue } else { let tempColumnTableView = DataTableView(frame: CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, dataViewHeight), style: .Plain, rowInfo: switchRowCount) self.columnTableView.append(tempColumnTableView) self.columnTableView[tableColumnsCount].dataTableDelegate = self self.scrollView.addSubview(self.columnTableView[tableColumnsCount]) tableColumnsCount += 1 } } for _ in SwitchTime().propertyNames() { let tempColumnTableView = DataTableView(frame: CGRectMake(CGFloat(tableColumnsCount) * WISCommon.DataTableColumnWidth, 0, WISCommon.DataTableColumnWidth, dataViewHeight), style: .Plain, rowInfo: nil) self.columnTableView.append(tempColumnTableView) self.columnTableView[tableColumnsCount].dataTableDelegate = self self.scrollView.addSubview(self.columnTableView[tableColumnsCount]) tableColumnsCount += 1 } fillDataTableContent() } func arrangeOperationSubView(viewHeight: CGFloat) { // Define the table dimensions let dataViewWidth = CURRENT_SCREEN_WIDTH let dataViewHeight = viewHeight - WISCommon.viewHeaderTitleHeight guard let scrollView = self.scrollView else { return } scrollView.frame = CGRectMake(WISCommon.firstColumnViewWidth, 0, dataViewWidth - WISCommon.firstColumnViewWidth, dataViewHeight) /* * Issue 1 中的 4# 问题,暂未解决 let opColumnCount = Operation().propertyNames().count - 2 let switchColumnCount = SwitchTime().propertyNames().count let totalColumnCount = opColumnCount + switchColumnCount if ( dataViewWidth - WISCommon.firstColumnViewWidth ) > CGFloat(totalColumnCount) * WISCommon.DataTableColumnWidth { // 重绘表格 let dataTableColumnWidth: CGFloat = ( dataViewWidth - WISCommon.firstColumnViewWidth) / CGFloat(totalColumnCount) let subviews = scrollView.subviews as! [DataTableView] for subview in subviews { subview.bounds.size = CGSize(width: dataTableColumnWidth, height: dataViewHeight) subview.layoutIfNeeded() } } */ } private func fillDataTableContent() { firstColumnTableView.viewModel.headerString = SearchParameter["date"]! + "\n" + getShiftName(SearchParameter["shiftNo"]!)[0] let firstColumnTitleArray = DJName firstColumnTableView.viewModel.titleArray = firstColumnTitleArray self.firstColumnTableView.viewModel.titleArraySubject .onNext(firstColumnTitleArray) var tableColumnsCount = 0 for p in Operation().propertyNames() { if p == "No" || p == "SwitchTimes" { continue } else { // header let columnTitle: String = self.tableTitleJSON["title"][p].stringValue self.columnTableView[tableColumnsCount].viewModel.headerString = columnTitle // content var contentArray: [String] = [] for j in 0 ..< self.tableContentJSON.count { let content = self.tableContentJSON[j][p].stringValue.trimNumberFromFractionalPart(2) contentArray.append(content) } self.columnTableView[tableColumnsCount].viewModel.titleArray = contentArray self.columnTableView[tableColumnsCount].viewModel.titleArraySubject.onNext(contentArray) self.columnTableView[tableColumnsCount].reloadData() tableColumnsCount += 1 } } for p in SwitchTime().propertyNames() { // header let columnTitle: String = self.tableTitleJSON["title"]["SwitchTimes"][p].stringValue self.columnTableView[tableColumnsCount].viewModel.headerString = columnTitle // content var contentArray: [String] = [] for i in 0 ..< self.tableContentJSON.count { if self.switchContentJSON[i].count == 0 { contentArray.append(EMPTY_STRING) } else { for j in 0 ..< self.switchRowCount[i] { let content = self.switchContentJSON[i][j][p].stringValue contentArray.append(content) } } } self.columnTableView[tableColumnsCount].viewModel.titleArray = contentArray self.columnTableView[tableColumnsCount].viewModel.titleArraySubject .onNext(contentArray) tableColumnsCount += 1 } } } // MARK: - Extension extension OperationView: DataTableViewDelegate { func dataTableViewContentOffSet(contentOffSet: CGPoint) { for subView in scrollView.subviews { if subView.isKindOfClass(DataTableView) { (subView as! DataTableView).setTableViewContentOffSet(contentOffSet) } } for subView in firstColumnView.subviews { (subView as! DataTableView).setTableViewContentOffSet(contentOffSet) } } } extension OperationView: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { // let p: CGPoint = scrollView.contentOffset // print(NSStringFromCGPoint(p)) } }
ccffa996befa70056ce6229ce3c3ef91
40.686364
226
0.633628
false
false
false
false
joemcbride/outlander-osx
refs/heads/master
src/Outlander/ExpUpdateHandler.swift
mit
1
// // ExpUpdateHandler.swift // Outlander // // Created by Joseph McBride on 4/23/15. // Copyright (c) 2015 Joe McBride. All rights reserved. // import Foundation @objc class ExpUpdateHandler : NSObject { class func newInstance() -> ExpUpdateHandler { return ExpUpdateHandler() } static let start_check = "Circle: " static let end_check = "EXP HELP for more information" var emitSetting : ((String,String)->Void)? var emitExp : ((SkillExp)->Void)? private var parsing = false private var exp_regex = "(\\w.*?):\\s+(\\d+)\\s(\\d+)%\\s(\\w.*?)\\s+\\(\\d{1,}/34\\)" func handle(nodes:[Node], text:String, context:GameContext) { if !self.parsing { if text.hasPrefix(ExpUpdateHandler.start_check) { self.parsing = true return } } else { if text.hasPrefix(ExpUpdateHandler.end_check) { self.parsing = false return } let groups = text[exp_regex].allGroups() for group in groups { let var_name = group[1].replace(" ", withString: "_") let skill = SkillExp() skill.name = var_name skill.mindState = LearningRate.fromDescription(group[4]) skill.ranks = NSDecimalNumber(string: "\(group[2]).\(group[3])") emitSetting?("\(var_name).Ranks", "\(skill.ranks)") emitSetting?("\(var_name).LearningRate", "\(skill.mindState.rateId)") emitSetting?("\(var_name).LearningRateName", "\(skill.mindState.desc)") emitExp?(skill) } } } }
63d87cbf7126e6af6d6b5f6c5392ed18
29.081967
90
0.497548
false
false
false
false
SettlePad/client-iOS
refs/heads/master
SettlePad/NewUOmeViewController.swift
mit
1
// // NewUOmeViewController.swift // SettlePad // // Created by Rob Everhardt on 01/02/15. // Copyright (c) 2015 SettlePad. All rights reserved. // import UIKit protocol NewUOmeModalDelegate { func transactionsPosted(controller:NewUOmeViewController) func transactionsPostCompleted(controller:NewUOmeViewController, error_msg: String?) } class NewUOmeViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, UIPickerViewDelegate, UIPickerViewDataSource { let footer = NewUOmeFooterView(frame: CGRectMake(0, 0, 320, 44)) var addressBookFooter = UINib(nibName: "NewUOmeAddressBook", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! NewUOmeAddressBook var delegate:NewUOmeModalDelegate! = nil var sortedCurrencies: [Currency] = [] var selectedCurrency: Currency = Currency.EUR @IBOutlet var newUOmeTableView: UITableView! @IBAction func closeView(sender: AnyObject) { if state == .Overview { //TODO: save draft memos so that they remain after the app is terminated (via Transactions class, in CoreData, see http://www.raywenderlich.com/85578/first-core-data-app-using-swift) self.dismissViewControllerAnimated(true, completion: nil) } else { formTo.text = "" switchState(.Overview) } } @IBOutlet var sendButton: UIBarButtonItem! @IBAction func sendUOmes(sender: AnyObject) { if formTo.text != "" { saveUOme() } if newTransactions.count > 0 { //Post activeUser!.transactions.post(newTransactions, success: { activeUser!.contacts.updateContacts( { self.delegate.transactionsPostCompleted(self, error_msg: nil) }, failure: {error in self.delegate.transactionsPostCompleted(self, error_msg: error.errorText) } ) }, failure: { error in self.delegate.transactionsPostCompleted(self, error_msg: error.errorText) } ) //Close viewcontroller delegate.transactionsPosted(self) self.dismissViewControllerAnimated(true, completion: nil) } } @IBAction func formCurrencyAction(sender: PickerButton) { sender.becomeFirstResponder() } @IBOutlet var formTo: UITextField! @IBOutlet var formDescription: UITextField! @IBOutlet var formType: UISegmentedControl! @IBOutlet var formCurrency: PickerButton! @IBOutlet var formAmount: UITextField! @IBOutlet var formSaveButton: UIButton! @IBOutlet var tableBottomConstraint: NSLayoutConstraint! var newTransactions = [Transaction]() enum State { case Overview //show all new transactions case NewUOme //show suggestions for email address } var matchedContactIdentifiers = [Identifier]() //Name, Identifier var state: State = .Overview var actInd: UIActivityIndicatorView = UIActivityIndicatorView() @IBAction func saveUOme(sender: AnyObject) { saveUOme() } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if state == .NewUOme { return false } else { return true } } @IBAction func viewTapped(sender: AnyObject) { self.view.endEditing(true) } @IBOutlet var tableSaveContraint: NSLayoutConstraint! //table to Save button @IBAction func formToEditingChanged(sender: AnyObject) { validateForm(true, finalCheck: false) //If not-empty, show suggestions if formTo.text != "" { getMatchedContactIdentifiers(formTo.text!) switchState(.NewUOme) } else { switchState(.Overview) } } @IBAction func formToEditingDidEnd(sender: AnyObject) { validateForm(false, finalCheck: false) //Hide suggestions if formTo.text != "" { switchState(.Overview) } } func switchState(explicitState: State?) { if let state = explicitState { self.state = state } else { if (self.state == .Overview) { self.state = .NewUOme } else { self.state = .Overview } } if (self.state == .Overview) { actInd.removeFromSuperview() formDescription.hidden = false formType.hidden = false formCurrency.hidden = false formAmount.hidden = false formSaveButton.hidden = false tableSaveContraint.active = true sendButton.enabled = true footer.setNeedsDisplay() newUOmeTableView.tableFooterView = footer newUOmeTableView.allowsSelection = false newUOmeTableView.reloadData() } else if (self.state == .NewUOme){ actInd.removeFromSuperview() formDescription.hidden = true formType.hidden = true formCurrency.hidden = true formAmount.hidden = true formSaveButton.hidden = true tableSaveContraint.active = false sendButton.enabled = false layoutAddressBookFooter() addressBookFooter.setNeedsDisplay() newUOmeTableView.tableFooterView = addressBookFooter newUOmeTableView.allowsSelection = true newUOmeTableView.reloadData() } } func layoutAddressBookFooter() { addressBookFooter.frame.size.width = newUOmeTableView.frame.width addressBookFooter.detailLabel.preferredMaxLayoutWidth = newUOmeTableView.frame.width - 40 //margin of 20 left and right addressBookFooter.frame.size.height = addressBookFooter.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height //Only works if preferred width is set for the objects that have variable height } @IBAction func formDescriptionEditingChanged(sender: AnyObject) { validateForm(true,finalCheck: false) } @IBAction func formAmountEditingChanged(sender: AnyObject) { validateForm(true, finalCheck: false) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. switchState(.Overview) addressBookFooter.footerUpdated = {(sender) in self.addressBookFooter = UINib(nibName: "NewUOmeAddressBook", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! NewUOmeAddressBook self.layoutAddressBookFooter() dispatch_async(dispatch_get_main_queue(), { self.newUOmeTableView.tableFooterView = self.addressBookFooter }) self.newUOmeTableView.reloadData() } //Sort currencies sortedCurrencies = Currency.allValues.sort({(left: Currency, right: Currency) -> Bool in left.toLongName().localizedCaseInsensitiveCompare(right.toLongName()) == NSComparisonResult.OrderedDescending}) //Link currency picker to delegate and datasource functions below formCurrency.modInputView.dataSource = self formCurrency.modInputView.delegate = self //Set currency picker to user's default currency let row: Int? = sortedCurrencies.indexOf(activeUser!.defaultCurrency) if row != nil { formCurrency.modInputView.selectRow(row!, inComponent: 0, animated: false) selectedCurrency = activeUser!.defaultCurrency formCurrency.setTitle(activeUser!.defaultCurrency.rawValue, forState: UIControlState.Normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func validateForm (whileEditing: Bool, finalCheck: Bool) -> Bool { var isValid = true var hasGivenFirstResponder = false /*Could also color the border, with formTo.layer.borderWidth = 1.0 formTo.layer.borderColor = Colors.danger.textToUIColor().CGColor */ if formTo.text!.isEmail() { formTo.backgroundColor = nil formTo.textColor = nil } else { isValid = false if finalCheck || (formTo.text != "" && !whileEditing) { formTo.backgroundColor = Colors.danger.backgroundToUIColor() formTo.textColor = Colors.danger.textToUIColor() if (!hasGivenFirstResponder && finalCheck) { formTo.becomeFirstResponder() hasGivenFirstResponder = true } } } if formDescription.text != "" { formDescription.backgroundColor = nil formDescription.textColor = nil } else { isValid = false if finalCheck { formDescription.backgroundColor = Colors.danger.backgroundToUIColor() formDescription.textColor = Colors.danger.textToUIColor() if (!hasGivenFirstResponder && finalCheck) { formDescription.becomeFirstResponder() hasGivenFirstResponder = true } } } if formAmount.text!.toDouble() != nil { formAmount.backgroundColor = nil formAmount.textColor = nil } else { isValid = false if finalCheck || (formDescription.text != "" && !whileEditing) { formAmount.backgroundColor = Colors.danger.backgroundToUIColor() formAmount.textColor = Colors.danger.textToUIColor() if (!hasGivenFirstResponder && finalCheck) { formAmount.becomeFirstResponder() hasGivenFirstResponder = true } } } return isValid } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (self.state == .Overview) { return newTransactions.count } else { return matchedContactIdentifiers.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if (self.state == .Overview) { //Show draft UOme's let cell = tableView.dequeueReusableCellWithIdentifier("TransactionCell", forIndexPath: indexPath) as! TransactionsCell // Configure the cell... cell.markup(newTransactions[indexPath.row]) cell.layoutIfNeeded() //to get right layout given dynamic height return cell } else { //show contacts let cell = tableView.dequeueReusableCellWithIdentifier("ContactCell", forIndexPath: indexPath) // Configure the cell... let contactIdentifier = matchedContactIdentifiers[indexPath.row] cell.textLabel?.text = contactIdentifier.resultingName cell.detailTextLabel?.text = contactIdentifier.identifierStr if contactIdentifier.contact != nil { //Is a uoless user cell.backgroundColor = Colors.primary.backgroundToUIColor() } else { cell.backgroundColor = UIColor.whiteColor() } cell.layoutIfNeeded() //to get right layout given dynamic height return cell } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { //Editable or not if (self.state == .Overview) { return true } else { return false } } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { //function required to have editable rows } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { //return [] let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in self.deleteTransaction(indexPath.row) }) deleteAction.backgroundColor = Colors.danger.textToUIColor() return [deleteAction] } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if (self.state == .NewUOme) { //Set value as "to" let contactIdentifier = matchedContactIdentifiers[indexPath.row] formTo.text = contactIdentifier.identifierStr switchState(.Overview) //goto amount if formDescription.text == "" { formDescription.becomeFirstResponder() } else { formAmount.becomeFirstResponder() } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //Set cell height to dynamic. Note that it also requires a cell.layoutIfNeeded in cellForRowAtIndexPath! newUOmeTableView.estimatedRowHeight = 70 newUOmeTableView.rowHeight = UITableViewAutomaticDimension } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) formTo.becomeFirstResponder() //If done earlier (eg. at viewWillAppear), the layouting is not done yet and keyboard will pop up before that. As that triggers an animated re-layouting, width-changes can also be seen animated. Can also do a self.view.layoutIfNeeded() before this line } func textFieldShouldReturn(textField: UITextField!) -> Bool { //textfields that should trigger this need to have their delegate set to the viewcontroller if (textField!.restorationIdentifier == "to") { //goto description formDescription.becomeFirstResponder() } else if (textField!.restorationIdentifier == "description") { //goto amount formAmount.becomeFirstResponder() } else if (textField!.restorationIdentifier == "amount") { saveUOme() } return true; } func saveUOme() { if validateForm(false, finalCheck: true) { var amount: Double if (formType.selectedSegmentIndex == 0) { amount = formAmount.text!.toDouble()! } else { amount = -1*formAmount.text!.toDouble()! } let matchedIdentifier: Identifier? = activeUser!.contacts.getIdentifier(formTo.text!) var name: String if matchedIdentifier != nil { name = matchedIdentifier!.resultingName } else { name = formTo.text! } let transaction = Transaction( name: name, identifier: formTo.text!, description: formDescription.text!, currency: selectedCurrency, amount: amount ) newTransactions.append(transaction) //Clean out the form, set focus on recipient newUOmeTableView.reloadData() footer.setNeedsDisplay() newUOmeTableView.tableFooterView = footer formTo.text = "" formTo.becomeFirstResponder() } } func deleteTransaction(index:Int){ newTransactions.removeAtIndex(index) newUOmeTableView.reloadData() footer.setNeedsDisplay() newUOmeTableView.tableFooterView = footer } func getMatchedContactIdentifiers(needle: String){ matchedContactIdentifiers.removeAll() //First add those that are registered at Settlepad for contactIdentifier in activeUser!.contacts.contactIdentifiers where contactIdentifier.contact != nil { if (contactIdentifier.identifierStr.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.contact?.name.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.contact?.friendlyName.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.localName?.lowercaseString.rangeOfString(needle.lowercaseString) != nil) { matchedContactIdentifiers.append(contactIdentifier) } } //Then add those from local address book only for contactIdentifier in activeUser!.contacts.contactIdentifiers where contactIdentifier.contact == nil { if (contactIdentifier.identifierStr.lowercaseString.rangeOfString(needle.lowercaseString) != nil || contactIdentifier.localName?.lowercaseString.rangeOfString(needle.lowercaseString) != nil) { matchedContactIdentifiers.append(contactIdentifier) } } } // Currency picker delegate func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1; } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return sortedCurrencies.count; } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return sortedCurrencies[row].toLongName() } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { formCurrency.setTitle(sortedCurrencies[row].rawValue, forState: UIControlState.Normal) selectedCurrency = sortedCurrencies[row] } func donePicker () { formCurrency.resignFirstResponder() } } class NewUOmeFooterView: UIView { override init (frame : CGRect) { super.init(frame : frame) self.opaque = false //Required for transparent background } /*convenience override init () { self.init(frame:CGRectMake(0, 0, 320, 44)) //By default, make a rect of 320x44 }*/ required init?(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } override func drawRect(rect: CGRect) { //To make sure we are not adding one layer of text onto another for view in self.subviews { view.removeFromSuperview() } let footerLabel: UILabel = UILabel(frame: rect) footerLabel.textColor = Colors.gray.textToUIColor() footerLabel.font = UIFont.boldSystemFontOfSize(11) footerLabel.textAlignment = NSTextAlignment.Center footerLabel.text = "Saved memos will be listed here to be all sent at once." self.addSubview(footerLabel) } }
ea0c9dd10903435b4e996a6d4db879b5
34.014679
404
0.645863
false
false
false
false
aolan/Cattle
refs/heads/master
CattleKit/UIView+CAFrame.swift
mit
1
// // UIView+CAFrame.swift // cattle // // Created by lawn on 15/11/5. // Copyright © 2015年 zodiac. All rights reserved. // import UIKit extension UIView{ func ca_minX() -> CGFloat{ return frame.origin.x } func ca_minX(x: CGFloat) -> Void{ frame.origin.x = x } func ca_minY() -> CGFloat{ return frame.origin.y } func ca_minY(y: CGFloat) -> Void{ frame.origin.y = y } func ca_maxX() -> CGFloat{ return frame.origin.x + frame.size.width } func ca_maxX(x:CGFloat) -> Void{ frame.origin.x = x - frame.size.width } func ca_maxY() -> CGFloat{ return frame.origin.y + frame.size.height } func ca_maxY(y:CGFloat) -> Void{ frame.origin.y = y - frame.size.height } func ca_width() -> CGFloat{ return frame.size.width } func ca_width(w:CGFloat) -> Void{ frame.size.width = w } func ca_heigth() -> CGFloat{ return frame.size.height } func ca_height(h:CGFloat) -> Void{ frame.size.height = h } func ca_centerX() -> CGFloat{ return frame.origin.x + frame.size.width/2.0 } func ca_centerX(x:CGFloat) -> Void{ frame.origin.x = x - frame.size.width/2.0 } func ca_centerY() -> CGFloat{ return frame.origin.y + frame.size.height/2.0 } func ca_centerY(y:CGFloat) -> Void{ frame.origin.y = y - frame.size.height/2.0 } func ca_center() -> CGPoint{ return CGPoint(x: ca_centerX(), y: ca_centerY()) } func ca_center(p:CGPoint) ->Void{ frame.origin.x = p.x - frame.size.width/2.0 frame.origin.y = p.y - frame.size.height/2.0 } func ca_size() -> CGSize{ return frame.size } func ca_size(size:CGSize) -> Void{ frame.size = size } func ca_addX(increment:CGFloat) -> Void{ frame.origin.x += increment } func ca_addY(increment:CGFloat) -> Void{ frame.origin.y += increment } }
199df8b7f0cc9a378482677d9b8a016c
16.693069
50
0.630106
false
false
false
false
VirgilSecurity/virgil-crypto-ios
refs/heads/master
Source/VirgilCrypto/VirgilCrypto+AuthEncrypt.swift
bsd-3-clause
1
// // Copyright (C) 2015-2021 Virgil Security Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation import VirgilCryptoFoundation extension VirgilCrypto { /// Signs (with private key) Then Encrypts data (and signature) for passed PublicKeys /// /// 1. Generates signature depending on KeyType /// 2. Generates random AES-256 KEY1 /// 3. Encrypts data with KEY1 using AES-256-GCM and generates signature /// 4. Encrypts signature with KEY1 using AES-256-GCM /// 5. Generates ephemeral key pair for each recipient /// 6. Uses Diffie-Hellman to obtain shared secret with each recipient's public key & each ephemeral private key /// 7. Computes KDF to obtain AES-256 key from shared secret for each recipient /// 8. Encrypts KEY1 with this key using AES-256-CBC for each recipient /// /// - Parameters: /// - data: Data to be signedThenEncrypted /// - privateKey: Sender private key /// - recipients: Recipients' public keys /// - enablePadding: If true, will add padding to plain text before encryption. /// This is recommended for data for which exposing length can /// cause security issues (e.g. text messages) /// - Returns: SignedThenEncrypted data /// - Throws: Rethrows from `RecipientCipher`. @objc open func authEncrypt(_ data: Data, with privateKey: VirgilPrivateKey, for recipients: [VirgilPublicKey], enablePadding: Bool = true) throws -> Data { return try self.encrypt(inputOutput: .data(input: data), signingOptions: SigningOptions(privateKey: privateKey, mode: .signThenEncrypt), recipients: recipients, enablePadding: enablePadding)! } /// Decrypts (with private key) data and signature and Verifies signature using any of signers' PublicKeys /// /// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key /// 2. Computes KDF to obtain AES-256 KEY2 from shared secret /// 3. Decrypts KEY1 using AES-256-CBC /// 4. Decrypts data and signature using KEY1 and AES-256-GCM /// 5. Finds corresponding PublicKey according to signer id inside data /// 6. Verifies signature /// /// - Parameters: /// - data: Signed Then Encrypted data /// - privateKey: Receiver's private key /// - signersPublicKeys: Array of possible signers public keys. /// WARNING: Data should have signature of ANY public key from array. /// - Returns: DecryptedThenVerified data /// - Throws: Rethrows from `RecipientCipher`. @objc open func authDecrypt(_ data: Data, with privateKey: VirgilPrivateKey, usingOneOf signersPublicKeys: [VirgilPublicKey]) throws -> Data { return try self.authDecrypt(data, with: privateKey, usingOneOf: signersPublicKeys, allowNotEncryptedSignature: false) } /// Decrypts (with private key) data and signature and Verifies signature using any of signers' PublicKeys /// /// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key /// 2. Computes KDF to obtain AES-256 KEY2 from shared secret /// 3. Decrypts KEY1 using AES-256-CBC /// 4. Decrypts data and signature using KEY1 and AES-256-GCM /// 5. Finds corresponding PublicKey according to signer id inside data /// 6. Verifies signature /// /// - Parameters: /// - data: Signed Then Encrypted data /// - privateKey: Receiver's private key /// - signersPublicKeys: Array of possible signers public keys. /// WARNING: Data should have signature of ANY public key from array. /// - allowNotEncryptedSignature: Allows storing signature in plain text /// for compatibility with deprecated signAndEncrypt /// - Returns: DecryptedThenVerified data /// - Throws: Rethrows from `RecipientCipher`. @objc open func authDecrypt(_ data: Data, with privateKey: VirgilPrivateKey, usingOneOf signersPublicKeys: [VirgilPublicKey], allowNotEncryptedSignature: Bool) throws -> Data { let verifyMode: VerifyingMode = allowNotEncryptedSignature ? .any : .decryptThenVerify return try self.decrypt(inputOutput: .data(input: data), verifyingOptions: VerifyingOptions(publicKeys: signersPublicKeys, mode: verifyMode), privateKey: privateKey)! } /// Signs (with private key) Then Encrypts stream (and signature) for passed PublicKeys /// /// 1. Generates signature depending on KeyType /// 2. Generates random AES-256 KEY1 /// 3. Encrypts data with KEY1 using AES-256-GCM and generates signature /// 4. Encrypts signature with KEY1 using AES-256-GCM /// 5. Generates ephemeral key pair for each recipient /// 6. Uses Diffie-Hellman to obtain shared secret with each recipient's public key & each ephemeral private key /// 7. Computes KDF to obtain AES-256 key from shared secret for each recipient /// 8. Encrypts KEY1 with this key using AES-256-CBC for each recipient /// /// - Parameters: /// - stream: Input stream /// - streamSize: Input stream size /// - outputStream: Output stream /// - privateKey: Private key to generate signatures /// - recipients: Recipients public keys /// - enablePadding: If true, will add padding to plain text before encryption. /// This is recommended for data for which exposing length can /// cause security issues (e.g. text messages) /// - Throws: Rethrows from `RecipientCipher`. @objc open func authEncrypt(_ stream: InputStream, streamSize: Int, to outputStream: OutputStream, with privateKey: VirgilPrivateKey, for recipients: [VirgilPublicKey], enablePadding: Bool = false) throws { _ = try self.encrypt(inputOutput: .stream(input: stream, streamSize: streamSize, output: outputStream), signingOptions: SigningOptions(privateKey: privateKey, mode: .signThenEncrypt), recipients: recipients, enablePadding: enablePadding) } /// Decrypts (using passed PrivateKey) then verifies (using one of public keys) stream /// /// - Note: Decrypted stream should not be used until decryption /// of whole InputStream completed due to security reasons /// /// 1. Uses Diffie-Hellman to obtain shared secret with sender ephemeral public key & recipient's private key /// 2. Computes KDF to obtain AES-256 KEY2 from shared secret /// 3. Decrypts KEY1 using AES-256-CBC /// 4. Decrypts data and signature using KEY1 and AES-256-GCM /// 5. Finds corresponding PublicKey according to signer id inside data /// 6. Verifies signature /// /// - Parameters: /// - stream: Stream with encrypted data /// - outputStream: Stream with decrypted data /// - privateKey: Recipient's private key /// - signersPublicKeys: Array of possible signers public keys. /// WARNING: Stream should have signature of ANY public key from array. /// - Throws: Rethrows from `RecipientCipher`. @objc open func authDecrypt(_ stream: InputStream, to outputStream: OutputStream, with privateKey: VirgilPrivateKey, usingOneOf signersPublicKeys: [VirgilPublicKey]) throws { _ = try self.decrypt(inputOutput: .stream(input: stream, streamSize: nil, output: outputStream), verifyingOptions: VerifyingOptions(publicKeys: signersPublicKeys, mode: .decryptThenVerify), privateKey: privateKey) } }
3d9c236dad62b0ccd2b15a7ec991c767
54.165746
116
0.636855
false
false
false
false
jnross/Bluetility
refs/heads/main
Bluetility/Device.swift
mit
1
// // Device.swift // Bluetility // // Created by Joseph Ross on 7/1/20. // Copyright © 2020 Joseph Ross. All rights reserved. // import CoreBluetooth protocol DeviceDelegate: AnyObject { func deviceDidConnect(_ device: Device) func deviceDidDisconnect(_ device: Device) func deviceDidUpdateName(_ device: Device) func device(_ device: Device, updated services: [CBService]) func device(_ device: Device, updated characteristics: [CBCharacteristic], for service: CBService) func device(_ device: Device, updatedValueFor characteristic: CBCharacteristic) } class Device : NSObject { let peripheral: CBPeripheral unowned var scanner: Scanner var advertisingData: [String:Any] var rssi: Int weak var delegate: DeviceDelegate? = nil // Transient data var manufacturerName: String? = nil var modelName: String? = nil init(scanner: Scanner, peripheral: CBPeripheral, advertisingData: [String: Any], rssi: Int) { self.scanner = scanner self.peripheral = peripheral self.advertisingData = advertisingData self.rssi = rssi super.init() peripheral.delegate = self } deinit { peripheral.delegate = nil } var friendlyName : String { if let advertisedName = advertisingData[CBAdvertisementDataLocalNameKey] as? String { return advertisedName } if let peripheralName = peripheral.name { return peripheralName } let infoFields = [manufacturerName, modelName].compactMap({$0}) if infoFields.count > 0 { return infoFields.joined(separator: " ") } return "Untitled" } var services: [CBService] { return peripheral.services ?? [] } func connect() { scanner.central.connect(self.peripheral, options: [:]) } func disconnect() { scanner.central.cancelPeripheralConnection(self.peripheral) } func discoverCharacteristics(for service: CBService) { peripheral.discoverCharacteristics(nil, for: service) } func read(characteristic: CBCharacteristic) { peripheral.readValue(for: characteristic) } func write(data: Data, for characteristic: CBCharacteristic, type:CBCharacteristicWriteType) { peripheral.writeValue(data, for: characteristic, type: type) } func setNotify(_ enabled: Bool, for characteristic: CBCharacteristic) { peripheral.setNotifyValue(enabled, for: characteristic) } } extension Device : CBPeripheralDelegate { func peripheralDidConnect() { peripheral.discoverServices(nil) delegate?.deviceDidConnect(self) } func peripheralDidDisconnect(error: Error?) { delegate?.deviceDidDisconnect(self) } func peripheralDidUpdateName(_ peripheral: CBPeripheral) { delegate?.deviceDidUpdateName(self) } func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let error = error { // TODO: report an error? assertionFailure(error.localizedDescription) } let services = peripheral.services ?? [] handleSpecialServices(services) delegate?.device(self, updated: services) } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let error = error { // TODO: report an error? assertionFailure(error.localizedDescription) } let characteristics = service.characteristics ?? [] handleSpecialCharacteristics(characteristics) delegate?.device(self, updated: characteristics, for: service) } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let error = error { // TODO: report an error? assertionFailure(error.localizedDescription) } handleSpecialCharacteristic(characteristic) delegate?.device(self, updatedValueFor: characteristic) } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { if let error = error { // TODO: report an error? assertionFailure(error.localizedDescription) } // TODO: report successful write? } } // MARK: Handle Special Characteristics fileprivate let specialServiceUUIDs = [ CBUUID(string: "180A"), // Device Information Service ] fileprivate let manufacturerNameUUID = CBUUID(string: "2A29") fileprivate let modelNumberUUID = CBUUID(string: "2A24") fileprivate let specialCharacteristicUUIDs = [ manufacturerNameUUID, // Manufacturer Name modelNumberUUID, // Model Number ] extension Device { func handleSpecialServices(_ services: [CBService]) { for service in services { if specialServiceUUIDs.contains(service.uuid) { peripheral.discoverCharacteristics(specialCharacteristicUUIDs, for: service) } } } func handleSpecialCharacteristics(_ characteristics: [CBCharacteristic]) { for characteristic in characteristics { if specialCharacteristicUUIDs.contains(characteristic.uuid) { peripheral.readValue(for: characteristic) handleSpecialCharacteristic(characteristic) } } } func handleSpecialCharacteristic(_ characteristic: CBCharacteristic) { guard let value = characteristic.value else { return } if specialCharacteristicUUIDs.contains(characteristic.uuid) { switch characteristic.uuid { case manufacturerNameUUID: manufacturerName = String(bytes: value, encoding: .utf8) case modelNumberUUID: modelName = String(bytes: value, encoding: .utf8) default: assertionFailure("Forgot to handle one of the UUIDs in specialCharacteristicUUIDs: \(characteristic.uuid)") } delegate?.deviceDidUpdateName(self) } } }
5198a6ea6b4eb26835ad6a51175ab7b4
31.091837
123
0.647218
false
false
false
false
DrGo/LearningSwift
refs/heads/master
PLAYGROUNDS/ExpressionParser/ExpressionParser/TokenParser.swift
gpl-3.0
2
// // TokenParser.swift // ExpressionParser // // Created by Kyle Oba on 2/6/15. // Copyright (c) 2015 Pas de Chocolat. All rights reserved. // import Foundation /*---------------------------------------------------------------------/ // Expressions - Can be numbers, references, binary expressions with, // an operator, or function calls. // // This recursive Enum is the Abstract Syntax Tree for our // spreadsheet expressions. // // ExpressionLike is a work around because Swift doesn't currently // allow recursive Enums. /---------------------------------------------------------------------*/ public protocol ExpressionLike { func toExpression() -> Expression } public enum Expression { case Number(Int) case Reference(String, Int) case BinaryExpression(String, ExpressionLike, ExpressionLike) case FunctionCall(String, ExpressionLike) } extension Expression: ExpressionLike { public func toExpression() -> Expression { return self } } // Computes expression values from a stream of tokens typealias ExpressionParser = Parser<Token, Expression> /*---------------------------------------------------------------------/ // optionalTransform - Generates a parser that satisfies a predicate // or returns nil /---------------------------------------------------------------------*/ func optionalTransform<A, T>(f: T -> A?) -> Parser<T, A> { return { f($0)! } </> satisfy { f($0) != nil } } /*---------------------------------------------------------------------/ // pNumber - Number parser /---------------------------------------------------------------------*/ let pNumber: ExpressionParser = optionalTransform { switch $0 { case .Number(let number): return Expression.Number(number) default: return nil } } /*---------------------------------------------------------------------/ // pReference - Cell reference parser /---------------------------------------------------------------------*/ let pReference: ExpressionParser = optionalTransform { switch $0 { case .Reference(let column, let row): return Expression.Reference(column, row) default: return nil } } let pNumberOrReference = pNumber <|> pReference extension Expression : Printable { public var description: String { switch (self) { case Number(let x): return "\(x)" case let .Reference(col, row): return "\(col)\(row)" case let Expression.BinaryExpression(binaryOp, expLike1, expLike2): let operand1 = expLike1.toExpression().description let operand2 = expLike2.toExpression().description return "\(operand1) \(binaryOp) \(operand2)" case let .FunctionCall(fn, expLike): let expr = expLike.toExpression().description return "\(fn)(\(expr))" } } } func readExpression(expr: Expression) -> String { var header = "" switch (expr) { case .Number: header = "Number" case .Reference: header = "Reference" case .BinaryExpression: header = "Binary Expression" case .FunctionCall: header = "Function" } return "\(header): \(expr.description)" } /*---------------------------------------------------------------------/ // pFunctionName - Function name parser /---------------------------------------------------------------------*/ let pFunctionName: Parser<Token, String> = optionalTransform { switch $0 { case .FunctionName(let name): return name default: return nil } } /*---------------------------------------------------------------------/ // pList - List parser /---------------------------------------------------------------------*/ func makeList(l: Expression, r: Expression) -> Expression { return Expression.BinaryExpression(":", l, r) } func op(opString: String) -> Parser<Token, String> { return const(opString) </> token(Token.Operator(opString)) } let pList: ExpressionParser = curry(makeList) </> pReference <* op(":") <*> pReference /*---------------------------------------------------------------------/ // parenthesized - Generates Parser for parenthesized expression /---------------------------------------------------------------------*/ func parenthesized<A>(p: Parser<Token, A>) -> Parser<Token, A> { return token(Token.Punctuation("(")) *> p <* token(Token.Punctuation(")")) } /*---------------------------------------------------------------------/ // pFunctionCall - Put it all together to create function call Parser /---------------------------------------------------------------------*/ func makeFunctionCall(name: String, arg: Expression) -> Expression { return Expression.FunctionCall(name, arg) } let pFunctionCall = curry(makeFunctionCall) </> pFunctionName <*> parenthesized(pList) /*---------------------------------------------------------------------/ // Parsers for formula primitives - start with the smallest /---------------------------------------------------------------------*/ func expression() -> ExpressionParser { return pSum } let pParenthesizedExpression = parenthesized(lazy(expression())) let pPrimitive = pNumberOrReference <|> pFunctionCall <|> pParenthesizedExpression /*---------------------------------------------------------------------/ // pMultiplier - Multiplication or Division are equal /---------------------------------------------------------------------*/ let pMultiplier = curry { ($0, $1) } </> (op("*") <|> op("/")) <*> pPrimitive /*---------------------------------------------------------------------/ // combineOperands - Build an expression tree from primitive and // multipier tuples /---------------------------------------------------------------------*/ func combineOperands(first: Expression, rest: [(String, Expression)]) -> Expression { return rest.reduce(first, combine: { result, pair in let (op, exp) = pair return Expression.BinaryExpression(op, result, exp) }) } /*---------------------------------------------------------------------/ // pProduct - Combine tuples from pMultiplier (also handles division) /---------------------------------------------------------------------*/ let pProduct = curry(combineOperands) </> pPrimitive <*> zeroOrMore(pMultiplier) /*---------------------------------------------------------------------/ // pSum - Do the same for addition and subtraction /---------------------------------------------------------------------*/ let pSummand = curry { ($0, $1) } </> (op("-") <|> op("+")) <*> pProduct let pSum = curry(combineOperands) </> pProduct <*> zeroOrMore(pSummand) /*---------------------------------------------------------------------/ // parseExpression - Tokenizer combined with Parsers /---------------------------------------------------------------------*/ func parseExpressionWithoutFlatmap(input: String) -> Expression? { if let tokens = parse(tokenize(), input) { return parse(expression(), tokens) } return nil } // Can also use `flatMap` for this func flatMap<A, B>(x: A?, f: A -> B?) -> B? { if let value = x { return f(value) } return nil } public func parseExpression(input: String) -> Expression? { return flatMap(parse(tokenize(), input)) { parse(expression(), $0) } }
5add9e3df68b50d236af74dd87e66b17
30.382609
86
0.489194
false
false
false
false
SirArkimedes/WWDC-2015
refs/heads/master
Andrew Robinson/GameScene.swift
mit
1
// // GameScene.swift // Andrew Robinson // // Created by Andrew Robinson on 4/19/15. // Copyright (c) 2015 Andrew Robinson. All rights reserved. // import UIKit import SpriteKit class GameScene: SKScene { var circles : [SKShapeNode] = [SKShapeNode]() var xVelocity: CGFloat = 0 var kMaxLeft : CGFloat = 0 var kMaxRight : CGFloat = 0 var kMaxBottom : CGFloat = 0 var kMaxTop : CGFloat = 0 override func didMoveToView(view: SKView) { let minusSize : CGFloat = 0 // Set variables kMaxLeft = CGFloat((5/6)*self.frame.size.width) + minusSize kMaxRight = self.frame.size.width/6 - minusSize kMaxBottom = self.frame.size.height/8 - minusSize kMaxTop = CGFloat((7/8)*self.frame.size.height) + minusSize var circle = self.circle(); self.addChild(circle) circle.physicsBody?.applyForce(CGVectorMake(50, 50)) circles.append(circle) // Fade it in circle.runAction(SKAction.fadeAlphaTo(1, duration: 1.5)) // Create the loop self.spawnMore(); // No gravity! self.physicsWorld.gravity = CGVectorMake(0, 0) self.physicsBody = SKPhysicsBody(edgeLoopFromRect:self.frame) } func circle() -> SKShapeNode { var circleRadius : CGFloat let randRadius : UInt32 = arc4random_uniform(3) var color : SKColor let randColor : UInt32 = arc4random_uniform(3) switch randRadius { case 0: circleRadius = 50 case 1: circleRadius = 30 case 2: circleRadius = 20 default: circleRadius = 10 } switch randColor { case 0: color = SKColor.blueColor() case 1: color = SKColor.purpleColor() case 2: color = SKColor.redColor() default: color = SKColor.blackColor() } var circle = SKShapeNode(circleOfRadius:circleRadius) // Size of Circle circle.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2) circle.physicsBody = SKPhysicsBody(circleOfRadius:circleRadius) circle.physicsBody!.dynamic = true circle.strokeColor = SKColor.clearColor() circle.fillColor = color circle.alpha = 0 return circle; } func spawnMore() { if circles.count < 10 { delay(1) { var circle = self.circle(); self.addChild(circle) circle.physicsBody?.applyForce(CGVectorMake(-500, -500)) self.circles.append(circle) // Fade it in circle.runAction(SKAction.fadeAlphaTo(1, duration: 1.5)) self.spawnMore(); } } } // MARK: Update override func update(currentTime: CFTimeInterval) { // Move! for sprite : SKShapeNode in circles { if sprite.position.x > kMaxLeft { sprite.physicsBody?.applyImpulse(CGVectorMake(-30, 0)) } if sprite.position.x < kMaxRight { sprite.physicsBody?.applyImpulse(CGVectorMake(30, 0)) } if sprite.position.y < kMaxBottom { sprite.physicsBody?.applyImpulse(CGVectorMake(0, 30)) } if sprite.position.y > kMaxTop { sprite.physicsBody?.applyImpulse(CGVectorMake(0, -30)) } } } // MARK: Delay func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } }
6433f9d98e1d2a56482dfbff6d2661b0
25.934641
88
0.514196
false
false
false
false