repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
apple/swift-system
Tests/SystemTests/FilePathTests/FilePathComponentsTest.swift
1
8531
/* This source file is part of the Swift System open source project Copyright (c) 2020 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information */ import XCTest #if SYSTEM_PACKAGE @testable import SystemPackage #else @testable import System #endif /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ struct TestPathComponents: TestCase { var path: FilePath var expectedRoot: FilePath.Root? var expectedComponents: [FilePath.Component] var pathComponents: Array<FilePath.Component> { Array(path.components) } let file: StaticString let line: UInt func failureMessage(_ reason: String?) -> String { """ Fail \(reason ?? "") path: \(path) components: \(pathComponents)) expected: \(expectedComponents) """ } init<C: Collection>( _ path: FilePath, root: FilePath.Root?, _ components: C, file: StaticString = #file, line: UInt = #line ) where C.Element == FilePath.Component { self.path = path self.expectedRoot = root self.expectedComponents = Array(components) self.file = file self.line = line } func testComponents() { expectEqual(expectedRoot, path.root) expectEqualSequence( expectedComponents, Array(path.components), "testComponents()") } func testBidi() { expectEqualSequence( expectedComponents.reversed(), path.components.reversed(), "reversed()") expectEqualSequence( path.components, path.components.reversed().reversed(), "reversed().reversed()") for i in 0 ..< path.components.count { expectEqualSequence( expectedComponents.dropLast(i), path.components.dropLast(i), "dropLast") expectEqualSequence( expectedComponents.suffix(i), path.components.suffix(i), "suffix") } } func testRRC() { // TODO: programmatic tests showing parity with Array<Component> } func testModify() { if path.root == nil { let rootedPath = FilePath(root: "/", path.components) expectNotEqual(rootedPath, path) var pathCopy = path expectEqual(path, pathCopy) pathCopy.components = rootedPath.components expectNil(pathCopy.root, "components.set doesn't assign root") expectEqual(path, pathCopy) } else { let rootlessPath = FilePath(root: nil, path.components) var pathCopy = path expectEqual(path, pathCopy) pathCopy.components = rootlessPath.components expectNotNil(pathCopy.root, "components.set preserves root") expectEqual(path, pathCopy) } } func runAllTests() { testComponents() testBidi() testRRC() testModify() } } /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/ final class FilePathComponentsTest: XCTestCase { func testAdHocRRC() { var path: FilePath = "/usr/local/bin" func expect( _ s: String, _ file: StaticString = #file, _ line: UInt = #line ) { if path == FilePath(s) { return } defer { print("expected: \(s), actual: \(path)") } XCTAssert(false, file: file, line: line) } // Run `body`, restoring `path` afterwards func restoreAfter( body: () -> () ) { let copy = path defer { path = copy } body() } // Interior removal keeps path prefix intact, if there is one restoreAfter { path = "prefix//middle1/middle2////suffix" let suffix = path.components.indices.last! path.components.removeSubrange(..<suffix) expect("suffix") } restoreAfter { path = "prefix//middle1/middle2////suffix" let firstMiddle = path.components.index( path.components.startIndex, offsetBy: 1) let suffix = path.components.indices.last! path.components.removeSubrange(firstMiddle ..< suffix) expect("prefix/suffix") } restoreAfter { path.components.removeFirst() expect("/local/bin") path.components.removeFirst() expect("/bin") } restoreAfter { path.components.insert( contentsOf: ["bar", "baz"], at: path.components.startIndex) expect("/bar/baz/usr/local/bin") } restoreAfter { path.components.insert("start", at: path.components.startIndex) expect("/start/usr/local/bin") path.components.insert("prefix", at: path.components.startIndex) expect("/prefix/start/usr/local/bin") path.components.removeSubrange( ..<path.components.index(path.components.startIndex, offsetBy: 4)) expect("/bin") path.components.removeFirst() expect("/") path.components.append(contentsOf: ["usr", "local", "bin"]) expect("/usr/local/bin") path.components.removeLast(2) expect("/usr") } restoreAfter { path.root = nil expect("usr/local/bin") path.components.removeAll() expect("") path.components.insert("foo", at: path.components.startIndex) expect("foo") path.components.removeAll() path.components.insert( contentsOf: ["bar", "baz"], at: path.components.startIndex) expect("bar/baz") } restoreAfter { path.components.append("tail") expect("/usr/local/bin/tail") path.components.append(contentsOf: ["tail2", "tail3", "tail4"]) expect("/usr/local/bin/tail/tail2/tail3/tail4") } // Insertion into the middle adds trailing separator restoreAfter { path.components.remove( at: path.components.index(after: path.components.startIndex)) expect("/usr/bin") path.components.insert("middle", at: path.components.indices.last!) expect("/usr/middle/bin") path.components.insert( contentsOf: ["middle2", "middle3"], at: path.components.indices.last!) expect("/usr/middle/middle2/middle3/bin") let slice = path.components.dropFirst().dropLast() let range = slice.startIndex ..< slice.endIndex path.components.replaceSubrange( range, with: ["newMiddle", "newMiddle2", "newMiddle3", "newMiddle4/"]) expect("/usr/newMiddle/newMiddle2/newMiddle3/newMiddle4/bin") } restoreAfter { path.components.removeLast(3) expect("/") path.components.append(contentsOf: ["bar", "baz"]) expect("/bar/baz") } // Empty insertions / removals restoreAfter { path.components.replaceSubrange(..<path.components.startIndex, with: []) expect("/usr/local/bin") path.components.replaceSubrange(path.components.endIndex..., with: []) expect("/usr/local/bin") path.components.insert(contentsOf: [], at: path.components.startIndex) expect("/usr/local/bin") path.components.insert(contentsOf: [], at: path.components.indices.last!) expect("/usr/local/bin") } } func testCases() { let testPaths: Array<TestPathComponents> = [ TestPathComponents("", root: nil, []), TestPathComponents("/", root: "/", []), TestPathComponents("foo", root: nil, ["foo"]), TestPathComponents("foo/", root: nil, ["foo"]), TestPathComponents("/foo", root: "/", ["foo"]), TestPathComponents("foo/bar", root: nil, ["foo", "bar"]), TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]), TestPathComponents("/foo/bar", root: "/", ["foo", "bar"]), TestPathComponents("///foo//", root: "/", ["foo"]), TestPathComponents("/foo///bar", root: "/", ["foo", "bar"]), TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]), TestPathComponents("foo///bar/baz/", root: nil, ["foo", "bar", "baz"]), TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"]), TestPathComponents("./", root: nil, ["."]), TestPathComponents("./..", root: nil, [".", ".."]), TestPathComponents("/./..//", root: "/", [".", ".."]), ] testPaths.forEach { $0.runAllTests() } } func testSeparatorNormalization() { var paths: Array<FilePath> = [ "/a/b", "/a/b/", "/a//b/", "/a/b//", "/a/b////", "/a////b/", ] #if !os(Windows) paths.append("//a/b") paths.append("///a/b") paths.append("///a////b") paths.append("///a////b///") #endif for path in paths { var path = path path._normalizeSeparators() XCTAssertEqual(path, "/a/b") } } } // TODO: Test hashValue and equatable for equal components, i.e. make // sure indices are not part of the hash.
apache-2.0
ccefae74dcc6fce7b12f70bdd5a142f6
29.467857
80
0.620795
4.09357
false
true
false
false
BurntCaramel/BurntCocoaUI
BurntCocoaUI/SegmentedControlAssistant.swift
1
5224
// // SegmentedControlAssistant.swift // BurntCocoaUI // // Created by Patrick Smith on 29/04/2015. // Copyright (c) 2015 Burnt Caramel. All rights reserved. // import Cocoa public struct SegmentedItemCustomization<T: UIChoiceRepresentative> { public typealias Item = T /** Customize the title dynamically, called for each segmented item representative. */ public var title: ((_ segmentedItemRepresentative: Item) -> String)? /** Customize the integer tag, called for each segemented item representative. */ public var tag: ((_ segmentedItemRepresentative: T) -> Int?)? } public class SegmentedControlAssistant<T: UIChoiceRepresentative> { public typealias Item = T public typealias Value = Item.UniqueIdentifier public typealias ItemUniqueIdentifier = Item.UniqueIdentifier public let segmentedControl: NSSegmentedControl public var segmentedCell: NSSegmentedCell { return segmentedControl.cell as! NSSegmentedCell } public init(segmentedControl: NSSegmentedControl) { self.segmentedControl = segmentedControl if let defaultSegmentedItemRepresentatives = self.defaultSegmentedItemRepresentatives { segmentedItemRepresentatives = defaultSegmentedItemRepresentatives } } public convenience init() { let segmentedControl = NSSegmentedControl() self.init(segmentedControl: segmentedControl) } /** The default item representatives to populate with. */ public var defaultSegmentedItemRepresentatives: [Item]? { return nil } /** Pass an array of item representatives for each segmented item. */ public var segmentedItemRepresentatives: [Item]! { willSet { if hasUpdatedBefore { previouslySelectedUniqueIdentifier = selectedUniqueIdentifier } } } /** Customize the segmented item’s title, tag with this. */ public var customization = SegmentedItemCustomization<Item>() fileprivate var hasUpdatedBefore: Bool = false fileprivate var previouslySelectedUniqueIdentifier: ItemUniqueIdentifier? /** Populates the segemented control with items created for each member of `segmentedItemRepresentatives` */ public func update() { let segmentedCell = self.segmentedCell let trackingMode = segmentedCell.trackingMode let segmentedItemRepresentatives = self.segmentedItemRepresentatives! // Update number of segments segmentedCell.segmentCount = segmentedItemRepresentatives.count let customization = self.customization // Update each segment from its corresponding representative var segmentIndex: Int = 0 for segmentedItemRepresentative in segmentedItemRepresentatives { let title = customization.title?(segmentedItemRepresentative) ?? segmentedItemRepresentative.title let tag = customization.tag?(segmentedItemRepresentative) ?? 0 segmentedCell.setLabel(title, forSegment: segmentIndex) segmentedCell.setTag(tag, forSegment: segmentIndex) segmentIndex += 1 } if trackingMode == .selectOne { self.selectedUniqueIdentifier = previouslySelectedUniqueIdentifier } hasUpdatedBefore = true previouslySelectedUniqueIdentifier = nil } /** Find the item representative for the passed segmented item index. - parameter segmentIndex: The index of the segmented item to find. - returns: The item representative that matched. */ public func itemRepresentative(at segmentIndex: Int) -> Item { return segmentedItemRepresentatives[segmentIndex] } /** Find the unique identifier for the passed segmented item index. - parameter segmentIndex: The index of the segmented item to find. - returns: The item representative that matched. */ public func uniqueIdentifier(at segmentIndex: Int) -> ItemUniqueIdentifier { return itemRepresentative(at: segmentIndex).uniqueIdentifier } /** The item representative for the selected segment, or nil if no segment is selected. */ public var selectedItemRepresentative: Item? { get { let index = segmentedCell.selectedSegment guard index != -1 else { return nil } return itemRepresentative(at: index) } set { selectedUniqueIdentifier = newValue?.uniqueIdentifier } } /** The unique identifier for the selected segment, or nil if no segment is selected. */ public var selectedUniqueIdentifier: ItemUniqueIdentifier? { get { return selectedItemRepresentative?.uniqueIdentifier } set(newIdentifier) { guard let newIdentifier = newIdentifier else { segmentedControl.selectedSegment = -1 return } for (index, itemRepresentative) in segmentedItemRepresentatives.enumerated() { if itemRepresentative.uniqueIdentifier == newIdentifier { segmentedControl.selectedSegment = index return } } segmentedControl.selectedSegment = -1 } } } extension SegmentedControlAssistant : UIControlAssistant { typealias Control = NSSegmentedControl var control: Control { return segmentedControl } var controlRenderer: (Value?) -> Control { return { newValue in self.selectedUniqueIdentifier = newValue return self.control } } } extension SegmentedControlAssistant where T : UIChoiceEnumerable { public var defaultSegmentedItemRepresentatives: [Item]? { return Item.allChoices.map{ $0 } } }
mit
5652f832d599ccdc41b3c83adb962308
26.340314
103
0.75699
4.592788
false
false
false
false
zhihuitang/Apollo
Apollo/GPX.swift
1
7429
// // GPX.swift // Trax // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // // Very simple GPX file parser. // Only verified to work for CS193p demo purposes! import Foundation class GPX: NSObject, XMLParserDelegate { // MARK: - Public API var waypoints = [Waypoint]() var tracks = [Track]() var routes = [Track]() typealias GPXCompletionHandler = (GPX?) -> Void class func parse(url: NSURL, completionHandler: @escaping GPXCompletionHandler) { GPX(url: url, completionHandler: completionHandler).parse() } // MARK: - Public Classes class Track: Entry { var fixes = [Waypoint]() override var description: String { let waypointDescription = "fixes=[\n" + fixes.map { $0.description }.joined(separator: "\n") + "\n]" return [super.description, waypointDescription].joined(separator: " ") } } class Waypoint: Entry { var latitude: Double var longitude: Double init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude super.init() } var info: String? { set { attributes["desc"] = newValue } get { return attributes["desc"] } } lazy var date: NSDate? = self.attributes["time"]?.asGpxDate override var description: String { return ["lat=\(latitude)", "lon=\(longitude)", super.description].joined(separator: " ") } } class Entry: NSObject { var links = [Link]() var attributes = [String:String]() var name: String? { set { attributes["name"] = newValue } get { return attributes["name"] } } override var description: String { var descriptions = [String]() if attributes.count > 0 { descriptions.append("attributes=\(attributes)") } if links.count > 0 { descriptions.append("links=\(links)") } return descriptions.joined(separator: " ") } } class Link: CustomStringConvertible { var href: String var linkattributes = [String:String]() init(href: String) { self.href = href } var url: NSURL? { return NSURL(string: href) } var text: String? { return linkattributes["text"] } var type: String? { return linkattributes["type"] } var description: String { var descriptions = [String]() descriptions.append("href=\(href)") if linkattributes.count > 0 { descriptions.append("linkattributes=\(linkattributes)") } return "[" + descriptions.joined(separator: " ") + "]" } } // MARK: - CustomStringConvertible override var description: String { var descriptions = [String]() if waypoints.count > 0 { descriptions.append("waypoints = \(waypoints)") } if tracks.count > 0 { descriptions.append("tracks = \(tracks)") } if routes.count > 0 { descriptions.append("routes = \(routes)") } return descriptions.joined(separator: "\n") } // MARK: - Private Implementation private let url: NSURL private let completionHandler: GPXCompletionHandler private init(url: NSURL, completionHandler: @escaping GPXCompletionHandler) { self.url = url self.completionHandler = completionHandler } private func complete(success: Bool) { DispatchQueue.main.async { self.completionHandler(success ? self : nil) } } private func fail() { complete(success: false) } private func succeed() { complete(success: true) } private func parse() { DispatchQueue.global(qos: .userInitiated).async { if let data = NSData(contentsOf: self.url as URL) { let parser = XMLParser(data: data as Data) parser.delegate = self parser.shouldProcessNamespaces = false parser.shouldReportNamespacePrefixes = false parser.shouldResolveExternalEntities = false parser.parse() } else { self.fail() } } } func parserDidEndDocument(_ parser: XMLParser) { succeed() } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { fail() } func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error) { fail() } private var input = "" func parser(_ parser: XMLParser, foundCharacters string: String) { input += string } private var waypoint: Waypoint? private var track: Track? private var link: Link? func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { switch elementName { case "trkseg": if track == nil { fallthrough } case "trk": tracks.append(Track()) track = tracks.last case "rte": routes.append(Track()) track = routes.last case "rtept", "trkpt", "wpt": let latitude = Double(attributeDict["lat"] ?? "0") ?? 0.0 let longitude = Double(attributeDict["lon"] ?? "0") ?? 0.0 waypoint = Waypoint(latitude: latitude, longitude: longitude) case "link": if let href = attributeDict["href"] { link = Link(href: href) } default: break } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { switch elementName { case "wpt": if waypoint != nil { waypoints.append(waypoint!); waypoint = nil } case "trkpt", "rtept": if waypoint != nil { track?.fixes.append(waypoint!); waypoint = nil } case "trk", "trkseg", "rte": track = nil case "link": if link != nil { if waypoint != nil { waypoint!.links.append(link!) } else if track != nil { track!.links.append(link!) } } link = nil default: if link != nil { link!.linkattributes[elementName] = input.trimmed } else if waypoint != nil { waypoint!.attributes[elementName] = input.trimmed } else if track != nil { track!.attributes[elementName] = input.trimmed } input = "" } } } // MARK: - Extensions private extension String { var trimmed: String { return (self as NSString).trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines) } } extension String { var asGpxDate: NSDate? { get { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z" return dateFormatter.date(from: self) as NSDate? } } }
apache-2.0
eb678cc06082847d3217b3a384f6bb32
31.871681
173
0.548122
5.03661
false
false
false
false
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/Utility/String+MD5.swift
1
1745
// // String+MD5.swift // Kingfisher // // Created by Wei Wang on 18//25. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CommonCrypto extension String: KingfisherCompatible { } extension KingfisherWrapper where Base == String { var md5: String { guard let data = base.data(using: .utf8) else { return base } var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) _ = data.withUnsafeBytes { bytes in return CC_MD5(bytes, CC_LONG(data.count), &digest) } return digest.map { String(format: "%02x", $0) }.joined() } }
mit
246478664ad82c0979102257f26c009a
39.581395
81
0.700287
4.115566
false
false
false
false
devxoul/allkdic
Allkdic/Types/KeyBinding.swift
1
3299
// The MIT License (MIT) // // Copyright (c) 2013 Suyeol Jeon (http://xoul.kr) // // 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. private let _dictionaryKeys = ["keyCode", "shift", "control", "option", "command"] public func ==(left: KeyBinding, right: KeyBinding) -> Bool { for key in _dictionaryKeys { if left.value(forKey: key) as? Int != right.value(forKey: key) as? Int { return false } } return true } open class KeyBinding: NSObject { var keyCode: Int = 0 var shift: Bool = false var control: Bool = false var option: Bool = false var command: Bool = false override open var description: String { var keys = [String]() if self.shift { keys.append("Shift") } if self.control { keys.append("Control") } if self.option { keys.append("Option") } if self.command { keys.append("Command") } if let keyString = type(of: self).keyStringFormKeyCode(self.keyCode) { keys.append(keyString.capitalized) } return keys.joined(separator: " + ") } @objc public override init() { super.init() } @objc public init(keyCode: Int, flags: Int) { super.init() self.keyCode = keyCode for i in 0...6 { if flags & (1 << i) != 0 { if i == 0 { self.control = true } else if i == 1 { self.shift = true } else if i == 3 { self.command = true } else if i == 5 { self.option = true } } } } @objc public init(dictionary: [AnyHashable: Any]?) { super.init() if dictionary == nil { return } for key in _dictionaryKeys { if let value = dictionary![key] as? Int { self.setValue(value, forKey: key) } } } open func toDictionary() -> [String: Int] { var dictionary = [String: Int]() for key in _dictionaryKeys { dictionary[key] = self.value(forKey: key) as! Int } return dictionary } open class func keyStringFormKeyCode(_ keyCode: Int) -> String? { return keyMap[keyCode] } open class func keyCodeFormKeyString(_ string: String) -> Int { for (keyCode, keyString) in keyMap { if keyString == string { return keyCode } } return NSNotFound } }
mit
91b529dbb429342e0071d65ef957fbe9
26.957627
82
0.63686
4.07284
false
false
false
false
qRoC/Loobee
Sources/Loobee/Library/AssertionConcern/AssertionGroup.swift
1
4298
// This file is part of the Loobee package. // // (c) Andrey Savitsky <[email protected]> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. /// Represents group of assertions for concrete data. /// /// That allows: /// - keep the purity of code with a large number of asserts; /// - aggregate the assertion results using specify strategy. public struct AssertionGroup { /// Delegate for deferred execution of an assertion. public typealias LazyYieldFunction = (@autoclosure () -> AssertionNotification?) -> Void /// Delegate for collect results of assertions. public typealias YieldFunction = (AssertionNotification?) -> Void /// Group notifications container. public let notifications: [AssertionNotification] /// @inlinable internal init(_ notifications: [AssertionNotification]) { self.notifications = notifications } /// Calls of asserts is aborting directly on the first notification. /// The returned group contains only this notification. /// /// let group = AssertionGroup.lazy("test") { value, yield in /// yield(assert("t", containedIn: value)) // ok /// yield(assert("a", containedIn: value)) // fail /// yield(assert("e", containedIn: value)) // never be executed /// yield(assert("b", containedIn: value)) // never be executed /// } /// print(group.notifications.count) // 1 /// @inlinable public static func lazy<T>( _ value: T, block: (_ value: T, _ yield: LazyYieldFunction) -> Void ) -> AssertionGroup { var notifications: [AssertionNotification] = [] block(value) { lazyAssert in if _slowPath(!notifications.isEmpty) { return } let assertResult = lazyAssert() if _fastPath(assertResult == nil) { return } notifications.append(assertResult!) } return .init(notifications) } /// All asserts will be called. The returned group contains all notifications. /// /// let group = AssertionGroup.all("test") { value, yield in /// yield(assert("t", containedIn: value)) // ok /// yield(assert("a", containedIn: value)) // fail /// yield(assert("e", containedIn: value)) // ok /// yield(assert("b", containedIn: value)) // fail /// } /// print(group.notifications.count) // 2 /// @inlinable public static func all<T>( _ value: T, block: (_ value: T, _ yield: YieldFunction) -> Void ) -> AssertionGroup { var notifications: [AssertionNotification] = [] block(value) { assertResult in if _fastPath(assertResult == nil) { return } notifications.append(assertResult!) } return .init(notifications) } /// If at least one assert was sucessful, the returned group does not /// contain any notifications. Otherwise, the returned group contains /// all the notifications. /// /// let group = AssertionGroup.anyOf("test") { value, yield in /// yield(assert("a", containedIn: value)) // fail /// yield(assert("t", containedIn: value)) // ok /// yield(assert("e", containedIn: value)) // never be executed /// yield(assert("b", containedIn: value)) // never be executed /// } /// print(group.notifications.count) // 0 /// @inlinable public static func anyOf<T>( _ value: T, block: (_ value: T, _ yield: LazyYieldFunction) -> Void ) -> AssertionGroup { var notifications: [AssertionNotification] = [] var hasSuccessful = false block(value) { lazyAssert in if _fastPath(hasSuccessful) { return } let assertResult = lazyAssert() if _fastPath(assertResult == nil) { hasSuccessful = true return } notifications.append(assertResult!) } return .init(_fastPath(hasSuccessful) ? [] : notifications) } }
mit
c0f16f41d38f4815fd3223ab8de4d309
32.84252
92
0.574919
4.723077
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift
54
1955
// // AnonymousDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 2/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /// Represents an Action-based disposable. /// /// When dispose method is called, disposal action will be dereferenced. fileprivate final class AnonymousDisposable : DisposeBase, Cancelable { public typealias DisposeAction = () -> Void private var _isDisposed: AtomicInt = 0 private var _disposeAction: DisposeAction? /// - returns: Was resource disposed. public var isDisposed: Bool { return _isDisposed == 1 } /// Constructs a new disposable with the given action used for disposal. /// /// - parameter disposeAction: Disposal action which will be run upon calling `dispose`. fileprivate init(_ disposeAction: @escaping DisposeAction) { _disposeAction = disposeAction super.init() } // Non-deprecated version of the constructor, used by `Disposables.create(with:)` fileprivate init(disposeAction: @escaping DisposeAction) { _disposeAction = disposeAction super.init() } /// Calls the disposal action if and only if the current instance hasn't been disposed yet. /// /// After invoking disposal action, disposal action will be dereferenced. fileprivate func dispose() { if AtomicCompareAndSwap(0, 1, &_isDisposed) { assert(_isDisposed == 1) if let action = _disposeAction { _disposeAction = nil action() } } } } extension Disposables { /// Constructs a new disposable with the given action used for disposal. /// /// - parameter dispose: Disposal action which will be run upon calling `dispose`. public static func create(with dispose: @escaping () -> ()) -> Cancelable { return AnonymousDisposable(disposeAction: dispose) } }
apache-2.0
b62f61eadf8c6cda2cd5498af21d3165
30.015873
95
0.653019
5.023136
false
false
false
false
SwiftOnEdge/Edge
Tests/HTTPTests/ServerTests.swift
1
4047
// // ServerTests.swift // Edge // // Created by Tyler Fleming Cloutier on 10/30/16. // // import Foundation import XCTest @testable import HTTP class ServerTests: XCTestCase { private func sendRequest(path: String, method: String) { let json = ["message": "Message to server!"] let jsonResponse = ["message": "Message received!"] let session = URLSession(configuration: .default) let rootUrl = "http://localhost:3001" let responseExpectation = expectation( description: "Did not receive a response for path: \(path)" ) let urlString = rootUrl + path let url = URL(string: urlString)! var req = URLRequest(url: url) req.httpMethod = method req.addValue("application/json", forHTTPHeaderField: "Content-Type") if method == "POST" { do { req.httpBody = try JSONSerialization.data(withJSONObject: json) } catch let error { XCTFail(String(describing: error)) } } session.dataTask(with: req) { (data, urlResp, err) in responseExpectation.fulfill() if let err = err { XCTFail("Error on response: \(err)") } guard let data = data else { XCTFail("No data returned") return } guard let stringBody = try? JSONSerialization.jsonObject(with: data) else { XCTFail("Problem deserializing body") return } guard let body = stringBody as? [String:String] else { XCTFail("Body not well formed json") return } XCTAssert(body == jsonResponse, "Received body \(body) != json \(jsonResponse)") }.resume() } func testServer() { let json = ["message": "Message to server!"] let jsonResponse = ["message": "Message received!"] let postRequestExpectation = expectation(description: "Did not receive a POST request.") let getRequestExpectation = expectation(description: "Did not receive a GET request.") func handleRequest(request: Request) -> Response { if request.method == .post { let data = Data(request.body) guard let stringBody = try? JSONSerialization.jsonObject(with: data) else { XCTFail("Problem deserializing body") fatalError() } guard let body = stringBody as? [String:String] else { XCTFail("Body not well formed json") fatalError() } XCTAssert(body == json, "Received body \(body) != json \(json)") postRequestExpectation.fulfill() } else if request.method == .get { getRequestExpectation.fulfill() } return try! Response(json: jsonResponse) } let server = HTTP.Server(reusePort: true) server.clients(host: "0.0.0.0", port: 3001).startWithNext { client in let requestStream = server.parse(data: client .read()) .map(handleRequest) requestStream.onNext { response in let writeStream = client.write(buffer: response.serialized) writeStream.onFailed { err in XCTFail(String(describing: err)) } writeStream.start() } requestStream.onFailed { clientError in XCTFail("ClientError: \(clientError)") } requestStream.onCompleted { } requestStream.start() } sendRequest(path: "", method: "POST") sendRequest(path: "", method: "GET") waitForExpectations(timeout: 1) { error in server.stop() } } } extension ServerTests { static var allTests = [ ("testServer", testServer), ] }
mit
121feeac49ff8c040372d51e4dbca151
32.446281
96
0.5404
5.168582
false
true
false
false
jay18001/brickkit-ios
Example/Source/Examples/Interactive/InvalidateHeightViewController.swift
1
1927
// // InvalidateHeightViewController.swift // BrickKit // // Created by Ruben Cagnie on 9/13/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import UIKit import BrickKit class InvalidateHeightViewController: BrickViewController { override class var brickTitle: String { return "Invalidate Height" } override class var subTitle: String { return "Change height dynamically" } var brick: LabelBrick! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .brickBackground self.registerBrickClass(LabelBrick.self) brick = LabelBrick(BrickIdentifiers.repeatLabel, backgroundColor: .brickGray1, dataSource: LabelBrickCellModel(text: "BRICK") { cell in cell.configure() }) let section = BrickSection(bricks: [ brick, LabelBrick(BrickIdentifiers.repeatLabel, backgroundColor: .brickGray2, dataSource: LabelBrickCellModel(text: "BRICK", configureCellBlock: LabelBrickCell.configure)) ], inset: 10, edgeInsets: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)) self.setSection(section) self.updateNavigationItem() } func updateNavigationItem() { let title: String switch brick.height { case .fixed(_): title = "Auto" default: title = "Fixed Height" } let selector: Selector = #selector(InvalidateHeightViewController.toggleHeights) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: self, action: selector) } func toggleHeights() { switch brick.height { case .fixed(_): brick.height = .auto(estimate: .fixed(size: 100)) default: brick.height = .fixed(size: 200) } self.brickCollectionView.invalidateBricks(false) self.updateNavigationItem() } }
apache-2.0
20c849d94d22993b967af161f1162a4e
27.746269
176
0.658359
4.802993
false
false
false
false
JoeLago/MHGDB-iOS
Pods/GRDB.swift/GRDB/QueryInterface/SQLCollection.swift
2
2599
// MARK: - SQLCollection /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// SQLCollection is the protocol for types that can be checked for inclusion. /// /// :nodoc: public protocol SQLCollection { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an SQL string that represents the collection. /// /// When the arguments parameter is nil, any value must be written down as /// a literal in the returned SQL: /// /// var arguments: StatementArguments? = nil /// let collection = SQLExpressionsArray([1,2,3]) /// collection.collectionSQL(&arguments) // "1,2,3" /// /// When the arguments parameter is not nil, then values may be replaced by /// `?` or colon-prefixed tokens, and fed into arguments. /// /// var arguments = StatementArguments() /// let collection = SQLExpressionsArray([1,2,3]) /// collection.collectionSQL(&arguments) // "?,?,?" /// arguments // [1,2,3] func collectionSQL(_ arguments: inout StatementArguments?) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an expression that check whether the collection contains /// the expression. func contains(_ value: SQLExpressible) -> SQLExpression } // MARK: Default Implementations extension SQLCollection { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns a SQLExpressionContains which applies the `IN` SQL operator. public func contains(_ value: SQLExpressible) -> SQLExpression { return SQLExpressionContains(value, self) } } // MARK: - SQLExpressionsArray /// SQLExpressionsArray wraps an array of expressions /// /// SQLExpressionsArray([1, 2, 3]) struct SQLExpressionsArray : SQLCollection { let expressions: [SQLExpression] init<S: Sequence>(_ expressions: S) where S.Iterator.Element : SQLExpressible { self.expressions = expressions.map { $0.sqlExpression } } func collectionSQL(_ arguments: inout StatementArguments?) -> String { return (expressions.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") } func contains(_ value: SQLExpressible) -> SQLExpression { if expressions.isEmpty { return false.databaseValue } else { return SQLExpressionContains(value, self) } } }
mit
d0bedb8b619489a43d5105f981dc595e
35.097222
101
0.644863
4.624555
false
false
false
false
yaxunliu/douyu-TV
douyu-TV/douyu-TV/Classes/Home/Model/RecommendRecycleModel.swift
1
818
// // RecycleModel.swift // Douyu-TV // // Created by 刘亚勋 on 2016/10/12. // Copyright © 2016年 刘亚勋. All rights reserved. // 推荐界面轮播图模型 import UIKit class RecommendRecycleModel: NSObject { // 标题 public var title = "" // 轮播图图片url public var pic_url = "" // 直播间模型即room public var live : BaseLiveModel = BaseLiveModel() // 房间模型 var room : [String : NSObject]?{ didSet{ guard let liveRoom = room else { return } live = BaseLiveModel(dict: liveRoom) } } init(dict : [String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
apache-2.0
0098aeb9ba777f5c9b4bd3dd2667af04
17.317073
73
0.552597
3.831633
false
false
false
false
steelwheels/Canary
Source/CNFileManager.swift
1
788
/* * @file CNFileManager.swift * @brief Extend FileManager class * @par Copyright * Copyright (C) 2018 Steel Wheels Project */ import Foundation public enum CNFileType: Int32 { case NotExist = 0 case File = 1 case Directory = 2 public var description: String { get { var result: String switch self { case .NotExist: result = "Not exist" case .File: result = "File" case .Directory: result = "Directory" } return result } } } public extension FileManager { public func checkFileType(pathString pathstr: String) -> CNFileType { var isdir = ObjCBool(false) if self.fileExists(atPath: pathstr, isDirectory: &isdir) { if isdir.boolValue { return .Directory } else { return .File } } else { return .NotExist } } }
gpl-2.0
284c536883a5173d3f9d167e97cd3ed7
17.325581
70
0.658629
3.139442
false
false
false
false
angelitomg/Speedometer
Speedometer/AppDelegate.swift
1
2781
// // AppDelegate.swift // Speedometer // // Created by Angelito Goulart on 12/10/15. // Copyright © 2015 AMG Labs. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func getConvertedSpeed(speed:Double, unit:String)->Double{ var convertedSpeed: Double = 0 if speed < 0 { return convertedSpeed; } switch (unit) { case "ft/s": convertedSpeed = speed * 3.281 case "km/h": convertedSpeed = speed * 3.6 case "ko": convertedSpeed = speed * 1.944 case "mph": convertedSpeed = speed * 2.237 case "m/s": convertedSpeed = speed default: convertedSpeed = 0 } return convertedSpeed; } }
mit
af4a6c1c55de8b6922f803d3672ad294
37.611111
285
0.688489
5.398058
false
false
false
false
tmandry/Swindler
Sources/Events.swift
1
6062
import Cocoa /// The protocol for all event structs. /// /// Usually not used directly. Used as a bound by `State.on(...)`. public protocol EventType { /// All events are marked as internal or external. Internal events were caused via Swindler, /// external events were not. var external: Bool { get } } internal extension EventType { // In a later version of Swift, this can be stored (lazily).. store as hashValue for more speed. // Instead of using this, we _could_ use an enum of all notifications and require each event to // declare a static var of its notification. That's error prone, though, and this is fast enough. static var typeName: String { return Mirror(reflecting: Self.self).description } } /// An event describing a property change. protocol PropertyEventType: EventType { associatedtype PropertyType associatedtype Object init(external: Bool, object: Object, oldValue: PropertyType, newValue: PropertyType) /// The old value of the property. var oldValue: PropertyType { get } /// The new value of the property. var newValue: PropertyType { get } // TODO: requestedVal? } protocol StatePropertyEventType: PropertyEventType { associatedtype Object = State init(external: Bool, state: Object, oldValue: PropertyType, newValue: PropertyType) } extension StatePropertyEventType { init(external: Bool, object: Object, oldValue: PropertyType, newValue: PropertyType) { self.init(external: external, state: object, oldValue: oldValue, newValue: newValue) } } public struct FrontmostApplicationChangedEvent: StatePropertyEventType { public typealias Object = State public typealias PropertyType = Application? public let external: Bool public let state: State public let oldValue: PropertyType public let newValue: PropertyType } public struct ApplicationLaunchedEvent: EventType { public let external: Bool public let application: Application } public struct ApplicationTerminatedEvent: EventType { public let external: Bool public let application: Application } public struct WindowCreatedEvent: EventType { public let external: Bool public let window: Window } public struct WindowDestroyedEvent: EventType { public let external: Bool public let window: Window } protocol WindowPropertyEventType: PropertyEventType { associatedtype Object = Window init(external: Bool, window: Object, oldValue: PropertyType, newValue: PropertyType) } extension WindowPropertyEventType { init(external: Bool, object: Object, oldValue: PropertyType, newValue: PropertyType) { self.init(external: external, window: object, oldValue: oldValue, newValue: newValue) } } public struct WindowFrameChangedEvent: WindowPropertyEventType { public typealias Object = Window public typealias PropertyType = CGRect public let external: Bool public let window: Window public let oldValue: PropertyType public let newValue: PropertyType } public struct WindowTitleChangedEvent: WindowPropertyEventType { public typealias Object = Window public typealias PropertyType = String public let external: Bool public let window: Window public let oldValue: PropertyType public let newValue: PropertyType } public struct WindowMinimizedChangedEvent: WindowPropertyEventType { public typealias Object = Window public typealias PropertyType = Bool public let external: Bool public let window: Window public let oldValue: PropertyType public let newValue: PropertyType } protocol ApplicationPropertyEventType: PropertyEventType { associatedtype Object = Application init(external: Bool, application: Object, oldValue: PropertyType, newValue: PropertyType) } extension ApplicationPropertyEventType { init(external: Bool, object: Object, oldValue: PropertyType, newValue: PropertyType) { self.init(external: external, application: object, oldValue: oldValue, newValue: newValue) } } public struct ApplicationIsHiddenChangedEvent: ApplicationPropertyEventType { public typealias Object = Application public typealias PropertyType = Bool public let external: Bool public let application: Application public let oldValue: PropertyType public let newValue: PropertyType } public struct ApplicationMainWindowChangedEvent: ApplicationPropertyEventType { public typealias Object = Application public typealias PropertyType = Window? public let external: Bool public let application: Application public let oldValue: PropertyType public let newValue: PropertyType } public struct ApplicationFocusedWindowChangedEvent: ApplicationPropertyEventType { public typealias Object = Application public typealias PropertyType = Window? public let external: Bool public let application: Application public let oldValue: PropertyType public let newValue: PropertyType } public struct ScreenLayoutChangedEvent: EventType { public let external: Bool public let addedScreens: [Screen] public let removedScreens: [Screen] /// Screens whose frame has changed (moved, resized, or both). public let changedScreens: [Screen] public let unchangedScreens: [Screen] } /// The space has changed, but we have not yet updated the list of known windows. public struct SpaceWillChangeEvent: EventType { public let external: Bool /// For each screen, a unique integer identifying the visible space. public let ids: [Int] } /// The space has changed, and the list of known windows is up to date. /// /// Note that this event may not correspond 1:1 with SpaceWillChangeEvent. /// In particular, if the space changes again before the list of known windows /// can be updated, SpaceWillChangeEvent will fire twice and this event will /// fire only once. public struct SpaceDidChangeEvent: EventType { public let external: Bool /// For each screen, a unique integer identifying the visible space. public let ids: [Int] }
mit
8426af5777aa217832167b92bae68d7d
34.040462
101
0.750742
5.12426
false
false
false
false
m-schmidt/Refracto
Refracto/ItemPickerController.swift
1
3786
// ItemPickerController.swift import UIKit enum PickerActionState { case update case dismiss case updateAndDismiss case abort } class ItemPickerController<T>: UITableViewController where T: ItemPickable { typealias Action<T> = (T, @escaping (PickerActionState) -> Void) -> Void private var selection: T? private let action: Action<T> private let allowReselection: Bool init(selection: T? = nil, allowReselection:Bool = false, action: @escaping Action<T>) { self.selection = selection self.allowReselection = allowReselection self.action = action super.init(style: .insetGrouped) } required init?(coder: NSCoder) { fatalError("ItemPickerController.init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = T.localizedTitleDescription tableView.delegate = self tableView.dataSource = self tableView.cellLayoutMarginsFollowReadableWidth = true tableView.backgroundColor = Colors.settingsBackground tableView.separatorColor = Colors.settingsCellSeparator tableView.register(ItemCell.self, forCellReuseIdentifier: ItemCell.identifier) navigationItem.largeTitleDisplayMode = .never } private func dismiss() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { self.navigationController?.popViewController(animated: true) } } private func handleSelection(ofItem item: T) { if item != selection || allowReselection { action(item) { state in switch state { case .update: self.selection = item self.tableView.reloadSections([0], with: .none) case .dismiss: self.dismiss() case .updateAndDismiss: self.selection = item self.tableView.reloadSections([0], with: .fade) self.dismiss() case .abort: break } } } else { dismiss() } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { guard let header = view as? UITableViewHeaderFooterView else { return } header.textLabel?.textColor = Colors.settingsCellSecondaryForeground } override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { guard let footer = view as? UITableViewHeaderFooterView else { return } footer.textLabel?.textColor = Colors.settingsCellSecondaryForeground } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) handleSelection(ofItem: T[indexPath.row]) } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return T.localizedFooterDescription } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return T.allCases.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: ItemCell.identifier, for: indexPath) as! ItemCell let item = T[indexPath.row] cell.configure(value: item, selected: item == self.selection) return cell } }
bsd-3-clause
b37131d7802c9a18f863037c88c2036f
33.733945
119
0.648706
5.309958
false
false
false
false
mnewmedia/cordova-plugin-webdav
src/ios/wXmlParser.swift
1
1359
// http://stackoverflow.com/questions/33156340/parsing-xml-file-in-swift-xcode-v-7-0-1-and-retrieving-values-from-dictionary class XmlParser: NSObject, NSXMLParserDelegate { var currentElement: String = "" var foundCharacters: String = "" var parsedClass: NSMutableArray = [] weak var parent:XmlParser? = nil // used in childs let parser = NSXMLParser(contentsOfURL:(NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss"))!)! func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { self.currentElement = elementName if elementName == "d:response" { let prop = XmlPropstat() self.parsedClass.addObject(prop) // now prop class has to parse further, let pop class know who we are so that once hes done XML processing it can return parsing responsibility back parser.delegate = prop prop.parent = self } } func parser(parser: NSXMLParser, foundCharacters string: String) { self.foundCharacters += string } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { } }
mit
ef4b8d2d5d9db01885f189c74ce876bd
39
173
0.662252
4.819149
false
false
false
false
dche/FlatCG
Sources/Normal.swift
1
1622
// // FlatCG - Normal.swift // // Copyright (c) 2016 The GLMath authors. // Licensed under MIT License. import simd import GLMath /// `Normal` is a `Vector` with restriction that its length must be `1`, i.e., /// it always be normalized. public struct Normal<T: Point>: Equatable { public typealias PointType = T public typealias VectorType = T.VectorType public typealias Component = VectorType.Component /// The vector representation of `self`. It is normalized. public let vector: VectorType init (_ vector: VectorType) { assert(vector.squareLength ~== 1) self.vector = vector } public init (vector: VectorType) { self.vector = normalize(vector) } public func dot(_ other: Normal) -> Component { return self.vector.dot(other.vector) } public static func == (lhs: Normal, rhs: Normal) -> Bool { return lhs.vector == rhs.vector } public static prefix func - (rhs: Normal) -> Normal { return Normal(-rhs.vector) } } extension Normal: CustomDebugStringConvertible { public var debugDescription: String { return "\(vector)" } } extension Normal where T.VectorType: Vector2 { public init (_ x: Component, _ y: Component) { self.init(vector: VectorType(x, y)) } } extension Normal where T.VectorType: Vector3 { public init (_ x: Component, _ y: Component, _ z: Component) { self.init(vector: VectorType(x, y, z)) } } public typealias Normal2D = Normal<Point2D> public typealias Normal3D = Normal<Point3D> // extension Normal: Transformable { // // }
mit
e79cfd2255c1f73d886ea5fbe79cace7
21.84507
78
0.646732
4.004938
false
false
false
false
joerocca/GitHawk
Pods/Highlightr/Pod/Classes/Theme.swift
1
12602
// // Theme.swift // Pods // // Created by Illanes, J.P. on 4/24/16. // // import Foundation #if os(iOS) || os(tvOS) import UIKit /// Typealias for UIColor public typealias RPColor = UIColor /// Typealias for UIFont public typealias RPFont = UIFont #else import AppKit /// Typealias for NSColor public typealias RPColor = NSColor /// Typealias for NSFont public typealias RPFont = NSFont #endif private typealias RPThemeDict = [String:[String:AnyObject]] private typealias RPThemeStringDict = [String:[String:String]] /// Theme parser, can be used to configure the theme parameters. open class Theme { internal let theme : String internal var lightTheme : String! /// Regular font to be used by this theme open var codeFont : RPFont! /// Bold font to be used by this theme open var boldCodeFont : RPFont! /// Italic font to be used by this theme open var italicCodeFont : RPFont! fileprivate var themeDict : RPThemeDict! fileprivate var strippedTheme : RPThemeStringDict! /// Default background color for the current theme. open var themeBackgroundColor : RPColor! /** Initialize the theme with the given theme name. - parameter themeString: Theme to use. */ init(themeString: String) { theme = themeString setCodeFont(RPFont(name: "Courier", size: 14)!) strippedTheme = stripTheme(themeString) lightTheme = strippedThemeToString(strippedTheme) themeDict = strippedThemeToTheme(strippedTheme) var bkgColorHex = strippedTheme[".hljs"]?["background"] if(bkgColorHex == nil) { bkgColorHex = strippedTheme[".hljs"]?["background-color"] } if let bkgColorHex = bkgColorHex { if(bkgColorHex == "white") { themeBackgroundColor = RPColor(white: 1, alpha: 1) }else if(bkgColorHex == "black") { themeBackgroundColor = RPColor(white: 0, alpha: 1) }else { let range = bkgColorHex.range(of: "#") let str = bkgColorHex.substring(from: (range?.lowerBound)!) themeBackgroundColor = colorWithHexString(str) } }else { themeBackgroundColor = RPColor.white } } /** Changes the theme font. This will try to automatically populate the codeFont, boldCodeFont and italicCodeFont properties based on the provided font. - parameter font: UIFont (iOS or tvOS) or NSFont (OSX) */ open func setCodeFont(_ font: RPFont) { codeFont = font #if os(iOS) || os(tvOS) let boldDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorFamilyAttribute:font.familyName, UIFontDescriptorFaceAttribute:"Bold"]) let italicDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorFamilyAttribute:font.familyName, UIFontDescriptorFaceAttribute:"Italic"]) let obliqueDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorFamilyAttribute:font.familyName, UIFontDescriptorFaceAttribute:"Oblique"]) #else let boldDescriptor = NSFontDescriptor(fontAttributes: [NSFontFamilyAttribute:font.familyName!, NSFontFaceAttribute:"Bold"]) let italicDescriptor = NSFontDescriptor(fontAttributes: [NSFontFamilyAttribute:font.familyName!, NSFontFaceAttribute:"Italic"]) let obliqueDescriptor = NSFontDescriptor(fontAttributes: [NSFontFamilyAttribute:font.familyName!, NSFontFaceAttribute:"Oblique"]) #endif boldCodeFont = RPFont(descriptor: boldDescriptor, size: font.pointSize) italicCodeFont = RPFont(descriptor: italicDescriptor, size: font.pointSize) if(italicCodeFont == nil || italicCodeFont.familyName != font.familyName) { italicCodeFont = RPFont(descriptor: obliqueDescriptor, size: font.pointSize) } else if(italicCodeFont == nil ) { italicCodeFont = font } if(boldCodeFont == nil) { boldCodeFont = font } if(themeDict != nil) { themeDict = strippedThemeToTheme(strippedTheme) } } internal func applyStyleToString(_ string: String, styleList: [String]) -> NSAttributedString { let returnString : NSAttributedString if styleList.count > 0 { var attrs = [String:AnyObject]() attrs[NSFontAttributeName] = codeFont for style in styleList { if let themeStyle = themeDict[style] { for (attrName, attrValue) in themeStyle { attrs.updateValue(attrValue, forKey: attrName) } } } returnString = NSAttributedString(string: string, attributes:attrs ) } else { returnString = NSAttributedString(string: string, attributes:[NSFontAttributeName:codeFont] ) } return returnString } fileprivate func stripTheme(_ themeString : String) -> [String:[String:String]] { let objcString = (themeString as NSString) let cssRegex = try! NSRegularExpression(pattern: "(?:(\\.[a-zA-Z0-9\\-_]*(?:[, ]\\.[a-zA-Z0-9\\-_]*)*)\\{([^\\}]*?)\\})", options:[.caseInsensitive]) let results = cssRegex.matches(in: themeString, options: [.reportCompletion], range: NSMakeRange(0, objcString.length)) var resultDict = [String:[String:String]]() for result in results { if(result.numberOfRanges == 3) { var attributes = [String:String]() let cssPairs = objcString.substring(with: result.rangeAt(2)).components(separatedBy: ";") for pair in cssPairs { let cssPropComp = pair.components(separatedBy: ":") if(cssPropComp.count == 2) { attributes[cssPropComp[0]] = cssPropComp[1] } } if attributes.count > 0 { resultDict[objcString.substring(with: result.rangeAt(1))] = attributes } } } var returnDict = [String:[String:String]]() for (keys,result) in resultDict { let keyArray = keys.replacingOccurrences(of: " ", with: ",").components(separatedBy: ",") for key in keyArray { var props : [String:String]? props = returnDict[key] if props == nil { props = [String:String]() } for (pName, pValue) in result { props!.updateValue(pValue, forKey: pName) } returnDict[key] = props! } } return returnDict } fileprivate func strippedThemeToString(_ theme: RPThemeStringDict) -> String { var resultString = "" for (key, props) in theme { resultString += key+"{" for (cssProp, val) in props { if(key != ".hljs" || (cssProp.lowercased() != "background-color" && cssProp.lowercased() != "background")) { resultString += "\(cssProp):\(val);" } } resultString+="}" } return resultString } fileprivate func strippedThemeToTheme(_ theme: RPThemeStringDict) -> RPThemeDict { var returnTheme = RPThemeDict() for (className, props) in theme { var keyProps = [String:AnyObject]() for (key, prop) in props { switch key { case "color": keyProps[attributeForCSSKey(key)] = colorWithHexString(prop) break case "font-style": keyProps[attributeForCSSKey(key)] = fontForCSSStyle(prop) break case "font-weight": keyProps[attributeForCSSKey(key)] = fontForCSSStyle(prop) break case "background-color": keyProps[attributeForCSSKey(key)] = colorWithHexString(prop) break default: break } } if keyProps.count > 0 { let key = className.replacingOccurrences(of: ".", with: "") returnTheme[key] = keyProps } } return returnTheme } fileprivate func fontForCSSStyle(_ fontStyle:String) -> RPFont { switch fontStyle { case "bold", "bolder", "600", "700", "800", "900": return boldCodeFont case "italic", "oblique": return italicCodeFont default: return codeFont } } fileprivate func attributeForCSSKey(_ key: String) -> String { switch key { case "color": return NSForegroundColorAttributeName case "font-weight": return NSFontAttributeName case "font-style": return NSFontAttributeName case "background-color": return NSBackgroundColorAttributeName default: return NSFontAttributeName } } fileprivate func colorWithHexString (_ hex:String) -> RPColor { var cString:String = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if (cString.hasPrefix("#")) { cString = (cString as NSString).substring(from: 1) } else { switch cString { case "white": return RPColor(white: 1, alpha: 1) case "black": return RPColor(white: 0, alpha: 1) case "red": return RPColor(red: 1, green: 0, blue: 0, alpha: 1) case "green": return RPColor(red: 0, green: 1, blue: 0, alpha: 1) case "blue": return RPColor(red: 0, green: 0, blue: 1, alpha: 1) default: return RPColor.gray } } if (cString.characters.count != 6 && cString.characters.count != 3 ) { return RPColor.gray } var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; var divisor : CGFloat if (cString.characters.count == 6 ) { let rString = (cString as NSString).substring(to: 2) let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2) let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2) Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) divisor = 255.0 }else { let rString = (cString as NSString).substring(to: 1) let gString = ((cString as NSString).substring(from: 1) as NSString).substring(to: 1) let bString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 1) Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) divisor = 15.0 } return RPColor(red: CGFloat(r) / divisor, green: CGFloat(g) / divisor, blue: CGFloat(b) / divisor, alpha: CGFloat(1)) } }
mit
1e24c99a36633a8ba2a72002ae971be9
33.620879
157
0.521266
5.441278
false
false
false
false
bingFly/SwiftTest
SwiftTest/SwiftTest/ViewController.swift
1
885
// // ViewController.swift // SwiftTest // // Created by hanbing on 15/10/29. // Copyright © 2015年 haodf. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() let fbv = FBShimmeringView(frame: self.titleLabel.frame) fbv.shimmering = true fbv.shimmeringBeginFadeDuration = 1 fbv.contentView = self.titleLabel fbv.shimmeringOpacity = 0.1 fbv.shimmeringSpeed = 100 self.titleLabel.backgroundColor = UIColor.clearColor() self.view.addSubview(fbv) fbv.mas_makeConstraints { (MASConstraintMaker make) -> Void in // make.top } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
6cf33efb061996eab04a7c9100389647
21.05
70
0.630385
4.569948
false
false
false
false
JiongXing/PhotoBrowser
Sources/JXPhotoBrowser/JXPhotoBrowserDefaultPageIndicator.swift
3
1125
// // JXPhotoBrowserDefaultPageIndicator.swift // JXPhotoBrowser // // Created by JiongXing on 2019/11/25. // Copyright © 2019 JiongXing. All rights reserved. // import UIKit open class JXPhotoBrowserDefaultPageIndicator: UIPageControl, JXPhotoBrowserPageIndicator { /// 页码与底部的距离 open lazy var bottomPadding: CGFloat = { if #available(iOS 11.0, *), let window = UIApplication.shared.keyWindow, window.safeAreaInsets.bottom > 0 { return 20 } return 15 }() open func setup(with browser: JXPhotoBrowser) { isEnabled = false } open func reloadData(numberOfItems: Int, pageIndex: Int) { numberOfPages = numberOfItems currentPage = min(pageIndex, numberOfPages - 1) sizeToFit() isHidden = numberOfPages <= 1 if let view = superview { center.x = view.bounds.width / 2 frame.origin.y = view.bounds.maxY - bottomPadding - bounds.height } } open func didChanged(pageIndex: Int) { currentPage = pageIndex } }
mit
86d55ac574376256f95fb81ac424523a
26.02439
91
0.617329
4.817391
false
false
false
false
davedelong/DDMathParser
Demo/GroupedTokenAnalyzerViewController.swift
1
3882
// // GroupedTokenAnalyzerViewController.swift // Demo // // Created by Dave DeLong on 11/21/17. // import Cocoa import MathParser class GroupedTokenAnalyzerViewController: AnalyzerViewController, NSOutlineViewDelegate, NSOutlineViewDataSource { @IBOutlet var tokenTree: NSOutlineView? var groupedToken: GroupedToken? override init() { super.init() title = "Grouped" } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func analyzeString(_ string: String) { let grouper = TokenGrouper(string: string) do { groupedToken = try grouper.group() } catch let e as MathParserError { groupedToken = nil analyzerDelegate?.analyzerViewController(self, wantsErrorPresented: e) } catch let other { fatalError("Unknown error grouping expression: \(other)") } tokenTree?.reloadItem(nil, reloadChildren: true) tokenTree?.expandItem(nil, expandChildren: true) } func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { if item == nil { return groupedToken == nil ? 0 : 1 } var maybeToken = item as? GroupedToken maybeToken = maybeToken ?? groupedToken guard let token = maybeToken else { return 0 } switch token.kind { case .function(_, let args): return args.count case .group(let args): return args.count default: return 0 } } func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { if item == nil, let t = groupedToken { return t } guard let token = item as? GroupedToken else { fatalError("should only have GroupedTokens") } switch token.kind { case .function(_, let arguments): return arguments[index] case .group(let arguments): return arguments[index] default: fatalError("only functions and groups have children") } } func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { return self.outlineView(outlineView, numberOfChildrenOfItem: item) > 0 } func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? { if item == nil { return "<root>"} guard let token = item as? GroupedToken else { fatalError("should only have GroupedToken") } let info: String switch token.kind { case .function(let f, let args): let argInfo = args.count == 1 ? "1 argument" : "\(args.count) arguments" info = "\(f)(\(argInfo))" case .group(let args): let argInfo = args.count == 1 ? "1 argument" : "\(args.count) arguments" info = "Group: (\(argInfo))" case .number(let d): info = "Number: \(d)" case .variable(let v): info = "Variable: \(v)" case .operator(let o): info = "Operator: \(o)" } return "\(info) - range: \(token.range)" } func outlineViewSelectionDidChange(_ notification: Notification) { let row = tokenTree?.selectedRow ?? -1 if row >= 0 { guard let item = tokenTree?.item(atRow: row) else { fatalError("missing item at row \(row)") } guard let token = item as? GroupedToken else { fatalError("only GroupedTokens should be in the tree") } analyzerDelegate?.analyzerViewController(self, wantsHighlightedRanges: [token.range]) } else { // unhighlight everything in the textfield analyzerDelegate?.analyzerViewController(self, wantsHighlightedRanges: []) } } }
mit
177e95a4feba14aad35dd8a4507596de
37.82
123
0.601236
4.901515
false
false
false
false
slepcat/mint
MINT/Shader.swift
1
4160
// // Shader.swift // MINT // // Created by NemuNeko on 2014/11/30. // Copyright (c) 2014年 Taizo A. All rights reserved. // import Foundation import Cocoa import OpenGL class Shader { var program:GLuint = 0 var positionSLot:GLint = 0 var colorSlot:GLint = 0 init?(shaderName:String) { //load shader source from the app bundle var vxShaderSource:UnsafePointer<CChar>? = getVertexShaderSource(shaderName) var fgShaderSource:UnsafePointer<CChar>? = getFragmentShaderSource(shaderName) //check cources if (vxShaderSource == nil)||(fgShaderSource == nil) { return nil } var vxSourceLength: GLint = numericCast(String(cString: vxShaderSource!).lengthOfBytes(using: String.Encoding.utf8)) var fgSourceLength: GLint = numericCast(String(cString: fgShaderSource!).lengthOfBytes(using: String.Encoding.utf8)) //prepare shader objects let vxShader : GLuint = glCreateShader(UInt32(GL_VERTEX_SHADER)) let fgShader : GLuint = glCreateShader(UInt32(GL_FRAGMENT_SHADER)) //set shader sources glShaderSource(vxShader, 1, &vxShaderSource, &vxSourceLength) glShaderSource(fgShader, 1, &fgShaderSource, &fgSourceLength) //compile shaders and check result glCompileShader(vxShader) var compiled:GLint = 0 glGetShaderiv(vxShader, UInt32(GL_COMPILE_STATUS), &compiled) if compiled == GL_FALSE { print("failed to compile vxShader") return nil } glCompileShader(fgShader) glGetShaderiv(fgShader, UInt32(GL_COMPILE_STATUS), &compiled) if compiled == GL_FALSE { print("failed to compile fgShader") return nil } vxShaderSource = nil fgShaderSource = nil //prepare program and attach shaders self.program = glCreateProgram() glAttachShader(self.program, vxShader) glAttachShader(self.program, fgShader) //link and check result glLinkProgram(self.program) var linked:GLint = 0 glGetProgramiv(self.program, UInt32(GL_LINK_STATUS), &linked) if linked == GL_FALSE { var buffSize:GLint = 0 print("failed to link Shaders") glGetProgramiv(self.program, UInt32(GL_INFO_LOG_LENGTH) , &buffSize) if buffSize > 0 { let infoLog = UnsafeMutablePointer<CChar>.allocate(capacity: numericCast(buffSize)) var l:GLsizei = 0 glGetProgramInfoLog(self.program, buffSize, &l, infoLog) print(String(cString: infoLog)) infoLog.deinitialize() } return nil } glDeleteShader(vxShader) glDeleteShader(fgShader) self.positionSLot = glGetAttribLocation(self.program, "Position") self.colorSlot = glGetAttribLocation(self.program, "SourceColor") } func getShaderSource(_ shaderName: String, ext: String) -> UnsafePointer<CChar>? { let appBundle = Bundle.main let shaderPath:String? = appBundle.path(forResource: shaderName, ofType: ext) if let path = shaderPath { do { let shaderSource = try NSString(contentsOfFile: path, encoding:String.Encoding.utf8.rawValue) let shaderSourceC:UnsafePointer<CChar>? = shaderSource.utf8String return shaderSourceC } catch { print("failed to read shader source") return nil } } return nil } func getVertexShaderSource(_ shaderName: String) -> UnsafePointer<CChar>? { return getShaderSource(shaderName, ext: "vs") } func getFragmentShaderSource(_ shaderName: String) -> UnsafePointer<CChar>? { return getShaderSource(shaderName, ext: "fs") } }
gpl-3.0
db482bfe6f7030a4d9b11a05f890a8f9
32.264
124
0.587302
4.708947
false
false
false
false
louisdh/panelkit
PanelKitTests/ViewController.swift
1
2296
// // ViewController.swift // PanelKit // // Created by Louis D'hauwe on 09/03/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import Foundation import UIKit import PanelKit class ViewController: UIViewController, PanelManager { var mapPanelContentVC: MapPanelContentViewController! var mapPanelVC: PanelViewController! var textPanelContentVC: TextPanelContentViewController! var textPanelVC: PanelViewController! var contentWrapperView: UIView! var contentView: UIView! var mapPanelBarBtn: UIBarButtonItem! var textPanelBarBtn: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() contentWrapperView = UIView(frame: view.bounds) view.addSubview(contentWrapperView) contentView = UIView(frame: contentWrapperView.bounds) contentWrapperView.addSubview(contentView) mapPanelContentVC = MapPanelContentViewController() mapPanelVC = PanelViewController(with: mapPanelContentVC, in: self) textPanelContentVC = TextPanelContentViewController() textPanelVC = PanelViewController(with: textPanelContentVC, in: self) enableTripleTapExposeActivation() mapPanelBarBtn = UIBarButtonItem(title: "Map", style: .done, target: self, action: nil) textPanelBarBtn = UIBarButtonItem(title: "Text", style: .done, target: self, action: nil) self.navigationItem.title = "Test" self.navigationItem.rightBarButtonItems = [mapPanelBarBtn, textPanelBarBtn] } // MARK: - Popover func showMapPanelFromBarButton(completion: @escaping (() -> Void)) { showPopover(mapPanelVC, from: mapPanelBarBtn, completion: completion) } func showTextPanelFromBarButton(completion: @escaping (() -> Void)) { showPopover(textPanelVC, from: textPanelBarBtn, completion: completion) } func showPopover(_ vc: UIViewController, from barButtonItem: UIBarButtonItem, completion: (() -> Void)? = nil) { vc.modalPresentationStyle = .popover vc.popoverPresentationController?.barButtonItem = barButtonItem present(vc, animated: false, completion: completion) } // MARK: - PanelManager let panelManagerLogLevel: LogLevel = .full var panelContentWrapperView: UIView { return contentWrapperView } var panelContentView: UIView { return contentView } var panels: [PanelViewController] { return [mapPanelVC, textPanelVC] } }
mit
f645f4d11d639c73adf9c3eba57e5256
24.786517
113
0.771242
4.195612
false
false
false
false
gitmalong/lovelySpriteKitHelpers
SKWeaponNode.swift
1
9747
// // Weapon.swift // // Created by gitmalong on 21.04.16. // /* Implements a basic weapon with ammo, magazine, fire and reload methods. You can pass hooks that are triggered for certain events (i.e. to play sound effects) - after the weapon fires - after the weapon starts to reload - after the weapon was reloaded Usage in SpriteKit: 1) Create a an instance of a SKWeapon conform class (you may use SKWeaponGenerator) 2) a) If you don't want to care a lot about when it should be allowed to fire (i.e. when the user touches your fire button) just call syncedFireAndReload(). It will try to fire everytime its possible and reloads automatically after a defined time span. Optionally you can pass hooks in form of blocks for the previously mentioned events b) Create your own fire logic with help of the available methods and variables */ import Foundation import SpriteKit /* Basic weapon protocol */ protocol Weapon:class { /// Time that should be waited for before it is allowed to fire again var rateOfFirePerSecond:NSTimeInterval { get set } /** If set to true syncedFireAndReload() does not subtract any ammo and allowedToFire() returns true even if ammo is 0. As a result reload() is never called on syncedFireAndReload(). */ var infiniteAmmo:Bool { get set } /// Ammo of the current magazine, set to 0 when infiniteAmmo is true var ammoOfCurrentMagazine:Int { get set } /// Ammo capacity of one magazine, set to 0 when infiniteAmmo is true var magazineSize:Int { get set } /// Remaining available magazines, set to 0 when infiniteAmmo is true var remainingMagazines:Int { get set } /// Time it should take to reload the weapon var reloadTimeSeconds:NSTimeInterval { get set } /// Damage points every shot should subtract var damagePoints:Int { get set } /// Is true if weapon is just firing, false if not var justFiring:Bool { get set } /// Is True if weapon is just being reloaded, false if not var justReloading:Bool { get set } /// Set to true if weapon should be reloaded automatically when the magazine is empty, false if not var autoReload:Bool { get set } /// Reloads weapon - Replaces ammoOfCurrentMagazine with magazineSize func reload() /// Reloads weapon, sets justReloading state, waits reloadTimeSeconds and calls hooks func reloadAndWait(afterReloadInit:(()->Void)?, afterReloadComplete:(()->Void)?) -> Void /// Subtracts 1 from ammoOfCurrentMagazine func subtractAmmo() -> Void /// Will only subtract ammo if infiniteAmmo == false func syncedSubtractAmmo() -> Void /// Fires, sets justFiring to true and after rateOfFirePerSecond seconds to false, calls hook func fireAndWait(afterFired:(()->Void)?) -> Void /// return magazineSize > 0 && justReloading == false && justFiring == false func allowedToReload() -> Bool /// return justFiring == false && justReloading == false && ammoOfCurrentMagazine > 0 func allowedToFire() -> Bool /// Returns unique identifier for object instance func getWeaponID() -> String /// Fires and reloads automatically when it is allowed func syncedFireAndReload(afterFired:(()->Void)?, afterReloadInit:(()->Void)?, afterReloadComplete:(()->Void)?) /// Fires when it is allowed func syncedFire(afterFired:(()->Void)?) /// Reloads when it is allowed func syncedReload(afterReloadInit:(()->Void)?, afterReloadComplete:(()->Void)?) } /** Default implementation for weapon protocol Following methods have not been implemented cause the wait() methods should be system / framework specific: reloadAndWait(), fireAndWait() syncedFireAndReload */ extension Weapon { /// Returns unique identifier for that weapon object func getWeaponID()->String { return String(ObjectIdentifier(self)) } /// tells you if it is allowed to reload the weapon func allowedToReload()->Bool { return magazineSize > 0 && justReloading == false && justFiring == false } /// tells you if it is allowed to fire. depending if weapon is just firing or just reloading. If infiniteAmmo is true it will return true even if ammoOfCurrentMagazine is 0 /// - Returns: Bool func allowedToFire()->Bool { return justFiring == false && justReloading == false && (infiniteAmmo == true || ammoOfCurrentMagazine > 0) } /// reloads the weapon. it discards current ammoOfCurrentMagazine and use a new magazine to refill it /// - Returns: Bool func reload() { ammoOfCurrentMagazine = magazineSize remainingMagazines = remainingMagazines-1 } /// Subtracts 1 from ammoOfCurrentMagazine. Does not include safety checks if there is enough ammo or not! func subtractAmmo() { ammoOfCurrentMagazine = ammoOfCurrentMagazine-1 } /// Subtracts ammo if infiniteAmmo is false func syncedSubtractAmmo() { if infiniteAmmo == false { subtractAmmo() } } /// only fires and automatically reloads when it is allowed func syncedFireAndReload(afterFired:(()->Void)?, afterReloadInit:(()->Void)?, afterReloadComplete:(()->Void)?) { if allowedToFire() { fireAndWait(afterFired) } else if (infiniteAmmo == false && ammoOfCurrentMagazine == 0) && allowedToReload() { // Reload reloadAndWait(afterReloadInit, afterReloadComplete: afterReloadComplete) } } /// Fires when it is allowed to fire func syncedFire(afterFired:(()->Void)?) { if allowedToFire() { fireAndWait(afterFired) } } /// Only reloads when it is allowed to reload func syncedReload(afterReloadInit:(()->Void)?, afterReloadComplete:(()->Void)?) { if allowedToReload() { // Reload reloadAndWait(afterReloadInit, afterReloadComplete: afterReloadComplete) } } } protocol SKWeapon:Weapon{ unowned var sknode:SKNode { get set } } /* Implements SpriteKit specific wait methods for weapon protocol */ extension SKWeapon { /// Fires and disallow fire for rateOfFirePerSecond seconds /// - Parameter afterFired: Optional block closure that is executed after the weapon fired /// - Returns: void func fireAndWait(afterFired:(()->Void)?) { justFiring = true syncedSubtractAmmo() if let afhook = afterFired { afhook() } // Wait let rateOfFireWait = SKAction.waitForDuration(rateOfFirePerSecond) let allowFireBlock = SKAction.runBlock { self.justFiring = false } let waitSequenceAction = SKAction.sequence([rateOfFireWait, allowFireBlock]) sknode.runAction(waitSequenceAction) } /// Reloads and waits for reloadTimeSeconds seconds /// - Parameter afterReloadInit: Optional block closure that is executed after the weapon starts to reload /// - Parameter afterReloadComplete: Optional block closure that is executed after the weapon was reloaded /// - Returns: Void func reloadAndWait(afterReloadInit:(()->Void)?, afterReloadComplete:(()->Void)?) { justReloading = true if let initHook = afterReloadInit { initHook() } // Wait let waitAction = SKAction.waitForDuration(reloadTimeSeconds) let allowReloadBlock = SKAction.runBlock { self.reload() self.justReloading = false if let finishHook = afterReloadComplete { finishHook() } } let waitAndAllowReloadSeq = SKAction.sequence([waitAction, allowReloadBlock]) sknode.runAction(waitAndAllowReloadSeq) } } protocol hasSKWeapon { var weapon:SKWeapon? { get set } } /// Inits class that conforms to SKWeapon class SKWeaponGenerator: SKWeapon { // SKWeapon unowned var sknode:SKNode // Weapon var infiniteAmmo: Bool var ammoOfCurrentMagazine:Int var magazineSize:Int var remainingMagazines:Int var rateOfFirePerSecond:NSTimeInterval var reloadTimeSeconds:NSTimeInterval var damagePoints:Int var justFiring:Bool var justReloading:Bool var autoReload:Bool // Inits default weeapon init(ammoOfCurrentMagazine:Int, magazineSize:Int, remainingMagazines:Int, rateOfFirePerSecond:NSTimeInterval, reloadTimeSeconds:NSTimeInterval, damagePoints:Int, autoReload:Bool, sknode:SKNode) { self.infiniteAmmo = false self.ammoOfCurrentMagazine = ammoOfCurrentMagazine self.magazineSize = magazineSize self.remainingMagazines = remainingMagazines self.rateOfFirePerSecond = rateOfFirePerSecond self.reloadTimeSeconds = reloadTimeSeconds self.damagePoints = damagePoints justFiring = false justReloading = false self.autoReload = autoReload self.sknode = sknode } /// Inits weapon with infinite ammo and that is never be reloaded init(rateOfFirePerSecond:NSTimeInterval, damagePoints:Int, sknode:SKNode) { self.infiniteAmmo = true self.ammoOfCurrentMagazine = 0 self.magazineSize = 0 self.remainingMagazines = 0 self.rateOfFirePerSecond = rateOfFirePerSecond self.reloadTimeSeconds = 0 self.damagePoints = damagePoints justFiring = false justReloading = false self.autoReload = true self.sknode = sknode } }
mit
820f6a2a891136a82e7fa8b5a07e2682
33.939068
337
0.665538
5.475843
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/CategorySelection/Views/Cells/CategoryPillCell.swift
1
2841
import KsApi import Library import Prelude import ReactiveSwift import UIKit protocol CategoryPillCellDelegate: AnyObject { func categoryPillCell( _ cell: CategoryPillCell, didTapAtIndex index: IndexPath, withCategory category: KsApi.Category ) } final class CategoryPillCell: UICollectionViewCell, ValueCell { private lazy var button: UIButton = { UIButton(type: .custom) }() var buttonWidthConstraint: NSLayoutConstraint? weak var delegate: CategoryPillCellDelegate? // MARK: - Properties private let viewModel: CategoryPillCellViewModelType = CategoryPillCellViewModel() // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) self.button.addTarget(self, action: #selector(CategoryPillCell.pillCellTapped), for: .touchUpInside) self.configureSubviews() self.bindStyles() self.bindViewModel() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Styles override func bindStyles() { super.bindStyles() _ = self.button |> buttonStyle } // MARK: - View Model override func bindViewModel() { super.bindViewModel() self.button.rac.title = self.viewModel.outputs.buttonTitle self.button.rac.selected = self.viewModel.outputs.isSelected self.viewModel.outputs.notifyDelegatePillCellTapped .observeForUI() .observeValues { [weak self] indexPath, category in guard let self = self else { return } self.delegate?.categoryPillCell(self, didTapAtIndex: indexPath, withCategory: category) } } // MARK: - Configuration func configureWith(value: CategoryPillCellValue) { self.viewModel.inputs.configure(with: value) } // MARK: - Functions private func configureSubviews() { _ = (self.button, self.contentView) |> ksr_addSubviewToParent() |> ksr_constrainViewToEdgesInParent(priority: .defaultHigh) self.buttonWidthConstraint = self.button.widthAnchor.constraint(lessThanOrEqualToConstant: 0) NSLayoutConstraint.activate([ self.buttonWidthConstraint, self.button.heightAnchor.constraint(greaterThanOrEqualToConstant: Styles.minTouchSize.height) ].compact()) } // MARK: - Accessors public func setIsSelected(_ isSelected: Bool) { self.viewModel.inputs.setIsSelected(selected: isSelected) } @objc func pillCellTapped() { self.viewModel.inputs.pillCellTapped() } } // MARK: - Styles private let buttonStyle: ButtonStyle = { button in button |> greyButtonStyle |> roundedStyle(cornerRadius: Styles.minTouchSize.height / 2) |> UIButton.lens.titleLabel.lineBreakMode .~ .byTruncatingTail |> UIButton.lens.titleColor(for: .selected) .~ UIColor.ksr_white |> UIButton.lens.backgroundColor(for: .selected) .~ UIColor.ksr_create_700 }
apache-2.0
6a2ddaec438d3dd181fbbda376f7e33b
25.305556
104
0.719465
4.552885
false
false
false
false
okla/QuickRearrangeTableView
Example/App/ViewController.swift
1
1861
import UIKit class ViewController: UIViewController { var currentIndexPath: NSIndexPath? var cellTitles = ["0x15", "0x2", "0x3", "0x4", "0x5", "0x6", "0x7", "0x8", "0x9", "0xA", "0xB", "0xC", "0xD", "0xE", "0xF", "0x10", "0x11", "0x12", "0x13", "0x14", "0x1"] override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() let tableView = TableView(frame: view.frame, style: .Plain) tableView.delegate = self tableView.dataSource = self tableView.setRearrangeOptions([.hover, .translucency], dataSource: self) view.addSubview(tableView) } } extension ViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } } extension ViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellTitles.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: nil) if indexPath == currentIndexPath { cell.backgroundColor = nil } else { cell.textLabel?.text = cellTitles[indexPath.row] } cell.separatorInset = UIEdgeInsetsZero cell.layoutMargins = UIEdgeInsetsZero return cell } } extension ViewController: RearrangeDataSource { func moveObjectAtCurrentIndexPath(to indexPath: NSIndexPath) { guard let unwrappedCurrentIndexPath = currentIndexPath else { return } let object = cellTitles[unwrappedCurrentIndexPath.row] cellTitles.removeAtIndex(unwrappedCurrentIndexPath.row) cellTitles.insert(object, atIndex: indexPath.row) } }
mit
0781037cba3eff023de9d11ecf837e83
23.826667
107
0.710371
4.420428
false
false
false
false
longbai/swift-sdk
Source/UploadToken.swift
1
1345
// // UploadToken.swift // QiniuSwift // // Created by bailong on 16/3/11. // Copyright © 2016年 Qiniu Cloud Storage. All rights reserved. // import Foundation struct UploadToken{ let accessKey:String; let bucket:String; let token:String; let hasReturnUrl:Bool; static func parse(token:String)->UploadToken?{ let strings = token.componentsSeparatedByString(":"); if (strings.count != 3){ return nil; } let data = Base64.urlSafeDecode(strings[2]) if data == nil { return nil } let dict = try?NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves); if dict == nil { return nil } let scope = dict!.objectForKey("scope") as! String? if scope == nil || scope == ""{ return nil } let deadline = dict!.objectForKey("deadline") if deadline == nil { return nil } let returnUrl = dict!.objectForKey("returnUrl") let hasReturnUrl = (returnUrl != nil) let strings2 = scope!.componentsSeparatedByString(":") let bucket = strings2[0] let ak = strings[0] return UploadToken(accessKey: ak, bucket: bucket, token: token, hasReturnUrl: hasReturnUrl) } }
mit
0cb915549f5368e3a5272e1e6d4e05f7
28.195652
114
0.588674
4.458472
false
false
false
false
fuzongjian/SwiftStudy
SwiftStudy/Project/动画集锦/仿支付宝雷达效果/RadarView.swift
1
4341
// // RadarView.swift // SwiftStudy // // Created by 付宗建 on 16/8/15. // Copyright © 2016年 youran. All rights reserved. // import UIKit class RadarView: UIView { var radarTimer: NSTimer? var radarClickButton: UIButton? override func drawRect(rect: CGRect) { } override init(frame: CGRect) { super.init(frame: frame) radarClickButton = UIButton(type: .System) radarClickButton?.frame = self.bounds radarClickButton?.layer.cornerRadius = (radarClickButton?.frame.size.width)!/2 radarClickButton?.layer.masksToBounds = true radarClickButton?.addTarget(self, action: #selector(radarClickButton(_:)), forControlEvents: .TouchUpInside) self.addSubview(radarClickButton!) raderColor = UIColor.blueColor() } func radarClickButton(sender: UIButton){ print("radarClickButton") } // 实现雷达画圈功能 func drawCircle (){ let center = CGPointMake(self.bounds.size.height/2, self.bounds.size.width/2) let path = UIBezierPath.init(arcCenter: center, radius: 25.0, startAngle: 0, endAngle:CGFloat(M_PI+M_PI), clockwise: true) let shapeLayer = CAShapeLayer.init() shapeLayer.frame = self.bounds shapeLayer.fillColor = raderColor?.CGColor shapeLayer.opacity = 0.2 shapeLayer.path = path.CGPath self.layer.insertSublayer(shapeLayer, below: radarClickButton?.layer) addAnimation(shapeLayer) } func addAnimation(shapeLayer: CAShapeLayer){ // 雷达圈的大小变化 let basicAnimation = CABasicAnimation.init() basicAnimation.keyPath = "path" let center = CGPointMake(self.bounds.size.height/2, self.bounds.size.width/2) let pathOne = UIBezierPath.init(arcCenter: center, radius: 1, startAngle: 0, endAngle: CGFloat(M_PI+M_PI), clockwise: true) let pathTwo = UIBezierPath.init(arcCenter: center, radius: UIScreen.mainScreen().bounds.size.width, startAngle: 0, endAngle: CGFloat(M_PI+M_PI), clockwise: true) basicAnimation.fromValue = pathOne.CGPath basicAnimation.toValue = pathTwo.CGPath basicAnimation.fillMode = kCAFillModeForwards // 雷达圈的透明度变化 let opacityAnimation = CABasicAnimation.init() opacityAnimation.keyPath = "opacity" opacityAnimation.fromValue = 0.2 opacityAnimation.toValue = 0.0 opacityAnimation.fillMode = kCAFillModeForwards // 动画组 let group = CAAnimationGroup.init() group.animations = [basicAnimation,opacityAnimation] group.duration = 4 group.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut) group.delegate = self group.removedOnCompletion = true shapeLayer.addAnimation(group, forKey: nil) } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { if flag == true{ if self.layer.sublayers![0].isKindOfClass(CAShapeLayer){ let shaperLayer: CAShapeLayer = self.layer.sublayers![0] as! CAShapeLayer shaperLayer.removeFromSuperlayer() } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // setter 方法的实现 var normalImage: UIImage?{// 正常状态下的图片 willSet{ radarClickButton?.setBackgroundImage(newValue, forState: .Normal) }didSet{ } } var selectImage: UIImage?{// 选中状态下的图片 willSet{ radarClickButton?.setBackgroundImage(newValue, forState: .Highlighted) }didSet{ } } var isStart: Bool?{// 是否直接开始雷达 默认no willSet{ if newValue == true{ radarTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(drawCircle), userInfo: nil, repeats: true) }else{ radarTimer?.invalidate() radarTimer = nil } }didSet{ } } var raderColor: UIColor?{// 波纹颜色 willSet{ }didSet{ } } }
apache-2.0
f2aeef3414328ebe2f24f19125046f59
34.644068
169
0.624584
4.747178
false
false
false
false
joshua7v/ResearchOL-iOS
ResearchOL/Class/Main/Tool/ROLNotifications.swift
1
978
// // ROLNotifications.swift // ResearchOL // // Created by Joshua on 15/5/15. // Copyright (c) 2015年 SigmaStudio. All rights reserved. // import UIKit class ROLNotifications: NSObject { static let userLoginNotification: String = "UserLoginNotification" static let userDidFinishedAnswerQuestionareNotification: String = "UserDidFinishedAnswerQuestionareNotification" static let userFinishedAnswerQuestionareNotification: String = "userFinishedAnswerQuestionareNotification" static let showMenuNotification: String = "ShowMenuNotification" static let userLogoutNotification = "UserLogoutNotification" static let avatarDidChangedNotification: String = "AvatarDidChangedNotification" static let signInNotification: String = "SignInNotification" static let userPointsDidAddNotification: String = "UserPointsDidAddNotification" static let userAnsweredQuestionaresDidAddNotification: String = "UserAnsweredQuestionaresDidAddNotification" }
mit
c7477030f31ed474117bdd20de6d13d8
45.47619
116
0.8125
4.855721
false
false
false
false
Stitch7/mclient
mclient/PrivateMessages/_MessageInputBar/Extensions/NSMutableAttributedString+MessageInputBar.swift
1
3043
/* MIT License Copyright (c) 2017-2018 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit extension NSMutableAttributedString { @discardableResult internal func bold(_ text: String, fontSize: CGFloat = UIFont.preferredFont(forTextStyle: .body).pointSize, textColor: UIColor = .black) -> NSMutableAttributedString { let attrs: [NSAttributedString.Key:AnyObject] = [ NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: fontSize), NSAttributedString.Key.foregroundColor : textColor ] let boldString = NSMutableAttributedString(string: text, attributes: attrs) self.append(boldString) return self } @discardableResult internal func normal(_ text: String, fontSize: CGFloat = UIFont.preferredFont(forTextStyle: .body).pointSize, textColor: UIColor = .black) -> NSMutableAttributedString { let attrs:[NSAttributedString.Key:AnyObject] = [ NSAttributedString.Key.font : UIFont.systemFont(ofSize: fontSize), NSAttributedString.Key.foregroundColor : textColor ] let normal = NSMutableAttributedString(string: text, attributes: attrs) self.append(normal) return self } } extension NSAttributedString { internal func replacingCharacters(in range: NSRange, with attributedString: NSAttributedString) -> NSMutableAttributedString { let ns = NSMutableAttributedString(attributedString: self) ns.replaceCharacters(in: range, with: attributedString) return ns } internal static func += (lhs: inout NSAttributedString, rhs: NSAttributedString) { let ns = NSMutableAttributedString(attributedString: lhs) ns.append(rhs) lhs = ns } internal static func + (lhs: NSAttributedString, rhs: NSAttributedString) -> NSAttributedString { let ns = NSMutableAttributedString(attributedString: lhs) ns.append(rhs) return NSAttributedString(attributedString: ns) } }
mit
5e3ce303464d122a1bcda451393f2c1a
40.684932
173
0.727571
5.282986
false
false
false
false
kbelter/SnazzyList
SnazzyList/Classes/src/TableView/Services/Cells/DropdownOptionSelectionTableCell.swift
1
7537
// // DropdownOptionSelectionTableCell.swift // Dms // // Created by Kevin on 9/24/18. // Copyright © 2018 DMS. All rights reserved. // /// This cell will fit the cases were you need to show a dropdown, the dropdown can be full screen or partial screen depending on the title. /// Screenshot: https://github.com/datamindedsolutions/noteworth-ios-documentation/blob/master/TableView%20Shared%20Cells/DropdownOptionSelectionTableCell.png?raw=true final class DropdownOptionSelectionTableCell: UITableViewCell { let containerView = UIView(backgroundColor: .white) let titleLabel = UILabel(font: .systemFont(ofSize: 12.0, weight: .medium), textColor: .blue, textAlignment: .left) let optionNameLabel = UILabel(font: .systemFont(ofSize: 17.0, weight: .medium), textColor: .blue, textAlignment: .left) let arrowDownImageView = UIImageView(image: UIImage(named: "down_arrow_selection", in: Bundle.resourceBundle(for: DropdownOptionSelectionTableCell.self), compatibleWith: nil), contentMode: .scaleAspectFit) let titleLineView = UIView(backgroundColor: .blue) let scrimView = UIView(backgroundColor: UIColor.white.withAlphaComponent(0.6)) override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var containerViewRightAnchor: NSLayoutConstraint? private var configFile: DropdownOptionSelectionTableCellConfigFile? } extension DropdownOptionSelectionTableCell: GenericTableCellProtocol { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, with item: Any) { guard let configFile = item as? DropdownOptionSelectionTableCellConfigFile else { return } self.configFile = configFile if let title = configFile.provider?.getSelectedDropdownOptionValue(forIdentifier: configFile.identifier) { optionNameLabel.text = title optionNameLabel.textColor = configFile.optionColor optionNameLabel.font = configFile.optionFont titleLabel.isHidden = false } else { optionNameLabel.text = configFile.title optionNameLabel.textColor = configFile.optionColor optionNameLabel.font = configFile.optionFont titleLabel.isHidden = true } titleLabel.text = configFile.title titleLabel.textColor = configFile.titleColor titleLabel.font = configFile.titleFont scrimView.isHidden = configFile.isEditable // TODO: check if it is the best way for add image if it is not null if let downArrowImage = configFile.downArrowImage { arrowDownImageView.image = downArrowImage } self.containerViewRightAnchor?.isActive = !configFile.adjustableToTitle self.contentView.layoutIfNeeded() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let configFile = self.configFile, configFile.isEditable else { return } configFile.actions?.tapDropdownOptionSelection(withIdentifier: configFile.identifier) } } extension DropdownOptionSelectionTableCell { private func setupViews() { setupBackground() setupContainerView() setupTitleLabel() setupOptionNameLabel() setupArrowDownImageView() setupTitleLineView() setupScrimView() } private func setupContainerView() { contentView.addSubview(containerView) } private func setupScrimView() { containerView.addSubview(scrimView) } private func setupTitleLabel() { titleLabel.numberOfLines = 1 containerView.addSubview(titleLabel) } private func setupOptionNameLabel() { optionNameLabel.numberOfLines = 1 containerView.addSubview(optionNameLabel) } private func setupArrowDownImageView() { containerView.addSubview(arrowDownImageView) } private func setupTitleLineView() { containerView.addSubview(titleLineView) } private func setupConstraints() { containerView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16.0).isActive = true containerViewRightAnchor = contentView.rightAnchor.constraint(equalTo: containerView.rightAnchor, constant: 16.0) containerViewRightAnchor?.isActive = true containerView.bind(withConstant: 0.0, boundType: .vertical) titleLabel.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true titleLabel.rightAnchor.constraint(lessThanOrEqualTo: arrowDownImageView.leftAnchor, constant: -10.0).isActive = true titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 12.0).isActive = true optionNameLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 12.0).isActive = true optionNameLabel.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true optionNameLabel.rightAnchor.constraint(lessThanOrEqualTo: arrowDownImageView.leftAnchor, constant: -4.0).isActive = true optionNameLabel.assignSize(height: 26.0) arrowDownImageView.assignSize(width: 18.0, height: 18.0) arrowDownImageView.rightAnchor.constraint(equalTo: containerView.rightAnchor, constant: -8.0).isActive = true arrowDownImageView.centerYAnchor.constraint(equalTo: optionNameLabel.centerYAnchor).isActive = true titleLineView.assignSize(height: 2.0) titleLineView.bind(withConstant: 0.0, boundType: .horizontal) titleLineView.topAnchor.constraint(equalTo: optionNameLabel.bottomAnchor, constant: 8.0).isActive = true scrimView.matchEdges(to: optionNameLabel) } } struct DropdownOptionSelectionTableCellConfigFile { let identifier: Any let title: String let titleColor: UIColor let titleFont: UIFont let optionColor: UIColor let optionFont: UIFont let downArrowImage: UIImage? let titleLineColor: UIColor let isEditable: Bool let adjustableToTitle: Bool weak var provider: DropdownOptionSelectionTableProvider? weak var actions: DropdownOptionSelectionTableActions? init(identifier: Any, title: String, titleColor: UIColor, titleFont: UIFont, optionColor: UIColor, optionFont: UIFont, downArrowImage: UIImage?, titleLineColor: UIColor, isEditable: Bool, adjustableToTitle: Bool, provider: DropdownOptionSelectionTableProvider?, actions: DropdownOptionSelectionTableActions?) { self.identifier = identifier self.title = title self.titleColor = titleColor self.titleFont = titleFont self.optionColor = optionColor self.optionFont = optionFont self.downArrowImage = downArrowImage self.titleLineColor = titleLineColor self.isEditable = isEditable self.adjustableToTitle = adjustableToTitle self.provider = provider self.actions = actions } } public protocol DropdownOptionSelectionTableProvider: class { func getSelectedDropdownOptionValue(forIdentifier identifier: Any) -> String? } public protocol DropdownOptionSelectionTableActions: class { func tapDropdownOptionSelection(withIdentifier identifier: Any) }
apache-2.0
fd2ede0a5d7ba0b483d2640830f36d4a
42.310345
314
0.719347
5.425486
false
true
false
false
doannx/tip-calculator-ios
tippy/Constant.swift
1
554
// // Constant.swift // tippy // // Created by john on 2/9/17. // Copyright © 2017 doannx. All rights reserved. // import Foundation class Const { static let Tip_Values = [15, 20, 25] static let Theme_Values = ["DARK", "LIGHT"] static let Theme_Key = "theme" static let Theme_Default_Value = 1 static let Tip_Key = "tip" static let Tip_Default_Value = 15 static let Time_Out_Value = 600 static let Bill_Key = "billAmount" static let Last_Active_Key = "lastActive" }
apache-2.0
cb82cea498186be9404af1e61139a55b
17.433333
49
0.59132
3.590909
false
false
false
false
offfffz/OutsideInTestingLab
OutsideInTestingLab/StringValidatorExtesions.swift
1
687
// // StringValidatorExtesions.swift // OutsideInTestingLab // // Created by offz on 9/12/2558 BE. // Copyright © 2558 offz. All rights reserved. // import Foundation let VALID_EMAIL_PATTERN = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" extension String { var isEmail: Bool { let regex = try? NSRegularExpression(pattern: VALID_EMAIL_PATTERN, options: .CaseInsensitive) let selfRange = NSMakeRange(0, characters.count) let options = NSMatchingOptions() return regex?.firstMatchInString(self, options: options, range: selfRange) != nil } }
mit
658c0b807b7f3bd8f894f88f3047c22d
31.714286
161
0.619534
3.16129
false
false
false
false
andrea-prearo/SwiftExamples
SmoothScrolling/Client/Shared/Extensions/UIImageView+Util.swift
1
853
// // UIImageView+Util.swift // SmoothScrolling // // Created by Andrea Prearo on 3/9/16. // Copyright © 2016 Andrea Prearo. All rights reserved. // import UIKit extension UIImageView { func setRoundedImage(_ image: UIImage?) { guard let image = image else { return } DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf.image = image strongSelf.roundedImage(10.0) } } } private extension UIImageView { func roundedImage(_ cornerRadius: CGFloat, withBorder: Bool = true) { layer.borderWidth = 1.0 layer.masksToBounds = false layer.cornerRadius = cornerRadius if withBorder { layer.borderColor = UIColor.white.cgColor } clipsToBounds = true } }
mit
5ce71a1dc6440f0c1e4ff74e1e7d876b
24.058824
73
0.606808
4.507937
false
false
false
false
snapsure-insurance-bot/snapsure-sdk-ios
Sources/Core/Services/MetadataService.swift
1
2491
// // Copyright © 2018 Picsure. All rights reserved. // import UIKit import Photos typealias ParametersCompletion = (Parameters?, Error?) -> Void final class MetadataService { private static let photoLibrary = PHPhotoLibrary.shared() static func metadata(from image: UIImage, completion: @escaping ParametersCompletion) { photoLibrary.save(image) { asset, error in if let error = error { completion(nil, error) return } guard let asset = asset else { completion(nil, nil) return } metadata(from: asset, completion: completion) } } private static func metadata(from asset: PHAsset, completion: @escaping ParametersCompletion) { PHImageManager.default().requestImageData(for: asset, options: nil) { data, _, _, _ in guard let data = data else { completion(nil, nil) return } completion(metadata(from: data), nil) } } private static func metadata(from data: Data) -> Parameters? { guard let selectedImageSourceRef = CGImageSourceCreateWithData(data as CFData, nil), let properties = CGImageSourceCopyPropertiesAtIndex(selectedImageSourceRef, 0, nil) as? Parameters else { return nil } return properties } } private extension PHPhotoLibrary { func save(_ image: UIImage, completion: ((PHAsset?, Error?) -> Void)? = nil) { guard PHPhotoLibrary.authorizationStatus() == .authorized else { completion?(nil, PicsureErrors.ImageErrors.missingPhotoPermission) return } var placeholder: PHObjectPlaceholder? performChanges({ let createAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image) guard let photoPlaceholder = createAssetRequest.placeholderForCreatedAsset else { completion?(nil, nil) return } placeholder = photoPlaceholder }, completionHandler: { success, _ in guard let placeholder = placeholder, success else { completion?(nil, nil) return } let assets = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: nil) let asset = assets.firstObject completion?(asset, nil) }) } }
mit
cda8075a54979a9321ff0280437e487e
33.583333
117
0.603213
5.496689
false
false
false
false
ashfurrow/RxSwift
RxSwift/Concurrency/AsyncLock.swift
4
2334
// // AsyncLock.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** In case nobody holds this lock, the work will be queued and executed immediately on thread that is requesting lock. In case there is somebody currently holding that lock, action will be enqueued. When owned of the lock finishes with it's processing, it will also execute and pending work. That means that enqueued work could possibly be executed later on a different thread. */ class AsyncLock<I: InvocableType> : Disposable , Lock , SynchronizedDisposeType { typealias Action = () -> Void var _lock = SpinLock() private var _queue: Queue<I> = Queue(capacity: 0) private var _isExecuting: Bool = false private var _hasFaulted: Bool = false // lock { func lock() { _lock.lock() } func unlock() { _lock.unlock() } // } private func enqueue(action: I) -> I? { _lock.lock(); defer { _lock.unlock() } // { if _hasFaulted { return nil } if _isExecuting { _queue.enqueue(action) return nil } _isExecuting = true return action // } } private func dequeue() -> I? { _lock.lock(); defer { _lock.unlock() } // { if _queue.count > 0 { return _queue.dequeue() } else { _isExecuting = false return nil } // } } func invoke(action: I) { let firstEnqueuedAction = enqueue(action) if let firstEnqueuedAction = firstEnqueuedAction { firstEnqueuedAction.invoke() } else { // action is enqueued, it's somebody else's concern now return } while true { let nextAction = dequeue() if let nextAction = nextAction { nextAction.invoke() } else { return } } } func dispose() { synchronizedDispose() } func _synchronized_dispose() { _queue = Queue(capacity: 0) _hasFaulted = true } }
mit
112b12f54a05be6948aba9c4e72c2c6c
21.442308
85
0.523136
4.743902
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/Operations/Sources/Features/Shared/URLSessionTaskOperation.swift
2
2125
// // URLSessionTaskOperation.swift // Operations // // Created by Daniel Thorpe on 01/10/2015. // Copyright © 2015 Dan Thorpe. All rights reserved. // import Foundation /** An Operation which is a simple wrapper around `NSURLSessionTask`. Note that the task will still need to be configured with a delegate as usual. Typically this operation would be used after the task is setup, so that conditions or observers can be attached. */ public class URLSessionTaskOperation: Operation { enum KeyPath: String { case State = "state" } public let task: NSURLSessionTask private var removedObserved = false private let lock = NSLock() public init(task: NSURLSessionTask) { assert(task.state == .Suspended, "NSURLSessionTask must be suspended, not \(task.state)") self.task = task super.init() addObserver(CancelledObserver { _ in task.cancel() }) } public override func execute() { assert(task.state == .Suspended, "NSURLSessionTask resumed outside of \(self)") task.addObserver(self, forKeyPath: KeyPath.State.rawValue, options: [], context: &URLSessionTaskOperationKVOContext) task.resume() } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard context == &URLSessionTaskOperationKVOContext else { return } lock.withCriticalScope { if object === task && keyPath == KeyPath.State.rawValue && !removedObserved { if case .Completed = task.state { finish(task.error) } switch task.state { case .Completed, .Canceling: task.removeObserver(self, forKeyPath: KeyPath.State.rawValue) removedObserved = true default: break } } } } } // swiftlint:disable variable_name private var URLSessionTaskOperationKVOContext = 0 // swiftlint:enable variable_name
gpl-3.0
69b71b11719ef3e361a8f6c44cedbb85
29.342857
164
0.635593
5.057143
false
false
false
false
tapglue/snaasSdk-iOS
Tests/Internal/RouterTest.swift
2
4665
// // RouterTest.swift // Tapglue // // Created by John Nilsen on 7/4/16. // Copyright © 2016 Tapglue. All rights reserved. // import XCTest import Nimble @testable import Tapglue class RouterTest: XCTestCase { override func setUp() { super.setUp() Router.configuration = Configuration() } override func tearDown() { super.tearDown() } func testRouterPostCreatesRequestWithMethod() { let request = Router.post("/login", payload: ["user_name":"paco"]) expect(request.httpMethod).to(equal("POST")) } func testRouterPostCreatesRequestWithPath() { let request = Router.post("/login", payload: ["a":"b"]) expect(request.URLString).to(equal("https://api.tapglue.com/0.4/login")) } func testRouterPostCreatesRequestWithPayload() { let payload = ["user_name":"paco", "password":"1234"] let request = Router.post("/login", payload: payload) if request.httpBody == nil { XCTFail("http body was nil!") return } let body = request.httpBody! do { let dictionary = try JSONSerialization.jsonObject(with: body, options: .mutableContainers) as? [String: String] expect(dictionary).to(equal(payload)) } catch { XCTFail("could not deserialize JSON") } } func testRouterPostAddsAppTokenHeader() { let request = Router.post("/login", payload: [:]) let headers = request.allHTTPHeaderFields! let authorizationHeader = headers["Authorization"] expect(authorizationHeader).to(contain("Basic ")) } func testRouterGetCreatesRequestWithMethod() { let request = Router.get("/me") expect(request.httpMethod).to(equal("GET")) } func testRouterGetBodyNil() { let request = Router.get("/me") expect(request.httpBody).to(beNil()) } func testRouterPutCreatesRequestWithMethod() { let request = Router.put("/me", payload: [:]) expect(request.httpMethod).to(equal("PUT")) } func testRouterPutCreatesRequestWithPayload() { let payload = ["user_name":"paco", "password":"1234"] let request = Router.put("/login", payload: payload) if request.httpBody == nil { fail("http body was nil!") return } let body = request.httpBody! do { let dictionary = try JSONSerialization.jsonObject(with: body, options: .mutableContainers) as? [String: String] expect(dictionary).to(equal(payload)) } catch { fail("could not deserialize JSON") } } func testRouterDeleteCreatesRequestWithMethod() { let request = Router.delete("/me") expect(request.httpMethod).to(equal("DELETE")) } func testRouterAddsOSHeader() { let request = Router.post("/login", payload: [:]) let headers = request.allHTTPHeaderFields! let header = headers["X-Tapglue-OS"] expect(header).to(equal("iOS")) } func testRouterAddsManufacturerHeader() { let request = Router.post("/login", payload: [:]) let headers = request.allHTTPHeaderFields! let header = headers["X-Tapglue-Manufacturer"] expect(header).to(equal("Apple")) } func testRouterAddsSDKVersionHeader() { let request = Router.get("/me") let headers = request.allHTTPHeaderFields! let header = headers["X-Tapglue-SDKVersion"] expect(header).to(equal(Router.sdkVersion)) } func testRouterAddsTimezoneHeader() { let request = Router.get("/me") let headers = request.allHTTPHeaderFields! let header = headers["X-Tapglue-Timezone"] expect(header).to(equal(NSTimeZone.localTimeZone().abbreviation()!)) } func testRouterAddsDeviceIdHeader() { let request = Router.get("/me") let headers = request.allHTTPHeaderFields! let header = headers["X-Tapglue-IDFV"] expect(header).toNot(beEmpty()) } func testRouterAddsModelHeader() { let request = Router.get("/me") let headers = request.allHTTPHeaderFields! let header = headers["X-Tapglue-Model"] expect(header).toNot(beEmpty()) } func testRouterAddsOsVersionHeader() { let request = Router.get("/me") let headers = request.allHTTPHeaderFields! let header = headers["X-Tapglue-OSVersion"] expect(header).toNot(beEmpty()) } }
apache-2.0
f9381b5c245aa95f0ee106706448b7dd
29.887417
123
0.599271
4.768916
false
true
false
false
vector-im/riot-ios
Riot/Modules/KeyVerification/Common/Verify/Scanning/KeyVerificationVerifyByScanningCoordinator.swift
2
3880
// File created from ScreenTemplate // $ createScreen.sh Verify KeyVerificationVerifyByScanning /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class KeyVerificationVerifyByScanningCoordinator: KeyVerificationVerifyByScanningCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private let keyVerificationRequest: MXKeyVerificationRequest private var keyVerificationVerifyByScanningViewModel: KeyVerificationVerifyByScanningViewModelType private let keyVerificationVerifyByScanningViewController: KeyVerificationVerifyByScanningViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: KeyVerificationVerifyByScanningCoordinatorDelegate? // MARK: - Setup init(session: MXSession, verificationKind: KeyVerificationKind, keyVerificationRequest: MXKeyVerificationRequest) { self.session = session self.keyVerificationRequest = keyVerificationRequest let keyVerificationVerifyByScanningViewModel = KeyVerificationVerifyByScanningViewModel(session: self.session, verificationKind: verificationKind, keyVerificationRequest: keyVerificationRequest) let keyVerificationVerifyByScanningViewController = KeyVerificationVerifyByScanningViewController.instantiate(with: keyVerificationVerifyByScanningViewModel) self.keyVerificationVerifyByScanningViewModel = keyVerificationVerifyByScanningViewModel self.keyVerificationVerifyByScanningViewController = keyVerificationVerifyByScanningViewController } // MARK: - Public methods func start() { self.keyVerificationVerifyByScanningViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.keyVerificationVerifyByScanningViewController } } // MARK: - KeyVerificationVerifyByScanningViewModelCoordinatorDelegate extension KeyVerificationVerifyByScanningCoordinator: KeyVerificationVerifyByScanningViewModelCoordinatorDelegate { func keyVerificationVerifyByScanningViewModelDidCancel(_ viewModel: KeyVerificationVerifyByScanningViewModelType) { self.delegate?.keyVerificationVerifyByScanningCoordinatorDidCancel(self) } func keyVerificationVerifyByScanningViewModel(_ viewModel: KeyVerificationVerifyByScanningViewModelType, didStartSASVerificationWithTransaction transaction: MXSASTransaction) { self.delegate?.keyVerificationVerifyByScanningCoordinator(self, didCompleteWithSASTransaction: transaction) } func keyVerificationVerifyByScanningViewModel(_ viewModel: KeyVerificationVerifyByScanningViewModelType, didScanOtherQRCodeData qrCodeData: MXQRCodeData, withTransaction transaction: MXQRCodeTransaction) { self.delegate?.keyVerificationVerifyByScanningCoordinator(self, didScanOtherQRCodeData: qrCodeData, withTransaction: transaction) } func keyVerificationVerifyByScanningViewModel(_ viewModel: KeyVerificationVerifyByScanningViewModelType, qrCodeDidScannedByOtherWithTransaction transaction: MXQRCodeTransaction) { self.delegate?.keyVerificationVerifyByScanningCoordinator(self, qrCodeDidScannedByOtherWithTransaction: transaction) } }
apache-2.0
2669daa82d456f6ea1acbc1a215eafd1
46.317073
209
0.803351
7.592955
false
false
false
false
acrookston/SQLite.swift
SQLite/Helpers.swift
1
4387
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public typealias Star = (Expression<Binding>?, Expression<Binding>?) -> Expression<Void> public func *(_: Expression<Binding>?, _: Expression<Binding>?) -> Expression<Void> { return Expression(literal: "*") } public protocol _OptionalType { associatedtype WrappedType } extension Optional : _OptionalType { public typealias WrappedType = Wrapped } // let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self) let SQLITE_TRANSIENT = unsafeBitCast(-1, sqlite3_destructor_type.self) extension String { @warn_unused_result func quote(mark: Character = "\"") -> String { let escaped = characters.reduce("") { string, character in string + (character == mark ? "\(mark)\(mark)" : "\(character)") } return "\(mark)\(escaped)\(mark)" } @warn_unused_result func join(expressions: [Expressible]) -> Expressible { var (template, bindings) = ([String](), [Binding?]()) for expressible in expressions { let expression = expressible.expression template.append(expression.template) bindings.appendContentsOf(expression.bindings) } return Expression<Void>(template.joinWithSeparator(self), bindings) } @warn_unused_result func infix<T>(lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression<T> { let expression = Expression<T>(" \(self) ".join([lhs, rhs]).expression) guard wrap else { return expression } return "".wrap(expression) } @warn_unused_result func prefix(expressions: Expressible) -> Expressible { return "\(self) ".wrap(expressions) as Expression<Void> } @warn_unused_result func prefix(expressions: [Expressible]) -> Expressible { return "\(self) ".wrap(expressions) as Expression<Void> } @warn_unused_result func wrap<T>(expression: Expressible) -> Expression<T> { return Expression("\(self)(\(expression.expression.template))", expression.expression.bindings) } @warn_unused_result func wrap<T>(expressions: [Expressible]) -> Expression<T> { return wrap(", ".join(expressions)) } } @warn_unused_result func infix<T>(lhs: Expressible, _ rhs: Expressible, wrap: Bool = true, function: String = #function) -> Expression<T> { return function.infix(lhs, rhs, wrap: wrap) } @warn_unused_result func wrap<T>(expression: Expressible, function: String = #function) -> Expression<T> { return function.wrap(expression) } @warn_unused_result func wrap<T>(expressions: [Expressible], function: String = #function) -> Expression<T> { return function.wrap(", ".join(expressions)) } @warn_unused_result func transcode(literal: Binding?) -> String { guard let literal = literal else { return "NULL" } switch literal { case let blob as Blob: return blob.description case let string as String: return string.quote("'") case let binding: return "\(binding)" } } @warn_unused_result func value<A: Value>(v: Binding) -> A { return A.fromDatatypeValue(v as! A.Datatype) as! A } @warn_unused_result func value<A: Value>(v: Binding?) -> A { return value(v!) }
mit
f5daf8398173818fa984705b7197ee21
34.95082
139
0.681487
4.237681
false
false
false
false
ozgur/AutoLayoutAnimation
pods/AlamofireImage/Source/UIImage+AlamofireImage.swift
56
12101
// // UIImage+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) || os(tvOS) || os(watchOS) import CoreGraphics import Foundation import UIKit // MARK: Initialization private let lock = NSLock() extension UIImage { /// Initializes and returns the image object with the specified data in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:)` method. /// /// - parameter data: The data object containing the image data. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data) -> UIImage? { lock.lock() let image = UIImage(data: data) lock.unlock() return image } /// Initializes and returns the image object with the specified data and scale in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:scale:)` method. /// /// - parameter data: The data object containing the image data. /// - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 /// results in an image whose size matches the pixel-based dimensions of the image. Applying a /// different scale factor changes the size of the image as reported by the size property. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data, scale: CGFloat) -> UIImage? { lock.lock() let image = UIImage(data: data, scale: scale) lock.unlock() return image } } // MARK: - Inflation extension UIImage { private struct AssociatedKey { static var inflated = "af_UIImage.Inflated" } /// Returns whether the image is inflated. public var af_inflated: Bool { get { if let inflated = objc_getAssociatedObject(self, &AssociatedKey.inflated) as? Bool { return inflated } else { return false } } set { objc_setAssociatedObject(self, &AssociatedKey.inflated, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation. /// /// Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it /// allows a bitmap representation to be constructed in the background rather than on the main thread. public func af_inflate() { guard !af_inflated else { return } af_inflated = true _ = cgImage?.dataProvider?.data } } // MARK: - Alpha extension UIImage { /// Returns whether the image contains an alpha component. public var af_containsAlphaComponent: Bool { let alphaInfo = cgImage?.alphaInfo return ( alphaInfo == .first || alphaInfo == .last || alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast ) } /// Returns whether the image is opaque. public var af_isOpaque: Bool { return !af_containsAlphaComponent } } // MARK: - Scaling extension UIImage { /// Returns a new version of the image scaled to the specified size. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageScaled(to size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: CGPoint.zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within /// a specified size. /// /// The resulting image contains an alpha component used to pad the width or height with the necessary transparent /// pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach. /// To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize` /// method in conjunction with a `.Center` content mode to achieve the same visual result. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFit size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a /// specified size. Any pixels that fall outside the specified size are clipped. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFill size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounded Corners extension UIImage { /// Returns a new version of the image with the corners rounded to the specified radius. /// /// - parameter radius: The radius to use when rounding the new image. /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the /// image has the same resolution for all screen scales such as @1x, @2x and /// @3x (i.e. single image from web server). Set to `false` for images loaded /// from an asset catalog with varying resolutions for each screen scale. /// `false` by default. /// /// - returns: A new image object. public func af_imageRounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let scaledRadius = divideRadiusByImageScale ? radius / scale : radius let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() draw(in: CGRect(origin: CGPoint.zero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } /// Returns a new version of the image rounded into a circle. /// /// - returns: A new image object. public func af_imageRoundedIntoCircle() -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = af_imageAspectScaled(toFill: squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } } #endif #if os(iOS) || os(tvOS) import CoreImage // MARK: - Core Image Filters @available(iOS 9.0, *) extension UIImage { /// Returns a new version of the image using a CoreImage filter with the specified name and parameters. /// /// - parameter name: The name of the CoreImage filter to use on the new image. /// - parameter parameters: The parameters to apply to the CoreImage filter. /// /// - returns: A new image object, or `nil` if the filter failed for any reason. public func af_imageFiltered(withCoreImageFilter name: String, parameters: [String: Any]? = nil) -> UIImage? { var image: CoreImage.CIImage? = ciImage if image == nil, let CGImage = self.cgImage { image = CoreImage.CIImage(cgImage: CGImage) } guard let coreImage = image else { return nil } let context = CIContext(options: [kCIContextPriorityRequestLow: true]) var parameters: [String: Any] = parameters ?? [:] parameters[kCIInputImageKey] = coreImage guard let filter = CIFilter(name: name, withInputParameters: parameters) else { return nil } guard let outputImage = filter.outputImage else { return nil } let cgImageRef = context.createCGImage(outputImage, from: outputImage.extent) return UIImage(cgImage: cgImageRef!, scale: scale, orientation: imageOrientation) } } #endif
mit
177d9affe5e8c0c51e426ec4af4963b0
38.161812
122
0.661102
4.834598
false
false
false
false
gitgitcode/LearnSwift
Calculator/Caiculator/Caiculator/ViewController.swift
1
2125
// // ViewController.swift // Caiculator // // Created by xuthus on 15/6/14. // Copyright (c) 2015年 xuthus. All rights reserved. // import UIKit class ViewController: UIViewController { //定义了一个类 //有针对的名字 单继承 @IBOutlet weak var display: UILabel! //prop !是 类型 未定义 var userIsInTheMiddletofTypingANumbser: Bool = false @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddletofTypingANumbser { display.text = display.text! + digit }else{ display.text = digit userIsInTheMiddletofTypingANumbser = true } println("digit = \(digit)") } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddletofTypingANumbser { enter() } switch operation { case "×": performOperation{$0 * $1} case "÷": performOperation{$1 / $0} case "+": performOperation{$0 + $1} case "−": performOperation{$1 - $0} default:break } } func performOperation(operation:(Double,Double) ->Double){ if operandStack.count >= 2 { //displayValue = operandStack.removeLast() * operandStack.removeLast() displayValue = operation(operandStack.removeLast(),operandStack.removeLast()) enter() } } // var operandStack: Array<Double> = Array<Double>() var operandStack = Array<Double>() @IBAction func enter() { userIsInTheMiddletofTypingANumbser = false operandStack.append(displayValue) println("operandStack = \(operandStack)") } //转化设置dipaly的值 var displayValue: Double { get { return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { //double -> string display.text = "\(newValue)" userIsInTheMiddletofTypingANumbser = false } } }
apache-2.0
52f02925113431791cb6e804c3c27d58
25.818182
89
0.580145
5.111386
false
false
false
false
EMart002/EMCommon
EMCommon/Classes/NSDate+EMKit.swift
1
1914
// // NSDate.swift // common-extentions // // Created by Martin Eberl on 07.07.16. // Copyright © 2016 Martin Eberl. All rights reserved. // import Foundation public func < (first: NSDate, second:NSDate) -> Bool { return first.compare(second) == .OrderedAscending } public func > (first:NSDate, second:NSDate) -> Bool { return first.compare(second) == .OrderedDescending } public func <= (first:NSDate, second:NSDate) -> Bool { let cmp = first.compare(second) return cmp == .OrderedAscending || cmp == .OrderedSame } public func >= (first:NSDate, second:NSDate) -> Bool { let cmp = first.compare(second) return cmp == .OrderedDescending || cmp == .OrderedSame } public func == (first:NSDate, second:NSDate) -> Bool { return first.compare(second) == .OrderedSame } public extension NSDate { public var year:Int { get { return (NSCalendar.currentCalendar() as NSCalendar).component(.Year, fromDate: self) } } public func dateBySettingYear(year:Int) ->NSDate? { return (NSCalendar.currentCalendar() as NSCalendar).dateBySettingUnit(.Year, value: year, ofDate: self, options: .WrapComponents) } public var month:Int { get { return (NSCalendar.currentCalendar() as NSCalendar).component(.Month, fromDate: self) } } public func dateBySettingMonth(month:Int) ->NSDate? { return (NSCalendar.currentCalendar() as NSCalendar).dateBySettingUnit(.Month, value:month, ofDate: self, options:.WrapComponents) } public var day:Int { get { return (NSCalendar.currentCalendar() as NSCalendar).component(.Day, fromDate: self) } } public func dateBySettingDay(day:Int) ->NSDate? { return (NSCalendar.currentCalendar() as NSCalendar).dateBySettingUnit(.Day, value:day, ofDate: self, options: .WrapComponents) } }
mit
537e2a007f52d453321fa5dc2eeabaaa
28.890625
137
0.655515
4.122845
false
false
false
false
EXXETA/JSONPatchSwift
JsonPatchSwiftTests/JPSMoveOperationTests.swift
1
3519
//===----------------------------------------------------------------------===// // // This source file is part of the JSONPatchSwift open source project. // // Copyright (c) 2015 EXXETA AG // Licensed under Apache License v2.0 // // //===----------------------------------------------------------------------===// import XCTest @testable import JsonPatchSwift import SwiftyJSON // http://tools.ietf.org/html/rfc6902#section-4.4 // 4. Operations // 4.4. move class JPSMoveOperationTests: XCTestCase { // http://tools.ietf.org/html/rfc6902#appendix-A.6 func testIfMoveValueInObjectReturnsExpectedValue() { let json = JSON(data: "{ \"foo\": { \"bar\": \"baz\", \"waldo\": \"fred\" }, \"qux\":{ \"corge\": \"grault\" } }".dataUsingEncoding(NSUTF8StringEncoding)!) let jsonPatch = try! JPSJsonPatch("{ \"op\": \"move\", \"path\": \"/qux/thud\", \"from\": \"/foo/waldo\" }") let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json) let expectedJson = JSON(data: " { \"foo\": { \"bar\": \"baz\" }, \"qux\": { \"corge\": \"grault\",\"thud\": \"fred\" } }".dataUsingEncoding(NSUTF8StringEncoding)!) XCTAssertEqual(resultingJson, expectedJson) } // http://tools.ietf.org/html/rfc6902#appendix-A.7 func testIfMoveIndizesInArrayReturnsExpectedValue() { let json = JSON(data: " { \"foo\" : [\"all\", \"grass\", \"cows\", \"eat\"]} ".dataUsingEncoding(NSUTF8StringEncoding)!) let jsonPatch = try! JPSJsonPatch("{ \"op\": \"move\", \"path\": \"/foo/3\", \"from\": \"/foo/1\" }") let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json) let expectedJson = JSON(data: "{ \"foo\" : [\"all\", \"cows\", \"eat\", \"grass\"]} ".dataUsingEncoding(NSUTF8StringEncoding)!) XCTAssertEqual(resultingJson, expectedJson) } func testIfObjectKeyMoveOperationReturnsExpectedValue() { let json = JSON(data: " { \"foo\" : { \"1\" : 2 }, \"bar\" : { }} ".dataUsingEncoding(NSUTF8StringEncoding)!) let jsonPatch = try! JPSJsonPatch("{ \"op\": \"move\", \"path\": \"/bar/1\", \"from\": \"/foo/1\" }") let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json) let expectedJson = JSON(data: "{ \"foo\" : { }, \"bar\" : { \"1\" : 2 }}".dataUsingEncoding(NSUTF8StringEncoding)!) XCTAssertEqual(resultingJson, expectedJson) } func testIfObjectKeyMoveToRootReplacesDocument() { let json = JSON(data: " { \"foo\" : { \"1\" : 2 }, \"bar\" : { }} ".dataUsingEncoding(NSUTF8StringEncoding)!) let jsonPatch = try! JPSJsonPatch("{ \"op\": \"move\", \"path\": \"\", \"from\": \"/foo\" }") let resultingJson = try! JPSJsonPatcher.applyPatch(jsonPatch, toJson: json) let expectedJson = JSON(data: "{ \"1\" : 2 }".dataUsingEncoding(NSUTF8StringEncoding)!) XCTAssertEqual(resultingJson, expectedJson) } func testIfMissingParameterReturnsError() { do { let result = try JPSJsonPatch("{ \"op\": \"move\", \"path\": \"/bar\"}") // 'from' parameter missing XCTFail(result.operations.last!.value.rawString()!) } catch JPSJsonPatch.JPSJsonPatchInitialisationError.InvalidPatchFormat(let message) { // Expected behaviour. XCTAssertNotNil(message) XCTAssertEqual(message, JPSConstants.JsonPatch.InitialisationErrorMessages.FromElementNotFound) } catch { XCTFail("Unexpected error.") } } }
apache-2.0
5a553e4239d22c9d56eab8359cd7e640
52.318182
171
0.585678
4.265455
false
true
false
false
jcadrg/ios-exercises
SwiftExercises.playground/section-1.swift
1
2468
import UIKit /* Strings */ func favoriteCheeseStringWithCheese(cheese: String) -> String { let resultString = "My favorite cheese is " + cheese return (resultString) } let fullSentence = favoriteCheeseStringWithCheese("cheddar") // Make fullSentence say "My favorite cheese is cheddar." /* Arrays & Dictionaries */ var numberArray = [1, 2, 3, 4] // Add 5 to this array numberArray.append(5) var numberDictionary = [1 : "one", 2 : "two", 3 : "three", 4 : "four"] // Add 5 : "five" to this dictionary numberDictionary [5]="five" /* Loops */ // Use a closed range loop to print 1 - 10, inclusively for i in 1...10{ println(i) } // Use a half-closed range loop to print 1 - 10, inclusively for i in 1..<11{ print(i) } let worf = [ "name": "Worf", "rank": "lieutenant", "information": "son of Mogh, slayer of Gowron", "favorite drink": "prune juice", "quote" : "Today is a good day to die."] let picard = [ "name": "Jean-Luc Picard", "rank": "captain", "information": "Captain of the USS Enterprise", "favorite drink": "tea, Earl Grey, hot"] let characters = [worf, picard] func favoriteDrinksArrayForCharacters(characters:Array<Dictionary<String, String>>) -> Array<String> { // return an array of favorite drinks, like ["prune juice", "tea, Earl Grey, hot"] var drinkArray = [String]() for character in characters { if let drink = character["favorite drink"] { drinkArray.append(drink) } } return drinkArray } let favoriteDrinks = favoriteDrinksArrayForCharacters(characters) favoriteDrinks /* Functions */ // Make a function that inputs an array of strings and outputs the strings separated by a semicolon let strings = ["milk", "eggs", "bread", "challah"] func stringOutput(stringArray:[String]) -> String{ let stringRepresentation = ";".join(stringArray) return stringRepresentation } let expectedOutput = "milk;eggs;bread;challah" stringOutput(strings) /* Closures */ let cerealArray = ["Golden Grahams", "Cheerios", "Trix", "Cap'n Crunch OOPS! All Berries", "Cookie Crisp"] // Use a closure to sort this array alphabetically /*let wizardsSortedByDarkArtsGrade = sorted(wizardsFromDatabase, {(student1: HogwartsStudent, student2: HogwartsStudent) -> Bool in return student1.darkArtsGrade > student2.darkArtsGrade })*/ let cerealArraySorting = sorted(cerealArray, { (a, b) -> Bool in return a<b })
mit
fd032a89f31db1294b382c99944dfab8
20.649123
131
0.675041
3.461431
false
false
false
false
LunarLincoln/nodekit-darwin-lite
src/nodekit/NKScripting/util/NKArchive/NKAR_EndRecord.swift
2
2894
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * Portions Copyright (c) 2015 lazyapps. 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. */ struct NKAR_EndRecord { let numEntries: UInt16 let centralDirectoryOffset: UInt32 } extension NKAR_EndRecord { /* ZIP FILE FORMAT: CENTRAL DIRECTORY AT END OF THE FILE end of central dir signature 4 bytes (0x06054b50) number of this disk 2 bytes number of the disk with the start of the central directory 2 bytes total number of entries in the central directory on this disk 2 bytes total number of entries in the central directory 2 bytes size of the central directory 4 bytes offset of start of central directory with respect to the starting disk number 4 bytes .ZIP file comment length 2 bytes .ZIP file comment (variable size) */ static let signature: [UInt8] = [0x06, 0x05, 0x4b, 0x50] static func findEndRecordInBytes(_ bytes: UnsafePointer<UInt8>, length: Int) -> NKAR_EndRecord? { var reader = NKAR_BytesReader(bytes: bytes, index: length - 1 - signature.count) let maxTry = Int(UInt16.max) let minReadTo = max(length-maxTry, 0) let rng = 0..<4 let indexFound: Bool = { while reader.index > minReadTo { for i in rng { if reader.byteb() != self.signature[i] { break } if i == (rng.upperBound - 1) { reader.skip(1); return true } } } return false }() if !indexFound { return nil } reader.skip(4) let numDisks = reader.le16() reader.skip(2) reader.skip(2) let numEntries = reader.le16() reader.skip(4) let centralDirectoryOffset = reader.le32() if numDisks > 1 { return nil } return NKAR_EndRecord(numEntries: numEntries, centralDirectoryOffset: centralDirectoryOffset) } }
apache-2.0
d95310537b28baa2a2e5bf5679ce3be8
28.530612
101
0.581202
4.564669
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/PeekAndPop/PeekTableVC.swift
1
2799
@objcMembers class PeekTableVC: HLCommonVC, UITableViewDataSource, UITableViewDelegate, PeekVCProtocol { var commitBlock: (() -> Void)? weak var viewControllerToShowBrowser: UIViewController? @IBOutlet weak var tableView: UITableView? var items: [PeekItem] = [] var variant: HLResultVariant! { didSet { items = createItems() setDividers() if self.isViewLoaded { self.tableView?.reloadData() } } } var filter: Filter? { didSet { items = createItems() setDividers() if self.isViewLoaded { self.tableView?.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() tableView?.allowsSelection = false tableView?.hl_registerNib(withName: PeekHotelRatingCell.hl_reuseIdentifier()) tableView?.hl_registerNib(withName: PeekHotelPriceCell.hl_reuseIdentifier()) tableView?.hl_registerNib(withName: PeekHotelMapCell.hl_reuseIdentifier()) tableView?.hl_registerNib(withName: PeekPhotoCell.hl_reuseIdentifier()) } internal func createItems() -> [PeekItem] { return [] } private func setDividers() { for i in 0..<items.count { let item = items[i] item.shouldDrawSeparator = shouldAddSeparator(index: i) } } private func shouldAddSeparator(index: Int) -> Bool { if index >= items.count - 1 { return false } let item = items[index] if item is MapPeekItem || item is PhotoPeekItem || item is AccomodationPeekItem { return false } let nextItem = items[index + 1] if nextItem is MapPeekItem || nextItem is PhotoPeekItem { return false } return true } // MARK: - Public func heightForVariant(_ variant: HLResultVariant!, peekWidth: CGFloat) -> CGFloat { var heightToReturn: CGFloat = 0.0 for item in items { heightToReturn += item.height(width: peekWidth, variant: variant) } return heightToReturn } // MARK: - UITableViewDataSource methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = items[indexPath.row] let cell = item.cell(tableView: tableView) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let item = items[indexPath.row] return item.height(width: tableView.frame.width, variant: variant) } }
mit
d28d839e8667d54e9bba1f8e209f325f
27.561224
100
0.608789
4.989305
false
false
false
false
Azero123/JW-Broadcasting
JW Broadcasting/AudioCategoryController.swift
1
13267
// // AudioCategoryController.swift // JW Broadcasting // // Created by Austin Zelenka on 12/17/15. // Copyright © 2015 xquared. All rights reserved. // import UIKit import AVKit class AudioCategoryController: UIViewController, UITableViewDelegate, UITableViewDataSource{ var categoryIndex=0 var previousLanguageCode=languageCode let images=["newsongs-singtojehovah","piano-singtojehovah","vocals-singtojehovah","kingdommelodies","drama","readings"] var playAll=false var shuffle=false var currentSongID=0 var nextSongID=0 var smartPlayer = SuperMediaPlayer() @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var BackgroundEffectView: UIVisualEffectView! @IBOutlet weak var categoryTitle: UILabel! @IBOutlet weak var subLabel: UILabel! @IBOutlet weak var categoryImage: UIImageView! @IBOutlet weak var playAllButton: UIButton! @IBOutlet weak var shuffleButton: UIButton! override func viewDidLoad() { super.viewDidLoad() playAllButton.clipsToBounds=false shuffleButton.clipsToBounds=false shuffleButton.titleLabel?.clipsToBounds=false let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" let title=categoryTitleCorrection(unfold("\(AudioDataURL)|category|subcategories|\(categoryIndex)|name") as! String) self.categoryTitle.text=title.componentsSeparatedByString("-")[0] if (title.componentsSeparatedByString("-").count>1){ self.subLabel.text=title.componentsSeparatedByString("-")[1] } else { self.subLabel.text="" } self.categoryImage.image=UIImage(named: images[categoryIndex]) //self.backgroundImageView.image=UIImage(named: images[categoryIndex]) self.categoryImage.contentMode = .ScaleToFill self.categoryImage.layoutIfNeeded() self.categoryImage.layer.shadowColor=UIColor.blackColor().CGColor self.categoryImage.layer.shadowOpacity=0.25 self.categoryImage.layer.shadowRadius=10 let playAllLabel=UILabel(frame: CGRect(x: 0, y: 70, width: 100, height: 50)) playAllLabel.text=unfold("\(base)/\(version)/translations/\(languageCode)|translations|\(languageCode)|itemPlayAllTitle") as? String self.playAllButton.addSubview(playAllLabel) playAllLabel.font=UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) playAllLabel.center=CGPoint(x: self.playAllButton.frame.size.width/2, y: playAllLabel.center.y) playAllLabel.textAlignment = .Center let shuffleLabel=UILabel(frame: CGRect(x: 0, y: 70, width: 100, height: 50)) shuffleLabel.text=unfold("\(base)/\(version)/translations/\(languageCode)|translations|\(languageCode)|itemShuffleTitle") as? String self.shuffleButton.addSubview(shuffleLabel) shuffleLabel.font=UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) shuffleLabel.center=CGPoint(x: self.playAllButton.frame.size.width/2, y: playAllLabel.center.y) shuffleLabel.textAlignment = .Center playAllButton.addTarget(self, action: "playAllButton:", forControlEvents: UIControlEvents.PrimaryActionTriggered) shuffleButton.addTarget(self, action: "shuffleButton:", forControlEvents: UIControlEvents.PrimaryActionTriggered) let guide=UIFocusGuide() guide.preferredFocusedView=playAllButton //guide.layoutFrame=CGRect(x: -100, y: -500, width: 200, height: 800) playAllButton.addLayoutGuide(guide) guide.trailingAnchor.constraintEqualToAnchor(playAllButton.trailingAnchor, constant: 0).active=true guide.topAnchor.constraintEqualToAnchor(playAllButton.topAnchor, constant: -1000).active=true guide.bottomAnchor.constraintEqualToAnchor(playAllButton.bottomAnchor, constant: 0).active=true guide.leadingAnchor.constraintEqualToAnchor(playAllButton.leadingAnchor, constant: 0).active=true } override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { print("began") for item in presses { if item.type == .Menu { print("start fade out") fadeVolume() playAll=false shuffle=false } } } override func viewWillAppear(animated: Bool) { print("view did appear") playAll=true shuffle=false if (previousLanguageCode != languageCode){ renewContent() } previousLanguageCode=languageCode self.view.hidden=false } override func viewDidDisappear(animated: Bool) { // self.player?.removeObserver(self, forKeyPath: "status") self.view.hidden=true } func renewContent(){ //http://mediator.jw.org/v1/categories/E/Audio?detailed=1 self.categoryImage.image=UIImage(named: images[categoryIndex]) self.backgroundImageView.image=UIImage(named: images[categoryIndex]) self.categoryImage.contentMode = .ScaleToFill self.categoryImage.layoutIfNeeded() /* fetchDataUsingCache(AudioDataURL, downloaded: { dispatch_async(dispatch_get_main_queue()) { } })*/ } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" let numberOfItems=unfold("\(AudioDataURL)|category|subcategories|\(categoryIndex)|media|count") as? Int if (numberOfItems != nil){ return numberOfItems! } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell=tableView.dequeueReusableCellWithIdentifier("item", forIndexPath: indexPath) cell.tag=indexPath.row let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" let title=unfold("\(AudioDataURL)|category|subcategories|\(categoryIndex)|media|\(indexPath.row)|title") as? String let extraction=titleExtractor(title!) print(extraction) var visualSongNumber:String?=nil if (extraction["visualNumber"] != nil){ visualSongNumber=extraction["visualNumber"]!//Int(extraction["visualNumber"]!) } let attributedString=NSMutableAttributedString(string: "\(extraction["correctedTitle"]!)\n", attributes: nil) let imageURL=unfold(nil, instructions: ["\(AudioDataURL)","category","subcategories",categoryIndex,"media",indexPath.row,"images",["sqr","sqs","cvr",""],["sm","md","lg","xs",""]]) as? String if (visualSongNumber != nil && (unfold("\(AudioDataURL)|category|subcategories|\(categoryIndex)|name") as! String).containsString("Sing to Jehovah")){ cell.textLabel?.numberOfLines=2 if (languageCode == "E"){ let attributes=[NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1),NSForegroundColorAttributeName:UIColor.grayColor()] attributedString.appendAttributedString(NSMutableAttributedString(string: "Song: \(visualSongNumber!)", attributes: attributes)) } else { attributedString.appendAttributedString(NSMutableAttributedString(string: "\(visualSongNumber!)", attributes: [NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1),NSForegroundColorAttributeName:UIColor.grayColor()])) } if (extraction["parentheses"] != nil){ attributedString.appendAttributedString(NSMutableAttributedString(string: "\(extraction["parentheses"]!)", attributes: [NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1),NSForegroundColorAttributeName:UIColor.grayColor()])) } //[NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1),NSForegroundColorAttributeName:UIColor.grayColor()] cell.textLabel?.attributedText=attributedString } else if (extraction["parentheses"] != nil){ cell.textLabel?.numberOfLines=2 attributedString.appendAttributedString(NSMutableAttributedString(string: "\(extraction["parentheses"]!)", attributes: [NSFontAttributeName : UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1),NSForegroundColorAttributeName:UIColor.grayColor()])) cell.textLabel?.attributedText=attributedString } else { //cell.textLabel?.numberOfLines=0 cell.textLabel?.text=attributedString.string } cell.detailTextLabel?.font=UIFont.preferredFontForTextStyle(UIFontTextStyleBody)//cell.detailTextLabel?.font.fontWithSize(30) cell.detailTextLabel?.text=unfold("\(AudioDataURL)|category|subcategories|\(categoryIndex)|media|\(indexPath.row)|durationFormattedHHMM") as? String //cell.imageView?.image=UIImage(named: "Singing") if (imageURL != nil){ fetchDataUsingCache(imageURL!, downloaded: { dispatch_async(dispatch_get_main_queue()) { if (cell.tag == indexPath.row){ cell.imageView?.image = imageUsingCache(imageURL!) cell.layoutIfNeeded() cell.layoutSubviews() cell.imageView?.layoutIfNeeded() } } }) } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 90 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { smartPlayer.player.removeAllItems() nextSongID=indexPath.row playAll=false shuffle=false playNextSong() self.smartPlayer.dismissWhenFinished=true self.smartPlayer.finishedPlaying = {() in } smartPlayer.playIn(self) } func playNextSong(){ let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" currentSongID=nextSongID //player?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.Prior, context: nil) //smartPlayer.nextDictionary=unfold("\(AudioDataURL)|category|subcategories|\(categoryIndex)|media|\(nextSongID)") as? NSDictionary smartPlayer.updatePlayerUsingDictionary((unfold("\(AudioDataURL)|category|subcategories|\(categoryIndex)|media|\(nextSongID)") as? NSDictionary)!) } func fadeVolume(){ self.smartPlayer.player.volume=(self.smartPlayer.player.volume)-0.05 if (self.smartPlayer.player.volume>0){ self.performSelector("fadeVolume", withObject: nil, afterDelay: 0.02) } else { self.performSelector("restoreVolume", withObject: nil, afterDelay: 0.5) } } func restoreVolume(){ self.smartPlayer.player.volume=1 } @IBAction func playAllButton(sender: AnyObject) { playAll=true nextSongID=0 playNextSong() self.smartPlayer.dismissWhenFinished=false self.smartPlayer.finishedPlaying = {() in self.nextSongID++ self.playNextSong() } self.smartPlayer.playIn(self) } @IBAction func shuffleButton(sender: AnyObject) { playAll=true shuffle=true self.smartPlayer.dismissWhenFinished=false let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" self.nextSongID=Int(arc4random_uniform(UInt32(unfold("\(AudioDataURL)|category|subcategories|\(self.categoryIndex)|media|count") as! Int)) + 1) playNextSong() self.smartPlayer.finishedPlaying = {() in let category="Audio" let categoriesDirectory=base+"/"+version+"/categories/"+languageCode let AudioDataURL=categoriesDirectory+"/"+category+"?detailed=1" self.nextSongID=Int(arc4random_uniform(UInt32(unfold("\(AudioDataURL)|category|subcategories|\(self.categoryIndex)|media|count") as! Int)) + 1) self.playNextSong() } self.smartPlayer.playIn(self) } }
mit
f2d82fe81b771726d256991480c80489
42.352941
269
0.657395
5.506849
false
false
false
false
edx/edx-app-ios
Source/MicrosoftSocial.swift
1
4840
// // MicrosoftSocial.swift // edX // // Created by Salman on 07/08/2018. // Copyright © 2018 edX. All rights reserved. // // import UIKit import MSAL typealias MSLoginCompletionHandler = (MSALAccount?, _ accessToken: String?, Error?) -> Void extension MSALError { enum custom: Int { case publicClientApplicationCreation = -500010 case noUserSignedIn = -500011 case userNotFound = -500012 } } class MicrosoftSocial: NSObject { static let shared = MicrosoftSocial() private let kScopes = ["User.Read", "email"] private var result: MSALResult? private override init() { super.init() NotificationCenter.default.oex_addObserver(observer: self, name: NSNotification.Name.OEXSessionEnded.rawValue) { (_, Observer, _) in Observer.logout() } } func loginFromController(controller : UIViewController, completion: @escaping MSLoginCompletionHandler) { do { let clientApplication = try createClientApplication() let webParameters = MSALWebviewParameters(parentViewController: controller) let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: webParameters) clientApplication.acquireToken(with: parameters) { (result: MSALResult?, error: Error?) in guard let result = result, error == nil else { completion(nil, nil, error) return } self.result = result // In the initial acquire token call we'll want to look at the account object // that comes back in the result. let account = result.account completion(account, result.accessToken, nil) } } catch let createApplicationError { completion(nil, nil, createApplicationError) } } private func createClientApplication() throws -> MSALPublicClientApplication { // Initialize a MSALPublicClientApplication with a given clientID and authority guard let kClientID = OEXConfig.shared().microsoftConfig.appID else { throw NSError(domain: "MSALErrorDomain", code: MSALError.custom.publicClientApplicationCreation.rawValue, userInfo: nil) } // This MSALPublicClientApplication object is the representation of your app listing, in MSAL. For your own app // go to the Microsoft App Portal to register your own applications with their own client IDs. let configuration = MSALPublicClientApplicationConfig(clientId: kClientID) do { return try MSALPublicClientApplication(configuration: configuration) } catch _ as NSError { throw NSError(domain: "MSALErrorDomain", code: MSALError.custom.publicClientApplicationCreation.rawValue, userInfo: nil) } } @discardableResult private func currentAccount() throws -> MSALAccount { let clientApplication = try createClientApplication() var account: MSALAccount? do { account = try clientApplication.allAccounts().first } catch _ as NSError { throw NSError(domain: "MSALErrorDomain", code: MSALError.custom.userNotFound.rawValue, userInfo: nil) } guard let currentAccount = account else { throw NSError(domain: "MSALErrorDomain", code: MSALError.custom.noUserSignedIn.rawValue, userInfo: nil) } return currentAccount } func getUser(completion: (_ user: MSALAccount) -> Void) { guard let user = result?.account else { return } completion(user) } private func logout() { do { let account = try? currentAccount() // Signing out an account requires removing this from MSAL and cleaning up any extra state that the application // might be maintaining outside of MSAL for the account. // This remove call only removes the account's tokens for this client ID in the local keychain cache. It does // not sign the account completely out of the device or remove tokens for the account for other client IDs. If // you have multiple applications sharing a client ID this will make the account effectively "disappear" for // those applications as well if you are using Keychain Cache Sharing (not currently available in MSAL // build preview). We do not recommend sharing a ClientID among multiple apps. if let account = account { let application = try createClientApplication() try application.remove(account) } } catch let error { Logger.logError("Logout", "Received error signing user out:: \(error)") } } }
apache-2.0
b9553a5ee008802133c2990c85dbf0a9
38.991736
140
0.648688
5.248373
false
false
false
false
orta/Elasticity
ElastiTV/ARDebugButton.swift
1
1319
// // ARDebugButton.swift // Elasticity // // Created by Orta Therox on 12/09/2015. // Copyright © 2015 Artsy. All rights reserved. // import UIKit class ARDebugButton: UIButton { override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { for item in presses { if item.type == UIPressType.Select { self.backgroundColor = UIColor.greenColor() print(item.force) } } } override func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { for item in presses { if item.type == UIPressType.Select { self.backgroundColor = UIColor.whiteColor() } } } override func pressesChanged(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { for item in presses { if item.type == UIPressType.Select { self.backgroundColor = UIColor.blackColor() print(item.force) } } } override func pressesCancelled(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { for item in presses { if item.type == UIPressType.Select { self.backgroundColor = UIColor.redColor() } } } }
mit
c670819b93b70cdcb75a82ed95c334e5
26.458333
93
0.57132
4.827839
false
false
false
false
alexzatsepin/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/UGC/UGCAddReview/UGCAddReviewController.swift
2
4210
@objc(MWMGCReviewSaver) protocol UGCReviewSaver { typealias onSaveHandler = (Bool) -> Void func saveUgc(model: UGCAddReviewController.Model, resultHandler: @escaping onSaveHandler) } @objc(MWMUGCAddReviewController) final class UGCAddReviewController: MWMTableViewController { typealias Model = UGCReviewModel weak var textCell: UGCAddReviewTextCell? var reviewPosted = false enum Sections { case ratings case text } @objc static func instance(model: Model, saver: UGCReviewSaver) -> UGCAddReviewController { let vc = UGCAddReviewController(nibName: toString(self), bundle: nil) vc.model = model vc.saver = saver return vc } private var model: Model! { didSet { sections = [] assert(!model.ratings.isEmpty) sections.append(.ratings) sections.append(.text) } } private var sections: [Sections] = [] private var saver: UGCReviewSaver! override func viewDidLoad() { super.viewDidLoad() configNavBar() configTableView() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if isMovingFromParentViewController && !reviewPosted { Statistics.logEvent(kStatUGCReviewCancel) } } private func configNavBar() { title = model.title navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onDone)) } private func configTableView() { tableView.register(cellClass: UGCAddReviewRatingCell.self) tableView.register(cellClass: UGCAddReviewTextCell.self) tableView.estimatedRowHeight = 48 tableView.rowHeight = UITableViewAutomaticDimension } @objc private func onDone() { guard let text = textCell?.reviewText else { assertionFailure() return } reviewPosted = true model.text = text saver.saveUgc(model: model, resultHandler: { (saveResult) in guard let nc = self.navigationController else { return } if !saveResult { nc.popViewController(animated: true) return } Statistics.logEvent(kStatUGCReviewSuccess) let onSuccess = { Toast.toast(withText: L("ugc_thanks_message_auth")).show() } let onError = { Toast.toast(withText: L("ugc_thanks_message_not_auth")).show() } let onComplete = { () -> Void in nc.popToRootViewController(animated: true) } if MWMAuthorizationViewModel.isAuthenticated() || MWMPlatform.networkConnectionType() == .none { if MWMAuthorizationViewModel.isAuthenticated() { onSuccess() } else { onError() } nc.popViewController(animated: true) } else { Statistics.logEvent(kStatUGCReviewAuthShown, withParameters: [kStatFrom: kStatAfterSave]) let authVC = AuthorizationViewController(barButtonItem: self.navigationItem.rightBarButtonItem!, sourceComponent: .UGC, successHandler: {_ in onSuccess()}, errorHandler: {_ in onError()}, completionHandler: {_ in onComplete()}) self.present(authVC, animated: true, completion: nil) } }) } override func numberOfSections(in _: UITableView) -> Int { return sections.count } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { switch sections[section] { case .ratings: return model.ratings.count case .text: return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch sections[indexPath.section] { case .ratings: let cell = tableView.dequeueReusableCell(withCellClass: UGCAddReviewRatingCell.self, indexPath: indexPath) as! UGCAddReviewRatingCell cell.model = model.ratings[indexPath.row] return cell case .text: let cell = tableView.dequeueReusableCell(withCellClass: UGCAddReviewTextCell.self, indexPath: indexPath) as! UGCAddReviewTextCell cell.reviewText = model.text textCell = cell return cell } } }
apache-2.0
31eb96ec68bc5e2d91c7ea2ddf83a96e
31.384615
139
0.663895
4.929742
false
false
false
false
KrishMunot/swift
benchmark/utils/ArgParse.swift
6
2652
//===--- ArgParse.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation public struct Arguments { public var progName: String public var positionalArgs: [String] public var optionalArgsMap: [String : String] init(_ pName: String, _ posArgs: [String], _ optArgsMap: [String : String]) { progName = pName positionalArgs = posArgs optionalArgsMap = optArgsMap } } /// Using Process.arguments, returns an Arguments struct describing /// the arguments to this program. If we fail to parse arguments, we /// return nil. /// /// We assume that optional switch args are of the form: /// /// --opt-name[=opt-value] /// -opt-name[=opt-value] /// /// with opt-name and opt-value not containing any '=' signs. Any /// other option passed in is assumed to be a positional argument. public func parseArgs(_ validOptions: [String]? = nil) -> Arguments? { let progName = Process.arguments[0] var positionalArgs = [String]() var optionalArgsMap = [String : String]() // For each argument we are passed... var passThroughArgs = false for arg in Process.arguments[1..<Process.arguments.count] { // If the argument doesn't match the optional argument pattern. Add // it to the positional argument list and continue... if passThroughArgs || !arg.characters.starts(with: "-".characters) { positionalArgs.append(arg) continue } if arg == "--" { passThroughArgs = true continue } // Attempt to split it into two components separated by an equals sign. let components = arg.components(separatedBy: "=") let optionName = components[0] if validOptions != nil && !validOptions!.contains(optionName) { print("Invalid option: \(arg)") return nil } var optionVal : String switch components.count { case 1: optionVal = "" case 2: optionVal = components[1] default: // If we do not have two components at this point, we can not have // an option switch. This is an invalid argument. Bail! print("Invalid option: \(arg)") return nil } optionalArgsMap[optionName] = optionVal } return Arguments(progName, positionalArgs, optionalArgsMap) }
apache-2.0
b3536fc56067c1576cf16611c5e3bcf1
33
80
0.645173
4.548885
false
false
false
false
fizx/jane
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Core/ByteBuffer.swift
2
2127
/* * Copyright 2016, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if SWIFT_PACKAGE import CgRPC #endif import Foundation // for String.Encoding /// Representation of raw data that may be sent and received using gRPC public class ByteBuffer { /// Pointer to underlying C representation let underlyingByteBuffer: UnsafeMutableRawPointer /// Creates a ByteBuffer from an underlying C representation. /// The ByteBuffer takes ownership of the passed-in representation. /// /// - Parameter underlyingByteBuffer: the underlying C representation init(underlyingByteBuffer: UnsafeMutableRawPointer) { self.underlyingByteBuffer = underlyingByteBuffer } /// Creates a byte buffer that contains a copy of the contents of `data` /// /// - Parameter data: the data to store in the buffer public init(data: Data) { var underlyingByteBuffer: UnsafeMutableRawPointer? data.withUnsafeBytes { bytes in underlyingByteBuffer = cgrpc_byte_buffer_create_by_copying_data(bytes, data.count) } self.underlyingByteBuffer = underlyingByteBuffer! } deinit { cgrpc_byte_buffer_destroy(underlyingByteBuffer) } /// Gets data from the contents of the ByteBuffer /// /// - Returns: data formed from the ByteBuffer contents public func data() -> Data? { var length: Int = 0 guard let bytes = cgrpc_byte_buffer_copy_data(underlyingByteBuffer, &length) else { return nil } return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: length, deallocator: .free) } }
mit
f604cb7d152bf85978cc6dc8da80709e
33.868852
88
0.723554
4.716186
false
false
false
false
FlameTinary/weiboSwift
weiboSwift/Pods/QorumLogs/QorumLogs.swift
1
12766
// // QorumLogs.swift // Qorum // // Created by Goktug Yilmaz on 27/08/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) || os(tvOS) import UIKit #endif /// Debug error level private let kLogDebug : String = "Debug"; /// Info error level private let kLogInfo : String = "Info"; /// Warning error level private let kLogWarning : String = "Warning"; /// Error error level private let kLogError : String = "Error"; public struct QorumLogs { /// While enabled QorumOnlineLogs does not work public static var enabled = false /// 1 to 4 public static var minimumLogLevelShown = 1 /// Change the array element with another UIColor. 0 is info gray, 5 is purple, rest are log levels public static var colorsForLogLevels: [QLColor] = [ QLColor(r: 120, g: 120, b: 120), //0 QLColor(r: 0, g: 180, b: 180), //1 QLColor(r: 0, g: 150, b: 0), //2 QLColor(r: 255, g: 190, b: 0), //3 QLColor(r: 255, g: 0, b: 0), //4 QLColor(r: 160, g: 32, b: 240)] //5 private static var showFiles = [String]() //========================================================================================================== // MARK: - Public Methods //========================================================================================================== /// Ignores all logs from other files public static func onlyShowTheseFiles(fileNames: Any...) { minimumLogLevelShown = 1 let showFiles = fileNames.map {fileName in return fileName as? String ?? { let classString: String = { if let obj: AnyObject = fileName as? AnyObject { let classString = String(type(of: obj)) return classString.ns.pathExtension } else { return String(fileName) } }() return classString }() } self.showFiles = showFiles print(ColorLog.colorizeString("QorumLogs: Only Showing: \(showFiles)", colorId: 5)) } /// Ignores all logs from other files public static func onlyShowThisFile(fileName: Any) { onlyShowTheseFiles(fileName) } /// Test to see if its working public static func test() { let oldDebugLevel = minimumLogLevelShown minimumLogLevelShown = 1 QL1(kLogDebug) QL2(kLogInfo) QL3(kLogWarning) QL4(kLogError) minimumLogLevelShown = oldDebugLevel } //========================================================================================================== // MARK: - Private Methods //========================================================================================================== private static func shouldPrintLine(level level: Int, fileName: String) -> Bool { if !QorumLogs.enabled { return false } else if QorumLogs.minimumLogLevelShown <= level { return QorumLogs.shouldShowFile(fileName) } else { return false } } private static func shouldShowFile(fileName: String) -> Bool { return QorumLogs.showFiles.isEmpty || QorumLogs.showFiles.contains(fileName) } } /// Debug error level private let kOnlineLogDebug : String = "1Debug"; /// Info error level private let kOnlineLogInfo : String = "2Info"; /// Warning error level private let kOnlineLogWarning : String = "3Warning"; /// Error error level private let kOnlineLogError : String = "4Error"; public struct QorumOnlineLogs { private static let appVersion = versionAndBuild() private static var googleFormLink: String! private static var googleFormAppVersionField: String! private static var googleFormUserInfoField: String! private static var googleFormMethodInfoField: String! private static var googleFormErrorTextField: String! /// Online logs does not work while QorumLogs is enabled public static var enabled = false /// 1 to 4 public static var minimumLogLevelShown = 1 /// Empty dictionary, add extra info like user id, username here public static var extraInformation = [String: String]() //========================================================================================================== // MARK: - Public Methods //========================================================================================================== /// Test to see if its working public static func test() { let oldDebugLevel = minimumLogLevelShown minimumLogLevelShown = 1 QL1(kLogDebug) QL2(kLogInfo) QL3(kLogWarning) QL4(kLogError) minimumLogLevelShown = oldDebugLevel } /// Setup Google Form links public static func setupOnlineLogs(formLink formLink: String, versionField: String, userInfoField: String, methodInfoField: String, textField: String) { googleFormLink = formLink googleFormAppVersionField = versionField googleFormUserInfoField = userInfoField googleFormMethodInfoField = methodInfoField googleFormErrorTextField = textField } //========================================================================================================== // MARK: - Private Methods //========================================================================================================== private static func sendError<T>(classInformation classInformation: String, textObject: T, level: String) { var text = "" if let stringObject = textObject as? String { text = stringObject } let versionLevel = (appVersion + " - " + level) let url = NSURL(string: googleFormLink) var postData = googleFormAppVersionField + "=" + versionLevel postData += "&" + googleFormUserInfoField + "=" + extraInformation.description postData += "&" + googleFormMethodInfoField + "=" + classInformation postData += "&" + googleFormErrorTextField + "=" + text let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding) #if os(OSX) if kCFCoreFoundationVersionNumber > kCFCoreFoundationVersionNumber10_10 { let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) task.resume() } else { NSURLConnection(request: request, delegate: nil)?.start() } #elseif os(iOS) NSURLSession.sharedSession().dataTaskWithRequest(request).resume(); #endif let printText = "OnlineLogs: \(extraInformation.description) - \(versionLevel) - \(classInformation) - \(text)" print(" \(ColorLog.colorizeString(printText, colorId: 5))\n", terminator: "") } private static func shouldSendLine(level level: Int, fileName: String) -> Bool { if !QorumOnlineLogs.enabled { return false } else if QorumOnlineLogs.minimumLogLevelShown <= level { return QorumLogs.shouldShowFile(fileName) } else { return false } } } ///Detailed logs only used while debugging public func QL1<T>(debug: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(debug,file: file,function: function,line: line,level:1) } ///General information about app state public func QL2<T>(info: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(info,file: file,function: function,line: line,level:2) } ///Indicates possible error public func QL3<T>(warning: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(warning,file: file,function: function,line: line,level:3) } ///En unexpected error occured public func QL4<T>(error: T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { QLManager(error,file: file,function: function,line: line,level:4) } private func printLog<T>(informationPart: String, text: T, level: Int) { print(" \(ColorLog.colorizeString(informationPart, colorId: 0))", terminator: "") print(" \(ColorLog.colorizeString(text, colorId: level))\n", terminator: "") } ///===== public func QLShortLine(file: String = #file, _ function: String = #function, _ line: Int = #line) { let lineString = "======================================" QLineManager(lineString, file: file, function: function, line: line) } ///+++++ public func QLPlusLine(file: String = #file, _ function: String = #function, _ line: Int = #line) { let lineString = "+++++++++++++++++++++++++++++++++++++" QLineManager(lineString, file: file, function: function, line: line) } ///Print data with level private func QLManager<T>(debug: T, file: String, function: String, line: Int, level : Int){ let levelText : String; switch (level) { case 1: levelText = kOnlineLogDebug case 2: levelText = kOnlineLogInfo case 3: levelText = kOnlineLogWarning case 4: levelText = kOnlineLogError default: levelText = kOnlineLogDebug } let fileExtension = file.ns.lastPathComponent.ns.pathExtension let filename = file.ns.lastPathComponent.ns.stringByDeletingPathExtension if QorumLogs.shouldPrintLine(level: level, fileName: filename) { let informationPart: String informationPart = "\(filename).\(fileExtension):\(line) \(function):" printLog(informationPart, text: debug, level: level) } else if QorumOnlineLogs.shouldSendLine(level: level, fileName: filename) { let informationPart = "\(filename).\(function)[\(line)]" QorumOnlineLogs.sendError(classInformation: informationPart, textObject: debug, level: levelText) } } ///Print line private func QLineManager(lineString : String, file: String, function: String, line: Int){ let fileExtension = file.ns.lastPathComponent.ns.pathExtension let filename = file.ns.lastPathComponent.ns.stringByDeletingPathExtension if QorumLogs.shouldPrintLine(level: 2, fileName: filename) { let informationPart: String informationPart = "\(filename).\(fileExtension):\(line) \(function):" printLog(informationPart, text: lineString, level: 5) } } private struct ColorLog { private static let ESCAPE = "\u{001b}[" private static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color private static let RESET_BG = ESCAPE + "bg;" // Clear any background color private static let RESET = ESCAPE + ";" // Clear any foreground or background color static func colorizeString<T>(object: T, colorId: Int) -> String { return "\(ESCAPE)fg\(QorumLogs.colorsForLogLevels[colorId].redColor),\(QorumLogs.colorsForLogLevels[colorId].greenColor),\(QorumLogs.colorsForLogLevels[colorId].blueColor);\(object)\(RESET)" } } private func versionAndBuild() -> String { let version = NSBundle.mainBundle().infoDictionary? ["CFBundleShortVersionString"] as! String let build = NSBundle.mainBundle().infoDictionary? [kCFBundleVersionKey as String] as! String return version == build ? "v\(version)" : "v\(version)(\(build))" } private extension String { /// Qorum Extension var ns: NSString { return self as NSString } } ///Used in color settings for QorumLogs public class QLColor { #if os(OSX) var color: NSColor #elseif os(iOS) || os(tvOS) var color: UIColor #endif public init(r: CGFloat, g: CGFloat, b: CGFloat) { #if os(OSX) color = NSColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1) #elseif os(iOS) || os(tvOS) color = UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1) #endif } public convenience init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { self.init(r: red * 255, g: green * 255, b: blue * 255) } var redColor: Int { var r: CGFloat = 0 color.getRed(&r, green: nil, blue: nil, alpha: nil) return Int(r * 255) } var greenColor: Int { var g: CGFloat = 0 color.getRed(nil, green: &g, blue: nil, alpha: nil) return Int(g * 255) } var blueColor: Int { var b: CGFloat = 0 color.getRed(nil, green: nil, blue: &b, alpha: nil) return Int(b * 255) } }
mit
e90521ca5a0e27a6ba17be73a72b25e9
34.960563
198
0.593451
4.777695
false
false
false
false
farhanpatel/firefox-ios
Extensions/NotificationService/NotificationService.swift
1
12270
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import Storage import Sync import UserNotifications private let log = Logger.browserLogger private let CategorySentTab = "org.mozilla.ios.SentTab.placeholder" class NotificationService: UNNotificationServiceExtension { var display: SyncDataDisplay! lazy var profile: ExtensionProfile = { let profile = ExtensionProfile(localName: "profile") return profile }() // This is run when an APNS notification with `mutable-content` is received. // If the app is backgrounded, then the alert notification is displayed. // If the app is foregrounded, then the notification.userInfo is passed straight to // AppDelegate.application(_:didReceiveRemoteNotification:completionHandler:) // Once the notification is tapped, then the same userInfo is passed to the same method in the AppDelegate. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { let userInfo = request.content.userInfo if Logger.logPII && log.isEnabledFor(level: .info) { // This will be visible in the Console.app when a push notification is received. NSLog("NotificationService APNS NOTIFICATION \(userInfo)") } guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else { Sentry.shared.sendWithStacktrace(message: "No notification content", tag: SentryTag.notificationService) return self.didFinish(PushMessage.accountVerified) } let queue = self.profile.queue self.display = SyncDataDisplay(content: content, contentHandler: contentHandler, tabQueue: queue) self.profile.syncDelegate = display let handler = FxAPushMessageHandler(with: profile) handler.handle(userInfo: userInfo).upon { res in self.didFinish(res.successValue, with: res.failureValue as? PushMessageError) } } func didFinish(_ what: PushMessage? = nil, with error: PushMessageError? = nil) { profile.shutdown() // We cannot use tabqueue after the profile has shutdown; // however, we can't use weak references, because TabQueue isn't a class. // Rather than changing tabQueue, we manually nil it out here. display.tabQueue = nil display.messageDelivered = false display.displayNotification(what, with: error) if !display.messageDelivered { let string = ["message": "\(what?.messageType.rawValue ?? "nil"), error=\(error?.description ?? "nil")"] Sentry.shared.send(message: "Empty notification", tag: SentryTag.notificationService, extra: string) display.displayUnknownMessageNotification() } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. didFinish(with: .timeout) } } class SyncDataDisplay { var contentHandler: ((UNNotificationContent) -> Void) var notificationContent: UNMutableNotificationContent var sentTabs: [SentTab] var tabQueue: TabQueue? var messageDelivered: Bool = false init(content: UNMutableNotificationContent, contentHandler: @escaping (UNNotificationContent) -> Void, tabQueue: TabQueue) { self.contentHandler = contentHandler self.notificationContent = content self.sentTabs = [] self.tabQueue = tabQueue } func displayNotification(_ message: PushMessage? = nil, with error: PushMessageError? = nil) { guard let message = message, error == nil else { Sentry.shared.send(message: "PushMessageError", tag: SentryTag.notificationService, description: "\(error?.description ??? "nil")") return displayUnknownMessageNotification() } switch message { case .accountVerified: displayAccountVerifiedNotification() case .deviceConnected(let deviceName): displayDeviceConnectedNotification(deviceName) case .deviceDisconnected(let deviceName): displayDeviceDisconnectedNotification(deviceName) case .thisDeviceDisconnected: displayThisDeviceDisconnectedNotification() case .collectionChanged(let collections): if collections.contains("clients") { displaySentTabNotification() } else { displayUnknownMessageNotification() } default: displayUnknownMessageNotification() break } } } extension SyncDataDisplay { func displayDeviceConnectedNotification(_ deviceName: String) { presentNotification(title: Strings.FxAPush_DeviceConnected_title, body: Strings.FxAPush_DeviceConnected_body, bodyArg: deviceName) } func displayDeviceDisconnectedNotification(_ deviceName: String?) { if let deviceName = deviceName { presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_body, bodyArg: deviceName) } else { // We should never see this branch presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_UnknownDevice_body) } } func displayThisDeviceDisconnectedNotification() { presentNotification(title: Strings.FxAPush_DeviceDisconnected_ThisDevice_title, body: Strings.FxAPush_DeviceDisconnected_ThisDevice_body) } func displayAccountVerifiedNotification() { presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } func displayUnknownMessageNotification() { // if, by any change we haven't dealt with the message, then perhaps we // can recycle it as a sent tab message. if sentTabs.count > 0 { displaySentTabNotification() } else { presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } Sentry.shared.sendWithStacktrace(message: "Unknown notification message", tag: SentryTag.notificationService) } } extension SyncDataDisplay { func displaySentTabNotification() { // We will need to be more precise about calling these SentTab alerts // once we are a) detecting different types of notifications and b) adding actions. // For now, we need to add them so we can handle zero-tab sent-tab-notifications. notificationContent.categoryIdentifier = CategorySentTab var userInfo = notificationContent.userInfo // Add the tabs we've found to userInfo, so that the AppDelegate // doesn't have to do it again. let serializedTabs = sentTabs.flatMap { t -> NSDictionary? in return [ "title": t.title, "url": t.url.absoluteString, "displayURL": t.url.absoluteDisplayString, "deviceName": t.deviceName as Any, ] as NSDictionary } func present(_ tabs: [NSDictionary]) { if !tabs.isEmpty { userInfo["sentTabs"] = tabs as NSArray } notificationContent.userInfo = userInfo presentSentTabsNotification(tabs) } let center = UNUserNotificationCenter.current() center.getDeliveredNotifications { notifications in let extra = ["notificationCount": "\(notifications.count)"] Sentry.shared.send(message: "deliveredNotification count", tag: SentryTag.notificationService, extra: extra) // Let's deal with sent-tab-notifications let sentTabNotifications = notifications.filter { $0.request.content.categoryIdentifier == CategorySentTab } // We can delete zero tab sent-tab-notifications let emptyTabNotificationsIds = sentTabNotifications.filter { $0.request.content.userInfo["sentTabs"] == nil }.map { $0.request.identifier } center.removeDeliveredNotifications(withIdentifiers: emptyTabNotificationsIds) // The one we've just received (but not delivered) may not have any tabs in it either // e.g. if the previous one consumed two tabs. if serializedTabs.count == 0 { // In that case, we try and recycle an existing notification (one that has a tab in it). if let firstNonEmpty = sentTabNotifications.first(where: { $0.request.content.userInfo["sentTabs"] != nil }), let previouslyDeliveredTabs = firstNonEmpty.request.content.userInfo["sentTabs"] as? [NSDictionary] { center.removeDeliveredNotifications(withIdentifiers: [firstNonEmpty.request.identifier]) return present(previouslyDeliveredTabs) } } // We have tabs in this notification, or we couldn't recycle an existing one that does. present(serializedTabs) } } func presentSentTabsNotification(_ tabs: [NSDictionary]) { let title: String let body: String if tabs.count == 0 { title = Strings.SentTab_NoTabArrivingNotification_title body = Strings.SentTab_NoTabArrivingNotification_body } else { let deviceNames = Set(tabs.flatMap { $0["deviceName"] as? String }) if let deviceName = deviceNames.first, deviceNames.count == 1 { title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName) } else { title = Strings.SentTab_TabArrivingNotification_NoDevice_title } if tabs.count == 1 { // We give the fallback string as the url, // because we have only just introduced "displayURL" as a key. body = (tabs[0]["displayURL"] as? String) ?? (tabs[0]["url"] as! String) } else if deviceNames.count == 0 { body = Strings.SentTab_TabArrivingNotification_NoDevice_body } else { body = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_body, AppInfo.displayName) } } presentNotification(title: title, body: body) } func presentNotification(title: String, body: String, titleArg: String? = nil, bodyArg: String? = nil) { func stringWithOptionalArg(_ s: String, _ a: String?) -> String { if let a = a { return String(format: s, a) } return s } notificationContent.title = stringWithOptionalArg(title, titleArg) notificationContent.body = stringWithOptionalArg(body, bodyArg) // This is the only place we call the contentHandler. contentHandler(notificationContent) // This is the only place we change messageDelivered. We can check if contentHandler hasn't be called because of // our logic (rather than something funny with our environment, or iOS killing us). messageDelivered = true } } extension SyncDataDisplay: SyncDelegate { func displaySentTab(for url: URL, title: String, from deviceName: String?) { if url.isWebPage() { sentTabs.append(SentTab(url: url, title: title, deviceName: deviceName)) let item = ShareItem(url: url.absoluteString, title: title, favicon: nil) _ = tabQueue?.addToQueue(item) } } } struct SentTab { let url: URL let title: String let deviceName: String? }
mpl-2.0
69bb2ff9fdb0d285052e8a1f758d94f9
43.296029
143
0.651508
5.453333
false
false
false
false
FreeLadder/Ladder
Ladder_iOS/FreeSS/ImageUtil.swift
1
3878
// // ImageUtil.swift // FreeSS // // Created by YogaXiong on 2017/4/5. // Copyright © 2017年 YogaXiong. All rights reserved. // import UIKit import Photos typealias DownloaderProgressBlock = (_ recivedSize: Int64, _ totalSize: Int64) -> () typealias DownloaderCompletionHandler = (_ data: Data?, _ image: UIImage?, _ error: Error?, _ finished: Bool) -> () class ImageUtil: NSObject { static let shared = ImageUtil() //暂时 fileprivate var data: Data = Data() fileprivate var expectedContentSize: Int64 = 0 fileprivate var progressBlock: DownloaderProgressBlock? fileprivate var completionHandler: DownloaderCompletionHandler? private func authorized() -> Bool { if PHPhotoLibrary.authorizationStatus() == .authorized || PHPhotoLibrary.authorizationStatus() == .notDetermined { return true } else { return false } } private func askForAuthorization() { guard let rc = UIApplication.shared.keyWindow?.rootViewController else { return } let alertC = UIAlertController(title: "请授权", message: "允许Ladder存照片!", preferredStyle: UIAlertControllerStyle.alert) let setting = UIAlertAction(title: "去设置", style: .default) { (action) in let url = URL(string: "prefs:root=Photo&path=com.YogaXiong.FreeSS")! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } else { UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } } let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil) alertC.addAction(cancel) alertC.addAction(setting) rc.present(alertC, animated: true, completion: nil) } func downloadImage(url: URL, progressBlock: DownloaderProgressBlock?, completionHandler: DownloaderCompletionHandler?) { self.progressBlock = progressBlock self.completionHandler = completionHandler let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20) let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) let task = session.dataTask(with: request) task.resume() session.finishTasksAndInvalidate() } func save(image: UIImage, completionHandler:((Bool, Error?) -> Void)?) { if !authorized() { askForAuthorization() return } PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAsset(from: image) }) { (success, error) in if let e = error { completionHandler?(false, e) } else { completionHandler?(true, nil) } } } } extension ImageUtil: URLSessionDataDelegate { func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { expectedContentSize = response.expectedContentLength data = Data() completionHandler(.allow) UIApplication.shared.isNetworkActivityIndicatorVisible = true } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { self.data.append(data) progressBlock?(Int64(self.data.count), expectedContentSize) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let error = error { completionHandler?(data, nil , error, false) }else { completionHandler?(data, UIImage(data: data) , nil, true) } UIApplication.shared.isNetworkActivityIndicatorVisible = false } }
mpl-2.0
2f242e9ad2139c4b9fa42ddb62f0b9c5
38.234694
179
0.652276
5.161074
false
false
false
false
hirohisa/RxSwift
RxTests/RxSwiftTests/TestImplementations/Result+Equatable.swift
5
621
// // RxResult+Equatable.swift // RxSwift // // Created by Krunoslav Zaher on 4/20/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift extension RxResult : Equatable { } public func == <E>(lhs: RxResult<E>, rhs: RxResult<E>) -> Bool { switch (lhs, rhs) { case (.Success(let boxed1), .Success(let boxed2)): var val1 = boxed1.value var val2 = boxed2.value return memcmp(&val1, &val2, sizeof(E)) == 0 case (.Failure(let error1), .Failure(let error2)): return error1 === error2 default: return false } }
mit
d86e53a3bcb6414521c2036c60bbf613
21.178571
64
0.615137
3.469274
false
false
false
false
Johnykutty/SwiftLint
Source/SwiftLintFramework/Rules/RuleConfigurations/SeverityLevelsConfiguration.swift
4
1831
// // SeverityLevelsConfiguration.swift // SwiftLint // // Created by Scott Hoyt on 1/19/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation public struct SeverityLevelsConfiguration: RuleConfiguration, Equatable { public var consoleDescription: String { let errorString: String if let errorValue = error { errorString = ", error: \(errorValue)" } else { errorString = "" } return "warning: \(warning)" + errorString } public var shortConsoleDescription: String { if let errorValue = error { return "w/e: \(warning)/\(errorValue)" } return "w: \(warning)" } var warning: Int var error: Int? var params: [RuleParameter<Int>] { if let error = error { return [RuleParameter(severity: .error, value: error), RuleParameter(severity: .warning, value: warning)] } return [RuleParameter(severity: .warning, value: warning)] } public mutating func apply(configuration: Any) throws { if let configurationArray = [Int].array(of: configuration), !configurationArray.isEmpty { warning = configurationArray[0] error = (configurationArray.count > 1) ? configurationArray[1] : nil } else if let configDict = configuration as? [String: Int], !configDict.isEmpty && Set(configDict.keys).isSubset(of: ["warning", "error"]) { warning = configDict["warning"] ?? warning error = configDict["error"] } else { throw ConfigurationError.unknownConfiguration } } } public func == (lhs: SeverityLevelsConfiguration, rhs: SeverityLevelsConfiguration) -> Bool { return lhs.warning == rhs.warning && lhs.error == rhs.error }
mit
91321e0cf92915f8377ffea99287a7f2
31.678571
97
0.613115
4.680307
false
true
false
false
optimizely/swift-sdk
Sources/Utils/Constants.swift
1
3245
// // Copyright 2019-2021, Optimizely, Inc. and contributors // // 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 struct Constants { struct Attributes { static let reservedBucketIdAttribute = "$opt_bucketing_id" static let reservedBotFilteringAttribute = "$opt_bot_filtering" static let reservedUserAgent = "$opt_user_agent" } struct ODP { static let keyForVuid = "vuid" static let keyForUserId = "fs_user_id" static let eventType = "fullstack" } enum EvaluationLogType: String { case experiment = "experiment" case rolloutRule = "rule" } enum VariableValueType: String { case string case integer case double case boolean case json } enum DecisionType: String { case abTest = "ab-test" case feature = "feature" case featureVariable = "feature-variable" case allFeatureVariables = "all-feature-variables" case featureTest = "feature-test" // Decide-APIs case flag = "flag" } enum DecisionSource: String { case experiment = "experiment" case featureTest = "feature-test" case rollout = "rollout" } struct DecisionInfoKeys { static let feature = "featureKey" static let featureEnabled = "featureEnabled" static let sourceInfo = "sourceInfo" static let source = "source" static let variable = "variableKey" static let variableType = "variableType" static let variableValue = "variableValue" static let variableValues = "variableValues" // Decide-API /// The flag key for which the decision has been made for. static let flagKey = "flagKey" /// The boolean value indicating if the flag is enabled or not. static let enabled = "enabled" /// The collection of variables assocaited with the decision. static let variables = "variables" /// The variation key of the decision. This value will be nil when decision making fails. static let variationKey = "variationKey" /// The rule key of the decision. static let ruleKey = "ruleKey" /// An array of error/info/debug messages describing why the decision has been made. static let reasons = "reasons" /// The boolean value indicating an decision event has been sent for the decision. static let decisionEventDispatched = "decisionEventDispatched" } struct ExperimentDecisionInfoKeys { static let experiment = "experimentKey" static let variation = "variationKey" } }
apache-2.0
dac1bfc38d5370bdace134257068ad58
33.521277
97
0.645609
4.81454
false
true
false
false
Zerofinancial/relay
Relay/LogRecord.swift
1
4641
// // LogRecord.swift // Relay // // Created by Evan Kimia on 1/8/17. // Copyright © 2017 zero. All rights reserved. // import Foundation import RealmSwift import CocoaLumberjackSwift public class LogRecord: Object { var uuid: String { guard let _uuid = _uuid else { fatalError() } return _uuid } var message: String { guard let _message = _message else { fatalError() } return _message } var flag: Int { guard let _flag = _flag.value else { fatalError() } return _flag } var level: Int { guard let _level = _level.value else { fatalError() } return _level } var line: Int { guard let _line = _line.value else { fatalError() } return _line } var file: String { guard let _file = _file else { fatalError() } return _file } var context: Int { guard let _context = _context.value else { fatalError() } return _context } var function: String { guard let _function = _function else { fatalError() } return _function } var date: Date { guard let _date = _date else { fatalError() } return _date } var uploadTaskID: Int? { get { return _uploadTaskID.value } set { _uploadTaskID.value = newValue } } @objc dynamic var uploadRetries = 0 @objc private dynamic var _uuid: String? @objc private dynamic var _message: String? private let _flag = RealmOptional<Int>() private let _level = RealmOptional<Int>() private let _line = RealmOptional<Int>() @objc private dynamic var _file: String? private let _context = RealmOptional<Int>() @objc private dynamic var _function: String? @objc private dynamic var _date: Date? @objc private dynamic var _additionalFieldsData: Data? private var _additionalFields: [String: String] { get { guard let data = _additionalFieldsData else { return [:] } do { return try [String: String].deserialize(data: data) } catch { fatalError("Encountered an error deserializing additional fields: \(error)") } } set { do { _additionalFieldsData = try newValue.serialize() } catch { fatalError("Encountered an error serializing additional fields: \(error)") } } } private let _uploadTaskID = RealmOptional<Int>() convenience init(logMessage: DDLogMessage, loggerIdentifier: String, additionalFields: [String: String] = [:]) { self.init() _uuid = UUID().uuidString _message = logMessage.message _flag.value = Int(logMessage.flag.rawValue) _level.value = Int(logMessage.level.rawValue) _line.value = Int(logMessage.line) _file = logMessage.file _context.value = logMessage.context _function = logMessage.function _date = logMessage.timestamp _additionalFields = additionalFields } var dict: [String: Any] { var dict: [String: Any] = [:] dict["uuid"] = uuid dict["message"] = message dict["flag"] = flag dict["level"] = level dict["date"] = date.description for (key, value) in _additionalFields { dict[key] = value } return dict } var logMessage: DDLogMessage { return DDLogMessage(message: message, level: DDLogLevel(rawValue: UInt(level))!, flag: DDLogFlag(rawValue: UInt(flag)), context: context, file: file, function: function, line: UInt(line), tag: nil, options: DDLogMessageOptions(rawValue:0), // Only value CocoaLumberjack uses. timestamp: date) } } extension Encodable { public func serialize() throws -> Data { return try JSONEncoder().encode(self) } } extension Decodable { public static func deserialize(data: Data) throws -> Self { return try JSONDecoder().decode(Self.self, from: data) } }
apache-2.0
c0b6dd6d3597f63488af73da87c71802
24.777778
116
0.519828
5.027086
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/RAM/RAM_Paginator.swift
1
20496
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension RAM { /// Gets the policies for the specified resources that you own and have shared. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getResourcePoliciesPaginator<Result>( _ input: GetResourcePoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetResourcePoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getResourcePolicies, tokenKey: \GetResourcePoliciesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getResourcePoliciesPaginator( _ input: GetResourcePoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetResourcePoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getResourcePolicies, tokenKey: \GetResourcePoliciesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets the resources or principals for the resource shares that you own. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getResourceShareAssociationsPaginator<Result>( _ input: GetResourceShareAssociationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetResourceShareAssociationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getResourceShareAssociations, tokenKey: \GetResourceShareAssociationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getResourceShareAssociationsPaginator( _ input: GetResourceShareAssociationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetResourceShareAssociationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getResourceShareAssociations, tokenKey: \GetResourceShareAssociationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets the invitations for resource sharing that you've received. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getResourceShareInvitationsPaginator<Result>( _ input: GetResourceShareInvitationsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetResourceShareInvitationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getResourceShareInvitations, tokenKey: \GetResourceShareInvitationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getResourceShareInvitationsPaginator( _ input: GetResourceShareInvitationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetResourceShareInvitationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getResourceShareInvitations, tokenKey: \GetResourceShareInvitationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Gets the resource shares that you own or the resource shares that are shared with you. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getResourceSharesPaginator<Result>( _ input: GetResourceSharesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetResourceSharesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getResourceShares, tokenKey: \GetResourceSharesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getResourceSharesPaginator( _ input: GetResourceSharesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetResourceSharesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getResourceShares, tokenKey: \GetResourceSharesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the resources in a resource share that is shared with you but that the invitation is still pending for. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPendingInvitationResourcesPaginator<Result>( _ input: ListPendingInvitationResourcesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPendingInvitationResourcesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPendingInvitationResources, tokenKey: \ListPendingInvitationResourcesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPendingInvitationResourcesPaginator( _ input: ListPendingInvitationResourcesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPendingInvitationResourcesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPendingInvitationResources, tokenKey: \ListPendingInvitationResourcesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the principals that you have shared resources with or that have shared resources with you. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPrincipalsPaginator<Result>( _ input: ListPrincipalsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPrincipalsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPrincipals, tokenKey: \ListPrincipalsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPrincipalsPaginator( _ input: ListPrincipalsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPrincipalsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPrincipals, tokenKey: \ListPrincipalsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the resources that you added to a resource shares or the resources that are shared with you. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listResourcesPaginator<Result>( _ input: ListResourcesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListResourcesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listResources, tokenKey: \ListResourcesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listResourcesPaginator( _ input: ListResourcesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListResourcesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listResources, tokenKey: \ListResourcesResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension RAM.GetResourcePoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RAM.GetResourcePoliciesRequest { return .init( maxResults: self.maxResults, nextToken: token, principal: self.principal, resourceArns: self.resourceArns ) } } extension RAM.GetResourceShareAssociationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RAM.GetResourceShareAssociationsRequest { return .init( associationStatus: self.associationStatus, associationType: self.associationType, maxResults: self.maxResults, nextToken: token, principal: self.principal, resourceArn: self.resourceArn, resourceShareArns: self.resourceShareArns ) } } extension RAM.GetResourceShareInvitationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RAM.GetResourceShareInvitationsRequest { return .init( maxResults: self.maxResults, nextToken: token, resourceShareArns: self.resourceShareArns, resourceShareInvitationArns: self.resourceShareInvitationArns ) } } extension RAM.GetResourceSharesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RAM.GetResourceSharesRequest { return .init( maxResults: self.maxResults, name: self.name, nextToken: token, resourceOwner: self.resourceOwner, resourceShareArns: self.resourceShareArns, resourceShareStatus: self.resourceShareStatus, tagFilters: self.tagFilters ) } } extension RAM.ListPendingInvitationResourcesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RAM.ListPendingInvitationResourcesRequest { return .init( maxResults: self.maxResults, nextToken: token, resourceShareInvitationArn: self.resourceShareInvitationArn ) } } extension RAM.ListPrincipalsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RAM.ListPrincipalsRequest { return .init( maxResults: self.maxResults, nextToken: token, principals: self.principals, resourceArn: self.resourceArn, resourceOwner: self.resourceOwner, resourceShareArns: self.resourceShareArns, resourceType: self.resourceType ) } } extension RAM.ListResourcesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> RAM.ListResourcesRequest { return .init( maxResults: self.maxResults, nextToken: token, principal: self.principal, resourceArns: self.resourceArns, resourceOwner: self.resourceOwner, resourceShareArns: self.resourceShareArns, resourceType: self.resourceType ) } }
apache-2.0
30edd951b5964911571c8f316b43317c
42.982833
168
0.649932
5.341673
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_02/06_ARInteraction/ARInteraction/ViewController.swift
1
9029
// // ViewController.swift // ARInteraction // // Created by Shuichi Tsutsumi on 2017/07/17. // Copyright © 2017 Shuichi Tsutsumi. All rights reserved. // import UIKit import SceneKit import ARKit fileprivate let duration1: CFTimeInterval = 0.5 fileprivate let duration2: CFTimeInterval = 0.2 class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate { @IBOutlet var sceneView: ARSCNView! @IBOutlet var trackingStateLabel: UILabel! @IBOutlet var lookAtSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self sceneView.session.delegate = self sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints] // シーンを生成してARSCNViewにセット sceneView.scene = SCNScene() // セッションのコンフィギュレーションを生成 let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal configuration.isLightEstimationEnabled = true // セッション開始 sceneView.session.run(configuration) } // MARK: - Private private func loadModel(for node: SCNNode) { guard let scene = SCNScene(named: "duck.scn", inDirectory: "models.scnassets/duck") else {fatalError()} for child in scene.rootNode.childNodes { node.addChildNode(child) } } private func planeHitTest(_ pos: CGPoint) { // 平面を対象にヒットテストを実行 let results = sceneView.hitTest(pos, types: .existingPlaneUsingExtent) // ヒット結果のうち、もっともカメラに近いものを取り出す if let result = results.first { // ヒットした平面のアンカーを取り出す guard let anchor = result.anchor else {return} // 対応するノードを取得 guard let node = sceneView.node(for: anchor) else {return} // 平面ジオメトリを持つ子ノードを探す for child in node.childNodes { guard let plane = child.geometry as? SCNPlane else {continue} // 半透明にして戻す SCNTransaction.begin() SCNTransaction.animationDuration = duration1 SCNTransaction.completionBlock = { SCNTransaction.animationDuration = duration2 plane.firstMaterial?.diffuse.contents = UIColor.yellow } plane.firstMaterial?.diffuse.contents = UIColor.yellow.withAlphaComponent(0.5) SCNTransaction.commit() break } } } private func virtualNodeHitTest(_ pos: CGPoint) -> Bool { // ヒットテストのオプション設定 let hitTestOptions = [SCNHitTestOption: Any]() // ヒットテスト実行 let results: [SCNHitTestResult] = sceneView.hitTest(pos, options: hitTestOptions) // ヒットしたノードに合致する仮想オブジェクトはあるか、再帰的に探す for child in sceneView.scene.rootNode.childNodes { guard let virtualNode = child as? VirtualObjectNode else {continue} for result in results { for virtualChild in virtualNode.childNodes { guard virtualChild == result.node else {continue} // 該当するノードにリアクションさせる virtualNode.react() return true } } } return false } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { print("anchor:\(anchor), node: \(node), node geometry: \(String(describing: node.geometry))") guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()} // 可視化用の平面ノードを追加 planeAnchor.addPlaneNode(on: node, color: UIColor.yellow) // 仮想オブジェクトのノードを作成 let virtualNode = VirtualObjectNode(anchorId: anchor.identifier) loadModel(for: virtualNode) DispatchQueue.main.async(execute: { // 仮想オブジェクトは**平面アンカーの向きの更新を受けないよう**、ルートに載せる self.sceneView.scene.rootNode.addChildNode(virtualNode) // 位置だけをアンカーに対応するノードに合わせる virtualNode.position = node.position }) } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()} planeAnchor.updatePlaneNode(on: node) // 更新されたアンカーに対応する仮想オブジェクトを探索 for child in sceneView.scene.rootNode.childNodes { guard let virtualNode = child as? VirtualObjectNode else {continue} guard anchor.identifier == virtualNode.anchorId else {continue} DispatchQueue.main.async(execute: { // 仮想オブジェクトの位置を更新 virtualNode.position = node.position }) } } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { print("\(self.classForCoder)/" + #function) // 削除されたアンカーに対応する仮想オブジェクトを探索 for child in sceneView.scene.rootNode.childNodes { guard let virtualNode = child as? VirtualObjectNode else {continue} guard anchor.identifier == virtualNode.anchorId else {continue} DispatchQueue.main.async(execute: { // 仮想オブジェクトを削除 virtualNode.removeFromParentNode() }) } } // MARK: - ARSessionObserver func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) { print("trackingState: \(camera.trackingState)") trackingStateLabel.text = camera.trackingState.description } // MARK: - ARSessionDelegate // func session(_ session: ARSession, didUpdate frame: ARFrame) { // DispatchQueue.main.async(execute: { // if !self.lookAtSwitch.isOn { // return // } // for child in self.sceneView.scene.rootNode.childNodes { // guard let virtualNode = child as? VirtualObjectNode else {continue} // // // カメラの位置を計算 // let mat = SCNMatrix4(frame.camera.transform) // let cameraPos = SCNVector3(mat.m41, mat.m42, mat.m43) // // // 仮想オブジェクトとカメラの成すベクトルの、x-z平面における角度を計算 // let vec = virtualNode.position - cameraPos // let angle = atan2f(vec.x, vec.z) // // // 仮想オブジェクトのrotationに反映 // SCNTransaction.begin() // SCNTransaction.animationDuration = 0.1 // virtualNode.rotation = SCNVector4Make(0, 1, 0, angle + Float.pi) // SCNTransaction.commit() // } // }) // } // MARK: - Touch Handlers override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // タップ位置のスクリーン座標を取得 guard let touch = touches.first else {return} let pos = touch.location(in: sceneView) // 仮想オブジェクトへのヒットテスト let isHit = virtualNodeHitTest(pos) if !isHit { // 検出済み平面へのヒットテスト planeHitTest(pos) } } // MARK: - Actions @IBAction func switchChanged(_ sender: UISwitch) { for child in self.sceneView.scene.rootNode.childNodes { guard let virtualNode = child as? VirtualObjectNode else {continue} if sender.isOn { // ビルボード制約を追加 let billboardConstraint = SCNBillboardConstraint() billboardConstraint.freeAxes = SCNBillboardAxis.Y virtualNode.constraints = [billboardConstraint] } else { virtualNode.constraints = [] } } } } extension SCNNode { func react() { SCNTransaction.begin() SCNTransaction.animationDuration = duration1 SCNTransaction.completionBlock = { SCNTransaction.animationDuration = duration2 self.opacity = 1.0 } self.opacity = 0.5 SCNTransaction.commit() } }
mit
d1483f86a30095fe97e64fe72b5fc034
33.245763
111
0.59218
4.734622
false
false
false
false
coderMONSTER/iosstar
iOSStar/Model/ShareDataModel/UserModel.swift
1
2310
// // StarUserModel.swift // iOSStar // // Created by sum on 2017/5/3. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import RealmSwift class UserInfo: Object { dynamic var agentName = "" dynamic var avatar_Large = "" dynamic var balance = 0.0 dynamic var id:Int64 = 142 dynamic var phone = "" dynamic var type = 0 } class StarUserModel: Object { dynamic var userinfo : UserInfo? dynamic var result : Int64 = 0 dynamic var token : String = " " dynamic var token_time:Int64 = 0 dynamic var id:Int64 = 0 override static func primaryKey() -> String?{ return "id" } class func upateUserInfo(userObject: AnyObject){ if let model = userObject as? StarUserModel { model.id = model.userinfo?.id ?? 0 UserDefaults.standard.setValue( model.userinfo?.id, forKey: SocketConst.Key.uid) let realm = try! Realm() try! realm.write { realm.add(model, update: true) NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.loginSuccessNotice), object: nil, userInfo: nil) } } } class func userInfo(userId: Int) -> StarUserModel? { let realm = try! Realm() let filterStr = "id = \(userId)" let user = realm.objects(StarUserModel.self).filter(filterStr).first if user != nil{ return user! }else{ return nil } } class func getCurrentUser() -> StarUserModel? { let userId = UserDefaults.standard.object(forKey: SocketConst.Key.uid) == nil ? 0 : ( UserDefaults.standard.object(forKey: SocketConst.Key.uid) as! Int64) let user = StarUserModel.userInfo(userId:Int(userId)) if user != nil { return user }else{ return nil } } } class WeChatPayResultModel: Object { dynamic var appid = "" dynamic var partnerid = "" dynamic var prepayid = "" dynamic var package = "" dynamic var noncestr = "" dynamic var timestamp = "" dynamic var sign = "" dynamic var rid = "" } class AliPayResultModel: Object { dynamic var orderinfo = "" dynamic var rid = "" }
gpl-3.0
c52731e1216c1e6f72526abef50c1752
26.464286
162
0.586909
4.296089
false
false
false
false
optimizely/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/UITableViewBinding.swift
2
4902
// // UITableViewBinding.swift // Mixpanel // // Created by Yarden Eitan on 8/24/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation import UIKit class UITableViewBinding: CodelessBinding { init(eventName: String, path: String, delegate: AnyClass) { super.init(eventName: eventName, path: path) self.swizzleClass = delegate } convenience init?(object: [String: Any]) { guard let path = object["path"] as? String, path.count >= 1 else { Logger.warn(message: "must supply a view path to bind by") return nil } guard let eventName = object["event_name"] as? String, eventName.count >= 1 else { Logger.warn(message: "binding requires an event name") return nil } guard let tableDelegate = object["table_delegate"] as? String, let tableDelegateClass = NSClassFromString(tableDelegate) else { Logger.warn(message: "binding requires a table_delegate class") return nil } self.init(eventName: eventName, path: path, delegate: tableDelegateClass) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func execute() { if !running { let executeBlock = { (view: AnyObject?, command: Selector, tableView: AnyObject?, indexPath: AnyObject?) in guard let tableView = tableView as? UITableView, let indexPath = indexPath as? IndexPath else { return } if let root = MixpanelInstance.sharedUIApplication()?.keyWindow?.rootViewController { // select targets based off path if self.path.isSelected(leaf: tableView, from: root) { var label = "" if let cell = tableView.cellForRow(at: indexPath) { if let cellText = cell.textLabel?.text { label = cellText } else { for subview in cell.contentView.subviews { if let lbl = subview as? UILabel, let text = lbl.text { label = text break } } } } self.track(event: self.eventName, properties: ["Cell Index": "\(indexPath.row)", "Cell Section": "\(indexPath.section)", "Cell Label": label]) } } } //swizzle Swizzler.swizzleSelector(NSSelectorFromString("tableView:didSelectRowAtIndexPath:"), withSelector: #selector(UIViewController.newDidSelectRowAtIndexPath(tableView:indexPath:)), for: swizzleClass, name: name, block: executeBlock) running = true } } override func stop() { if running { //unswizzle Swizzler.unswizzleSelector(NSSelectorFromString("tableView:didSelectRowAtIndexPath:"), aClass: swizzleClass, name: name) running = false } } override var description: String { return "UITableView Codeless Binding: \(eventName) for \(path)" } override func isEqual(_ object: Any?) -> Bool { guard let object = object as? UITableViewBinding else { return false } if object === self { return true } else { return super.isEqual(object) } } override var hash: Int { return super.hash } } extension UIViewController { @objc func newDidSelectRowAtIndexPath(tableView: UITableView, indexPath: IndexPath) { let originalSelector = NSSelectorFromString("tableView:didSelectRowAtIndexPath:") if let originalMethod = class_getInstanceMethod(type(of: self), originalSelector), let swizzle = Swizzler.swizzles[originalMethod] { typealias MyCFunction = @convention(c) (AnyObject, Selector, UITableView, IndexPath) -> Void let curriedImplementation = unsafeBitCast(swizzle.originalMethod, to: MyCFunction.self) curriedImplementation(self, originalSelector, tableView, indexPath) for (_, block) in swizzle.blocks { block(self, swizzle.selector, tableView, indexPath as AnyObject?) } } } }
apache-2.0
b5e5f9236547b448f86ede97f0386ff6
35.574627
135
0.52071
5.806872
false
false
false
false
pj4533/wat
wat/PacketManager.swift
1
2848
// // PacketManager.swift // wat // // Created by PJ Gray on 8/15/14. // Copyright (c) 2014 Say Goodnight Software. All rights reserved. // import Cocoa class PacketManager: NSObject { let errorHandler: ErrorHandler let callbackManager: SGSPacketCallbackManager let deviceName: String init(deviceName: String) { self.deviceName = deviceName self.errorHandler = ErrorHandler() self.callbackManager = SGSPacketCallbackManager() super.init() } func capture() { var error: UnsafeMutablePointer<CChar> error = nil println("Opening device: \(self.deviceName)") var descr = pcap_create(self.deviceName,error) self.errorHandler.handleError(error) self.errorHandler.handleResult(pcap_set_promisc(descr, 1),message: "Couldn't set promisc mode") self.errorHandler.handleResult(pcap_set_rfmon(descr, 1), message: "Couldn't set monitor mode") self.errorHandler.handleResult(pcap_activate(descr), message: "Error activating") println("Datalink Name: \(String.fromCString(pcap_datalink_val_to_name(pcap_datalink(descr)))!)") println("Datalink Description: \(String.fromCString(pcap_datalink_val_to_description(pcap_datalink(descr)))!)") self.callbackManager.registerPacketCallbackWithDescriptor(descr, withBlock: {(packet: RadioTapPacket!) -> Void in var outputString = "(\(packet.frameControl!.frameControlType.simpleDescription()))" outputString += " \(packet.frameControl!.frameControlSubType.simpleDescription())" outputString += " Size: \(packet.rawData.length)" if packet.frameControl?.frameControlType == FrameControl.FrameControlType.Management { if packet.frameControl?.frameControlSubType == FrameControl.FrameControlSubType.Authentication { if packet.managementFrame?.destAddr != nil { outputString += " DEST: \(packet.managementFrame!.destAddrString!)" } if (packet.managementFrame?.sourceAddr != nil) { outputString += " SOURCE: \(packet.managementFrame!.sourceAddrString!)" } } } else if packet.frameControl?.frameControlType == FrameControl.FrameControlType.Data { if packet.dataFrame?.destAddr != nil { outputString += " DEST: \(packet.dataFrame!.destAddrString!)" } if (packet.dataFrame?.sourceAddr != nil) { outputString += " SOURCE: \(packet.dataFrame!.sourceAddrString!)" } } println(outputString) }) } }
mit
f5ae3bf0b5655d6fe169f0d0b91ddcf9
38.555556
121
0.602528
4.918826
false
false
false
false
hejunbinlan/Carlos
Carlos/BasicCache.swift
2
2422
import Foundation /// A wrapper cache that explicitly takes get, set, clear and memory warning closures public final class BasicCache<A, B>: CacheLevel { public typealias KeyType = A public typealias OutputType = B private let getClosure: (key: A) -> CacheRequest<B> private let setClosure: (key: A, value: B) -> Void private let clearClosure: () -> Void private let memoryClosure: () -> Void /** Initializes a new instance of a BasicCache specifying closures for get, set, clear and onMemoryWarning, thus determining the behavior of the cache level as a whole :param: getClosure The closure to execute when you call get(key) on this instance :param: setClosure The closure to execute when you call set(value, key) on this instance :param: clearClosure The closure to execute when you call clear() on this instance :param: memoryClosure The closure to execute when you call onMemoryWarning() on this instance, or when a memory warning is thrown by the system and the cache level is listening for memory pressure events */ public init(getClosure: (key: A) -> CacheRequest<B>, setClosure: (key: A, value: B) -> Void, clearClosure: () -> Void, memoryClosure: () -> Void) { self.getClosure = getClosure self.setClosure = setClosure self.clearClosure = clearClosure self.memoryClosure = memoryClosure } /** Asks the cache to get the value for a given key :param: key The key you want to get the value for :returns: The result of the getClosure specified when initializing the instance */ public func get(key: KeyType) -> CacheRequest<OutputType> { return getClosure(key: key) } /** Asks the cache to set a value for the given key :param: value The value to set on the cache :param: key The key to use for the given value :discussion: This call executes the setClosure specified when initializing the instance */ public func set(value: B, forKey key: A) { setClosure(key: key, value: value) } /** Asks the cache to clear its contents :discussion: This call executes the clearClosure specified when initializing the instance */ public func clear() { clearClosure() } /** Tells the cache that a memory warning event was received :discussion: This call executes the memoryClosure specified when initializing the instance */ public func onMemoryWarning() { memoryClosure() } }
mit
a1156e83710673e94c9d5620e7321881
34.632353
205
0.716763
4.613333
false
false
false
false
Za1006/TIY-Assignments
Jackpot/Jackpot/JackpotTableViewController.swift
1
4862
// // JackpotTableViewController.swift // Jackpot // // Created by Elizabeth Yeh on 10/14/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit protocol WinningTicketViewControllerDelegate { func winningTicketWasAdded(ticket: JackpotTicket) } class JackpotTableViewController: UITableViewController,WinningTicketViewControllerDelegate { @IBOutlet weak var addButton: UIBarButtonItem! var storeTicket = Array<JackpotTicket>() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return storeTicket.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("JackpotCell", forIndexPath: indexPath) // Configure the cell... let aTicket = storeTicket[indexPath.row] // cell.numbersLabel.text = aTicket.description() // cell.textLabel?.text = "\(numbersInCell.ticket)" if aTicket.winner { cell.backgroundColor = UIColor.greenColor() cell.payOutLabel.text = aTicket.payOut } else { cell.backgroundColor = UIColor.whiteColor() cell.payOutLabel.text = "" } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.indentifier == "ShowWinningTicketSegue" { let winningTicketVC = segue.destinationViewController as! WinningTicketViewController winningTicketVC.delegate = self } // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } // MARK: - Winning ticket view controller delegate func winningTicketWasAdded(ticket: JackpotTicket) { navigationController?.dismissViewControllerAnimated(true, completion: nil) checkForWinnersUsingTicket(ticket) } // MARK: - Action Handler @IBAction func addTapped(sender: UIBarButtonItem) { _ = JackpotTicket() // let newPath = NSIndexPath(forRow: storeTicket.count, inSection: 0) storeTicket.append(JackpotTicket()) self.tableView.reloadData() } // MARK: - Private methods func checkingForWinnersUsingTicket(winningTicket: JackpotTicket) { for ticket in tickets { ticket.compareWithTicket(winningTicket) } tableView.reloadData() } }
cc0-1.0
3e03e7539e6e5398ad311b386e0e5bab
29.192547
157
0.665295
5.389135
false
false
false
false
exyte/Macaw
Source/animation/Easing.swift
1
2614
// // Easing.swift // Pods // // Created by Yuri Strot on 9/2/16. // // #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif open class Easing { public static let ease: Easing = Easing() public static let linear: Easing = Easing() public static let easeIn: Easing = EaseIn() public static let easeOut: Easing = EaseOut() public static let easeInOut: Easing = EaseInOut() public static let elasticOut: Easing = ElasticOut() public static let elasticInOut: Easing = ElasticInOut() public static func elasticOut(elasticity: Double = 10.0) -> ElasticOut { return ElasticOut(elasticity: elasticity) } public static func elasticInOut(elasticity: Double = 10.0) -> ElasticInOut { return ElasticInOut(elasticity: elasticity) } open func progressFor(time: Double) -> Double { return time } } private class EaseIn: Easing { override open func progressFor(time t: Double) -> Double { return t * t } } private class EaseOut: Easing { override open func progressFor(time t: Double) -> Double { return -(t * (t - 2)) } } private class EaseInOut: Easing { override open func progressFor(time t: Double) -> Double { if t < 0.5 { return 2.0 * t * t } else { return -2.0 * t * t + 4.0 * t - 1.0 } } } public class ElasticOut: Easing { let elasticity: Double init(elasticity: Double = 10.0) { // less elasticity means more springy effect self.elasticity = elasticity } override open func progressFor(time: Double) -> Double { if time == 0 { return 0 } let t = time / 0.5 if t == 2 { return 1 } let p = 0.3 let s = p / 4 let postFix = pow(2, -elasticity * t) return (postFix * sin((t - s) * (2 * .pi) / p ) + 1) } } public class ElasticInOut: Easing { let elasticity: Double init(elasticity: Double = 10.0) { // less elasticity means more springy effect self.elasticity = elasticity } override open func progressFor(time: Double) -> Double { if time == 0 { return 0 } let t = time / 0.5 - 1 if t == 1 { return 1 } let p = 0.3 * 1.5 let s = p / 4 if t < 0 { let postFix = pow(2, elasticity * t) return (-0.5 * (postFix * sin((t - s) * (2 * .pi) / p))) } let postFix = pow(2, -elasticity * t) return (postFix * sin((t - s) * (2 * .pi) / p ) * 0.5 + 1) } }
mit
b802a4c1087df88a26fdf5826ae4f01c
23.429907
82
0.552028
3.766571
false
false
false
false
gowansg/firefox-ios
Client/Frontend/Browser/BrowserViewController.swift
1
61827
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import WebKit import Storage import Snap private let OKString = NSLocalizedString("OK", comment: "OK button") private let CancelString = NSLocalizedString("Cancel", comment: "Cancel button") private let KVOLoading = "loading" private let KVOEstimatedProgress = "estimatedProgress" private let HomeURL = "about:home" class BrowserViewController: UIViewController { private var urlBar: URLBarView! private var readerModeBar: ReaderModeBarView! private var toolbar: BrowserToolbar? private var tabManager: TabManager! private var homePanelController: HomePanelViewController? private var searchController: SearchViewController? private var webViewContainer: UIView! private let uriFixup = URIFixup() private var screenshotHelper: ScreenshotHelper! private var homePanelIsInline = false private var searchLoader: SearchLoader! let profile: Profile // These views wrap the urlbar and toolbar to provide background effects on them private var header: UIView! private var footer: UIView! private var footerBackground: UIView? private var previousScroll: CGPoint? = nil init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) didInit() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func didInit() { let defaultURL = NSURL(string: HomeURL)! let defaultRequest = NSURLRequest(URL: defaultURL) tabManager = TabManager(defaultNewTabRequest: defaultRequest) tabManager.addDelegate(self) screenshotHelper = BrowserScreenshotHelper(controller: self) } override func preferredStatusBarStyle() -> UIStatusBarStyle { if header == nil { return UIStatusBarStyle.LightContent } if header.transform.ty == 0 { return UIStatusBarStyle.LightContent } return UIStatusBarStyle.Default } func shouldShowToolbar() -> Bool { return traitCollection.verticalSizeClass != .Compact && traitCollection.horizontalSizeClass != .Regular } private func updateToolbarState() { let showToolbar = shouldShowToolbar() urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.browserToolbarDelegate = nil footerBackground?.removeFromSuperview() footerBackground = nil toolbar = nil if showToolbar { toolbar = BrowserToolbar() toolbar?.browserToolbarDelegate = self footerBackground = wrapInEffect(toolbar!, parent: footer) } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab { tab.webView.scrollView.contentInset = UIEdgeInsetsMake(AppConstants.ToolbarHeight + AppConstants.StatusBarHeight, 0, toolbar?.frame.height ?? 0, 0) } } override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { updateToolbarState() super.traitCollectionDidChange(previousTraitCollection) } override func viewDidLoad() { webViewContainer = UIView() view.addSubview(webViewContainer) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.setTranslatesAutoresizingMaskIntoConstraints(false) urlBar.delegate = self header = wrapInEffect(urlBar, parent: view) urlBar.browserToolbarDelegate = self searchLoader = SearchLoader(history: profile.history, urlBar: urlBar) // Setup the reader mode control bar. This bar starts not visible with a zero height. readerModeBar = ReaderModeBarView(frame: CGRectZero) readerModeBar.delegate = self view.addSubview(readerModeBar) readerModeBar.hidden = true footer = UIView() self.view.addSubview(footer) super.viewDidLoad() } override func viewWillAppear(animated: Bool) { if (tabManager.count == 0) { tabManager.addTab() } super.viewWillAppear(animated) } override func updateViewConstraints() { webViewContainer.snp_remakeConstraints { make in make.edges.equalTo(self.view) return } urlBar.snp_remakeConstraints { make in make.edges.equalTo(self.header) return } header.snp_remakeConstraints { make in make.top.equalTo(self.view.snp_top) make.height.equalTo(AppConstants.ToolbarHeight + AppConstants.StatusBarHeight) make.leading.trailing.equalTo(self.view) } header.setNeedsUpdateConstraints() readerModeBar.snp_remakeConstraints { make in make.top.equalTo(self.header.snp_bottom) make.height.equalTo(AppConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } // Setup the bottom toolbar toolbar?.snp_remakeConstraints { make in make.edges.equalTo(self.footerBackground!) make.height.equalTo(AppConstants.ToolbarHeight) } adjustFooterSize() footerBackground?.snp_remakeConstraints { make in make.bottom.left.right.equalTo(self.footer) make.height.equalTo(AppConstants.ToolbarHeight) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp_remakeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.equalTo(self.view) let url = self.tabManager.selectedTab?.url if url?.absoluteString == HomeURL && self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } else { make.bottom.equalTo(self.view.snp_bottom) } } super.updateViewConstraints() } private func wrapInEffect(view: UIView, parent: UIView) -> UIView { let effect = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) effect.setTranslatesAutoresizingMaskIntoConstraints(false) view.backgroundColor = UIColor.clearColor() effect.addSubview(view) parent.addSubview(effect) return effect } private func showHomePanelController(#inline: Bool) { homePanelIsInline = inline if homePanelController == nil { homePanelController = HomePanelViewController() homePanelController!.profile = profile homePanelController!.delegate = self homePanelController!.url = tabManager.selectedTab?.displayURL homePanelController!.view.alpha = 0 view.addSubview(homePanelController!.view) UIView.animateWithDuration(0.2, animations: { () -> Void in self.homePanelController!.view.alpha = 1 }, completion: { _ in self.webViewContainer.accessibilityElementsHidden = true }) addChildViewController(homePanelController!) } toolbar?.hidden = !inline view.setNeedsUpdateConstraints() } private func hideHomePanelController() { if let controller = homePanelController { UIView.animateWithDuration(0.2, animations: { () -> Void in controller.view.alpha = 0 }, completion: { _ in controller.view.removeFromSuperview() controller.removeFromParentViewController() self.homePanelController = nil self.webViewContainer.accessibilityElementsHidden = false self.toolbar?.hidden = false }) } } private func updateInContentHomePanel(url: NSURL?) { if !urlBar.isEditing { if url?.absoluteString == HomeURL { showHomePanelController(inline: true) } else { hideHomePanelController() } } } private func showSearchController() { if searchController != nil { return } searchController = SearchViewController() searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader.addListener(searchController!) view.addSubview(searchController!.view) searchController!.view.snp_makeConstraints { make in make.top.equalTo(self.urlBar.snp_bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.hidden = true addChildViewController(searchController!) } private func hideSearchController() { if let searchController = searchController { searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.hidden = false } } private func finishEditingAndSubmit(var url: NSURL) { urlBar.updateURL(url) urlBar.finishEditing() if let tab = tabManager.selectedTab { tab.loadRequest(NSURLRequest(URL: url)) } } private func addBookmark(url: String, title: String?) { let shareItem = ShareItem(url: url, title: title, favicon: nil) profile.bookmarks.shareItem(shareItem) // Dispatch to the main thread to update the UI dispatch_async(dispatch_get_main_queue()) { _ in self.toolbar?.updateBookmarkStatus(true) self.urlBar.updateBookmarkStatus(true) } } private func removeBookmark(url: String) { var bookmark = BookmarkItem(guid: "", title: "", url: url) profile.bookmarks.remove(bookmark, success: { success in self.toolbar?.updateBookmarkStatus(!success) self.urlBar.updateBookmarkStatus(!success) }, failure: { err in println("Err removing bookmark \(err)") }) } override func accessibilityPerformEscape() -> Bool { if let selectedTab = tabManager.selectedTab { if selectedTab.canGoBack { tabManager.selectedTab?.goBack() return true } } return false } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) { if object as? WKWebView !== tabManager.selectedTab?.webView { return } switch keyPath { case KVOEstimatedProgress: urlBar.updateProgressBar(change[NSKeyValueChangeNewKey] as! Float) case KVOLoading: toolbar?.updateReloadStatus(change[NSKeyValueChangeNewKey] as! Bool) urlBar.updateReloadStatus(change[NSKeyValueChangeNewKey] as! Bool) default: assertionFailure("Unhandled KVO key: \(keyPath)") } } } extension BrowserViewController: URLBarDelegate { func urlBarDidPressReload(urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressStop(urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(urlBar: URLBarView) { let controller = TabTrayController() controller.profile = profile controller.tabManager = tabManager controller.transitioningDelegate = self controller.modalPresentationStyle = .Custom if let tab = tabManager.selectedTab { tab.screenshot = screenshotHelper.takeScreenshot(tab, aspectRatio: 0, quality: 1) } presentViewController(controller, animated: true, completion: nil) } func urlBarDidPressReaderMode(urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .Available: enableReaderMode() case .Active: disableReaderMode() case .Unavailable: break } } } } func urlBarDidLongPressReaderMode(urlBar: URLBarView) { if let tab = tabManager.selectedTab { if var url = tab.displayURL { if let absoluteString = url.absoluteString { let result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail? // TODO Followup bug, provide some form of 'this has been added' feedback? } } } } func urlBarDidLongPressLocation(urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let pasteboardContents = UIPasteboard.generalPasteboard().string // Check if anything is on the pasteboard if pasteboardContents != nil { let pasteAndGoAction = UIAlertAction(title: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), style: .Default, handler: { (alert: UIAlertAction!) -> Void in self.urlBar(urlBar, didSubmitText: pasteboardContents!) }) longPressAlertController.addAction(pasteAndGoAction) let pasteAction = UIAlertAction(title: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), style: .Default, handler: { (alert: UIAlertAction!) -> Void in urlBar.updateURLBarText(pasteboardContents!) }) longPressAlertController.addAction(pasteAction) } let copyAddressAction = UIAlertAction(title: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), style: .Default, handler: { (alert: UIAlertAction!) -> Void in UIPasteboard.generalPasteboard().string = urlBar.currentURL().absoluteString }) longPressAlertController.addAction(copyAddressAction) let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel alert view"), style: .Cancel, handler: nil) longPressAlertController.addAction(cancelAction) if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .Any } self.presentViewController(longPressAlertController, animated: true, completion: nil) } func urlBar(urlBar: URLBarView, didEnterText text: String) { searchLoader.query = text if text.isEmpty { hideSearchController() } else { showSearchController() searchController!.searchQuery = text } } func urlBar(urlBar: URLBarView, didSubmitText text: String) { var url = uriFixup.getURL(text) // If we can't make a valid URL, do a search query. if url == nil { url = profile.searchEngines.defaultEngine.searchURLForQuery(text) } // If we still don't have a valid URL, something is broken. Give up. if url == nil { println("Error handling URL entry: " + text) return } finishEditingAndSubmit(url!) } func urlBarDidBeginEditing(urlBar: URLBarView) { showHomePanelController(inline: false) } func urlBarDidEndEditing(urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url) } } extension BrowserViewController: BrowserToolbarDelegate { func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) { let controller = BackForwardListViewController() controller.listData = tabManager.selectedTab?.backList controller.tabManager = tabManager presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) { let controller = BackForwardListViewController() controller.listData = tabManager.selectedTab?.forwardList controller.tabManager = tabManager presentViewController(controller, animated: true, completion: nil) } func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let tab = tabManager.selectedTab, let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { isBookmarked in if isBookmarked { self.removeBookmark(url) } else { self.addBookmark(url, title: tab.title) } }, failure: { err in println("Bookmark error: \(err)") } ) } else { println("Bookmark error: No tab is selected, or no URL in tab.") } } func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) { } func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) { if let selected = tabManager.selectedTab { if let url = selected.displayURL { var activityViewController = UIActivityViewController(activityItems: [selected.title ?? url.absoluteString!, url], applicationActivities: nil) // Hide 'Add to Reading List' which currently uses Safari activityViewController.excludedActivityTypes = [UIActivityTypeAddToReadingList] if let popoverPresentationController = activityViewController.popoverPresentationController { // Using the button for the sourceView here results in this not showing on iPads. popoverPresentationController.sourceView = toolbar ?? urlBar popoverPresentationController.sourceRect = button.frame ?? button.frame popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up } presentViewController(activityViewController, animated: true, completion: nil) } } } } extension BrowserViewController: BrowserDelegate { private func findSnackbar(bars: [AnyObject], barToFind: SnackBar) -> Int? { for (index, bar) in enumerate(bars) { if bar === barToFind { return index } } return nil } private func adjustFooterSize(top: UIView? = nil) { footer.snp_remakeConstraints { make in let bars = self.footer.subviews make.bottom.equalTo(self.view.snp_bottom) if let top = top { make.top.equalTo(top.snp_top) } else if bars.count > 0 { if let bar = bars[bars.count-1] as? SnackBar { make.top.equalTo(bar.snp_top) } else { make.top.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } } make.leading.trailing.equalTo(self.view) } } // This removes the bar from its superview and updates constraints appropriately private func finishRemovingBar(bar: SnackBar) { // If there was a bar above this one, we need to remake its constraints so that it doesn't // try to sit about "this" bar anymore. let bars = footer.subviews if let index = findSnackbar(bars, barToFind: bar) { if index < bars.count-1 { if var nextbar = bars[index+1] as? SnackBar { nextbar.snp_remakeConstraints { make in if index > 1 { if let bar = bars[index-1] as? SnackBar { make.bottom.equalTo(bar.snp_top) } } else { make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom) } make.left.width.equalTo(self.footer) } nextbar.setNeedsUpdateConstraints() } } } // Really remove the bar bar.removeFromSuperview() } private func finishAddingBar(bar: SnackBar) { footer.addSubview(bar) bar.snp_makeConstraints({ make in // If there are already bars showing, add this on top of them let bars = self.footer.subviews if bars.count > 1 { if let view = bars[bars.count - 2] as? UIView { make.bottom.equalTo(view.snp_top) } } make.left.width.equalTo(self.footer) }) } func showBar(bar: SnackBar, animated: Bool) { finishAddingBar(bar) adjustFooterSize(top: bar) bar.hide() UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.show() }) } func removeBar(bar: SnackBar, animated: Bool) { bar.show() let bars = footer.subviews let index = findSnackbar(bars, barToFind: bar)! UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in bar.hide() // Make sure all the bars above it slide down as well for i in index..<bars.count { if let sibling = bars[i] as? SnackBar { sibling.transform = CGAffineTransformMakeTranslation(0, bar.frame.height) } } }) { success in // Undo all the animation transforms for i in index..<bars.count { if let bar = bars[i] as? SnackBar { bar.transform = CGAffineTransformIdentity } } // Really remove the bar self.finishRemovingBar(bar) // Adjust the footer size to only contain the bars self.adjustFooterSize() } } func removeAllBars() { let bars = footer.subviews for bar in bars { if let bar = bar as? SnackBar { bar.removeFromSuperview() } } self.adjustFooterSize() } func browser(browser: Browser, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL) { finishEditingAndSubmit(url) } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) { finishEditingAndSubmit(url) } } extension BrowserViewController: UIScrollViewDelegate { private func clamp(y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { if y >= max { return max } else if y <= min { return min } return y } private func scrollUrlBar(dy: CGFloat) { let newY = clamp(header.transform.ty + dy, min: -AppConstants.ToolbarHeight, max: 0) header.transform = CGAffineTransformMakeTranslation(0, newY) let percent = 1 - newY / -AppConstants.ToolbarHeight urlBar.alpha = percent self.setNeedsStatusBarAppearanceUpdate() } private func scrollReaderModeBar(dy: CGFloat) { let newY = clamp(readerModeBar.transform.ty + dy, min: -AppConstants.ToolbarHeight, max: 0) readerModeBar.transform = CGAffineTransformMakeTranslation(0, newY) let percent = 1 - newY / -AppConstants.ToolbarHeight readerModeBar.alpha = percent } private func scrollToolbar(dy: CGFloat) { let newY = clamp(footer.transform.ty - dy, min: 0, max: toolbar?.frame.height ?? 0) footer.transform = CGAffineTransformMakeTranslation(0, newY) } func scrollViewWillBeginDragging(scrollView: UIScrollView) { previousScroll = scrollView.contentOffset } // Careful! This method can be called multiple times concurrently. func scrollViewDidScroll(scrollView: UIScrollView) { if var prev = previousScroll { if let tab = tabManager.selectedTab { if tab.loading { return } let offset = scrollView.contentOffset var delta = CGPoint(x: prev.x - offset.x, y: prev.y - offset.y) previousScroll = offset let inset = tab.webView.scrollView.contentInset if let tab = self.tabManager.selectedTab { let newInset = clamp(inset.top + delta.y, min: AppConstants.StatusBarHeight, max: AppConstants.ToolbarHeight + AppConstants.StatusBarHeight) tab.webView.scrollView.contentInset = UIEdgeInsetsMake(newInset, 0, clamp(newInset - AppConstants.StatusBarHeight, min: 0, max: toolbar?.frame.height ?? 0), 0) tab.webView.scrollView.scrollIndicatorInsets = tab.webView.scrollView.contentInset } // Adjust the urlbar, reader bar, and toolbar by the change in the contentInset scrollUrlBar(tab.webView.scrollView.contentInset.top - inset.top) scrollReaderModeBar(tab.webView.scrollView.contentInset.top - inset.top) scrollToolbar(tab.webView.scrollView.contentInset.top - inset.top) } } } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { previousScroll = nil if tabManager.selectedTab?.loading ?? false { return } let offset = scrollView.contentOffset // If we're moving up, or the header is half onscreen, hide the toolbars if velocity.y < 0 || self.header.transform.ty > -self.header.frame.height / 2 { showToolbars(animated: true) } else { hideToolbars(animated: true) } } func scrollViewDidScrollToTop(scrollView: UIScrollView) { showToolbars(animated: true) } private func hideToolbars(#animated: Bool, completion: ((finished: Bool) -> Void)? = nil) { UIView.animateWithDuration(animated ? 0.5 : 0.0, animations: { () -> Void in self.scrollUrlBar(CGFloat(-1*MAXFLOAT)) self.scrollToolbar(CGFloat(-1*MAXFLOAT)) self.header.transform = CGAffineTransformMakeTranslation(0, -self.urlBar.frame.height + AppConstants.StatusBarHeight) self.footer.transform = CGAffineTransformMakeTranslation(0, self.toolbar?.frame.height ?? 0) // Reset the insets so that clicking works on the edges of the screen if let tab = self.tabManager.selectedTab { tab.webView.scrollView.contentInset = UIEdgeInsets(top: AppConstants.StatusBarHeight, left: 0, bottom: 0, right: 0) tab.webView.scrollView.scrollIndicatorInsets = UIEdgeInsets(top: AppConstants.StatusBarHeight, left: 0, bottom: 0, right: 0) } self.setNeedsStatusBarAppearanceUpdate() }, completion: completion) } private func showToolbars(#animated: Bool, completion: ((finished: Bool) -> Void)? = nil) { UIView.animateWithDuration(animated ? 0.5 : 0.0, animations: { () -> Void in self.scrollUrlBar(CGFloat(MAXFLOAT)) self.scrollToolbar(CGFloat(MAXFLOAT)) self.header.transform = CGAffineTransformIdentity self.footer.transform = CGAffineTransformIdentity // Reset the insets so that clicking works on the edges of the screen if let tab = self.tabManager.selectedTab { tab.webView.scrollView.contentInset = UIEdgeInsets(top: self.header.frame.height + (self.readerModeBar.hidden ? 0 : self.readerModeBar.frame.height), left: 0, bottom: self.toolbar?.frame.height ?? 0, right: 0) tab.webView.scrollView.scrollIndicatorInsets = UIEdgeInsets(top: self.header.frame.height + (self.readerModeBar.hidden ? 0 : self.readerModeBar.frame.height), left: 0, bottom: self.toolbar?.frame.height ?? 0, right: 0) } self.setNeedsStatusBarAppearanceUpdate() }, completion: completion) } } extension BrowserViewController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { wv.accessibilityLabel = nil } if let wv = selected?.webView { wv.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the web view") webViewContainer.addSubview(wv) if let url = wv.URL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.toolbar?.updateBookmarkStatus(bookmarked) self.urlBar.updateBookmarkStatus(bookmarked) }, failure: { err in println("Error getting bookmark status: \(err)") }) } } removeAllBars() urlBar.updateURL(selected?.displayURL) if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } showToolbars(animated: false) toolbar?.updateBackStatus(selected?.canGoBack ?? false) toolbar?.updateFowardStatus(selected?.canGoForward ?? false) toolbar?.updateReloadStatus(selected?.webView.loading ?? false) self.urlBar.updateBackStatus(selected?.canGoBack ?? false) self.urlBar.updateFowardStatus(selected?.canGoForward ?? false) self.urlBar.updateProgressBar(Float(selected?.webView.estimatedProgress ?? 0)) if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .Active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } updateInContentHomePanel(selected?.displayURL) } func tabManager(tabManager: TabManager, didCreateTab tab: Browser) { if let readerMode = ReaderMode(browser: tab) { readerMode.delegate = self tab.addHelper(readerMode, name: ReaderMode.name()) } let favicons = FaviconManager(browser: tab, profile: profile) tab.addHelper(favicons, name: FaviconManager.name()) let passwords = PasswordHelper(browser: tab, profile: profile) tab.addHelper(passwords, name: PasswordHelper.name()) let longPressBrowserHelper = LongPressBrowserHelper(browser: tab) longPressBrowserHelper.delegate = self tab.addHelper(longPressBrowserHelper, name: LongPressBrowserHelper.name()) } func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int) { urlBar.updateTabCount(tabManager.count) webViewContainer.insertSubview(tab.webView, atIndex: 0) tab.webView.scrollView.contentInset = UIEdgeInsetsMake(AppConstants.ToolbarHeight + AppConstants.StatusBarHeight, 0, toolbar?.frame.height ?? 0, 0) tab.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(AppConstants.ToolbarHeight + AppConstants.StatusBarHeight, 0, toolbar?.frame.height ?? 0, 0) tab.webView.snp_makeConstraints { make in make.top.equalTo(self.view.snp_top) make.leading.trailing.bottom.equalTo(self.view) } // Observers that live as long as the tab. Make sure these are all cleared // in didRemoveTab below! tab.webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil) tab.webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil) tab.webView.UIDelegate = self tab.browserDelegate = self tab.webView.navigationDelegate = self tab.webView.scrollView.delegate = self } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex: Int) { urlBar.updateTabCount(tabManager.count) tab.webView.removeObserver(self, forKeyPath: KVOEstimatedProgress) tab.webView.removeObserver(self, forKeyPath: KVOLoading) tab.webView.UIDelegate = nil tab.browserDelegate = nil tab.webView.navigationDelegate = nil tab.webView.scrollView.delegate = nil tab.webView.removeFromSuperview() } } extension BrowserViewController: WKNavigationDelegate { func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { if tabManager.selectedTab?.webView !== webView { return } // If we are going to navigate to a new page, hide the reader mode button. Unless we // are going to a about:reader page. Then we keep it on screen: it will change status // (orange color) as soon as the page has loaded. if let url = webView.URL { if !ReaderModeUtils.isReaderModeURL(url) { urlBar.updateReaderModeState(ReaderModeState.Unavailable) } } } func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) { let url = navigationAction.request.URL if url == nil { return } var openExternally = false if let scheme = url!.scheme { switch scheme { case "about", "http", "https": // TODO: Check for urls that we want to special case. decisionHandler(WKNavigationActionPolicy.Allow) return default: if UIApplication.sharedApplication().canOpenURL(url!) { // Ask the user if it's okay to open the url with UIApplication. let alert = UIAlertController( title: String(format: NSLocalizedString("Opening %@", comment:"Opening an external URL"), url!), message: NSLocalizedString("This will open in another application", comment: "Opening an external app"), preferredStyle: UIAlertControllerStyle.Alert ) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction!) in // NOP })) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Alert OK Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(url!) return })) presentViewController(alert, animated: true, completion: nil) } decisionHandler(WKNavigationActionPolicy.Cancel) } } } func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) { if let tab = tabManager.selectedTab { if tab.webView == webView { urlBar.updateURL(tab.displayURL); toolbar?.updateBackStatus(webView.canGoBack) toolbar?.updateFowardStatus(webView.canGoForward) urlBar.updateBackStatus(webView.canGoBack) urlBar.updateFowardStatus(webView.canGoForward) showToolbars(animated: false) if let url = tab.displayURL?.absoluteString { profile.bookmarks.isBookmarked(url, success: { bookmarked in self.toolbar?.updateBookmarkStatus(bookmarked) self.urlBar.updateBookmarkStatus(bookmarked) }, failure: { err in println("Error getting bookmark status: \(err)") }) } if let url = tab.url { if ReaderModeUtils.isReaderModeURL(url) { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } updateInContentHomePanel(tab.displayURL) } } } func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if challenge.protectionSpace.authenticationMethod != NSURLAuthenticationMethodClientCertificate { if let tab = tabManager.getTab(webView) { let helper = tab.getHelper(name: PasswordHelper.name()) as! PasswordHelper helper.handleAuthRequest(self, challenge: challenge) { password in if let password = password { completionHandler(.UseCredential, password.credential) } else { completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil) } } } } } func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { let tab: Browser! = tabManager.getTab(webView) tab.expireSnackbars() let notificationCenter = NSNotificationCenter.defaultCenter() var info = [NSObject: AnyObject]() info["url"] = tab.displayURL info["title"] = tab.title notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info) if let url = webView.URL { // The screenshot immediately after didFinishNavigation is actually a screenshot of the // previous page, presumably due to some iOS bug. Adding a small delay seems to fix this, // and the current page gets captured as expected. let time = dispatch_time(DISPATCH_TIME_NOW, Int64(100 * NSEC_PER_MSEC)) dispatch_after(time, dispatch_get_main_queue()) { if webView.URL != url { // The page changed during the delay, so we missed our chance to get a thumbnail. return } if let screenshot = self.screenshotHelper.takeScreenshot(tab, aspectRatio: CGFloat(ThumbnailCellUX.ImageAspectRatio), quality: 0.5) { let thumbnail = Thumbnail(image: screenshot) self.profile.thumbnails.set(url, thumbnail: thumbnail, complete: nil) } } } if tab == tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } } } extension BrowserViewController: WKUIDelegate { func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { // If the page uses window.open() or target="_blank", open the page in a new tab. // TODO: This doesn't work for window.open() without user action (bug 1124942). let tab = tabManager.addTab(request: navigationAction.request, configuration: configuration) return tab.webView } func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { tabManager.selectTab(tabManager.getTab(webView)) // Show JavaScript alerts. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler() })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { tabManager.selectTab(tabManager.getTab(webView)) // Show JavaScript confirm dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(true) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(false) })) presentViewController(alertController, animated: true, completion: nil) } func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String!) -> Void) { tabManager.selectTab(tabManager.getTab(webView)) // Show JavaScript input dialogs. let title = frame.request.URL!.host let alertController = UIAlertController(title: title, message: prompt, preferredStyle: UIAlertControllerStyle.Alert) var input: UITextField! alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField!) in textField.text = defaultText input = textField }) alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in completionHandler(input.text) })) alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in completionHandler(nil) })) presentViewController(alertController, animated: true, completion: nil) } } extension BrowserViewController: ReaderModeDelegate, UIPopoverPresentationControllerDelegate { func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab == browser { println("DEBUG: New readerModeState: \(state.rawValue)") urlBar.updateReaderModeState(state) } } func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) { self.showReaderModeBar(animated: true) browser.showContent(animated: true) } // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } } extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String:AnyObject] = style.encode() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let readerMode = tabManager.getTab(tabIndex).getHelper(name: "ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.Active { readerMode.style = style } } } } } extension BrowserViewController: LongPressDelegate { func longPressBrowserHelper(longPressBrowserHelper: LongPressBrowserHelper, didLongPressElements elements: [LongPressElementType : NSURL]) { var actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) var dialogTitleURL: NSURL? if let linkURL = elements[LongPressElementType.Link] { dialogTitleURL = linkURL let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu option") var openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) in let request = NSURLRequest(URL: linkURL) let tab = self.tabManager.addTab(request: request) } actionSheetController.addAction(openNewTabAction) let copyTitle = NSLocalizedString("Copy", comment: "Context menu option") var copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in var pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = linkURL.absoluteString } actionSheetController.addAction(copyAction) } if let imageURL = elements[LongPressElementType.Image] { if dialogTitleURL == nil { dialogTitleURL = imageURL } let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu option") var saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in var imageData = NSData(contentsOfURL: imageURL) if imageData != nil { UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!), nil, nil, nil) } }) } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image URL", comment: "Context menu option") var copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in var pasteBoard = UIPasteboard.generalPasteboard() pasteBoard.string = imageURL.absoluteString } actionSheetController.addAction(copyAction) } actionSheetController.title = dialogTitleURL!.absoluteString var cancelAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: nil) actionSheetController.addAction(cancelAction) if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = self.view popoverPresentationController.sourceRect = CGRectInset(CGRect(origin: longPressBrowserHelper.longPressGestureRecognizer.locationInView(self.view), size: CGSizeZero), -8, -8) popoverPresentationController.permittedArrowDirections = .Any } self.presentViewController(actionSheetController, animated: true, completion: nil) } } extension BrowserViewController : UIViewControllerTransitioningDelegate { func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return TransitionManager(show: false) } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return TransitionManager(show: true) } } extension BrowserViewController : Transitionable { func transitionablePreHide(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's off screen for i in 0..<tabManager.count { let tab = tabManager.getTab(i) tab.webView.hidden = true } self.homePanelController?.view.hidden = true } func transitionablePreShow(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's off screen for i in 0..<tabManager.count { let tab = tabManager.getTab(i) tab.webView.hidden = true } self.homePanelController?.view.hidden = true } func transitionableWillShow(transitionable: Transitionable, options: TransitionOptions) { view.alpha = 1 footer.transform = CGAffineTransformIdentity header.transform = CGAffineTransformIdentity } func transitionableWillHide(transitionable: Transitionable, options: TransitionOptions) { view.alpha = 0 footer.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, footer.frame.height) header.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, header.frame.height) } func transitionableWillComplete(transitionable: Transitionable, options: TransitionOptions) { // Move all the webview's back on screen for i in 0..<tabManager.count { let tab = tabManager.getTab(i) tab.webView.hidden = false } self.homePanelController?.view.hidden = false } } extension BrowserViewController { private func updateScrollbarInsets() { if let tab = self.tabManager.selectedTab { tab.webView.scrollView.contentInset = UIEdgeInsets(top: self.header.frame.height + (self.readerModeBar.hidden ? 0 : self.readerModeBar.frame.height), left: 0, bottom: toolbar?.frame.height ?? 0, right: 0) tab.webView.scrollView.scrollIndicatorInsets = UIEdgeInsets(top: self.header.frame.height + (self.readerModeBar.hidden ? 0 : self.readerModeBar.frame.height), left: 0, bottom: toolbar?.frame.height ?? 0, right: 0) } } func showReaderModeBar(#animated: Bool) { if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } } else { readerModeBar.unread = true readerModeBar.added = false } readerModeBar.hidden = false updateScrollbarInsets() } func hideReaderModeBar(#animated: Bool) { readerModeBar.hidden = true updateScrollbarInsets() } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { if let webView = tabManager.selectedTab?.webView { let backList = webView.backForwardList.backList as! [WKBackForwardListItem] let forwardList = webView.backForwardList.forwardList as! [WKBackForwardListItem] if let currentURL = webView.backForwardList.currentItem?.URL { if let readerModeURL = ReaderModeUtils.encodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == readerModeURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL { webView.goToBackForwardListItem(forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object) { ReaderModeCache.sharedInstance.put(currentURL, readabilityResult, error: nil) webView.loadRequest(NSURLRequest(URL: readerModeURL)) } }) } } } } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let webView = tabManager.selectedTab?.webView { let backList = webView.backForwardList.backList as! [WKBackForwardListItem] let forwardList = webView.backForwardList.forwardList as! [WKBackForwardListItem] if let currentURL = webView.backForwardList.currentItem?.URL { if let originalURL = ReaderModeUtils.decodeURL(currentURL) { if backList.count > 1 && backList.last?.URL == originalURL { webView.goToBackForwardListItem(backList.last!) } else if forwardList.count > 0 && forwardList.first?.URL == originalURL { webView.goToBackForwardListItem(forwardList.first!) } else { webView.loadRequest(NSURLRequest(URL: originalURL)) } } } } } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .Settings: if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover let popoverPresentationController = readerModeStyleViewController.popoverPresentationController popoverPresentationController?.backgroundColor = UIColor.whiteColor() popoverPresentationController?.delegate = self popoverPresentationController?.sourceView = readerModeBar popoverPresentationController?.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: AppConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up self.presentViewController(readerModeStyleViewController, animated: true, completion: nil) } case .MarkAsRead: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = true } } case .MarkAsUnread: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .AddToReadingList: if let tab = tabManager.selectedTab, let url = tab.url where ReaderModeUtils.isReaderModeURL(url) { if let url = ReaderModeUtils.decodeURL(url), let absoluteString = url.absoluteString { let result = profile.readingList?.createRecordWithURL(absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail? readerModeBar.added = true } } case .RemoveFromReadingList: if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false } } } } } extension BrowserViewController: UIStateRestoring { override func encodeRestorableStateWithCoder(coder: NSCoder) { super.encodeRestorableStateWithCoder(coder) tabManager.encodeRestorableStateWithCoder(coder) } override func decodeRestorableStateWithCoder(coder: NSCoder) { super.decodeRestorableStateWithCoder(coder) tabManager.decodeRestorableStateWithCoder(coder) } } private class BrowserScreenshotHelper: ScreenshotHelper { private weak var controller: BrowserViewController? init(controller: BrowserViewController) { self.controller = controller } func takeScreenshot(tab: Browser, aspectRatio: CGFloat, quality: CGFloat) -> UIImage? { if let url = tab.url { if url.absoluteString == HomeURL { if let homePanel = controller?.homePanelController { return homePanel.view.screenshot(aspectRatio, quality: quality) } } else { let offset = CGPointMake(0, -tab.webView.scrollView.contentInset.top) return tab.webView.screenshot(aspectRatio, offset: offset, quality: quality) } } return nil } }
mpl-2.0
ad14fd0a5dc09a7b439bfc31af0ac77c
42.570825
234
0.641031
5.751349
false
false
false
false
ingresse/ios-sdk
IngresseSDK/Model/TransactionTicket.swift
1
1798
// // Copyright © 2017 Ingresse. All rights reserved. // public class TransactionTicket: NSObject, Codable { @objc public var id: Int = 0 @objc public var code: String = "" @objc public var name: String = "" @objc public var checked: Bool = false @objc public var lastUpdate: Int = 0 @objc public var transferred: Bool = false @objc public var ticket: String = "" @objc public var type: String = "" @objc public var ticketId: Int = 0 @objc public var typeId: Int = 0 @objc public var price: String = "" @objc public var tax: String = "" @objc public var percentTax: Int = 0 @objc public var sessions: [BasketSessions] = [] public required init(from decoder: Decoder) throws { guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return } id = container.decodeKey(.id, ofType: Int.self) code = container.decodeKey(.code, ofType: String.self) name = container.decodeKey(.name, ofType: String.self) checked = container.decodeKey(.checked, ofType: Bool.self) lastUpdate = container.decodeKey(.lastUpdate, ofType: Int.self) transferred = container.decodeKey(.transferred, ofType: Bool.self) ticket = container.decodeKey(.ticket, ofType: String.self) ticketId = container.decodeKey(.ticketId, ofType: Int.self) type = container.decodeKey(.type, ofType: String.self) typeId = container.decodeKey(.typeId, ofType: Int.self) price = container.decodeKey(.price, ofType: String.self) tax = container.decodeKey(.tax, ofType: String.self) percentTax = container.decodeKey(.percentTax, ofType: Int.self) sessions = try container.decodeIfPresent([BasketSessions].self, forKey: .sessions) ?? [] } }
mit
f2c174ad4f8e7f9da3fcf6a43a72d903
43.925
96
0.666667
4.21831
false
false
false
false
ambientlight/GithubIssuesExtension
GithubIssueEditorExtension/extensions/extension_String.swift
1
6070
// // extension_String.swift // GithubIssuesExtension // // Created by Taras Vozniuk on 23/11/2016. // Copyright © 2016 Ambientlight. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation extension String { /// checks whether the reciever is and xcode-placeholder public var isPlaceholder: Bool { return self.hasPrefix("<#") && self.hasSuffix("#>") } /// Removes occurences of all characters from passed character set /// /// - Parameter set: a character set of characters to remove from string /// - Returns: the resulting string with all occuranences of chars from character set removed public func removingCharacters(in set: CharacterSet) -> String { var target = self for character in set.allCharacters { target = target.replacingOccurrences(of: "\(character)", with: String()) } return target } /// Verifies whether the reciever(regex pattern) has matches in a passed string /// /// - Parameter string: string to validate the regex pattern /// - Returns: true if the passed string has matches of reciever(regex patterm) public func hasMatches(in string: String) -> Bool { guard let regex = try? NSRegularExpression(pattern: self, options: .caseInsensitive), regex.numberOfCaptureGroups != 0 else { return false } return regex.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.characters.count)) > 0 } /// Retrieve the capturing groups values in a first match of reciever(regex pattern) in the passed string /// /// - Parameter string: string to extract the capturing groups of reciever(regex pattern) /// - Returns: an array of capturing groups values, empty array if passed string doesn't match reciever(regex pattern) public func firstMatchCapturingGroups(in string: String) -> [String] { guard let regex = try? NSRegularExpression(pattern: self, options: .caseInsensitive), regex.numberOfCaptureGroups != 0 else { return [] } if let match = regex.firstMatch(in: string, options: [], range: NSMakeRange(0, string.characters.count)){ var targetStrings = [String]() for index in 1 ... regex.numberOfCaptureGroups { let groupRange = match.rangeAt(index) targetStrings.append((string as NSString).substring(with: groupRange)) } return targetStrings } else { return [] } } /// Enumerates capturing groups of each match of reciever(regex pattern) in a passed string /// /// - Parameters: /// - string: string to extract the capturing groups of reciever(regex pattern) /// - enumerator: callback capturing groups enumerator public func enumerateCapturingGroups(in string: String, enumerator: ([String]) -> Void){ guard let regex = try? NSRegularExpression(pattern: self, options: .caseInsensitive), regex.numberOfCaptureGroups != 0 else { return } let matches = regex.matches(in: string, options: [], range: NSMakeRange(0, string.characters.count)) for match in matches { var targetStrings = [String]() for index in 1 ... regex.numberOfCaptureGroups { let groupRange = match.rangeAt(index) targetStrings.append((string as NSString).substring(with: groupRange)) } enumerator(targetStrings) } } /// Retrieve capturing groups values in each match of reciever(regex pattern) in the passed string /// /// - Parameter string: string to extract the capturing groups of reciever(regex pattern) /// - Returns: array of array of capturing groups values (for each match), empty array if passed string doesn't match reciever(regex pattern) public func capturingGroups(in string: String) -> [[String]] { var targetCapturingGroups = [[String]]() self.enumerateCapturingGroups(in: string) { (capturingGroups) in targetCapturingGroups.append(capturingGroups) } return targetCapturingGroups } /// Extracts the indentation (in form of spaces or tabs) present before any other content /// /// - Returns: indentation string (in form of spaces or tabs)s public func extractingIndentation() -> String { let nonSpaceCharacters = CharacterSet.whitespacesAndNewlines.inverted let indentationEndIndex: String.Index let targetLine = self // retriving the possion of next character after indentation if let range = targetLine.rangeOfCharacter(from: nonSpaceCharacters){ indentationEndIndex = range.lowerBound } else { // if line contains only whitespaces and newlines, set the indendationEndIndex // to the position before the last (carrier return) character indentationEndIndex = (targetLine.isEmpty) ? targetLine.endIndex : targetLine.index(before: targetLine.endIndex) } // construct the indendentation string that will be prefixed in each string we will insert let currentIndentation = targetLine.substring(to: indentationEndIndex).trimmingCharacters(in: CharacterSet.newlines) return currentIndentation } }
apache-2.0
c2d18d3fd8561a5268287c561757697c
41.145833
145
0.651837
5.200514
false
false
false
false
mutualmobile/VIPER-SWIFT
VIPER-SWIFT/Classes/Modules/Add/User Interface/Wireframe/AddWireframe.swift
1
1965
// // AddWireframe.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit let AddViewControllerIdentifier = "AddViewController" class AddWireframe : NSObject, UIViewControllerTransitioningDelegate { var addPresenter : AddPresenter? var presentedViewController : UIViewController? func presentAddInterfaceFromViewController(_ viewController: UIViewController) { let newViewController = addViewController() newViewController.eventHandler = addPresenter newViewController.modalPresentationStyle = .custom newViewController.transitioningDelegate = self addPresenter?.configureUserInterfaceForPresentation(newViewController) viewController.present(newViewController, animated: true, completion: nil) presentedViewController = newViewController } func dismissAddInterface() { presentedViewController?.dismiss(animated: true, completion: nil) } func addViewController() -> AddViewController { let storyboard = mainStoryboard() let addViewController: AddViewController = storyboard.instantiateViewController(withIdentifier: AddViewControllerIdentifier) as! AddViewController return addViewController } func mainStoryboard() -> UIStoryboard { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) return storyboard } // MARK: UIViewControllerTransitioningDelegate func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AddDismissalTransition() } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return AddPresentationTransition() } }
mit
02cebb4cb97851d5051eda7f1f930de9
34.089286
169
0.733333
6.616162
false
false
false
false
zhuhaow/Soca-iOS
Pods/SocaCore/Pod/Classes/Socket/Adapter/HTTPAdapter.swift
2
2996
// // HTTPAdapter.swift // Soca // // Created by Zhuhao Wang on 2/22/15. // Copyright (c) 2015 Zhuhao Wang. All rights reserved. // import Foundation class HTTPAdapter : ServerAdapter { var auth: Authentication? convenience init(request: ConnectRequest, delegateQueue: dispatch_queue_t, serverHost: String, serverPort: Int, auth: Authentication?) { self.init(request: request, delegateQueue: delegateQueue, serverHost: serverHost, serverPort: serverPort) self.auth = auth } override func connectToRemote() { socket.connectToHost(serverHost, withPort: serverPort) } override func connectionEstablished() { connectResponse = connectRequest.getResponse() if connectRequest.method == .HTTP_REQUEST { if let auth = auth { connectResponse!.headerToAdd = [("Proxy-Authorization", auth.authString())] } connectResponse?.rewritePath = false connectResponse?.removeHTTPProxyHeader = false } else { var message = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "CONNECT", NSURL(string: "\(connectRequest.host):\(connectRequest.port)"), kCFHTTPVersion1_1).takeRetainedValue() if let auth = auth { CFHTTPMessageSetHeaderFieldValue(message, "Proxy-Authorization", auth.authString()) } CFHTTPMessageSetHeaderFieldValue(message, "Host", "\(connectRequest.host):\(connectRequest.port)") CFHTTPMessageSetHeaderFieldValue(message, "Content-Length", "0") var requestData = CFHTTPMessageCopySerializedMessage(message).takeRetainedValue() writeData(requestData, withTag: SocketTag.HTTP.Header) readDataToData(Utils.HTTPData.DoubleCRLF, withTag: SocketTag.HTTP.ConnectResponse) } sendResponse(response: connectResponse) } override func proxySocketReadyForward() { if connectRequest.method == .HTTP_REQUEST { readDataForForward() } } override func updateRequest(request: ConnectRequest) -> ConnectResponse? { connectRequest = request return getResponseForHTTPRequest() } override func didReadData(data: NSData, withTag tag: Int) { switch tag { case SocketTag.HTTP.ConnectResponse: readDataForForward() case SocketTag.Forward: sendData(data) readDataForForward() default: break } } override func didReceiveDataFromLocal(data: NSData) { writeData(data, withTag: SocketTag.Forward) } func getResponseForHTTPRequest() -> ConnectResponse { let response = connectRequest.getResponse() if let auth = auth { response.headerToAdd = [("Proxy-Authorization", auth.authString())] } response.rewritePath = false response.removeHTTPProxyHeader = false return response } }
mit
7ccb836e847bac15d73cc307f1fa21f4
35.54878
187
0.646195
5.312057
false
false
false
false
rnystrom/WatchKit-by-Tutorials
SousChef/SousChef/Controllers/RecipeDetailController.swift
1
3273
// // RecipeDetailController.swift // SousChef // // Created by Ryan Nystrom on 11/24/14. // Copyright (c) 2014 Ryan Nystrom. All rights reserved. // import UIKit import SousChefKit class RecipeDetailController: UIViewController { var recipe: Recipe? lazy var groceryList = GroceryList() enum RecipeDetailSelection: Int { case Ingredients = 0, Steps } lazy var ingredientsController: RecipeIngredientsController! = { let controller = self.storyboard?.instantiateViewControllerWithIdentifier("RecipeIngredientsController") as? RecipeIngredientsController controller?.recipe = self.recipe controller?.tableView.contentInset = self.tableInsets return controller }() lazy var stepsController: RecipeStepsController! = { let controller = self.storyboard?.instantiateViewControllerWithIdentifier("RecipeStepsController") as? RecipeStepsController controller?.steps = self.recipe?.steps controller?.timers = self.recipe?.timers controller?.tableView.contentInset = self.tableInsets return controller }() // don't rely on automaticallyAdjustsScrollViewInsets since we're swapping child controllers var tableInsets: UIEdgeInsets { var insets = UIEdgeInsetsZero if let nav = navigationController { insets.top = CGRectGetHeight(nav.navigationBar.bounds) insets.top += 20 // status bar } if let tab = tabBarController { insets.bottom = CGRectGetHeight(tab.tabBar.bounds) } return insets } override func viewDidLoad() { super.viewDidLoad() updateSelectedController(.Ingredients) } func onPromptAddGroceries(sender: AnyObject) { let name = recipe?.name ?? "this recipe" let alert = UIAlertController(title: "Grocery List", message: "Do you want to add all of the ingredients for \(name) to your grocery list?", preferredStyle: .Alert) // TODO: add all items to grocery list alert.addAction(UIAlertAction(title: "Add Items", style: .Default, handler: { _ in if let items = self.recipe?.ingredients { for item in items { self.groceryList.addItemToList(item) } self.groceryList.sync() } })) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(alert, animated: true, completion: nil) } @IBAction func onSegmentChange(sender: UISegmentedControl) { if let index = RecipeDetailSelection(rawValue: sender.selectedSegmentIndex) { updateSelectedController(index) } else { println("Unsupported recipe detail selection \(sender.selectedSegmentIndex)") abort() } } func updateSelectedController(selected: RecipeDetailSelection) { switch selected { case .Ingredients: addSubViewController(ingredientsController) stepsController.removeFromSuperViewController() navigationItem.rightBarButtonItem = promptActionButton() break case .Steps: addSubViewController(stepsController) ingredientsController.removeFromSuperViewController() navigationItem.rightBarButtonItem = nil break } } func promptActionButton() -> UIBarButtonItem { return UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "onPromptAddGroceries:") } }
mit
881fd7acbedc447d8f4508c24a1b9abc
31.405941
168
0.724106
4.974164
false
false
false
false
Ribeiro/PapersPlease
Classes/ValidationTypes/ValidatorUITextCompareType.swift
1
2632
// // ValidatorUITextCompareType.swift // PapersPlease // // Created by Brett Walker on 7/4/14. // Copyright (c) 2014 Poet & Mountain, LLC. All rights reserved. // import Foundation import UIKit class ValidatorUITextCompareType:ValidatorStringCompareType { var lastStringValue:String = "" override init() { super.init() self.sendsUpdates = true } func dealloc() { NSNotificationCenter.defaultCenter().removeObserver(self) } override func isTextValid(text: String) -> Bool { super.isTextValid(text) self.lastStringValue = text return self.valid } func registerTextFieldToMatch(textField:UITextField) { // add listener for object which will pass on text changes to validator unit NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textDidChangeNotification:"), name: UITextFieldTextDidChangeNotification, object: textField) self.comparisonString = textField.text } func registerTextViewToMatch(textView:UITextView) { // add listener for object which will pass on text changes to validator unit NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("textDidChangeNotification:"), name: UITextViewTextDidChangeNotification, object: textView) self.comparisonString = textView.text } // MARK: Notification methods @objc func textDidChangeNotification(notification:NSNotification) { if (notification.name == UITextFieldTextDidChangeNotification) { if let text_field:UITextField = notification.object as? UITextField { self.comparisonString = text_field.text } } else if (notification.name == UITextViewTextDidChangeNotification) { if let text_view:UITextView = notification.object as? UITextView { self.comparisonString = text_view.text } } // because we are observing a UI text object to match against, we have to manually re-validate here // otherwise, .valid could return true when it actually isn't self.valid = self.isTextValid(self.lastStringValue) // post notification let dict = ["status" : self.valid] NSNotificationCenter.defaultCenter().postNotificationName(ValidatorUpdateNotification, object: self, userInfo: dict) } class override func type() -> String { return "ValidationTypeUITextCompare" } }
mit
079635caa140fc4735fdfe005aeeadb5
30.345238
175
0.654255
5.471933
false
false
false
false
tjw/swift
test/decl/protocol/conforms/self.swift
1
2333
// RUN: %target-typecheck-verify-swift protocol P { associatedtype T = Int func hasDefault() func returnsSelf() -> Self func hasDefaultTakesT(_: T) func returnsSelfTakesT(_: T) -> Self } extension P { func hasDefault() {} func returnsSelf() -> Self { return self } func hasDefaultTakesT(_: T) {} func returnsSelfTakesT(_: T) -> Self { // expected-error {{method 'returnsSelfTakesT' in non-final class 'Class' cannot be implemented in a protocol extension because it returns `Self` and has associated type requirements}} return self } } // This fails class Class : P {} // This succeeds, because the class is final final class FinalClass : P {} // This succeeds, because we're not using the default implementation class NonFinalClass : P { func returnsSelfTakesT(_: T) -> Self { return self } } // Test for default implementation that comes from a constrained extension // - https://bugs.swift.org/browse/SR-7422 // FIXME: Better error message here? class SillyClass {} protocol HasDefault { func foo() // expected-note@-1 {{protocol requires function 'foo()' with type '() -> ()'; do you want to add a stub?}} } extension HasDefault where Self == SillyClass { func foo() {} // expected-note@-1 {{candidate has non-matching type '<Self> () -> ()'}} } extension SillyClass : HasDefault {} // expected-error@-1 {{type 'SillyClass' does not conform to protocol 'HasDefault'}} // This is OK, though class SeriousClass {} extension HasDefault where Self : SeriousClass { func foo() {} // expected-note@-1 {{candidate has non-matching type '<Self> () -> ()'}} // FIXME: the above diangostic is from trying to check conformance for // 'SillyClass' and not 'SeriousClass'. Evidently name lookup finds members // from all constrained extensions, and then if any don't have a matching // generic signature, diagnostics doesn't really know what to do about it. } extension SeriousClass : HasDefault {} // https://bugs.swift.org/browse/SR-7428 protocol Node { associatedtype ValueType = Int func addChild<ChildType>(_ child: ChildType) where ChildType: Node, ChildType.ValueType == Self.ValueType } extension Node { func addChild<ChildType>(_ child: ChildType) where ChildType: Node, ChildType.ValueType == Self.ValueType {} } class IntNode: Node {}
apache-2.0
1629664d43d344b3e684ff4d5edebbf7
25.511364
225
0.698671
4.06446
false
false
false
false
matteinn/VialerSIPLib
Example/VialerSIPLib/NSUserActivity+StartCallConvertible.swift
2
1250
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Extension to allow creating a CallKit CXStartCallAction from an NSUserActivity which the app was launched with */ import Foundation import Intents @available(iOS 10.0, *) extension NSUserActivity: StartCallConvertible { var startCallHandle: String? { guard let interaction = interaction, let startCallIntent = interaction.intent as? SupportedStartCallIntent, let contact = startCallIntent.contacts?.first else { return nil } return contact.personHandle?.value } var video: Bool? { guard let interaction = interaction, let startCallIntent = interaction.intent as? SupportedStartCallIntent else { return nil } return startCallIntent is INStartVideoCallIntent } } @available(iOS 10.0, *) protocol SupportedStartCallIntent { var contacts: [INPerson]? { get } } @available(iOS 10.0, *) extension INStartAudioCallIntent: SupportedStartCallIntent {} @available(iOS 10.0, *) extension INStartVideoCallIntent: SupportedStartCallIntent {}
gpl-3.0
163600515f34db612a811854b4366729
25
111
0.674679
4.894118
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/NSTimeZone.swift
1
11989
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // @_implementationOnly import CoreFoundation open class NSTimeZone : NSObject, NSCopying, NSSecureCoding, NSCoding { typealias CFType = CFTimeZone private var _base = _CFInfo(typeID: CFTimeZoneGetTypeID()) private var _name: UnsafeMutableRawPointer? = nil private var _data: UnsafeMutableRawPointer? = nil private var _periods: UnsafeMutableRawPointer? = nil private var _periodCnt = Int32(0) internal final var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) } // Primary creation method is +timeZoneWithName:; the // data-taking variants should rarely be used directly public convenience init?(name tzName: String) { self.init(name: tzName, data: nil) } public init?(name tzName: String, data aData: Data?) { super.init() /* From https://developer.apple.com/documentation/foundation/nstimezone/1387250-init: "Discussion As of macOS 10.6, the underlying implementation of this method has been changed to ignore the specified data parameter." */ if !_CFTimeZoneInit(_cfObject, tzName._cfObject, nil) { return nil } } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let name = aDecoder.decodeObject(of: NSString.self, forKey: "NS.name") let data = aDecoder.decodeObject(of: NSData.self, forKey: "NS.data") if name == nil { return nil } self.init(name: String._unconditionallyBridgeFromObjectiveC(name), data: data?._swiftObject) } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSTimeZone else { return false } return isEqual(to: other._swiftObject) } open override var description: String { return CFCopyDescription(_cfObject)._swiftObject } deinit { _CFDeinit(self) } // `init(forSecondsFromGMT:)` is not a failable initializer, so we need a designated initializer that isn't failable. internal init(_name tzName: String) { super.init() _CFTimeZoneInit(_cfObject, tzName._cfObject, nil) } // Time zones created with this never have daylight savings and the // offset is constant no matter the date; the name and abbreviation // do NOT follow the POSIX convention (of minutes-west). public convenience init(forSecondsFromGMT seconds: Int) { let sign = seconds < 0 ? "-" : "+" let absoluteValue = abs(seconds) var minutes = absoluteValue / 60 if (absoluteValue % 60) >= 30 { minutes += 1 } var hours = minutes / 60 minutes %= 60 hours = min(hours, 99) // Two digits only; leave CF to enforce actual max offset. let mm = minutes < 10 ? "0\(minutes)" : "\(minutes)" let hh = hours < 10 ? "0\(hours)" : "\(hours)" self.init(_name: "GMT" + sign + hh + mm) } public convenience init?(abbreviation: String) { let abbr = abbreviation._cfObject let possibleName: NSString? = withExtendedLifetime(abbr) { return unsafeBitCast(CFDictionaryGetValue(CFTimeZoneCopyAbbreviationDictionary(), unsafeBitCast(abbr, to: UnsafeRawPointer.self)), to: NSString?.self) } guard let name = possibleName else { return nil } self.init(name: name._swiftObject , data: nil) } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.name._bridgeToObjectiveC(), forKey:"NS.name") // Darwin versions of this method can and will encode mutable data, however it is not required for compatibility aCoder.encode(self.data._bridgeToObjectiveC(), forKey:"NS.data") } public static var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open var name: String { guard type(of: self) === NSTimeZone.self else { NSRequiresConcreteImplementation() } return CFTimeZoneGetName(_cfObject)._swiftObject } open var data: Data { guard type(of: self) === NSTimeZone.self else { NSRequiresConcreteImplementation() } return CFTimeZoneGetData(_cfObject)._swiftObject } open func secondsFromGMT(for aDate: Date) -> Int { guard type(of: self) === NSTimeZone.self else { NSRequiresConcreteImplementation() } return Int(CFTimeZoneGetSecondsFromGMT(_cfObject, aDate.timeIntervalSinceReferenceDate)) } open func abbreviation(for aDate: Date) -> String? { guard type(of: self) === NSTimeZone.self else { NSRequiresConcreteImplementation() } return CFTimeZoneCopyAbbreviation(_cfObject, aDate.timeIntervalSinceReferenceDate)._swiftObject } open func isDaylightSavingTime(for aDate: Date) -> Bool { guard type(of: self) === NSTimeZone.self else { NSRequiresConcreteImplementation() } return CFTimeZoneIsDaylightSavingTime(_cfObject, aDate.timeIntervalSinceReferenceDate) } open func daylightSavingTimeOffset(for aDate: Date) -> TimeInterval { guard type(of: self) === NSTimeZone.self else { NSRequiresConcreteImplementation() } return CFTimeZoneGetDaylightSavingTimeOffset(_cfObject, aDate.timeIntervalSinceReferenceDate) } open func nextDaylightSavingTimeTransition(after aDate: Date) -> Date? { guard type(of: self) === NSTimeZone.self else { NSRequiresConcreteImplementation() } let ti = CFTimeZoneGetNextDaylightSavingTimeTransition(_cfObject, aDate.timeIntervalSinceReferenceDate) guard ti > 0 else { return nil } return Date(timeIntervalSinceReferenceDate: ti) } open class var system: TimeZone { return CFTimeZoneCopySystem()._swiftObject } open class func resetSystemTimeZone() { CFTimeZoneResetSystem() } open class var `default`: TimeZone { get { return CFTimeZoneCopyDefault()._swiftObject } set { CFTimeZoneSetDefault(newValue._cfObject) } } open class var local: TimeZone { return TimeZone(adoptingReference: __NSLocalTimeZone.shared, autoupdating: true) } open class var knownTimeZoneNames: [String] { guard let knownNames = CFTimeZoneCopyKnownNames() else { return [] } return knownNames._nsObject._bridgeToSwift() as! [String] } open class var abbreviationDictionary: [String : String] { get { guard let dictionary = CFTimeZoneCopyAbbreviationDictionary() else { return [:] } return dictionary._nsObject._bridgeToSwift() as! [String : String] } set { CFTimeZoneSetAbbreviationDictionary(newValue._cfObject) } } open class var timeZoneDataVersion: String { return __CFTimeZoneCopyDataVersionString()._swiftObject } open var secondsFromGMT: Int { let currentDate = Date() return secondsFromGMT(for: currentDate) } /// The abbreviation for the receiver, such as "EDT" (Eastern Daylight Time). (read-only) /// /// This invokes `abbreviationForDate:` with the current date as the argument. open var abbreviation: String? { let currentDate = Date() return abbreviation(for: currentDate) } open var isDaylightSavingTime: Bool { let currentDate = Date() return isDaylightSavingTime(for: currentDate) } open var daylightSavingTimeOffset: TimeInterval { let currentDate = Date() return daylightSavingTimeOffset(for: currentDate) } /*@NSCopying*/ open var nextDaylightSavingTimeTransition: Date? { let currentDate = Date() return nextDaylightSavingTimeTransition(after: currentDate) } open func isEqual(to aTimeZone: TimeZone) -> Bool { return CFEqual(self._cfObject, aTimeZone._cfObject) } open func localizedName(_ style: NameStyle, locale: Locale?) -> String? { let cfStyle = CFTimeZoneNameStyle(rawValue: style.rawValue)! return CFTimeZoneCopyLocalizedName(self._cfObject, cfStyle, locale?._cfObject ?? CFLocaleCopyCurrent())._swiftObject } } extension NSTimeZone: _SwiftBridgeable { typealias SwiftType = TimeZone var _swiftObject: TimeZone { return TimeZone(reference: self) } } extension CFTimeZone : _SwiftBridgeable, _NSBridgeable { typealias NSType = NSTimeZone var _nsObject : NSTimeZone { return unsafeBitCast(self, to: NSTimeZone.self) } var _swiftObject: TimeZone { return _nsObject._swiftObject } } extension TimeZone : _NSBridgeable { typealias NSType = NSTimeZone typealias CFType = CFTimeZone var _nsObject : NSTimeZone { return _bridgeToObjectiveC() } var _cfObject : CFTimeZone { return _nsObject._cfObject } } extension NSTimeZone { public enum NameStyle : Int { case standard // Central Standard Time case shortStandard // CST case daylightSaving // Central Daylight Time case shortDaylightSaving // CDT case generic // Central Time case shortGeneric // CT } } extension NSNotification.Name { public static let NSSystemTimeZoneDidChange = NSNotification.Name(rawValue: kCFTimeZoneSystemTimeZoneDidChangeNotification._swiftObject) } internal class __NSLocalTimeZone: NSTimeZone { static var shared = __NSLocalTimeZone() private init() { super.init(_name: "GMT+0000") } public convenience required init?(coder aDecoder: NSCoder) { // We do not encode details of the local time zone, merely the placeholder object. self.init() } override func encode(with aCoder: NSCoder) { // We do not encode details of the local time zone, merely the placeholder object. } private var system: NSTimeZone { return NSTimeZone.system._nsObject } override var name: String { return system.name } override var data: Data { return system.data } override func secondsFromGMT(for aDate: Date) -> Int { return system.secondsFromGMT(for: aDate) } override func abbreviation(for aDate: Date) -> String? { return system.abbreviation(for: aDate) } override func isDaylightSavingTime(for aDate: Date) -> Bool { return system.isDaylightSavingTime(for: aDate) } override func daylightSavingTimeOffset(for aDate: Date) -> TimeInterval { return system.daylightSavingTimeOffset(for: aDate) } override func nextDaylightSavingTimeTransition(after aDate: Date) -> Date? { return system.nextDaylightSavingTimeTransition(after: aDate) } override func localizedName(_ style: NSTimeZone.NameStyle, locale: Locale?) -> String? { return system.localizedName(style, locale: locale) } override var description: String { return "Local Time Zone (\(system.description))" } override func copy(with zone: NSZone? = nil) -> Any { return self } }
apache-2.0
01606a692171d4f04dbc4695283ba8c2
34.158358
162
0.65485
5.041632
false
false
false
false
nathawes/swift
test/Interop/Cxx/extern-var/extern-var-silgen.swift
12
2352
// RUN: %target-swift-emit-sil %s -I %S/Inputs -enable-cxx-interop | %FileCheck %s import ExternVar func getCounter() -> CInt { return counter } // CHECK: // clang name: counter // CHECK: sil_global public_external @counter : $Int32 // CHECK: // clang name: Namespaced::counter // CHECK: sil_global public_external @{{_ZN10Namespaced7counterE|\?counter@Namespaced@@3HA}} : $Int32 // CHECK: sil hidden @$s4main10getCounters5Int32VyF : $@convention(thin) () -> Int32 // CHECK: [[COUNTER:%.*]] = global_addr @counter : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[COUNTER]] : $*Int32 // CHECK: [[LOAD:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: return [[LOAD]] : $Int32 func setCounter(_ c: CInt) { counter = c } // CHECK: sil hidden @$s4main10setCounteryys5Int32VF : $@convention(thin) (Int32) -> () // CHECK: [[COUNTER:%.*]] = global_addr @counter : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[COUNTER]] : $*Int32 // CHECK: store %0 to [[ACCESS]] : $*Int32 func getNamespacedCounter() -> CInt { return Namespaced.counter } // sil hidden @$s4main20getNamespacedCounters5Int32VyF : $@convention(thin) () -> Int32 // CHECK: [[ADDR:%.*]] = global_addr @{{_ZN10Namespaced7counterE|\?counter@Namespaced@@3HA}} : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int32 // CHECK: [[LOAD:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: return [[LOAD]] : $Int32 func setNamespacedCounter(_ c: CInt) { Namespaced.counter = c } // CHECK: sil hidden @$s4main20setNamespacedCounteryys5Int32VF : $@convention(thin) (Int32) -> () // CHECK: [[ADDR:%.*]] = global_addr @{{_ZN10Namespaced7counterE|\?counter@Namespaced@@3HA}} : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int32 // CHECK: store %0 to [[ACCESS]] : $*Int32 func modifyInout(_ c: inout CInt) { c = 42 } func passingVarAsInout() { modifyInout(&counter) } // CHECK: sil hidden @$s4main17passingVarAsInoutyyF : $@convention(thin) () -> () // CHECK: [[COUNTER:%.*]] = global_addr @counter : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[COUNTER]] : $*Int32 // CHECK: [[FUNCTION:%.*]] = function_ref @$s4main11modifyInoutyys5Int32VzF : $@convention(thin) (@inout Int32) -> () // CHECK: apply [[FUNCTION]]([[ACCESS]]) : $@convention(thin) (@inout Int32) -> ()
apache-2.0
adef05bb78b5d729f0717d20b4529475
38.2
117
0.639031
3.262136
false
false
false
false
nathawes/swift
test/SourceKit/CursorInfo/cursor_info_async.swift
23
1853
import Foo // REQUIRES: objc_interop // RUN: %empty-directory(%t) // RUN: %build-clang-importer-objc-overlays // Perform 8 concurrent cursor infos, which is often enough to cause // contention. We disable printing the requests to minimize delay. // RUN: %sourcekitd-test -req=interface-gen-open -module Foo -- \ // RUN: -F %S/../Inputs/libIDE-mock-sdk \ // RUN: -target %target-triple %clang-importer-sdk-nosource -I %t \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 \ // RUN: == -async -dont-print-request -req=cursor -pos=60:15 | %FileCheck %s -check-prefix=CHECK-FOO // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions // CHECK-FOO: <decl.struct><syntaxtype.keyword>struct</syntaxtype.keyword> <decl.name>FooRuncingOptions
apache-2.0
e858900a9b3d84fa90b63818fa518303
60.766667
103
0.70966
3.314848
false
false
false
false
tguidon/SwiftySports
ArenaKit/TennisCourtView.swift
1
4598
// // TennisCourtView.swift // SwiftySports // // Created by Taylor Guidon on 1/17/17. // Copyright © 2017 Taylor Guidon. All rights reserved. // import UIKit import SnapKit class TennisCourtView: UIView { let tennisCourt = TennisCourt() // tennisCourtView holds the court's UI elements // dataView holds potential data overlays private let tennisCourtView = UIView() private let dataView = UIView() private let netLine = UIView() private let topSinglesSideline = UIView() private let bottomSinglesSideline = UIView() private let leftServiceLine = UIView() private let rightServiceLine = UIView() private let leftCenterServiceLine = UIView() private let rightCenterServiceLine = UIView() // Array of all lines private var courtLines: [UIView] = [] // Colors with a redraw on set tp update view var courtColor: UIColor = UIColor(red:0.55, green:0.84, blue:0.57, alpha:1.00) { didSet { draw() } } var lineColor: UIColor = .white { didSet { draw() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // build array of lines courtLines = [netLine, topSinglesSideline, bottomSinglesSideline, leftServiceLine, rightServiceLine, leftCenterServiceLine, rightCenterServiceLine] self.backgroundColor = .clear } func setup() { // Add the base green court tennisCourtView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(tennisCourtView) // Add and setup lines courtLines.forEach({ $0.translatesAutoresizingMaskIntoConstraints = false }) courtLines.forEach({ tennisCourtView.addSubview($0) }) } override func layoutSubviews() { super.layoutSubviews() tennisCourt.initWithWidth(self.frame.width) draw() } private func draw() { // Draw the main court view tennisCourtView.backgroundColor = courtColor tennisCourtView.layer.borderColor = lineColor.cgColor tennisCourtView.layer.borderWidth = tennisCourt.lineWidth tennisCourtView.snp.remakeConstraints { (make) in make.top.equalTo(0) make.left.equalTo(0) make.right.equalTo(0) make.bottom.equalTo(0) } courtLines.forEach({ $0.backgroundColor = lineColor }) // Draw the net netLine.snp.remakeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalTo(tennisCourt.lineWidth) make.top.equalToSuperview() make.bottom.equalToSuperview() } // Draw sidelines topSinglesSideline.snp.remakeConstraints { (make) in make.left.equalToSuperview() make.right.equalToSuperview() make.top.equalToSuperview().offset(tennisCourt.sidelineOffset) make.height.equalTo(tennisCourt.lineWidth) } bottomSinglesSideline.snp.remakeConstraints { (make) in make.left.equalToSuperview() make.right.equalToSuperview() make.bottom.equalToSuperview().offset(-tennisCourt.sidelineOffset) make.height.equalTo(tennisCourt.lineWidth) } // Draw the service lines leftServiceLine.snp.remakeConstraints { (make) in make.width.equalTo(tennisCourt.lineWidth) make.top.equalToSuperview() make.bottom.equalToSuperview() make.centerX.equalToSuperview().offset(-tennisCourt.serviceLineOffset) } rightServiceLine.snp.remakeConstraints { (make) in make.width.equalTo(tennisCourt.lineWidth) make.top.equalToSuperview() make.bottom.equalToSuperview() make.centerX.equalToSuperview().offset(tennisCourt.serviceLineOffset) } // Draw the center service lines leftCenterServiceLine.snp.remakeConstraints { (make) in make.height.equalTo(tennisCourt.lineWidth) make.left.equalTo(leftServiceLine.snp.right) make.right.equalTo(netLine.snp.left) make.centerY.equalToSuperview() } rightCenterServiceLine.snp.remakeConstraints { (make) in make.height.equalTo(tennisCourt.lineWidth) make.left.equalTo(netLine.snp.right) make.right.equalTo(rightServiceLine.snp.left) make.centerY.equalToSuperview() } } }
mit
9a5995cd7df22ef281941ba128fce06b
34.361538
90
0.632804
5.046103
false
false
false
false
sergii-frost/weeknum-ios
weeknum/weeknum/Designables.swift
1
1214
// // Designables.swift // weeknum // // Created by Sergii Nezdolii on 02/07/16. // Copyright © 2016 FrostDigital. All rights reserved. // import UIKit extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } } func fadeTransition(_ duration:CFTimeInterval = CATransaction.animationDuration()) { let animation:CATransition = CATransition() animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.type = kCATransitionFade animation.duration = duration self.layer.add(animation, forKey: kCATransitionFade) } }
mit
78d56d80089f1b27cffa6d8930e75b2e
23.755102
88
0.592745
5.228448
false
false
false
false
payjp/payjp-ios
Sources/Networking/Models/Token.swift
1
3610
// // Token.swift // PAYJP // // Created by [email protected] on 9/29/16. // Copyright © 2016 PAY, Inc. All rights reserved. // // https://pay.jp/docs/api/#token-トークン // import Foundation typealias RawValue = [String: Any] /// PAY.JP token object. /// cf. [https://pay.jp/docs/api/#token-トークン](https://pay.jp/docs/api/#token-トークン) @objcMembers @objc(PAYToken) public final class Token: NSObject, Decodable { public let identifer: String public let livemode: Bool public let used: Bool public let card: Card public let createdAt: Date public var rawValue: [String: Any]? // MARK: - Decodable private enum CodingKeys: String, CodingKey { case id = "id" case livemode case used case card case createdAt = "created" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) identifer = try container.decode(String.self, forKey: .id) livemode = try container.decode(Bool.self, forKey: .livemode) used = try container.decode(Bool.self, forKey: .used) card = try container.decode(Card.self, forKey: .card) createdAt = try container.decode(Date.self, forKey: .createdAt) } public init(identifier: String, livemode: Bool, used: Bool, card: Card, createAt: Date, rawValue: [String: Any]? = nil) { self.identifer = identifier self.livemode = livemode self.used = used self.card = card self.createdAt = createAt self.rawValue = rawValue } } extension Token: JSONDecodable { /** * Provide a factory function to decode json by JSONDecoder * and also desereialize all fields as a arbitrary dictionary by JSONSerialization. */ static func decodeJson(with data: Data, using decoder: JSONDecoder) throws -> Token { let token = try decoder.decode(self, from: data) // assign rawValue by JSONSerialization let jsonOptions = JSONSerialization.ReadingOptions.allowFragments guard let rawValue = try JSONSerialization.jsonObject(with: data, options: jsonOptions) as? RawValue, let cardRawValue = rawValue["card"] as? RawValue else { let context = DecodingError.Context(codingPath: [], debugDescription: "Cannot deserialize rawValue") throw DecodingError.dataCorrupted(context) } token.rawValue = rawValue token.card.rawValue = cardRawValue return token } } extension Token { public override func isEqual(_ object: Any?) -> Bool { if let object = object as? Token { return self.identifer == object.identifer } return false } } // MARK: - ThreeDSecure extension Token { private var tdsBaseUrl: URL { return URL(string: "\(PAYJPApiEndpoint)tds/\(identifer)")! } var tdsEntryUrl: URL { let url = tdsBaseUrl.appendingPathComponent("start") var components = URLComponents(url: url, resolvingAgainstBaseURL: true)! components.queryItems = [ URLQueryItem(name: "publickey", value: PAYJPSDK.publicKey), URLQueryItem(name: "back", value: PAYJPSDK.threeDSecureURLConfiguration?.redirectURLKey) ] return components.url! } var tdsFinishUrl: URL { return tdsBaseUrl.appendingPathComponent("finish") } }
mit
1f9865616ff0917e06ddf066923a68d1
31.008929
100
0.6159
4.602054
false
false
false
false
YouareMylovelyGirl/Sina-Weibo
新浪微博/新浪微博/Classes/Tools(工具)/Extension/UIBarButtonItem+Extension.swift
1
1475
// // UIBarButtonItem+Extension.swift // 新浪微博 // // Created by 阳光 on 2017/6/5. // Copyright © 2017年 YG. All rights reserved. // import Foundation import UIKit extension UIBarButtonItem { /// 创建UIBarBarItem /// /// - Parameters: /// - title: title /// - fontSize: fontSize 默认16 /// - target: target /// - action: action /// - isBack: 是否返回按钮, 如果是加上箭头 convenience init(title: String, fontSize: CGFloat = 16, target: AnyObject?, action: Selector, isBack: Bool = false) { let btn = UIButton.init(type: .custom) // btn.frame = CGRect(x: 0, y: 0, width: 60, height: 60) btn.titleLabel?.font = UIFont.systemFont(ofSize: fontSize ) btn.setTitle(title, for: .normal) btn.setTitleColor(UIColor.darkGray, for: .normal) btn.setTitleColor(UIColor.orange, for: .highlighted) if isBack { let imageNormal = "navigationbar_back_withtext" let imageLight = "navigationbar_back_withtext_highlighted" btn.setImage(UIImage.init(named: imageNormal), for: .normal) btn.setImage(UIImage.init(named: imageLight), for: .highlighted) } btn.sizeToFit() btn.addTarget(target, action: action, for: .touchUpInside) //self.init 实例化 UIBarButtonItem self.init(customView: btn) } }
apache-2.0
8c3f5d2888017b99f59c545cb071f1c1
29.212766
121
0.588028
4.115942
false
false
false
false
Alloc-Studio/Hypnos
Hypnos/Pods/JLToast/JLToast/JLToast.swift
1
4153
/* * JLToast.swift * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2013-2015 Su Yeol Jeon * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. * */ import UIKit public struct JLToastDelay { public static let ShortDelay: NSTimeInterval = 2.0 public static let LongDelay: NSTimeInterval = 3.5 } @objc public class JLToast: NSOperation { public var view: JLToastView = JLToastView() public var text: String? { get { return self.view.textLabel.text } set { self.view.textLabel.text = newValue } } public var delay: NSTimeInterval = 0 public var duration: NSTimeInterval = JLToastDelay.ShortDelay private var _executing = false override public var executing: Bool { get { return self._executing } set { self.willChangeValueForKey("isExecuting") self._executing = newValue self.didChangeValueForKey("isExecuting") } } private var _finished = false override public var finished: Bool { get { return self._finished } set { self.willChangeValueForKey("isFinished") self._finished = newValue self.didChangeValueForKey("isFinished") } } public class func makeText(text: String) -> JLToast { return JLToast.makeText(text, delay: 0, duration: JLToastDelay.ShortDelay) } public class func makeText(text: String, duration: NSTimeInterval) -> JLToast { return JLToast.makeText(text, delay: 0, duration: duration) } public class func makeText(text: String, delay: NSTimeInterval, duration: NSTimeInterval) -> JLToast { let toast = JLToast() toast.text = text toast.delay = delay toast.duration = duration return toast } public func show() { JLToastCenter.defaultCenter().addToast(self) } override public func start() { if !NSThread.isMainThread() { dispatch_async(dispatch_get_main_queue(), { self.start() }) } else { super.start() } } override public func main() { self.executing = true dispatch_async(dispatch_get_main_queue(), { self.view.updateView() self.view.alpha = 0 JLToastWindow.sharedWindow.addSubview(self.view) UIView.animateWithDuration( 0.5, delay: self.delay, options: .BeginFromCurrentState, animations: { self.view.alpha = 1 }, completion: { completed in UIView.animateWithDuration( self.duration, animations: { self.view.alpha = 1.0001 }, completion: { completed in self.finish() UIView.animateWithDuration( 0.5, animations: { self.view.alpha = 0 }, completion:{ completed in self.view.removeFromSuperview() }) } ) } ) }) } public override func cancel() { super.cancel() self.finish() self.view.removeFromSuperview() } public func finish() { self.executing = false self.finished = true } }
mit
bc45955974cdc471f28a4742cb7d4b28
27.452055
106
0.511438
5.40052
false
false
false
false
relayr/apple-sdk
Sources/common/services/Database/DB.swift
1
7201
import ReactiveSwift import Result import Foundation /// Service in charge of querying and setting information from the database. public enum DB { /// List of errors specific to the database operations. public enum Error : Swift.Error { /// The database data could not be parsed. case invalidData(Data) /// The database resource is not in the expected format. case invalidFormat(Any) /// An atomic database operation failed. case operationFailed /// The database entry could not be found. case resourceNotFound } } internal extension DB { /// It creates a file URL for a specific file. static func fileURL(relativeTo url: URL, withName name: String, fileExtension: String="json") -> URL { return url.appendingPathComponent(name, isDirectory: false).appendingPathExtension(fileExtension) } /// Creates a folder at the specified file system URL. /// /// If the intermediate directories are not there, this method will create the appropriate folders. /// - parameter url: Absolute URL within the file system. static func create(directoryAtURL url: URL) throws { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } /// Retrieves a JSON file at the specified URL in the file system. /// - parameter url: Absolute URL within the file system. /// - throws: Only `DB.Error`s are thrown. /// - returns: The JSON representation, if successful, or `nil` if there was no file on that URL. static func retrieve<T>(jsonWithURL url: URL) throws -> T? { let (manager, path) = (FileManager.default, url.path) guard manager.fileExists(atPath: path) else { return nil } guard let fileData = manager.contents(atPath: path) else { throw DB.Error.operationFailed } let json: Any do { json = try Parser.toJSON(fromData: fileData) } catch { throw DB.Error.invalidData(fileData) } guard let result = json as? T else { throw DB.Error.invalidFormat(json) } return result } /// Stores a JSON file representation at the specified URL in the file system. /// /// If there was a previous file in that path, it is replaced. /// - parameter json: JSON file representation (dictionary or array). /// - parameter url: Absolute URL within the file system. /// - throws: Only `DB.Error`s are thrown. static func store(json: Any, withURL url: URL) throws { let data: Data do { data = try Parser.toData(fromJSON: json) } catch { throw DB.Error.invalidFormat(json) } guard FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil) else { throw Error.operationFailed } } /// Removes a JSON in the specified path in the file system. /// - parameter path: Absolute path in the file system. static func remove(jsonFromURL url: URL) throws { let (manager, path) = (FileManager.default, url.path) guard manager.fileExists(atPath: path) else { return } do { try manager.removeItem(atPath: path) } catch { throw DB.Error.operationFailed } } } internal extension DB { /// Retrieves an entry from the database identified by the URL in the file system. /// - parameter fileURL: The address of the targeted file. static func getEntry<T:JSONable>(fromFileURL fileURL: URL) -> SignalProducer<T,DB.Error> { return SignalProducer(result: Result { try DB.retrieve(jsonWithURL: fileURL) }.flatMap { (file) in Result(file, failWith: DB.Error.resourceNotFound) }.flatMap { (file) in Result { try T(fromJSON: file) } } ) } /// Sets an entry in the database identified by the URL in the file system. /// - parameter data: Data to be added to the database. /// - parameter fileURL: The address of the targeted file. /// - parameter action: Decides what to the if there was a previous file and whether the data need to be merge (giving preference to the new fields). static func setEntry<T:JSONable>(_ data: T, toFileURL fileURL: URL) -> SignalProducer<(),DB.Error> { return SignalProducer(result: Result { try DB.store(json: data.json, withURL: fileURL) }) } /// Looks for an entry which is a dictionary [String:V] and contains the key/value element passed as argument. static func lookForEntry<T:JSONable,V:Equatable>(withElement element: (key: String, value: V), inFolderURL folderURL: URL) -> SignalProducer<T,DB.Error> where T.JSONType == Dictionary<String,Any> { return SignalProducer { (generator, _) in do { let filesURLs = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) for url in filesURLs { guard let json: T.JSONType = try DB.retrieve(jsonWithURL: url), let jsonValue = json[element.key] as? V, jsonValue == element.value else { continue } generator.send(value: try T(fromJSON: json)) return generator.sendCompleted() } } catch let error as DB.Error { return generator.send(error: error) } catch { return generator.send(error: .operationFailed) } generator.send(error: .resourceNotFound) } } /// Looks for entries which are dictionaries [String:V] and contains the key/value element passed as argument. static func lookForEntries<T:JSONable,V:Equatable>(withElement element: (key: String, value: V), inFolderURL folderURL: URL) -> SignalProducer<[T],DB.Error> where T.JSONType == Dictionary<String,Any> { return SignalProducer { (generator, _) in var result = [T]() do { let filesURL = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) for url in filesURL { guard let json : T.JSONType = try DB.retrieve(jsonWithURL: url), let jsonValue = json[element.key] as? V, jsonValue == element.value else { continue } result.append(try T(fromJSON: json)) } } catch let error as DB.Error { return generator.send(error: error) } catch { return generator.send(error: .operationFailed) } guard !result.isEmpty else { return generator.send(error: .resourceNotFound) } generator.send(value: result) generator.sendCompleted() } } }
mit
18c66760101e9d7e7b2d02ad72978502
41.863095
205
0.605194
4.836132
false
false
false
false
cschlessinger/dbc-civichack-artistnonprofit
iOS/DevBootcampHackathon/DevBootcampHackathon/images/Source/ImageGallery/ImageGalleryView.swift
1
9527
import UIKit import Photos protocol ImageGalleryPanGestureDelegate: class { func panGestureDidStart() func panGestureDidChange(translation: CGPoint) func panGestureDidEnd(translation: CGPoint, velocity: CGPoint) func presentViewController(controller: UIAlertController) func dismissViewController(controller: UIAlertController) func permissionGranted() func hideViews() } public class ImageGalleryView: UIView { struct Dimensions { static let galleryHeight: CGFloat = 160 static let galleryBarHeight: CGFloat = 24 static let indicatorWidth: CGFloat = 41 static let indicatorHeight: CGFloat = 8 } lazy public var collectionView: UICollectionView = { [unowned self] in let collectionView = UICollectionView(frame: CGRectMake(0, 0, 0, 0), collectionViewLayout: self.collectionViewLayout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = Configuration.mainColor collectionView.showsHorizontalScrollIndicator = false return collectionView }() lazy var collectionViewLayout: UICollectionViewLayout = { [unowned self] in let layout = UICollectionViewFlowLayout() layout.scrollDirection = .Horizontal layout.minimumInteritemSpacing = Configuration.cellSpacing layout.minimumLineSpacing = 2 layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) return layout }() lazy var topSeparator: UIView = { [unowned self] in let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.addGestureRecognizer(self.panGestureRecognizer) view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6) return view }() lazy var indicator: UIView = { let view = UIView() view.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.6) view.layer.cornerRadius = Dimensions.indicatorHeight / 2 view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in let gesture = UIPanGestureRecognizer() gesture.addTarget(self, action: "handlePanGestureRecognizer:") return gesture }() public lazy var noImagesLabel: UILabel = { [unowned self] in let label = UILabel() label.font = Configuration.noImagesFont label.textColor = Configuration.noImagesColor label.text = Configuration.noImagesTitle label.alpha = 0 label.sizeToFit() self.addSubview(label) return label }() public lazy var selectedStack = ImageStack() lazy var assets = [PHAsset]() weak var delegate: ImageGalleryPanGestureDelegate? var collectionSize: CGSize? var shouldTransform = false var imagesBeforeLoading = 0 var fetchResult: PHFetchResult? var canFetchImages = false var imageLimit = 0 // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) backgroundColor = Configuration.mainColor collectionView.registerClass(ImageGalleryViewCell.self, forCellWithReuseIdentifier: CollectionView.reusableIdentifier) [collectionView, topSeparator].forEach { addSubview($0) } topSeparator.addSubview(indicator) imagesBeforeLoading = 0 fetchPhotos() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout public override func layoutSubviews() { super.layoutSubviews() updateNoImagesLabel() } func updateFrames() { let totalWidth = UIScreen.mainScreen().bounds.width let collectionFrame = frame.height == Dimensions.galleryBarHeight ? 100 + Dimensions.galleryBarHeight : frame.height collectionView.dataSource = self collectionView.delegate = self topSeparator.frame = CGRect(x: 0, y: 0, width: totalWidth, height: Dimensions.galleryBarHeight) indicator.frame = CGRect(x: (totalWidth - Dimensions.indicatorWidth) / 2, y: (topSeparator.frame.height - Dimensions.indicatorHeight) / 2, width: Dimensions.indicatorWidth, height: Dimensions.indicatorHeight) collectionView.frame = CGRect(x: 0, y: topSeparator.frame.height, width: totalWidth, height: collectionFrame - topSeparator.frame.height) collectionSize = CGSize(width: collectionView.frame.height, height: collectionView.frame.height) } func updateNoImagesLabel() { let height = CGRectGetHeight(bounds) let threshold = Dimensions.galleryBarHeight * 2 if threshold > height || collectionView.alpha != 0 { noImagesLabel.alpha = 0 } else { noImagesLabel.center = CGPoint(x: CGRectGetWidth(bounds)/2, y: height/2) noImagesLabel.alpha = (height > threshold) ? 1 : (height - Dimensions.galleryBarHeight) / threshold } } // MARK: - Photos handler func fetchPhotos(completion: (() -> Void)? = nil) { ImagePicker.fetch { assets in self.assets.removeAll() self.assets.appendContentsOf(assets) self.collectionView.reloadData() completion?() } } // MARK: - Pan gesture recognizer func handlePanGestureRecognizer(gesture: UIPanGestureRecognizer) { guard let superview = superview else { return } let translation = gesture.translationInView(superview) let velocity = gesture.velocityInView(superview) switch gesture.state { case .Began: delegate?.panGestureDidStart() case .Changed: delegate?.panGestureDidChange(translation) case .Ended: delegate?.panGestureDidEnd(translation, velocity: velocity) default: break } } // MARK: - Private helpers func getImage(name: String) -> UIImage { let traitCollection = UITraitCollection(displayScale: 3) var bundle = NSBundle(forClass: self.classForCoder) if let bundlePath = NSBundle(forClass: self.classForCoder).resourcePath?.stringByAppendingString("/ImagePicker.bundle"), resourceBundle = NSBundle(path: bundlePath) { bundle = resourceBundle } guard let image = UIImage(named: name, inBundle: bundle, compatibleWithTraitCollection: traitCollection) else { return UIImage() } return image } func displayNoImagesMessage(hideCollectionView: Bool) { collectionView.alpha = hideCollectionView ? 0 : 1 updateNoImagesLabel() } func checkStatus() { let currentStatus = PHPhotoLibrary.authorizationStatus() guard currentStatus != .Authorized else { return } if currentStatus == .NotDetermined { delegate?.hideViews() } PHPhotoLibrary.requestAuthorization { (authorizationStatus) -> Void in dispatch_async(dispatch_get_main_queue(), { if authorizationStatus == .Denied { let alertController = UIAlertController(title: "Permission denied", message: "Please, allow the application to access to your photo library.", preferredStyle: .Alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { _ in if let settingsURL = NSURL(string: UIApplicationOpenSettingsURLString) { UIApplication.sharedApplication().openURL(settingsURL) } } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { _ in self.delegate?.dismissViewController(alertController) } alertController.addAction(alertAction) alertController.addAction(cancelAction) self.delegate?.presentViewController(alertController) } else if authorizationStatus == .Authorized { self.delegate?.permissionGranted() } }) } } } // MARK: CollectionViewFlowLayout delegate methods extension ImageGalleryView: UICollectionViewDelegateFlowLayout { public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { guard let collectionSize = collectionSize else { return CGSizeZero } return collectionSize } } // MARK: CollectionView delegate methods extension ImageGalleryView: UICollectionViewDelegate { public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? ImageGalleryViewCell else { return } let asset = assets[indexPath.row] ImagePicker.resolveAsset(asset) { image in guard let _ = image else { return } if cell.selectedImageView.image != nil { UIView.animateWithDuration(0.2, animations: { cell.selectedImageView.transform = CGAffineTransformMakeScale(0.1, 0.1) }) { _ in cell.selectedImageView.image = nil } self.selectedStack.dropAsset(asset) } else if self.imageLimit == 0 || self.imageLimit > self.selectedStack.assets.count { cell.selectedImageView.image = self.getImage("selectedImageGallery") cell.selectedImageView.transform = CGAffineTransformMakeScale(0, 0) UIView.animateWithDuration(0.2) { _ in cell.selectedImageView.transform = CGAffineTransformIdentity } self.selectedStack.pushAsset(asset) } } } public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { guard indexPath.row + 10 >= assets.count && indexPath.row < fetchResult?.count && canFetchImages else { return } fetchPhotos() canFetchImages = false } }
mit
09305ce49fe1292554a0f58208b3176a
32.42807
176
0.720164
5.379447
false
false
false
false
Shivol/Swift-CS333
playgrounds/persistence/notes-core-data/notes-core-data/Note.swift
3
1137
// // Note+CoreDataClass.swift // notes-core-data // // Created by Илья Лошкарёв on 22.03.17. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import UIKit import CoreData @objc(Note) public class Note: NSManagedObject { @NSManaged public var date: NSDate? @NSManaged public var content: String? @NSManaged public var color: UIColor? public override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { super.init(entity: entity, insertInto: context) } public convenience init(content: String) { self.init(entity: Note.entity(), insertInto: CoreDataContainer.context) self.content = content self.date = Date() as NSDate self.color = UIColor.random } // MARK: String Convertable static let dateFormatter: DateFormatter = { let df = DateFormatter() df.dateFormat = "hh:mm:ss dd.MM.yyyy" return df }() override public var description: String { return "(\(Note.dateFormatter.string(from: date as! Date))) " + content! } }
mit
d4fc7afe08cf46df3745661410a3af65
26.121951
100
0.649281
4.360784
false
false
false
false
pabiagioli/icloud-filepicker-swift-ionic3
src/ios/DocumentPickerSwift.swift
1
3892
// // DocumentPickerSwift.swift // // // Created by Pablo Biagioli on 5/5/17. // // import Foundation @objc(DocumentPickerSwift) class DocumentPickerSwift: CDVPlugin, UIDocumentMenuDelegate, UIDocumentPickerDelegate { var pluginResult: CDVPluginResult? var command: CDVInvokedUrlCommand? func isSupported () -> Bool { return NSClassFromString("UIDocumentPickerViewController") != nil } @objc(isAvailable:)func isAvailable(command: CDVInvokedUrlCommand) { print("isAvailable - begin") let supported: Bool = isSupported() commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_OK, messageAs: supported), callbackId: command.callbackId) print("isAvailable - end") } @available(iOS 8.0, *) @objc(pickFile:)func pickFile(command: CDVInvokedUrlCommand) { print("pickFile - begin") self.command = command let UTIsArray: [String] let UTIs: Any? = command.arguments[0] var supported: Bool = true //var UTIsArray: [Any]? = nil if(!( UTIs is NSNull)) { if (UTIs is String) { UTIsArray = [UTIs as! String] }else if (UTIs is [String]){ UTIsArray = UTIs as! [String] }else { supported = false UTIsArray = ["not supported"] commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: UTIsArray[0]), callbackId: self.command?.callbackId) } }else{ UTIsArray = ["public.data"] } if !isSupported() { supported = false commandDelegate.send(CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "your device can't show the file picker"), callbackId: self.command?.callbackId) } if supported { pluginResult = CDVPluginResult(status: CDVCommandStatus_NO_RESULT) pluginResult?.keepCallback = true displayDocumentPicker(UTIsArray) } print("pickFile - end") } // MARK: - UIDocumentMenuDelegate @available(iOS 8.0, *) func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { documentPicker.delegate = self documentPicker.modalPresentationStyle = .fullScreen viewController.present(documentPicker, animated: true, completion: { _ in }) } @available(iOS 8.0, *) func documentMenuWasCancelled(_ documentMenu: UIDocumentMenuViewController) { pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "canceled") pluginResult?.keepCallback = false commandDelegate.send(pluginResult, callbackId: command?.callbackId) } // MARK: - UIDocumentPickerDelegate @available(iOS 8.0, *) func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: url.path) pluginResult?.keepCallback = false commandDelegate.send(pluginResult, callbackId: command?.callbackId) } @available(iOS 8.0, *) func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: "canceled") pluginResult?.keepCallback = false commandDelegate.send(pluginResult, callbackId: command?.callbackId) } @available(iOS 8.0, *) func displayDocumentPicker(_ UTIs: [String]) { let importMenu = UIDocumentMenuViewController(documentTypes: UTIs, in: .import) importMenu.delegate = self importMenu.popoverPresentationController?.sourceView = viewController.view viewController.present(importMenu, animated: true, completion: { _ in }) } }
gpl-3.0
e33ea61941465cb03ab37a3d19c442ea
40.849462
172
0.664954
5.182423
false
false
false
false
soutaro/Gunma
Gunma/StronglyConnectedComponents.swift
1
2787
import Foundation public extension Graph { /** Returns new graph which vertices are strongly connected components of given graph. */ public static func stronglyConnectedComponents(graph: Graph<V>) -> Graph<Set<V>> { var successors: [V: Set<V>] = [:] graph.eachEdge { (from, to) in if var vertices = successors[from] { vertices.insert(to) successors[from] = vertices } else { successors[from] = Set(arrayLiteral: to) } } var index: UInt = 0 var indexes: [V: UInt] = [:] var lowlinks: [V: UInt] = [:] var onStack: [V: Bool] = [:] var stack: [V] = [] var components: [V: Set<V>] = [:] graph.eachVertex { v in if indexes[v] == nil { self.stronglyConnect(graph, vertex: v, index: &index, indexes: &indexes, lowlinks: &lowlinks, onStack: &onStack, stack: &stack, successors: &successors) { component in for v in component { components[v] = component } } } } var edges: Set<Edge<Set<V>>> = Set() graph.eachEdge { let from = components[$0]! let to = components[$1]! if from != to { edges.insert(Edge(start: from, end: to)) } } return Graph<Set<V>>(vertices: Set(components.values), edges: edges) } static func stronglyConnect<V>(graph: Graph<V>, vertex: V, inout index: UInt, inout indexes: [V: UInt], inout lowlinks: [V: UInt], inout onStack: [V: Bool], inout stack: [V], inout successors: [V: Set<V>], callback: (Set<V>) -> ()) { indexes[vertex] = index lowlinks[vertex] = index index += 1 stack.append(vertex) onStack[vertex] = true for w in successors[vertex]! { if indexes[w] == nil { self.stronglyConnect(graph, vertex: w, index: &index, indexes: &indexes, lowlinks: &lowlinks, onStack: &onStack, stack: &stack, successors: &successors, callback: callback) lowlinks[vertex] = min(lowlinks[vertex]!, lowlinks[w]!) } else if onStack[w] == true { lowlinks[vertex] = min(lowlinks[vertex]!, indexes[w]!) } } if lowlinks[vertex]! == indexes[vertex]! { var component = Set<V>() var w: V repeat { w = stack.popLast()! onStack[w] = false component.insert(w) } while w != vertex callback(component) } } }
mit
03a1108bf74caad7b0815981beb57be2
34.291139
237
0.489415
4.382075
false
false
false
false
sareninden/DataSourceFramework
DataSourceFrameworkDemo/DataSourceFrameworkDemo/MovingTableViewController.swift
1
2279
import Foundation import UIKit import DataSourceFramework class MovingTableViewController : BaseTableViewController { // MARK:- Class Variables // MARK:- Variables // MARK:- Init and Dealloc override init() { super.init() title = "Moving" tableView.editing = true tableController.cellReuseIdentifier = TABLE_CELL_DEFAULT_IDENTIFIER tableController.movingDelegate = self tableController.canEdit = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- Public Class Methods // MARK:- Internal Instance Methods override func loadData() { for sectionIndex in 0 ..< 20 { let section = sectionWithHeaderTitle("Section \(sectionIndex)") for row in 0...3 { let item = TableItem(text: "Start section \(sectionIndex) row \(row)") section.addItem(item) } tableController.addSection(section) } } } extension MovingTableViewController : TableControllerMovingInterface { func tableController(tableController : TableController, tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath? { return nil } func tableController(tableController : TableController, tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool? { return true } func tableController(tableController : TableController, tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { let fromSection = tableController.sectionAtIndex(sourceIndexPath.section) let toSection = tableController.sectionAtIndex(destinationIndexPath.section) let item = fromSection.itemAtIndex(sourceIndexPath.section) fromSection.removeItemAtIndex(sourceIndexPath.item) toSection.insertItem(item, atIndex: destinationIndexPath.item) } }
gpl-3.0
41749a36a7ef6563b61cfa333eda06dc
31.557143
235
0.652918
6.456091
false
false
false
false
iccub/freestyle-timer-ios
freestyle-timer-ios/choose-mode/ChooseModeVC.swift
1
3149
/* Copyright © 2017 Michał Buczek. This file is part of Freestyle Timer. Freestyle Timer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Freestyle Timer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Freestyle Timer. If not, see <http://www.gnu.org/licenses/>. */ import UIKit import os.log /** First app screen that allows user to choose timer mode or open settings. This ViewController embeds a page VC for swipe gestures to choose the right timer mode. */ class ChooseModeVC: UIViewController { static let log = OSLog(subsystem: "com.michalbuczek.freestyle_timer_ios.logs", category: "ChooseModeVC") // MARK: - IBOutlets @IBOutlet weak var timerModesPageControl: UIPageControl! @IBOutlet weak var timerModeContainerView: UIView! var currentTimerModePageIndex = 0 { didSet { timerModesPageControl.currentPage = currentTimerModePageIndex view.backgroundColor = TimerMode.backgroundColor(for: currentTimerModePageIndex) } } weak var timerModeChangedDelegate: TimerTypesPageVCDelegate? // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() timerModeChangedDelegate = self // Proceeding to a timer screen can be done by either clicking on select button or container view let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ChooseModeVC.timerModeTapped)) tapGesture.numberOfTapsRequired = 1 tapGesture.numberOfTouchesRequired = 1 timerModeContainerView.addGestureRecognizer(tapGesture) timerModeContainerView.isUserInteractionEnabled = true currentTimerModePageIndex = 0 } // MARK: - Segue navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "gotoTimerVC" { guard let vc = segue.destination as? TimerVC else { os_log("Destination segue is not of TimerVC type", log: ChooseModeVC.log, type: .error) return } let selectedTimerMode = TimerMode.timerMode(for: currentTimerModePageIndex) vc.timerMode = selectedTimerMode os_log("%@ timer mode was chosen", log: ChooseModeVC.log, type: .debug, selectedTimerMode.title) } } @objc func timerModeTapped() { performSegue(withIdentifier: "gotoTimerVC", sender: nil) } } // MARK: - Delegates extension ChooseModeVC: TimerTypesPageVCDelegate { func timerModeChanged(index: Int) { guard currentTimerModePageIndex != index else { return } currentTimerModePageIndex = index } }
gpl-3.0
ecbbdf59401bedb438264076291169f7
36.023529
110
0.694312
5.00318
false
false
false
false
RickieL/learn-swift
swift-enumerations.playground/section-1.swift
1
1809
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // Enumeration syntax enum CompassPoint { case North case South case East case West } enum Planet { case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } var directionToHead = CompassPoint.West // matching enumeration values with a switch statement directionToHead = .South switch directionToHead { case .North: println("Lots of planets have a north") case .South: println("Watch out for penguins") case .East: println("Where the sun rises") case .West: println("Where the skies are blue") } let somePlanet = Planet.Earth switch somePlanet { case .Earth: println("Mostly harmless") default: println("Not a safe place for humans") } // associated values enum Barcode { case UPCA(Int, Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) productBarcode = .QRCode("ABCDEFGHIJKLMNOPQRSTUVWXYZ") switch productBarcode { case .UPCA(let numberSystem, let manufacturer, let product, let check): println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).") case .QRCode(let productCode): println("QR Code: \(productCode)") } // raw values enum ASCIIControlCharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" } enum PlanetNew: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } let earthsOrder = PlanetNew.Earth.rawValue // initializing from a row value let possiblePlanet = PlanetNew(rawValue: 7) if let somePlanet = possiblePlanet { switch somePlanet { case .Uranus: println("It's Uranus") default: println("Some other planet") } } else { println("no that planet") }
bsd-3-clause
e1b043b208c8263edae5245e6ba682a4
20.807229
77
0.693201
3.865385
false
false
false
false
benlangmuir/swift
test/refactoring/ConvertToIfLet/basic.swift
28
910
func foo(idxOpt: Int?) { guard let idx = idxOpt else { return } print(idx) } func bar(fooOpt: Int?) { guard let foo = fooOpt else { return } let incrementedFoo = foo + 1 print(incrementedFoo) } func fooBar(idxOpt: Int?) { guard let idx = idxOpt else { print("nil") return } print(idx) } // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %refactor -convert-to-iflet -source-filename %s -pos=2:3 -end-pos=5:13 > %t.result/L2-3.swift // RUN: diff -u %S/Outputs/basic/L2-3.swift.expected %t.result/L2-3.swift // RUN: %refactor -convert-to-iflet -source-filename %s -pos=9:3 -end-pos=13:24 > %t.result/L9-3.swift // RUN: diff -u %S/Outputs/basic/L9-3.swift.expected %t.result/L9-3.swift // RUN: %refactor -convert-to-iflet -source-filename %s -pos=17:3 -end-pos=21:13 > %t.result/L17-3.swift // RUN: diff -u %S/Outputs/basic/L17-3.swift.expected %t.result/L17-3.swift
apache-2.0
7eb596f22abc6ccc00c1d6d03da480f2
26.575758
104
0.650549
2.520776
false
false
false
false
rechsteiner/Parchment
ParchmentTests/PagingViewControllerTests.swift
1
17537
import Foundation @testable import Parchment import UIKit import XCTest final class PagingViewControllerTests: XCTestCase { func testReloadMenu() { // Arrange let viewController0 = UIViewController() let viewController1 = UIViewController() let dataSource = ReloadingDataSource() dataSource.viewControllers = [viewController0, viewController1] dataSource.items = [Item(index: 0), Item(index: 1)] let pagingViewController = PagingViewController() pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.dataSource = dataSource pagingViewController.register(ItemCell.self, for: Item.self) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act let item2 = Item(index: 0) let item3 = Item(index: 1) let viewController2 = UIViewController() let viewController3 = UIViewController() dataSource.viewControllers = [viewController2, viewController3] dataSource.items = [item2, item3] pagingViewController.reloadMenu() pagingViewController.view.layoutIfNeeded() // Assert // Updates the cells let cell2 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ItemCell let cell3 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? ItemCell XCTAssertEqual(pagingViewController.collectionView.numberOfItems(inSection: 0), 2) XCTAssertEqual(cell2?.item, item2) XCTAssertEqual(cell3?.item, item3) // Should not updated the view controllers XCTAssertEqual(pagingViewController.pageViewController.selectedViewController, viewController0) } func testReloadData() { // Arrange let dataSource = ReloadingDataSource() let viewController0 = UIViewController() let viewController1 = UIViewController() dataSource.viewControllers = [viewController0, viewController1] dataSource.items = [Item(index: 0), Item(index: 1)] let pagingViewController = PagingViewController() pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.dataSource = dataSource pagingViewController.register(ItemCell.self, for: Item.self) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act let item2 = Item(index: 2) let item3 = Item(index: 3) let viewController2 = UIViewController() let viewController3 = UIViewController() dataSource.items = [item2, item3] dataSource.viewControllers = [viewController2, viewController3] pagingViewController.reloadData(around: item2) pagingViewController.view.layoutIfNeeded() // Assert let cell2 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ItemCell let cell3 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? ItemCell XCTAssertEqual(cell2?.item, item2) XCTAssertEqual(cell3?.item, item3) XCTAssertEqual(pagingViewController.state, PagingState.selected(pagingItem: item2)) XCTAssertEqual(pagingViewController.pageViewController.selectedViewController, viewController2) } func testReloadDataSameItemsUpdatesViewControllers() { // Arrange let dataSource = ReloadingDataSource() let viewController0 = UIViewController() let viewController1 = UIViewController() dataSource.viewControllers = [viewController0, viewController1] dataSource.items = [Item(index: 0), Item(index: 1)] let pagingViewController = PagingViewController() pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.dataSource = dataSource pagingViewController.register(ItemCell.self, for: Item.self) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act let viewController2 = UIViewController() let viewController3 = UIViewController() dataSource.viewControllers = [viewController2, viewController3] pagingViewController.reloadData() pagingViewController.view.layoutIfNeeded() // Assert XCTAssertEqual(pagingViewController.pageViewController.selectedViewController, viewController2) } func testReloadDataSelectsPreviouslySelectedItem() { // Arrange let dataSource = ReloadingDataSource() let item0 = Item(index: 0) let item1 = Item(index: 1) let item2 = Item(index: 2) let viewController0 = UIViewController() let viewController1 = UIViewController() let viewController2 = UIViewController() dataSource.items = [item0, item1, item2] dataSource.viewControllers = [ viewController0, viewController1, viewController2, ] let pagingViewController = PagingViewController() pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.dataSource = dataSource pagingViewController.register(ItemCell.self, for: Item.self) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act pagingViewController.select(index: 1) pagingViewController.view.layoutIfNeeded() pagingViewController.reloadData() pagingViewController.view.layoutIfNeeded() // Assert let cell0 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ItemCell let cell1 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? ItemCell let cell2 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 2, section: 0)) as? ItemCell XCTAssertEqual(cell0?.item, item0) XCTAssertEqual(cell1?.item, item1) XCTAssertEqual(cell2?.item, item2) XCTAssertEqual(pagingViewController.state, PagingState.selected(pagingItem: item1)) } func testReloadDataSelectsFirstItemForAllNewAllItems() { // Arrange let dataSource = ReloadingDataSource() let viewController0 = UIViewController() let viewController1 = UIViewController() dataSource.viewControllers = [viewController0, viewController1] dataSource.items = [Item(index: 0), Item(index: 1)] let pagingViewController = PagingViewController() pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.dataSource = dataSource pagingViewController.register(ItemCell.self, for: Item.self) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act let item2 = Item(index: 2) let item3 = Item(index: 3) pagingViewController.select(index: 1) pagingViewController.view.layoutIfNeeded() dataSource.items = [item2, item3] pagingViewController.reloadData() pagingViewController.view.layoutIfNeeded() // Assert let cell2 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ItemCell let cell3 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? ItemCell XCTAssertEqual(cell2?.item, item2) XCTAssertEqual(cell3?.item, item3) XCTAssertEqual(pagingViewController.state, PagingState.selected(pagingItem: item2)) } func testReloadDataDisplayEmptyViewForNoItems() { // Arrange let dataSource = ReloadingDataSource() let pagingViewController = PagingViewController() pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.dataSource = dataSource let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act pagingViewController.reloadData() // Assert XCTAssertEqual(pagingViewController.pageViewController.scrollView.subviews, []) XCTAssertEqual(pagingViewController.collectionView.numberOfItems(inSection: 0), 0) } func testReloadDataEmptyBeforeUsesWidthDelegate() { // Arrange let dataSource = ReloadingDataSource() let delegate = SizeDelegate() let pagingViewController = PagingViewController() pagingViewController.dataSource = dataSource pagingViewController.sizeDelegate = delegate pagingViewController.register(ItemCell.self, for: Item.self) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act let item0 = Item(index: 0) let item1 = Item(index: 1) dataSource.viewControllers = [UIViewController(), UIViewController()] dataSource.items = [item0, item1] pagingViewController.reloadData() pagingViewController.view.layoutIfNeeded() // Assert let cell0 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ItemCell let cell1 = pagingViewController.collectionView.cellForItem(at: IndexPath(item: 1, section: 0)) as? ItemCell XCTAssertEqual(cell0?.item, item0) XCTAssertEqual(cell1?.item, item1) XCTAssertEqual(cell0?.bounds.width, 100) XCTAssertEqual(cell1?.bounds.width, 50) } func selectFirstPagingItem() { // Arrange let dataSource = DataSource() let pagingViewController = PagingViewController() pagingViewController.register(ItemCell.self, for: Item.self) pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.infiniteDataSource = dataSource let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 50)) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act pagingViewController.select(pagingItem: Item(index: 0)) // Assert let items = pagingViewController.collectionView.numberOfItems(inSection: 0) XCTAssertEqual(items, 21) } func selectCenterPagingItem() { // Arrange let dataSource = DataSource() let pagingViewController = PagingViewController() pagingViewController.register(ItemCell.self, for: Item.self) pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.infiniteDataSource = dataSource let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 50)) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act pagingViewController.select(pagingItem: Item(index: 20)) // Assert let items = pagingViewController.collectionView.numberOfItems(inSection: 0) XCTAssertEqual(items, 21) } func selectLastPagingIteme() { // Arrange let dataSource = DataSource() let pagingViewController = PagingViewController() pagingViewController.register(ItemCell.self, for: Item.self) pagingViewController.menuItemSize = .fixed(width: 100, height: 50) pagingViewController.infiniteDataSource = dataSource let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 50)) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Act pagingViewController.select(pagingItem: Item(index: 50)) // Assert let items = pagingViewController.collectionView.numberOfItems(inSection: 0) XCTAssertEqual(items, 21) } func testSelectIndexBeforeInitialRender() { // Arrange let viewController0 = UIViewController() let viewController1 = UIViewController() let item0 = Item(index: 0) let item1 = Item(index: 1) let dataSource = ReloadingDataSource() dataSource.viewControllers = [viewController0, viewController1] dataSource.items = [item0, item1] let pagingViewController = PagingViewController() pagingViewController.dataSource = dataSource pagingViewController.register(ItemCell.self, for: Item.self) // Act pagingViewController.select(index: 1) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Assert XCTAssertEqual(pagingViewController.pageViewController.selectedViewController, viewController1) XCTAssertEqual(pagingViewController.collectionView.indexPathsForSelectedItems, [IndexPath(item: 1, section: 0)]) XCTAssertEqual(pagingViewController.state, PagingState.selected(pagingItem: item1)) } func testReloadDataBeforeInitialRender() { // Arrange let viewController0 = UIViewController() let viewController1 = UIViewController() let viewController2 = UIViewController() let item0 = Item(index: 0) let item1 = Item(index: 1) let item2 = Item(index: 2) let dataSource = ReloadingDataSource() dataSource.viewControllers = [viewController0, viewController1, viewController2] dataSource.items = [item0, item1, item2] let pagingViewController = PagingViewController() pagingViewController.dataSource = dataSource pagingViewController.register(ItemCell.self, for: Item.self) // Act pagingViewController.reloadData() pagingViewController.select(index: 1) let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 1000, height: 50)) window.rootViewController = pagingViewController window.makeKeyAndVisible() pagingViewController.view.layoutIfNeeded() // Assert XCTAssertEqual(pagingViewController.pageViewController.selectedViewController, viewController1) XCTAssertEqual(pagingViewController.collectionView.indexPathsForSelectedItems, [IndexPath(item: 1, section: 0)]) XCTAssertEqual(pagingViewController.state, PagingState.selected(pagingItem: item1)) } func testRetainCycles() { var instance: DeinitPagingViewController? = DeinitPagingViewController() let expectation = XCTestExpectation() instance?.deinitCalled = { expectation.fulfill() } DispatchQueue.global(qos: .background).async { instance = nil } wait(for: [expectation], timeout: 2) } } private class DataSource: PagingViewControllerInfiniteDataSource { func pagingViewController(_: PagingViewController, itemAfter: PagingItem) -> PagingItem? { guard let item = itemAfter as? Item else { return nil } if item.index < 50 { return Item(index: item.index + 1) } return nil } func pagingViewController(_: PagingViewController, itemBefore: PagingItem) -> PagingItem? { guard let item = itemBefore as? Item else { return nil } if item.index > 0 { return Item(index: item.index - 1) } return nil } func pagingViewController(_: PagingViewController, viewControllerFor _: PagingItem) -> UIViewController { return UIViewController() } } private class SizeDelegate: PagingViewControllerSizeDelegate { func pagingViewController(_: PagingViewController, widthForPagingItem pagingItem: PagingItem, isSelected _: Bool) -> CGFloat { guard let item = pagingItem as? Item else { return 0 } if item.index == 0 { return 100 } else { return 50 } } } private class DeinitPagingViewController: PagingViewController { var deinitCalled: (() -> Void)? deinit { deinitCalled?() } } private class ReloadingDataSource: PagingViewControllerDataSource { var items: [Item] = [] var viewControllers: [UIViewController] = [] func numberOfViewControllers(in _: PagingViewController) -> Int { return items.count } func pagingViewController(_: PagingViewController, viewControllerAt index: Int) -> UIViewController { return viewControllers[index] } func pagingViewController(_: PagingViewController, pagingItemAt index: Int) -> PagingItem { return items[index] } }
mit
33b09586672619cbac600bac352b93b9
38.057906
130
0.688145
5.502667
false
false
false
false
contentful/contentful.swift
Sources/Contentful/Asset.swift
1
6471
// // Asset.swift // Contentful // // Created by Boris Bügling on 18/08/15. // Copyright © 2015 Contentful GmbH. All rights reserved. // import Foundation /// A simple protocol to bridge `Contentful.Asset` and other formats for storing asset information. public protocol AssetProtocol: FlatResource { /// String representation for the URL of the media file associated with this asset. var urlString: String? { get } } /// Classes conforming to this protocol can be decoded during JSON deserialization as reprsentations /// of Contentful assets. public protocol AssetDecodable: AssetProtocol, Decodable {} /// An asset represents a media file in Contentful. public class Asset: LocalizableResource, AssetDecodable { /// The key paths for member fields of an Asset public enum Fields: String, CodingKey { /// Title description and file keys. case title, description, file } /// The URL for the underlying media file. Returns nil if the url was omitted from the response (i.e. `select` operation in query) /// or if the underlying media file is still processing with Contentful. public var url: URL? { guard let url = file?.url else { return nil } return url } /// String representation for the URL of the media file associated with this asset. Optional for compatibility with `select` operator queries. /// Also, If the media file is still being processed, as the final stage of uploading to your space, this property will be nil. public var urlString: String? { guard let urlString = url?.absoluteString else { return nil } return urlString } /// The title of the asset. Optional for compatibility with `select` operator queries. public var title: String? { return fields["title"] as? String } /// Description of the asset. Optional for compatibility with `select` operator queries. public var description: String? { return fields["description"] as? String } /// Metadata describing the file associated with the asset. Optional for compatibility with `select` operator queries. public var file: FileMetadata? { return fields["file"] as? FileMetadata } } public extension AssetProtocol { /// The URL for the underlying media file with additional options for server side manipulations /// such as format changes, resizing, cropping, and focusing on different areas including on faces, /// among others. /// /// - Parameter imageOptions: An array of `ImageOption` that will be used for server side manipulations. /// - Returns: The URL for the image with the image manipulations, represented in the `imageOptions` parameter, applied. /// - Throws: Will throw `SDKError` if the SDK is unable to generate a valid URL with the desired ImageOptions. func url(with imageOptions: [ImageOption] = []) throws -> URL { guard let url = try urlString?.url(with: imageOptions) else { throw SDKError.invalidURL(string: urlString ?? "No url string is stored for Asset: \(id)") } return url } } extension Asset { /// Metadata describing underlying media file. public struct FileMetadata: Decodable { /// Original filename of the file. public let fileName: String /// Content type of the file. public let contentType: String /// Details of the file, depending on it's MIME type. public let details: Details? /// The remote URL for the binary data for this Asset. /// If the media file is still being processed, as the final stage of uploading to your space, this property will be nil. public let url: URL? /// The size and dimensions of the underlying media file if it is an image. public struct Details: Decodable { /// The size of the file in bytes. public let size: Int /// Additional information describing the image the asset references. public let imageInfo: ImageInfo? /// A lightweight struct to hold the dimensions information for the this file, if it is an image type. public struct ImageInfo: Decodable { /// The width of the image. public let width: Double /// The height of the image. public let height: Double public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) width = try container.decode(Double.self, forKey: .width) height = try container.decode(Double.self, forKey: .height) } private enum CodingKeys: String, CodingKey { case width, height } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) size = try container.decode(Int.self, forKey: .size) imageInfo = try container.decodeIfPresent(ImageInfo.self, forKey: .image) } private enum CodingKeys: String, CodingKey { case size, image } } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) fileName = try container.decode(String.self, forKey: .fileName) contentType = try container.decode(String.self, forKey: .contentType) details = try container.decode(Details.self, forKey: .details) // Decodable handles URL's automatically but we need to prepend the https protocol. let urlString = try container.decode(String.self, forKey: .url) guard let url = URL(string: "https:" + urlString) else { throw SDKError.invalidURL(string: "Asset had urlString incapable of being made into a Foundation.URL object \(urlString)") } self.url = url } private enum CodingKeys: String, CodingKey { case fileName, contentType, url, details } } } extension Asset: EndpointAccessible { public static let endpoint = Endpoint.assets } extension Asset: ResourceQueryable { /// The QueryType for an Asset is AssetQuery public typealias QueryType = AssetQuery }
mit
c04e93feb175e03522a11516c6e87642
38.932099
146
0.644767
4.987664
false
false
false
false
brokenseal/iOS-exercises
Team Treehouse/RestaurantFinder/RestaurantFinder/LocationManager.swift
1
5626
// // LocationManager.swift // RestaurantFinder // // Created by Davide Callegari on 06/07/17. // Copyright © 2017 Davide Callegari. All rights reserved. // import Foundation import CoreLocation import MapKit extension Coordinate { init(location: CLLocation) { latitude = location.coordinate.latitude longitude = location.coordinate.longitude } } enum Message: Hashable { case locationFix case permissionUpdate case locationError } typealias Listener = ((Any) -> Void) typealias Listeners = [Message: [Listener]] final class LocationManager: NSObject, CLLocationManagerDelegate { private let manager = CLLocationManager() var listeners: Listeners = [:] let authorized: Bool = { return CLLocationManager.authorizationStatus() == .authorizedWhenInUse }() var started = false override init() { super.init() manager.delegate = self manager.distanceFilter = 1000.0 // meters manager.desiredAccuracy = kCLLocationAccuracyThreeKilometers } func startListeningForLocationChanges() { if authorized && !started { started = true manager.startUpdatingLocation() } } func on(_ message: Message, listener: @escaping Listener) { if listeners[message] == nil { listeners[message] = [] } listeners[message]!.append(listener) } func getPermission(){ if CLLocationManager.authorizationStatus() == .notDetermined { manager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if authorized { return } if let permissionUpdateListeners = listeners[.permissionUpdate] { for listener in permissionUpdateListeners { listener(status) } } if status == .authorizedWhenInUse { self.startListeningForLocationChanges() } else if status == .denied { // notify users that the app won't work } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { guard let locationErrorListeners = listeners[.locationError] else { return } for listener in locationErrorListeners { listener(error) } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first, let locationFixListeners = listeners[.locationFix] else { return } locationFixListeners.forEach { listener in DispatchQueue.main.async { // TODO check if this is actually fixing it listener(Coordinate(location: location)) } } } deinit { listeners = [:] } } struct Pin { let title: String var latitude: Double var longitude: Double } final class SimpleMapManager: NSObject, MKMapViewDelegate { private let map:MKMapView var regionRadius: Double init(_ map: MKMapView, regionRadius: Double?){ self.map = map self.regionRadius = regionRadius ?? 1000.0 super.init() map.delegate = self } func showRegion(latitude: Double, longitude: Double){ let location = CLLocationCoordinate2D( latitude: latitude, longitude: longitude ) let region = MKCoordinateRegionMakeWithDistance(location, regionRadius * 2, regionRadius * 2) map.setRegion(region, animated: true) } func addPin(title: String, latitude: Double, longitude: Double){ let pin = MKPointAnnotation() pin.title = title pin.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) map.addAnnotation(pin) } func addPins(pinsData: [Pin]){ for pinData in pinsData { addPin(title: pinData.title, latitude: pinData.latitude, longitude: pinData.longitude) } } func removeAllPins(){ if map.annotations.count == 0 { return } map.removeAnnotations(map.annotations) } // MARK: MKMapViewDelegate methods func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) { for annotationView in views { let button = UIButton(type: .detailDisclosure) annotationView.canShowCallout = true annotationView.rightCalloutAccessoryView = button } /* MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"loc"]; annotationView.canShowCallout = YES; annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; */ } } class SimpleAlert { private let alert: UIAlertController static func `default`(title: String, message: String) -> SimpleAlert { let alert = SimpleAlert(title: title, message: message) return alert } init(title: String, message: String) { self.alert = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert ) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) } func show(using viewController: UIViewController) { viewController.present(alert, animated: true, completion: nil) } }
mit
f2d48bd221aaa54e01994f2b4d579e65
28.920213
126
0.634311
5.372493
false
false
false
false
polymr/polymyr-api
Sources/App/Stripe/HTTPClient.swift
1
3382
// // HTTPClient.swift // subber-api // // Created by Hakon Hanesand on 1/19/17. // // import JSON import HTTP import Foundation import Vapor public struct StripeHTTPError: AbortError { public let status: HTTP.Status public let reason: String public let metadata: Node? init(node: Node, code: Status) { self.metadata = node self.status = code self.reason = "Stripe Error" } } func createToken(token: String) throws -> [HeaderKey: String] { let base64 = token.bytes.base64Encoded return try ["Authorization" : "Basic \(base64.string())"] } public class HTTPClient { let baseURLString: String init(urlString: String) { baseURLString = urlString } func get<T: NodeConvertible>(_ resource: String, query: [String : NodeRepresentable] = [:], token: String = Stripe.secret) throws -> T { let response = try drop.client.get(baseURLString + resource, query: query, createToken(token: token)) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) return try T.init(node: json.makeNode(in: emptyContext)) } func get_list<T: NodeConvertible>(_ resource: String, query: [String : NodeRepresentable] = [:], token: String = Stripe.secret) throws -> [T] { let response = try drop.client.get(baseURLString + resource, query: query, createToken(token: token)) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) guard let objects = json.node["data"]?.array else { throw Abort.custom(status: .internalServerError, message: "Unexpected response formatting. \(json)") } return try objects.map { return try T.init(node: $0) } } func post<T: NodeConvertible>(_ resource: String, query: [String : NodeRepresentable] = [:], token: String = Stripe.secret) throws -> T { let response = try drop.client.post(baseURLString + resource, query: query, createToken(token: token)) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) return try T.init(node: json.makeNode(in: emptyContext)) } func delete(_ resource: String, query: [String : NodeRepresentable] = [:], token: String = Stripe.secret) throws -> JSON { let response = try drop.client.delete(baseURLString + resource, query: query, createToken(token: token)) guard let json = try? response.json() else { throw Abort.custom(status: .internalServerError, message: response.description) } try checkForStripeError(in: json, from: resource) return json } private func checkForStripeError(in json: JSON, from resource: String) throws { if json["error"] != nil { throw StripeHTTPError(node: json.node, code: .internalServerError) } } }
mit
0c2f6c2994e693481d543f49019e18fe
33.510204
147
0.624187
4.515354
false
false
false
false
zhaobin19918183/zhaobinCode
HTK/HTK/Common/Common.swift
1
1345
// // Common.swift // EveryOne // // Created by Zhao.bin on 16/1/12. // Copyright © 2016年 Zhao.bin. All rights reserved. // import Foundation import UIKit //Colors let systemColorClear : UIColor = UIColor.clear let SystemColorGreen : UIColor = UIColor(red: 76/255.0, green: 217/255.0, blue: 100/255.0, alpha: 1) let SystemColorGray : UIColor = UIColor(red: 200/255.0, green: 200/255.0, blue: 200/255.0, alpha: 1) let SystemColorLightRed : UIColor = UIColor(red: 220/255.0, green: 100/255.0, blue: 80/255.0, alpha: 1) let SystemColorRed : UIColor = UIColor(red: 250/255.0, green: 100/255.0, blue: 80/255.0, alpha: 1) let SystemColorLightBlack : UIColor = UIColor(red: 100/255.0, green: 100/255.0, blue: 100/255.0, alpha: 1) let SystemColorBlue : UIColor = UIColor(red: 90/255.0, green: 185/255.0, blue: 230/255.0, alpha: 1) let SystemColorLightWhite : UIColor = UIColor(red: 150/255.0, green: 150/255.0, blue: 150/255.0, alpha: 1) //Paths //Level - 1 private let kPathRootArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let kPathRoot = kPathRootArray[0] as String //Level - 2 let kPathCoreData = kPathRoot + "/Coredata" //Level - 3 let kPathSQLITE = kPathCoreData + "/Model.Sqlite" let Common_busUrl = "http://op.juhe.cn/189/bus/busline" let Common_OK = " 确认" let Common_Warning = "警告"
gpl-3.0
a25b530cdd8dd727e7b4e2fd901b1571
37.114286
107
0.715142
2.957871
false
false
false
false
lennet/proNotes
app/proNotes/Model/DocumentLayer/ImageLayer.swift
1
1965
// // ImageLayer.swift // proNotes // // Created by Leo Thomas on 20/02/16. // Copyright © 2016 leonardthomas. All rights reserved. // import UIKit class ImageLayer: MovableLayer { var image: UIImage? { get { return ImageCache.sharedInstance[imageKey] } set { ImageCache.sharedInstance[imageKey] = newValue } } let imageKey = UUID().uuidString init(index: Int, docPage: DocumentPage, origin: CGPoint, size: CGSize?, image: UIImage) { super.init(index: index, type: .image, docPage: docPage, origin: origin, size: size ?? image.size) self.image = image } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder, type: .image) type = .image if let imageData = aDecoder.decodeObject(forKey: imageDataKey) as? Data { image = UIImage(data: imageData)! } else { image = UIImage() } } required init(coder aDecoder: NSCoder, type: DocumentLayerType) { fatalError("init(coder:type:) has not been implemented") } private final let imageDataKey = "imageData" override func encode(with aCoder: NSCoder) { guard let image = image else { return } if let imageData = UIImageJPEGRepresentation(image, 1.0) { aCoder.encode(imageData, forKey: imageDataKey) } else { print("Could not save drawing Image") } super.encode(with: aCoder) } override func undoAction(_ oldObject: Any?) { if let image = oldObject as? UIImage { self.image = image } else { super.undoAction(oldObject) } } override func isEqual(_ object: Any?) -> Bool { guard object is ImageLayer else { return false } if !super.isEqual(object) { return false } return true } }
mit
c67227b22bc778977492d759741e95a7
24.179487
106
0.57332
4.473804
false
false
false
false