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
SwiftKidz/Slip
Sources/Classes/AsyncOperation.swift
1
2652
/* MIT License Copyright (c) 2016 SwiftKidz 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 class AsyncOperation: Operation { fileprivate enum ChangeKey: String { case isFinished, isExecuting } let runQueue: DispatchQueue let order: Int var asyncBlock: () -> Void var finishedOp: Bool = false { didSet { didChangeValue(forKey: ChangeKey.isFinished.rawValue) } willSet { willChangeValue(forKey: ChangeKey.isFinished.rawValue) } } var executingOp: Bool = false { didSet { didChangeValue(forKey: ChangeKey.isExecuting.rawValue) } willSet { willChangeValue(forKey: ChangeKey.isExecuting.rawValue) } } init(qos: DispatchQoS = .background, orderNumber: Int) { order = orderNumber runQueue = DispatchQueue( label: "com.slip.asyncOperation.runQueue", qos: qos ) asyncBlock = {} } } extension AsyncOperation { override func start() { guard !isCancelled else { return } executingOp = true runQueue.async { [unowned self] in self.asyncBlock() } } func markAsFinished() { executingOp = false finishedOp = true } } extension AsyncOperation { override var isAsynchronous: Bool { return true } override var isFinished: Bool { get { return finishedOp } set { finishedOp = newValue } } override var isExecuting: Bool { get { return executingOp } set { executingOp = newValue } } }
mit
de2917397c4f29758b137f7ce590cbcc
26.625
79
0.665913
4.857143
false
false
false
false
emadhegab/GenericDataSource
Sources/CompositeSupplementaryViewCreator.swift
3
8560
// // CompositeSupplementaryViewCreator.swift // GenericDataSource // // Created by Mohamed Afifi on 10/15/16. // Copyright © 2016 mohamede1945. All rights reserved. // import Foundation /// Represents a supplementary view creator that manages other creators depending on the kind. /// /// Usually this is used if you have multiple supplementary views (e.g. headers and footers) /// and you need to have different views or different logic of configuration for the header than the footer. /// Then you should use `CompositeSupplementaryViewCreator`. /// /// For example: /// ```swift /// // define a composite creators. /// let creator = CompositeSupplementaryViewCreator() /// /// let headerCreator: SupplementaryViewCreator = <...> /// let footerCreator: SupplementaryViewCreator = <...> /// /// // add them to the composite creator. /// creator.add(creator: headerCreator, forKind: UICollectionElementKindSectionHeader) /// creator.add(creator: footerCreator, forKind: UICollectionElementKindSectionFooter) /// /// // Then assign the composite creator to the data source. /// dataSource.supplementaryViewCreator = creator /// ``` open class CompositeSupplementaryViewCreator: NSObject, SupplementaryViewCreator { /// The list of child creators and their kind. open private(set) var creators: [String: SupplementaryViewCreator] /// Creates new instance with the passed creators. /// /// - parameter creators: The list of creators with their kind. public init(creators: [String: SupplementaryViewCreator] = [:]) { self.creators = creators } /// Creates new instance with header creator. /// /// - parameter headerCreator: The header creator. public convenience init(headerCreator: SupplementaryViewCreator) { self.init(creators: [UICollectionElementKindSectionHeader: headerCreator]) } /// Creates new instance with footer creator. /// /// - parameter footerCreator: The footer creator. public convenience init(footerCreator: SupplementaryViewCreator) { self.init(creators: [UICollectionElementKindSectionFooter: footerCreator]) } /// Creates new instance with header and footer creator. /// /// - parameter headerCreator: The header creator. /// - parameter footerCreator: The footer creator. public convenience init(headerCreator: SupplementaryViewCreator, footerCreator: SupplementaryViewCreator) { self.init(creators: [UICollectionElementKindSectionHeader: headerCreator, UICollectionElementKindSectionFooter: footerCreator]) } /// Adds a new child creator for the specified kind. /// /// - parameter creator: The child creator that will handle the supplementary view calls for the specified kind. /// - parameter kind: The kind which the creator will only operate for. open func add(creator: SupplementaryViewCreator, forKind kind: String) { creators[kind] = creator } /// Removes a creator for the passed kind. /// /// - parameter kind: The kind for which the creator is no longer needed. open func removeCreator(forKind kind: String) { creators.removeValue(forKey: kind) } /// Removes all creators. open func removeAllCreators() { creators.removeAll() } /// Gets the supplementary view creator for the passed kind. /// /// It crashes if there is no such creator. /// /// - parameter kind: The kind for which the creator needed. /// /// - returns: The supplementary view creator for the passed kind. open func creator(ofKind kind: String) -> SupplementaryViewCreator { let creator: SupplementaryViewCreator = cast(creators[kind], message: "Cannot find creator of kind '\(kind)'") return creator } /// Gets the supplementary view for the passed kind at the specified index path. /// /// It delegates the call to `creator(ofKind: kind)`. /// /// For `UITableView`, it can be either `UICollectionElementKindSectionHeader` or /// `UICollectionElementKindSectionFooter` for header and footer views respectively. /// /// - parameter collectionView: The general collection view requesting the index path. /// - parameter kind: The kind of the supplementary view. For `UITableView`, it can be either /// `UICollectionElementKindSectionHeader` or `UICollectionElementKindSectionFooter` for /// header and footer views respectively. /// - parameter indexPath: The index path at which the supplementary view is requested. /// /// - returns: The supplementary view dequeued and configured appropriately. open func collectionView(_ collectionView: GeneralCollectionView, viewOfKind kind: String, at indexPath: IndexPath) -> ReusableSupplementaryView? { let viewCreator = creators[kind] return viewCreator?.collectionView(collectionView, viewOfKind: kind, at: indexPath) } /// Gets the size of the supplementary view for the passed kind at the specified index path. /// /// It delegates the call to `creator(ofKind: kind)`. /// /// * For `UITableView` just supply the height width is don't care. /// * For `UICollectionViewFlowLayout` supply the height if it's vertical scrolling, or width if it's horizontal scrolling. /// * Specifying `CGSize.zero`, means don't display a supplementary view and `viewOfKind` will not be called. /// /// - parameter collectionView: The general collection view requesting the index path. /// - parameter kind: The kind of the supplementary view. For `UITableView`, it can be either /// `UICollectionElementKindSectionHeader` or `UICollectionElementKindSectionFooter` for /// header and footer views respectively. /// - parameter indexPath: The index path at which the supplementary view size is requested. /// /// - returns: The size of the supplementary view. open func collectionView(_ collectionView: GeneralCollectionView, sizeForViewOfKind kind: String, at indexPath: IndexPath) -> CGSize { let viewCreator = creators[kind] return viewCreator?.collectionView(collectionView, sizeForViewOfKind: kind, at: indexPath) ?? .zero } /// Supplementary view is about to be displayed. Called exactly before the supplementary view is displayed. /// /// It delegates the call to `creator(ofKind: kind)`. /// /// - parameter collectionView: The general collection view requesting the index path. /// - parameter view: The supplementary view that will be displayed. /// - parameter kind: The kind of the supplementary view. For `UITableView`, it can be either /// `UICollectionElementKindSectionHeader` or `UICollectionElementKindSectionFooter` for /// header and footer views respectively. /// - parameter indexPath: The index path at which the supplementary view is. open func collectionView(_ collectionView: GeneralCollectionView, willDisplayView view: ReusableSupplementaryView, ofKind kind: String, at indexPath: IndexPath) { let viewCreator = creator(ofKind: kind) viewCreator.collectionView(collectionView, willDisplayView: view, ofKind: kind, at: indexPath) } /// Supplementary view has been displayed and user scrolled it out of the screen. /// Called exactly after the supplementary view is scrolled out of the screen. /// /// It delegates the call to `creator(ofKind: kind)`. /// /// - parameter collectionView: The general collection view requesting the index path. /// - parameter view: The supplementary view that will be displayed. /// - parameter kind: The kind of the supplementary view. For `UITableView`, it can be either /// `UICollectionElementKindSectionHeader` or `UICollectionElementKindSectionFooter` for /// header and footer views respectively. /// - parameter indexPath: The index path at which the supplementary view is. open func collectionView(_ collectionView: GeneralCollectionView, didEndDisplayingView view: ReusableSupplementaryView, ofKind kind: String, at indexPath: IndexPath) { let viewCreator = creator(ofKind: kind) viewCreator.collectionView(collectionView, didEndDisplayingView: view, ofKind: kind, at: indexPath) } }
mit
26937bbff8b03a94f8f72541d89b7288
50.251497
171
0.692137
5.342697
false
false
false
false
tndatacommons/OfficeHours-iOS
OfficeHours/ScheduleController.swift
1
2555
// // ScheduleController.swift // OfficeHours // // Created by Ismael Alonso on 12/7/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import UIKit class ScheduleController: UITableViewController, AddCourseDelegate, CourseEditorDelegate{ var courses = [CourseModel]() override func viewDidLoad(){ super.viewDidLoad() //Automatic height calculation tableView.rowHeight = UITableViewAutomaticDimension //Dummy data courses.append(CourseModel(code: "COMP 1900", name: "Intro to CS", meetingTime: "MW 7", lastMeetingDate: "12/14", instructorName: "Someboody")) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return courses.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: "CourseCell", for: indexPath) as! CourseCell cell.bind(course: courses[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat{ return 67 } @IBAction func addClicked(_ sender: Any){ if SharedData.getUser()!.isStudent(){ performSegue(withIdentifier: "AddCourseFromSchedule", sender: self) } else{ performSegue(withIdentifier: "CourseEditorFromSchedule", sender: self) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?){ if segue.identifier == "AddCourseFromSchedule"{ let addCourseController = segue.destination as! AddCourseController addCourseController.delegate = self } else if segue.identifier == "CourseEditorFromSchedule"{ let courseEditorController = segue.destination as! CourseEditorController courseEditorController.delegate = self } else if segue.identifier == "CourseFromSchedule"{ let courseController = segue.destination as! CourseController let indexPath = tableView.indexPath(for: sender as! CourseCell) courseController.course = courses[indexPath!.row] } } func onCourseAdded(course: CourseModel){ courses.append(course) tableView.reloadData() } func onCourseSaved(_ course: CourseModel){ courses.append(course) tableView.reloadData() } }
apache-2.0
420551cae86b7951d948732256f41c1a
33.513514
151
0.660141
5.06746
false
false
false
false
mattjgalloway/emoncms-ios
EmonCMSiOS/Model/Feed.swift
1
1093
// // Feed.swift // EmonCMSiOS // // Created by Matt Galloway on 12/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation import RealmSwift final class Feed: Object { dynamic var id: String = "" dynamic var name: String = "" dynamic var tag: String = "" dynamic var time: Date = Date() dynamic var value: Double = 0 override class func primaryKey() -> String? { return "id" } } extension Feed { static func from(json: [String:Any]) -> Feed? { guard let id = json["id"] as? String else { return nil } guard let name = json["name"] as? String else { return nil } guard let tag = json["tag"] as? String else { return nil } guard let timeAny = json["time"], let timeDouble = Double(timeAny) else { return nil } guard let valueAny = json["value"], let value = Double(valueAny) else { return nil } let time = Date(timeIntervalSince1970: timeDouble) let feed = Feed() feed.id = id feed.name = name feed.tag = tag feed.time = time feed.value = value return feed } }
mit
a132535190e6b46035beadbc2e5b054b
20.84
64
0.630037
3.64
false
false
false
false
zixun/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/Helper/CCURLHelper.swift
1
888
// // CCPTools.swift // CocoaChinaPlus // // Created by zixun on 15/8/22. // Copyright © 2015年 zixun. All rights reserved. // import Foundation class CCURLHelper: NSObject { class func generateIdentity(_ url: String) -> String { let target = url.lowercased(); if (target.range(of: "wap") != nil) { //wap return url.components(separatedBy: "=").last! }else { //pc return url.components(separatedBy: "/").last!.components(separatedBy: ".").first! } } class func generateWapURL(_ identity:String) -> String { return "http://www.cocoachina.com/cms/wap.php?action=article&id=\(identity)" } class func generateWapURLFromURL(_ url:String) -> String { let identity = self.generateIdentity(url) return self.generateWapURL(identity) } }
mit
66efb45a9b4e6721c081e2eb8f107255
25.818182
93
0.589831
3.933333
false
false
false
false
MAARK/Charts
Source/Charts/Components/Legend.swift
4
14372
// // Legend.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(ChartLegend) open class Legend: ComponentBase { @objc(ChartLegendForm) public enum Form: Int { /// Avoid drawing a form case none /// Do not draw the a form, but leave space for it case empty /// Use default (default dataset's form to the legend's form) case `default` /// Draw a square case square /// Draw a circle case circle /// Draw a horizontal line case line } @objc(ChartLegendHorizontalAlignment) public enum HorizontalAlignment: Int { case left case center case right } @objc(ChartLegendVerticalAlignment) public enum VerticalAlignment: Int { case top case center case bottom } @objc(ChartLegendOrientation) public enum Orientation: Int { case horizontal case vertical } @objc(ChartLegendDirection) public enum Direction: Int { case leftToRight case rightToLeft } /// The legend entries array @objc open var entries = [LegendEntry]() /// Entries that will be appended to the end of the auto calculated entries after calculating the legend. /// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect) @objc open var extraEntries = [LegendEntry]() /// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom. /// /// **default**: false (automatic legend) private var _isLegendCustom = false /// The horizontal alignment of the legend @objc open var horizontalAlignment: HorizontalAlignment = HorizontalAlignment.left /// The vertical alignment of the legend @objc open var verticalAlignment: VerticalAlignment = VerticalAlignment.bottom /// The orientation of the legend @objc open var orientation: Orientation = Orientation.horizontal /// Flag indicating whether the legend will draw inside the chart or outside @objc open var drawInside: Bool = false /// Flag indicating whether the legend will draw inside the chart or outside @objc open var isDrawInsideEnabled: Bool { return drawInside } /// The text direction of the legend @objc open var direction: Direction = Direction.leftToRight @objc open var font: NSUIFont = NSUIFont.systemFont(ofSize: 10.0) @objc open var textColor = NSUIColor.black /// The form/shape of the legend forms @objc open var form = Form.square /// The size of the legend forms @objc open var formSize = CGFloat(8.0) /// The line width for forms that consist of lines @objc open var formLineWidth = CGFloat(3.0) /// Line dash configuration for shapes that consist of lines. /// /// This is how much (in pixels) into the dash pattern are we starting from. @objc open var formLineDashPhase: CGFloat = 0.0 /// Line dash configuration for shapes that consist of lines. /// /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] @objc open var formLineDashLengths: [CGFloat]? @objc open var xEntrySpace = CGFloat(6.0) @objc open var yEntrySpace = CGFloat(0.0) @objc open var formToTextSpace = CGFloat(5.0) @objc open var stackSpace = CGFloat(3.0) @objc open var calculatedLabelSizes = [CGSize]() @objc open var calculatedLabelBreakPoints = [Bool]() @objc open var calculatedLineSizes = [CGSize]() public override init() { super.init() self.xOffset = 5.0 self.yOffset = 3.0 } @objc public init(entries: [LegendEntry]) { super.init() self.entries = entries } @objc open func getMaximumEntrySize(withFont font: NSUIFont) -> CGSize { var maxW = CGFloat(0.0) var maxH = CGFloat(0.0) var maxFormSize: CGFloat = 0.0 for entry in entries { let formSize = entry.formSize.isNaN ? self.formSize : entry.formSize if formSize > maxFormSize { maxFormSize = formSize } guard let label = entry.label else { continue } let size = (label as NSString).size(withAttributes: [.font: font]) if size.width > maxW { maxW = size.width } if size.height > maxH { maxH = size.height } } return CGSize( width: maxW + maxFormSize + formToTextSpace, height: maxH ) } @objc open var neededWidth = CGFloat(0.0) @objc open var neededHeight = CGFloat(0.0) @objc open var textWidthMax = CGFloat(0.0) @objc open var textHeightMax = CGFloat(0.0) /// flag that indicates if word wrapping is enabled /// this is currently supported only for `orientation == Horizontal`. /// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps. /// /// **default**: true @objc open var wordWrapEnabled = true /// if this is set, then word wrapping the legend is enabled. @objc open var isWordWrapEnabled: Bool { return wordWrapEnabled } /// The maximum relative size out of the whole chart view in percent. /// If the legend is to the right/left of the chart, then this affects the width of the legend. /// If the legend is to the top/bottom of the chart, then this affects the height of the legend. /// /// **default**: 0.95 (95%) @objc open var maxSizePercent: CGFloat = 0.95 @objc open func calculateDimensions(labelFont: NSUIFont, viewPortHandler: ViewPortHandler) { let maxEntrySize = getMaximumEntrySize(withFont: labelFont) let defaultFormSize = self.formSize let stackSpace = self.stackSpace let formToTextSpace = self.formToTextSpace let xEntrySpace = self.xEntrySpace let yEntrySpace = self.yEntrySpace let wordWrapEnabled = self.wordWrapEnabled let entries = self.entries let entryCount = entries.count textWidthMax = maxEntrySize.width textHeightMax = maxEntrySize.height switch orientation { case .vertical: var maxWidth = CGFloat(0.0) var width = CGFloat(0.0) var maxHeight = CGFloat(0.0) let labelLineHeight = labelFont.lineHeight var wasStacked = false for i in 0 ..< entryCount { let e = entries[i] let drawingForm = e.form != .none let formSize = e.formSize.isNaN ? defaultFormSize : e.formSize let label = e.label if !wasStacked { width = 0.0 } if drawingForm { if wasStacked { width += stackSpace } width += formSize } if label != nil { let size = (label! as NSString).size(withAttributes: [.font: labelFont]) if drawingForm && !wasStacked { width += formToTextSpace } else if wasStacked { maxWidth = max(maxWidth, width) maxHeight += labelLineHeight + yEntrySpace width = 0.0 wasStacked = false } width += size.width maxHeight += labelLineHeight + yEntrySpace } else { wasStacked = true width += formSize if i < entryCount - 1 { width += stackSpace } } maxWidth = max(maxWidth, width) } neededWidth = maxWidth neededHeight = maxHeight case .horizontal: let labelLineHeight = labelFont.lineHeight let contentWidth: CGFloat = viewPortHandler.contentWidth * maxSizePercent // Prepare arrays for calculated layout if calculatedLabelSizes.count != entryCount { calculatedLabelSizes = [CGSize](repeating: CGSize(), count: entryCount) } if calculatedLabelBreakPoints.count != entryCount { calculatedLabelBreakPoints = [Bool](repeating: false, count: entryCount) } calculatedLineSizes.removeAll(keepingCapacity: true) // Start calculating layout let labelAttrs = [NSAttributedString.Key.font: labelFont] var maxLineWidth: CGFloat = 0.0 var currentLineWidth: CGFloat = 0.0 var requiredWidth: CGFloat = 0.0 var stackedStartIndex: Int = -1 for i in 0 ..< entryCount { let e = entries[i] let drawingForm = e.form != .none let label = e.label calculatedLabelBreakPoints[i] = false if stackedStartIndex == -1 { // we are not stacking, so required width is for this label only requiredWidth = 0.0 } else { // add the spacing appropriate for stacked labels/forms requiredWidth += stackSpace } // grouped forms have null labels if label != nil { calculatedLabelSizes[i] = (label! as NSString).size(withAttributes: labelAttrs) requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0 requiredWidth += calculatedLabelSizes[i].width } else { calculatedLabelSizes[i] = CGSize() requiredWidth += drawingForm ? formSize : 0.0 if stackedStartIndex == -1 { // mark this index as we might want to break here later stackedStartIndex = i } } if label != nil || i == entryCount - 1 { let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace if (!wordWrapEnabled || // No word wrapping, it must fit. currentLineWidth == 0.0 || // The line is empty, it must fit. (contentWidth - currentLineWidth >= requiredSpacing + requiredWidth)) // It simply fits { // Expand current line currentLineWidth += requiredSpacing + requiredWidth } else { // It doesn't fit, we need to wrap a line // Add current line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) // Start a new line calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true currentLineWidth = requiredWidth } if i == entryCount - 1 { // Add last line size to array calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight)) maxLineWidth = max(maxLineWidth, currentLineWidth) } } stackedStartIndex = label != nil ? -1 : stackedStartIndex } neededWidth = maxLineWidth neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) + yEntrySpace * CGFloat(calculatedLineSizes.count == 0 ? 0 : (calculatedLineSizes.count - 1)) } neededWidth += xOffset neededHeight += yOffset } /// MARK: - Custom legend /// Sets a custom legend's entries array. /// * A nil label will start a group. /// This will disable the feature that automatically calculates the legend entries from the datasets. /// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed). @objc open func setCustom(entries: [LegendEntry]) { self.entries = entries _isLegendCustom = true } /// Calling this will disable the custom legend entries (set by `setLegend(...)`). Instead, the entries will again be calculated automatically (after `notifyDataSetChanged()` is called). @objc open func resetCustom() { _isLegendCustom = false } /// **default**: false (automatic legend) /// `true` if a custom legend entries has been set @objc open var isLegendCustom: Bool { return _isLegendCustom } }
apache-2.0
6add714519bdb2b389f7cd2d9647d912
33.219048
190
0.526301
5.7488
false
false
false
false
KrishMunot/swift
benchmark/single-source/ArrayOfGenericPOD.swift
2
1930
//===--- ArrayOfGenericPOD.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 // //===----------------------------------------------------------------------===// // This benchmark tests creation and destruction of arrays of enum and // generic type bound to trivial types. It should take the same time as // ArrayOfPOD. (In practice, it takes a little longer to construct // the optional arrays). // // For comparison, we always create three arrays of 200,000 words. // An integer enum takes two words. class RefArray<T> { var array : [T] init(_ i:T) { array = [T](repeating: i, count: 100000) } } // Check the performance of destroying an array of enums (optional) where the // enum has a single payload of trivial type. Destroying the // elements should be a nop. @inline(never) func genEnumArray() { _ = RefArray<Int?>(3) // should be a nop } // Check the performance of destroying an array of implicit unwrapped // optional where the optional has a single payload of trivial // type. Destroying the elements should be a nop. @inline(never) func genIOUArray() { _ = RefArray<Int!>(3) // should be a nop } // Check the performance of destroying an array of structs where the // struct has multiple fields of trivial type. Destroying the // elements should be a nop. struct S<T> { var x : T var y : T } @inline(never) func genStructArray() { _ = RefArray<S<Int>>(S(x:3,y:4)) // should be a nop } @inline(never) public func run_ArrayOfGenericPOD(_ N: Int) { for _ in 0...N { genEnumArray() genIOUArray() genStructArray() } }
apache-2.0
240a774c340dcc76db5d181e95fd9457
27.80597
80
0.653368
3.852295
false
false
false
false
kaneshin/ActiveRecord
Source/Context.swift
1
4503
// Context.swift // // Copyright (c) 2015 Shintaro Kaneko // // 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 CoreData public protocol Context { /// Main queue context var defaultManagedObjectContext: NSManagedObjectContext? { get } /// Context for writing to the PersistentStore var writerManagedObjectContext: NSManagedObjectContext? { get } /// PersistentStoreCoordinator var persistentStoreCoordinator: NSPersistentStoreCoordinator? { get } /// ManagedObjectModel var managedObjectModel: NSManagedObjectModel? { get } /// Store URL var storeURL: NSURL? { get } } public class ARContext: NSObject, Context { public override init() { super.init() } /// Main queue context public var defaultManagedObjectContext: NSManagedObjectContext? { return self.lazyDefaultManagedObjectContext } /// Context for writing to the PersistentStore public var writerManagedObjectContext: NSManagedObjectContext? { return self.lazyWriterManagedObjectContext } /// PersistentStoreCoordinator public var persistentStoreCoordinator: NSPersistentStoreCoordinator? /// ManagedObjectModel public var managedObjectModel: NSManagedObjectModel? { return self.lazyManagedObjectModel } /// Store URL public var storeURL: NSURL? { return self.lazyStoreURL } ////////////////////////////////////////////////// private lazy var lazyDefaultManagedObjectContext: NSManagedObjectContext? = { let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.parentContext = self.writerManagedObjectContext managedObjectContext.mergePolicy = NSOverwriteMergePolicy return managedObjectContext }() private lazy var lazyWriterManagedObjectContext: NSManagedObjectContext? = { let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator managedObjectContext.mergePolicy = NSOverwriteMergePolicy return managedObjectContext }() lazy var lazyManagedObjectModel: NSManagedObjectModel = { return NSManagedObjectModel.mergedModelFromBundles(nil)! }() lazy var lazyStoreURL: NSURL = { return self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.defaultStoreName) }() /// default store name lazy var defaultStoreName: String = { var defaultName = NSBundle.mainBundle().objectForInfoDictionaryKey(String(kCFBundleNameKey)) as? String if defaultName == nil { defaultName = "DefaultStore.sqlite" } if !(defaultName!.hasSuffix("sqlite")) { defaultName = defaultName?.stringByAppendingPathExtension("sqlite") } return defaultName! }() /// Application's document directory lazy var applicationDocumentsDirectory: NSURL = { let fileManager = NSFileManager.defaultManager() let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls.last as! NSURL }() }
mit
7d329ffdd50f8d71174cb9f8df2d8dd7
34.738095
111
0.715079
5.956349
false
false
false
false
ioscreator/ioscreator
IOSPageControlTutorial/IOSPageControlTutorial/ViewController.swift
1
1427
// // ViewController.swift // IOSPageControlTutorial // // Created by Arthur Knopper on 21/01/2020. // Copyright © 2020 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var scrollView: UIScrollView! var movies: [String] = ["bad-boys","joker","hollywood"] var frame = CGRect.zero override func viewDidLoad() { super.viewDidLoad() pageControl.numberOfPages = movies.count setupScreens() scrollView.delegate = self } func setupScreens() { for index in 0..<movies.count { frame.origin.x = scrollView.frame.size.width * CGFloat(index) frame.size = scrollView.frame.size let imgView = UIImageView(frame: frame) imgView.image = UIImage(named: movies[index]) self.scrollView.addSubview(imgView) } scrollView.contentSize = CGSize(width: (scrollView.frame.size.width * CGFloat(movies.count)), height: scrollView.frame.size.height) scrollView.delegate = self } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width pageControl.currentPage = Int(pageNumber) } }
mit
7ee8c01cb394d336e4f61a2fbf78e7df
29.340426
139
0.636746
4.85034
false
false
false
false
oisdk/PretendDependSwift
PretendDependSwift/PretendDependSwift/Playground.playground/Contents.swift
1
1749
import PretendDependSwift //: This is a small framework that allows some pseudo-dependent typing. The first tool is the `Nat` protocol: it represents the //: natural numbers. The numbers zero to nine are given names: Zero() One() Five() //: However, those are just typealiases. Each number is just the `Succ` struct nested n times over `Zero`. One.self == Succ<Zero>.self Three.self == Succ<Succ<Succ<Zero>>>.self //: Some basic arithmetic can be performed AddFour<Three>.Result.self == Seven.self //: A length-indexed array has been implemented using this num type: let ar = emptyArray() +| 1 +| 2 +| 3 for i in ar { print(i) } //: It works like a normal array, except that its length cannot be mutated. Its members can be mutated, however, via indexing: var mutAr = emptyArray() +| 1 +| 2 +| 3 mutAr[0] = 0 mutAr //: Appending, preppending, and removal of elements works by returning a whole new array, rather than mutating the original in-place var toChop = emptyArray() +| 1 +| 2 +| 3 +| 4 +| 5 toChop.appended(100) toChop.removeLast() //: Removal operations are only defined on arrays that are not empty let sizeOne = emptyArray() +| 1 let empty = sizeOne.removeLast().1 //: There are a number of functions that use the constant-size property of these arrays to yield efifciency benefits. For instance, `zip` will only take arrays of the same length, which allows for slightly faster iteration. `zipWith` is a function that acts like a chained `zip` and `map`: let frst = emptyArray() +| 1 +| 2 +| 3 +| 4 +| 5 let scnd = emptyArray() +| 10 +| 20 +| 30 +| 40 +| 50 zipWith(frst, scnd, combine: +) //: Their constant size makes `ConstArray`s particularly suited to matrix manipulation: let mat = emptyArray() +| frst +| scnd transpose(mat)
mit
8ada1c2918661d3139995a6a22aa10f2
50.441176
289
0.716981
3.753219
false
false
false
false
ZB0106/MCSXY
MCSXY/MCSXY/Tools/RHFactory/RHLabel.swift
1
873
// // RHLabel.swift // MCSXY // // Created by 瞄财网 on 2017/7/18. // Copyright © 2017年 瞄财网. All rights reserved. // import UIKit class RHLabel: UILabel { class func label(frame :CGRect? = CGRect.zero, text :String? = nil, font :UIFont? = nil, textColor :UIColor? = nil, textAlignment :NSTextAlignment? = nil, numberOfLines :Int? = nil) -> RHLabel { let label = RHLabel(); if let frame = frame { label.frame = frame } if let font = font { label.font = font } if let textColor = textColor { label.textColor = textColor } if let textAlignment = textAlignment { label.textAlignment = textAlignment } if let numberOfLines = numberOfLines { label.numberOfLines = numberOfLines } if let text = text { label.text = text } return label; } }
mit
4790e3e467028bead68d87ececb2b6a3
21.578947
197
0.602564
3.813333
false
false
false
false
dasdom/Swiftandpainless
SwiftAndPainlessPlayground.playground/Pages/Classes - Basics.xcplaygroundpage/Contents.swift
1
501
import Foundation /*: [⬅️](@previous) [➡️](@next) # Classes: Basics */ class ToDo { var name: String = "er" let dueDate: NSDate let locationName: String init(name: String, date: NSDate, locationName: String) { self.name = name dueDate = date self.locationName = locationName } } let todo = ToDo(name: "Give talk", date: NSDate(), locationName: "Köln") print(todo) /*: Classes don't have automatic initializers and they also don't print nicely by their own. */
mit
deec4b739381e57a2ac2a1d747be0c91
20.391304
89
0.660569
3.671642
false
false
false
false
Schatzjason/cs212
Networking/Galaxy/Galaxy/ViewController.swift
1
3107
import UIKit class GalaxyViewController: UIViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var button: UIButton! @IBOutlet var activityIndicator: UIActivityIndicatorView! // We will use this to keep track of our state for now var isDownloading: Bool! override func viewDidLoad() { super.viewDidLoad() // Set the initial state isDownloading = false; toggleViews(isDownloading: false) } // Whenever the button is clicked, toggle between the two states // downloading, and not downloading @IBAction func downloadOrCancel() { if isDownloading { cancelTheDownload() } else { startTheDownload() } } // Here's where we will start the downloading magic func startTheDownload() { isDownloading = true toggleViews(isDownloading: true) // Make the url let url = URL(string: GalaxyURLs.nextURLString)! // Create the download task let task = URLSession.shared.dataTask(with: url) { data, response, error in var galaxyImage: UIImage? if let error = error { print(error) galaxyImage = nil } if let data = data { galaxyImage = UIImage(data: data) } // Pass these lines back to the main thread DispatchQueue.main.async { self.imageView.image = galaxyImage self.isDownloading = false self.toggleViews(isDownloading: false) } } // Start the task task.resume() print("leaving startTheDownload") } func cancelTheDownload() { isDownloading = false toggleViews(isDownloading: false) } // Use this method to toggle the state of the UI func toggleViews(isDownloading: Bool) { // Button let buttonTitle = isDownloading ? "Cancel" : "Start" button.setTitle(buttonTitle, for: .normal) // Activity Indicator if isDownloading { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } // Image View imageView.isHidden = isDownloading } // This is just a way to experiment with work that takes // a long time. Counts the number of prime values between // 1 and size func busyWork(_ size: Int) { var primeCount = 3 for value in 5...size { var isPrime = true; let highestFactor = Int(sqrt(Double(value))) for potentialFactor in 2...highestFactor { if (value % potentialFactor == 0) { isPrime = false } } if isPrime { primeCount += 1 } } print(primeCount) } }
mit
fe9ff5815812f0ee670c84adffcf3e87
25.784483
68
0.529771
5.293015
false
false
false
false
antlr/antlr4
runtime/Swift/Sources/Antlr4/ListTokenSource.swift
7
6541
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// Provides an implementation of _org.antlr.v4.runtime.TokenSource_ as a wrapper around a list /// of _org.antlr.v4.runtime.Token_ objects. /// /// If the final token in the list is an _org.antlr.v4.runtime.Token#EOF_ token, it will be used /// as the EOF token for every call to _#nextToken_ after the end of the /// list is reached. Otherwise, an EOF token will be created. /// public class ListTokenSource: TokenSource { /// /// The wrapped collection of _org.antlr.v4.runtime.Token_ objects to return. /// internal let tokens: [Token] /// /// The name of the input source. If this value is `null`, a call to /// _#getSourceName_ should return the source name used to create the /// the next token in _#tokens_ (or the previous token if the end of /// the input has been reached). /// private let sourceName: String? /// /// The index into _#tokens_ of token to return by the next call to /// _#nextToken_. The end of the input is indicated by this value /// being greater than or equal to the number of items in _#tokens_. /// internal var i = 0 /// /// This field caches the EOF token for the token source. /// internal var eofToken: Token? /// /// This is the backing field for _#getTokenFactory_ and /// _setTokenFactory_. /// private var _factory = CommonTokenFactory.DEFAULT /// /// Constructs a new _org.antlr.v4.runtime.ListTokenSource_ instance from the specified /// collection of _org.antlr.v4.runtime.Token_ objects. /// /// - parameter tokens: The collection of _org.antlr.v4.runtime.Token_ objects to provide as a /// _org.antlr.v4.runtime.TokenSource_. /// public convenience init(_ tokens: [Token]) { self.init(tokens, nil) } /// /// Constructs a new _org.antlr.v4.runtime.ListTokenSource_ instance from the specified /// collection of _org.antlr.v4.runtime.Token_ objects and source name. /// /// - parameter tokens: The collection of _org.antlr.v4.runtime.Token_ objects to provide as a /// _org.antlr.v4.runtime.TokenSource_. /// - parameter sourceName: The name of the _org.antlr.v4.runtime.TokenSource_. If this value is /// `null`, _#getSourceName_ will attempt to infer the name from /// the next _org.antlr.v4.runtime.Token_ (or the previous token if the end of the input has /// been reached). /// public init(_ tokens: [Token], _ sourceName: String?) { self.tokens = tokens self.sourceName = sourceName } public func getCharPositionInLine() -> Int { if i < tokens.count { return tokens[i].getCharPositionInLine() } else if let eofToken = eofToken { return eofToken.getCharPositionInLine() } else if !tokens.isEmpty { // have to calculate the result from the line/column of the previous // token, along with the text of the token. let lastToken = tokens.last! if let tokenText = lastToken.getText() { if let lastNewLine = tokenText.lastIndex(of: "\n") { return tokenText.distance(from: lastNewLine, to: tokenText.endIndex) - 1 } } return (lastToken.getCharPositionInLine() + lastToken.getStopIndex() - lastToken.getStartIndex() + 1) } else { // only reach this if tokens is empty, meaning EOF occurs at the first // position in the input return 0 } } public func nextToken() -> Token { if i >= tokens.count { if eofToken == nil { var start = -1 if tokens.count > 0 { let previousStop = tokens[tokens.count - 1].getStopIndex() if previousStop != -1 { start = previousStop + 1 } } let stop = max(-1, start - 1) let source = TokenSourceAndStream(self, getInputStream()) eofToken = _factory.create(source, CommonToken.EOF, "EOF", CommonToken.DEFAULT_CHANNEL, start, stop, getLine(), getCharPositionInLine()) } return eofToken! } let t = tokens[i] if i == tokens.count - 1 && t.getType() == CommonToken.EOF { eofToken = t } i += 1 return t } public func getLine() -> Int { if i < tokens.count { return tokens[i].getLine() } else if let eofToken = eofToken { return eofToken.getLine() } else if !tokens.isEmpty { // have to calculate the result from the line/column of the previous // token, along with the text of the token. let lastToken = tokens.last! var line = lastToken.getLine() if let tokenText = lastToken.getText() { for c in tokenText { if c == "\n" { line += 1 } } } // if no text is available, assume the token did not contain any newline characters. return line } else { // only reach this if tokens is empty, meaning EOF occurs at the first // position in the input return 1 } } public func getInputStream() -> CharStream? { if i < tokens.count { return tokens[i].getInputStream() } else if let eofToken = eofToken { return eofToken.getInputStream() } else if !tokens.isEmpty { return tokens.last!.getInputStream() } // no input stream information is available return nil } public func getSourceName() -> String { if let sourceName = sourceName { return sourceName } if let inputStream = getInputStream() { return inputStream.getSourceName() } return "List" } public func setTokenFactory(_ factory: TokenFactory) { self._factory = factory } public func getTokenFactory() -> TokenFactory { return _factory } }
bsd-3-clause
a87f214c107fa943835380a20f43c04a
32.372449
152
0.566121
4.458759
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIComponents/ImagePickerLibrary/QMUIAlbumViewController.swift
1
11203
// // QMUIAlbumViewController.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // // 相册预览图的大小默认值 private let QMUIAlbumViewControllerDefaultAlbumTableViewCellHeight: CGFloat = 67 // 相册预览大小(正方形),如果想要跟图片一样高,则设置成跟 QMUIAlbumViewControllerDefaultAlbumTableViewCellHeight 一样的值就好了 private let QMUIAlbumViewControllerDefaultAlbumImageSize: CGFloat = 57 // 相册缩略图的 left,默认 -1,表示和上下一样大 private let QMUIAlbumViewControllerDefaultAlbumImageLeft: CGFloat = -1 // 相册名称的字号默认值 private let QMUIAlbumTableViewCellDefaultAlbumNameFontSize: CGFloat = 16 // 相册资源数量的字号默认值 private let QMUIAlbumTableViewCellDefaultAlbumAssetsNumberFontSize: CGFloat = 16 // 相册名称的 insets 默认值 private let QMUIAlbumTableViewCellDefaultAlbumNameInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 4) @objc protocol QMUIAlbumViewControllerDelegate: NSObjectProtocol { /// 点击相簿里某一行时,需要给一个 QMUIImagePickerViewController 对象用于展示九宫格图片列表 @objc optional func imagePickerViewController(for albumViewController: QMUIAlbumViewController) -> QMUIImagePickerViewController /** * 取消查看相册列表后被调用 */ @objc optional func albumViewControllerDidCancel(_ albumViewController: QMUIAlbumViewController) /** * 即将需要显示 Loading 时调用 * * @see shouldShowDefaultLoadingView */ @objc optional func albumViewControllerWillStartLoad(_ albumViewController: QMUIAlbumViewController) /** * 即将需要隐藏 Loading 时调用 * * @see shouldShowDefaultLoadingView */ @objc optional func albumViewControllerWillFinishLoad(_ albumViewController: QMUIAlbumViewController) } class QMUIAlbumTableViewCell: QMUITableViewCell { var albumImageSize: CGFloat = QMUIAlbumViewControllerDefaultAlbumImageSize // 相册缩略图的 insets var albumImageMarginLeft: CGFloat = QMUIAlbumViewControllerDefaultAlbumImageLeft // 相册缩略图的 left var albumNameFontSize = QMUIAlbumTableViewCellDefaultAlbumNameFontSize // 相册名称的字号 var albumAssetsNumberFontSize = QMUIAlbumTableViewCellDefaultAlbumAssetsNumberFontSize // 相册资源数量的字号 var albumNameInsets = QMUIAlbumTableViewCellDefaultAlbumNameInsets // 相册名称的 insets override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } override func didInitialized(_ style: UITableViewCell.CellStyle) { super.didInitialized(style) imageView?.contentMode = .scaleAspectFill imageView?.clipsToBounds = true detailTextLabel?.textColor = UIColorGrayDarken } override func updateCellAppearance(_ indexPath: IndexPath) { super.updateCellAppearance(indexPath) textLabel?.font = UIFontBoldMake(albumNameFontSize) detailTextLabel?.font = UIFontMake(albumAssetsNumberFontSize) } override func layoutSubviews() { super.layoutSubviews() let imageEdgeTop = contentView.bounds.height.center(albumImageSize) let imageEdgeLeft = albumImageMarginLeft == QMUIAlbumViewControllerDefaultAlbumImageLeft ? imageEdgeTop : albumImageMarginLeft guard let imageView = imageView, let textLabel = textLabel, let detailTextLabel = detailTextLabel else { return } imageView.frame = CGRect(x: imageEdgeLeft, y: imageEdgeTop, width: albumImageSize, height: albumImageSize) textLabel.frame = textLabel.frame.setXY(imageView.frame.maxX + albumNameInsets.left, textLabel.qmui_minYWhenCenterInSuperview) let textLabelMaxWidth = contentView.bounds.width - textLabel.frame.minX - detailTextLabel.bounds.width - albumNameInsets.right if textLabel.bounds.width > textLabelMaxWidth { textLabel.frame = textLabel.frame.setWidth(textLabelMaxWidth) } detailTextLabel.frame = detailTextLabel.frame.setXY(textLabel.frame.maxX + albumNameInsets.right, detailTextLabel.qmui_minYWhenCenterInSuperview) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } class QMUIAlbumViewController: QMUICommonTableViewController { var albumTableViewCellHeight: CGFloat = QMUIAlbumViewControllerDefaultAlbumTableViewCellHeight // 相册列表 cell 的高度,同时也是相册预览图的宽高 weak var albumViewControllerDelegate: QMUIAlbumViewControllerDelegate? var contentType = QMUIAlbumContentType.all // 相册展示内容的类型,可以控制只展示照片、视频或音频(仅 iOS 8.0 及以上版本支持)的其中一种,也可以同时展示所有类型的资源,默认展示所有类型的资源。 var tipTextWhenNoPhotosAuthorization: String? var tipTextWhenPhotosEmpty: String? /** * 加载相册列表时会出现 loading,若需要自定义 loading 的形式,可将该属性置为 NO,默认为 YES。 * @see albumViewControllerWillStartLoad: & albumViewControllerWillFinishLoad: */ var shouldShowDefaultLoadingView = true private var albumsArray: [QMUIAssetsGroup] = [] private var imagePickerViewController: QMUIImagePickerViewController? override func setNavigationItems(_ isInEditMode: Bool, animated: Bool) { super.setNavigationItems(isInEditMode, animated: animated) title = title ?? "照片" navigationItem.rightBarButtonItem = UIBarButtonItem.item(title: "取消", target: self, action: #selector(handleCancelSelectAlbum)) } @objc override func initTableView() { super.initTableView() tableView.separatorStyle = .none } override func viewDidLoad() { super.viewDidLoad() if QMUIAssetsManager.authorizationStatus == .notAuthorized { // 如果没有获取访问授权,或者访问授权状态已经被明确禁止,则显示提示语,引导用户开启授权 var tipString = tipTextWhenNoPhotosAuthorization if tipString == nil { let mainInfoDictionary = Bundle.main.infoDictionary var appName = mainInfoDictionary?["CFBundleDisplayName"] if appName == nil { appName = mainInfoDictionary?[kCFBundleNameKey as String] } tipString = "请在设备的\"设置-隐私-照片\"选项中,允许\(appName!)访问你的手机相册" } showEmptyViewWith(text: tipString, detailText: nil, buttonTitle: nil, buttonAction: nil) } else { albumViewControllerDelegate?.albumViewControllerWillStartLoad?(self) // 获取相册列表较为耗时,交给子线程去处理,因此这里需要显示 Loading if shouldShowDefaultLoadingView { showEmptyViewWithLoading() } DispatchQueue.global().async { QMUIAssetsManager.shared.enumerateAllAlbums(withAlbumContentType: self.contentType, usingBlock: {[weak self] resultAssetsGroup in guard let strongSelf = self else { return } // 这里需要对 UI 进行操作,因此放回主线程处理 DispatchQueue.main.async { if let asset = resultAssetsGroup { strongSelf.albumsArray.append(asset) } else { strongSelf.refreshAlbumAndShowEmptyTipIfNeed() } } }) } } } func refreshAlbumAndShowEmptyTipIfNeed() { if albumsArray.isEmpty { let tipString = tipTextWhenPhotosEmpty ?? "空照片" showEmptyViewWith(text: tipString, detailText: nil, buttonTitle: nil, buttonAction: nil) } else { albumViewControllerDelegate?.albumViewControllerWillStartLoad?(self) if shouldShowDefaultLoadingView { hideEmptyView() } tableView.reloadData() } } /// 在 QMUIAlbumViewController 被放到 UINavigationController 里之后,可通过调用这个方法,来尝试直接进入上一次选中的相册列表 func pickLastAlbumGroupDirectlyIfCan() { let assetsGroup = QMUIImagePickerHelper.assetsGroupOfLastPickerAlbum(with: nil) pickAlbumsGroup(assetsGroup, animated: false) } private func pickAlbumsGroup(_ assetsGroup: QMUIAssetsGroup?, animated: Bool) { guard let assetsGroup = assetsGroup else { return } if imagePickerViewController == nil { imagePickerViewController = albumViewControllerDelegate?.imagePickerViewController?(for: self) } assert(imagePickerViewController != nil, "albumViewControllerDelegate 必须实现 imagePickerViewController(for:) 并返回一个 \(NSStringFromClass(QMUIImagePickerViewController.self)) 对象") imagePickerViewController?.refresh(with: assetsGroup) imagePickerViewController?.title = assetsGroup.name navigationController?.pushViewController(imagePickerViewController!, animated: animated) } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return albumsArray.count } override func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat { return albumTableViewCellHeight } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? QMUIAlbumTableViewCell if cell == nil { cell = QMUIAlbumTableViewCell(tableView: tableView, style: .subtitle, reuseIdentifier: "cell") cell?.accessoryType = .disclosureIndicator } let assetsGroup = albumsArray[indexPath.row] // 显示相册缩略图 cell?.imageView?.image = assetsGroup.posterImage(with: CGSize(width: albumTableViewCellHeight, height: albumTableViewCellHeight)) // 显示相册名称 cell?.textLabel?.text = assetsGroup.name // 显示相册中所包含的资源数量 cell?.detailTextLabel?.text = "\(assetsGroup.numberOfAssets)" cell?.updateCellAppearance(indexPath) return cell ?? UITableViewCell() } func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) { pickAlbumsGroup(albumsArray[indexPath.row], animated: true) } @objc func handleCancelSelectAlbum() { navigationController?.dismiss(animated: true, completion: { self.albumViewControllerDelegate?.albumViewControllerDidCancel?(self) self.imagePickerViewController?.selectedImageAssetArray.removeAll() }) } }
mit
beb96ba0425e61f980073464a9a84a2d
41.107438
182
0.696173
5.07723
false
false
false
false
Tornquist/NTKit
NTKit/NTTileView/NTTileViewRowLayout.swift
1
5706
// // NTTileViewRowLayout.swift // NTKit // // Created by Nathan Tornquist on 2/23/16. // Copyright © 2016 Nathan Tornquist. All rights reserved. // // Hosted on github at github.com/Tornquist/NTKit // // 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 open class NTTileViewRowLayout: NTTileViewLayoutProtocol { weak open var tileView: NTTileView! //MARK: - Configuration Variables var expandAnimationDuration: Double = 0.5 var collapseAnimationDuration: Double = 0.5 enum LayoutActions { case none case reset case focus case collapse } var lastAction: LayoutActions = .none var lastActionIndex: Int = 0 public convenience init(tileView: NTTileView) { self.init() self.tileView = tileView } //MARK: - NTTileViewLayoutProtocol Methods open func resetTileLayout() { lastAction = .reset let viewWidth = tileView.frame.width let viewHeight = tileView.frame.height let tileWidth = viewWidth let tileHeight = viewHeight / CGFloat(tileView.tiles.count) for (index, view) in tileView.views.enumerated() { // Set View Position view.frame = CGRect(x: 0, y: CGFloat(index)*tileHeight, width: tileWidth, height: tileHeight) // Adjust Tile based on anchor let tile = tileView.tiles[index] position(tile, inView: view) } } open func focus(onTileWithIndex tileIndex: Int) { lastAction = .focus lastActionIndex = tileIndex let viewWidth = tileView.frame.width let viewHeight = tileView.frame.height let tileWidth = viewWidth let expandedTileHeight = viewHeight let collapsedTileHeight = CGFloat(0) var heightCounter: CGFloat = CGFloat(0) UIView.animate(withDuration: expandAnimationDuration, animations: { for (index, view) in self.tileView.views.enumerated() { let height = (index == tileIndex) ? expandedTileHeight : collapsedTileHeight let newFrame = CGRect(x: 0, y: heightCounter, width: tileWidth, height: height) view.frame = newFrame let tile = self.tileView.tiles[index] self.position(tile, inView: view) // Prepare for next tile heightCounter = heightCounter + height } }) } open func collapseAll() { lastAction = .collapse let viewWidth = tileView.frame.width let viewHeight = tileView.frame.height let tileWidth = viewWidth let tileHeight = viewHeight / CGFloat(tileView.tiles.count) UIView.animate(withDuration: collapseAnimationDuration, animations: { for (index, view) in self.tileView.views.enumerated() { // Set View Position view.frame = CGRect(x: 0, y: CGFloat(index)*tileHeight, width: tileWidth, height: tileHeight) // Adjust Tile based on anchor let tile = self.tileView.tiles[index] self.position(tile, inView: view) } }) } open func updateForFrame() { switch lastAction { case .reset: self.resetTileLayout() case .collapse: self.collapseAll() case .focus: self.focus(onTileWithIndex: lastActionIndex) default: break } } // MARK: - Helper Methods for LayoutProtocol implementation func position(_ tile: NTTile, inView view: UIView) { // Base Positioning let anchor = tile.anchorPoint() let viewCenter = CGPoint(x: view.frame.midX, y: view.frame.midY) var newX = viewCenter.x - anchor.x - view.frame.origin.x var newY = viewCenter.y - anchor.y - view.frame.origin.y let width = (tileView.frame.width > view.frame.width) ? tileView.frame.width : view.frame.width let height = (tileView.frame.height > view.frame.height) ? tileView.frame.height : view.frame.height // Apply Corrections if (newX > 0) { newX = 0 } if (newX + width < view.frame.width) { newX = view.frame.width - width } if (newY > 0) { newY = 0 } if (newY + height < view.frame.height) { newY = view.frame.height - height } // Set New Frame var newFrame: CGRect! newFrame = CGRect(x: newX, y: newY, width: width, height: height) tile.view.frame = newFrame } }
mit
52898a17fc3777a65c510386f6a654a5
35.806452
109
0.62156
4.450078
false
false
false
false
FranDepascuali/ProyectoAlimentar
ProyectoAlimentar/UIComponents/Common/DonationDetailsView/DonationDetailsView.swift
1
1916
// // BaseDonationCell.swift // ProyectoAlimentar // // Created by Francisco Depascuali on 10/29/16. // Copyright © 2016 Alimentar. All rights reserved. // import UIKit import Core public final class DonationDetailsView: UIView, NibLoadable { @IBOutlet weak var placeImageView: UIImageView! { didSet { placeImageView.image = UIImage(named: "restaurant_placeholder")! } } @IBOutlet weak var placeNameLabel: UILabel! { didSet { placeNameLabel.setFont(pointSize: 16.0) placeNameLabel.textColor = ColorPalette.primaryTextColor } } @IBOutlet weak var distanceToPlaceLabel: UILabel! { didSet { distanceToPlaceLabel.setFont(pointSize: 16) distanceToPlaceLabel.textColor = ColorPalette.primaryTextColor } } @IBOutlet weak var locationIconImageView: UIImageView! { didSet { locationIconImageView.image = UIImage(identifier: .LocationIcon) } } @IBOutlet weak var locationLabel: UILabel! { didSet { locationLabel.setFont(pointSize: 14) locationLabel.textColor = ColorPalette.secondaryTextColor } } @IBOutlet weak var timeOpenedImageView: UIImageView! { didSet { timeOpenedImageView.image = UIImage(identifier: .TimeOpenedIcon) } } @IBOutlet weak var timeOpenedLabel: UILabel! { didSet { timeOpenedLabel.setFont(pointSize: 14) timeOpenedLabel.textColor = ColorPalette.secondaryTextColor } } public func bindViewModel(_ viewModel: DonationDetailsViewModel) { placeNameLabel.text = viewModel.placeName distanceToPlaceLabel.text = viewModel.distance locationLabel.text = viewModel.placeDirection timeOpenedLabel.text = viewModel.timeOpened } }
apache-2.0
80a84dfad2d94c6bbda84e4d1370c87e
28.015152
76
0.643342
5.066138
false
false
false
false
benlangmuir/swift
test/Generics/concrete_same_type_versus_anyobject.swift
6
1517
// RUN: %target-typecheck-verify-swift -warn-redundant-requirements // RUN: not %target-swift-frontend -typecheck -debug-generic-signatures %s 2>&1 | %FileCheck %s struct S {} class C {} struct G1<T : AnyObject> {} // CHECK: ExtensionDecl line={{.*}} base=G1 // CHECK-NEXT: Generic signature: <T> extension G1 where T == S {} // expected-error@-1 {{no type for 'T' can satisfy both 'T : AnyObject' and 'T == S'}} // CHECK: ExtensionDecl line={{.*}} base=G1 // CHECK-NEXT: Generic signature: <T where T == C> extension G1 where T == C {} struct G2<U> {} // CHECK: ExtensionDecl line={{.*}} base=G2 // CHECK-NEXT: Generic signature: <U> extension G2 where U == S, U : AnyObject {} // expected-error@-1 {{no type for 'U' can satisfy both 'U : AnyObject' and 'U == S'}} // CHECK: ExtensionDecl line={{.*}} base=G2 // CHECK-NEXT: Generic signature: <U where U == C> extension G2 where U == C, U : AnyObject {} // expected-warning@-1 {{redundant constraint 'U' : 'AnyObject'}} // CHECK: ExtensionDecl line={{.*}} base=G2 // CHECK-NEXT: Generic signature: <U where U : C> extension G2 where U : C, U : AnyObject {} // expected-warning@-1 {{redundant constraint 'U' : 'AnyObject'}} // Explicit AnyObject conformance vs derived same-type protocol P { associatedtype A where A == C } // CHECK: .explicitAnyObjectIsRedundant@ // CHECK-NEXT: Generic signature: <T where T : P> func explicitAnyObjectIsRedundant<T : P>(_: T) where T.A : AnyObject {} // expected-warning@-1 {{redundant constraint 'T.A' : 'AnyObject'}}
apache-2.0
d234224a234ef41560fed7758a22bab2
34.27907
95
0.665129
3.408989
false
false
false
false
codepgq/AnimateDemo
Animate/Animate/controller/CATransitionAnimation/TransitionController.swift
1
3242
// // TransitionController.swift // Animate // // Created by Mac on 17/2/8. // Copyright © 2017年 Mac. All rights reserved. // import UIKit func arcRandom(_ random : UInt32) -> CGFloat{ return CGFloat(arc4random() % random) / CGFloat(random) } let collectionViewCellKey = "TransitionAnimtionCell" class TransitionController: UIViewController { @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var segment: UISegmentedControl! var imgNamed = "icon2" let datas : [String] = ["fade","moveIn","push","reveal","cube", "suckEffect", "rippleEffect", "pageCurl", "pageUnCurl", "oglFlip", "cameraIrisHollowOpen", "cameraIrisHollowClose", "spewEffect","genieEffect","unGenieEffect","twist","tubey","swirl","charminUltra", "zoomyIn", "zoomyOut", "oglApplicationSuspend"] let derection : [String] = [kCATransitionFromRight,kCATransitionFromLeft,kCATransitionFromTop,kCATransitionFromBottom] override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellKey) } @IBAction func segMentValueChange(_ sender: UISegmentedControl) { print(sender.selectedSegmentIndex) } func startTransitionAnimate(type : String){ imgView.layer.removeAllAnimations() let derectionStr = derection[segment.selectedSegmentIndex] let transitionAni = Animate.transitionAnimationWith(duration: 0.75, type: type, subtype: derectionStr, startProgress: 0, endProgress: 1) imgView.image = UIImage(named: imgNamed) imgView.layer.add(transitionAni, forKey: "transition") //改变图片的名称 imgNamed = (imgNamed == "icon1") ? "icon2" : "icon1" } } // MARK - CollectionView extension TransitionController: UICollectionViewDelegate,UICollectionViewDataSource{ public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return datas.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellKey, for: indexPath) cell.backgroundColor = randomColor() let lbl = UILabel(frame: cell.contentView.bounds) lbl.numberOfLines = 0 lbl.textAlignment = .center lbl.text = datas[indexPath.item] lbl.adjustsFontSizeToFitWidth = true lbl.textColor = UIColor.white cell.contentView.addSubview(lbl) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) startTransitionAnimate(type: datas[indexPath.item]) } func randomColor() -> UIColor{ return UIColor(red: arcRandom(255), green: arcRandom(255), blue: arcRandom(255), alpha: 1) } }
apache-2.0
8ce367dc0306700eae16d354de2bfbeb
35.235955
315
0.688062
4.735683
false
false
false
false
hachinobu/SwiftQiitaClient
SwiftQiitaClient/Bond.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
1
3971
//: Playground - noun: a place where people can play import UIKit import Bond let numA = Observable<Int>(0) //定義時でも処理が走る numA.observe { (value) -> Void in print("observe \(value)") } //定義時には無視される numA.observeNew { (value) -> Void in print("observeNew \(value)") } numA.next(2) //片方向Binding let numB = Observable<Int>(10) let numC = Observable<Int>(11) //numB observe valueをnumC.next(value)している let disposeNumB = numB.bindTo(numC) numC.value //bindingを切る disposeNumB.dispose() numB.next(12) numB.value numC.value //map observe時にtransformを元に値変換した値を元にEventProducerを作成する //public func map<T>(transform: EventType -> T) -> EventProducer<T> { // return EventProducer(replayLength: replayLength) { sink in // return observe { event in // sink(transform(event)) // } // } //} let numD = Observable<Int>(100) let numDStr = numD.map { (value) -> String in print("map \(value)") return String(value) }.map { (value) -> String in print("value: \(value)") return "value: \(value)" } numD.observers.count numDStr.observers.count numD.next(100) numD.value numD.observers.count numDStr.observers.count numDStr.deinitDisposable.dispose() numD.observers.count numDStr.observers.count numDStr.observe { (value) -> Void in print("numDStr \(value)") } numD.observe { (value) -> Void in } numD.observers.count numDStr.observers.count numD.next(102) //紐付け削除 numDStr.deinitDisposable.dispose() numD.next(103) // filter 条件に合う場合のみその値のEventProducerを生成する let filterNum = Observable<Int>(200) filterNum.observe { (value) -> Void in print("observable filterNum") } let filterEventProducer = filterNum.filter { (value) in return value % 2 == 0 } filterEventProducer.observe { (value) -> Void in print("filterObserve \(value)") } filterNum.next(2) //条件に合わないので登録されているobserveが実行されない filterNum.next(13) //deliverOn 渡したQueue内で非同期でEventProducerを生成する //BackgroundスレッドとMainスレッドで交互に処理するような時に有効 //Backgroundで画像ダウンロードしてMainで紐付けみたいな let image = Observable<UIImage>(UIImage()) let urlStr = Observable<String>("http://gazou") urlStr.deliverOn(.Background).map { (ulr) -> UIImage in return UIImage() }.deliverOn(.Main).bindTo(image) let deliverOnNum = Observable<Int>(300) deliverOnNum.deliverOn(.Background).map { value in return String(value) } deliverOnNum.next(233) //startwith 最初の初期化でも処理実行したい場合 let startNum = Observable(20) startNum.observe { (value) -> Void in print("before startwith \(value)") } let startEventP = startNum.startWith(2) startEventP.observe { (value) -> Void in print("startEventP") } startNum.next(100) //combineLatestWith let numE = Observable(3) let numF = Observable(4) let numEF = numE.combineLatestWith(numF) numEF.observe { (value1, value2) -> Void in print(value1 + value2) } numE.next(10) numF.next(10) //flatmap let flatNum1 = Observable(1) let flatNum2 = Observable(2) let flatEP = flatNum1.flatMap(.Latest) { (value) in return Observable(String(value)) } flatEP.observe { (value) -> Void in print("fep \(value)") } let flatEP2 = flatNum2.flatMap(.Merge) { (value) in return Observable(String(value)) } flatEP2.observe { (value) -> Void in print("fep2 \(value)") } flatNum1.next(3) flatNum2.next(12) //ignoreNil let nilNumA = Observable<Int?>(nil) nilNumA.observe { (value) -> Void in print(value) } let nilEP = nilNumA.ignoreNil() nilEP.observe { (value) -> Void in print("nilEP \(value)") } nilNumA.next(1) //distinct let disNum1 = Observable(1) let disEP = disNum1.distinct() disEP.observe { (value) -> Void in print("dis \(value)") } disNum1.next(1) disNum1.next(2)
mit
b9001f2bd8b97cdadaa53e6dc5cf4e22
18.303191
69
0.703775
2.900879
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift
120
2318
// // UIBarButtonItem+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/31/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif fileprivate var rx_tap_key: UInt8 = 0 extension Reactive where Base: UIBarButtonItem { /// Bindable sink for `enabled` property. public var isEnabled: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: self.base) { UIElement, value in UIElement.isEnabled = value } } /// Bindable sink for `title` property. public var title: UIBindingObserver<Base, String> { return UIBindingObserver(UIElement: self.base) { UIElement, value in UIElement.title = value } } /// Reactive wrapper for target action pattern on `self`. public var tap: ControlEvent<Void> { let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<Void> in Observable.create { [weak control = self.base] observer in guard let control = control else { observer.on(.completed) return Disposables.create() } let target = BarButtonItemTarget(barButtonItem: control) { observer.on(.next()) } return target } .takeUntil(self.deallocated) .share() } return ControlEvent(events: source) } } @objc final class BarButtonItemTarget: RxTarget { typealias Callback = () -> Void weak var barButtonItem: UIBarButtonItem? var callback: Callback! init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { self.barButtonItem = barButtonItem self.callback = callback super.init() barButtonItem.target = self barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) } override func dispose() { super.dispose() #if DEBUG MainScheduler.ensureExecutingOnScheduler() #endif barButtonItem?.target = nil barButtonItem?.action = nil callback = nil } func action(_ sender: AnyObject) { callback() } } #endif
mit
0e8a0aa1fce08deca6a1ea97ac4e5e01
25.033708
84
0.592145
4.867647
false
false
false
false
shiguredo/sora-ios-sdk
Sora/WebSocketChannel.swift
1
5526
import Foundation /** WebSocket のステータスコードを表します。 */ public enum WebSocketStatusCode { /// 1000 case normal /// 1001 case goingAway /// 1002 case protocolError /// 1003 case unhandledType /// 1005 case noStatusReceived /// 1006 case abnormal /// 1007 case invalidUTF8 /// 1008 case policyViolated /// 1009 case messageTooBig /// 1010 case missingExtension /// 1011 case internalError /// 1012 case serviceRestart /// 1013 case tryAgainLater /// 1015 case tlsHandshake /// その他のコード case other(Int) static let table: [(WebSocketStatusCode, Int)] = [ (.normal, 1000), (.goingAway, 1001), (.protocolError, 1002), (.unhandledType, 1003), (.noStatusReceived, 1005), (.abnormal, 1006), (.invalidUTF8, 1007), (.policyViolated, 1008), (.messageTooBig, 1009), (.missingExtension, 1010), (.internalError, 1011), (.serviceRestart, 1012), (.tryAgainLater, 1013), (.tlsHandshake, 1015), ] // MARK: - インスタンスの生成 /** 初期化します。 - parameter rawValue: ステータスコード */ public init(rawValue: Int) { for pair in WebSocketStatusCode.table { if pair.1 == rawValue { self = pair.0 return } } self = .other(rawValue) } // MARK: 変換 /** 整数で表されるステータスコードを返します。 - returns: ステータスコード */ public func intValue() -> Int { switch self { case .normal: return 1000 case .goingAway: return 1001 case .protocolError: return 1002 case .unhandledType: return 1003 case .noStatusReceived: return 1005 case .abnormal: return 1006 case .invalidUTF8: return 1007 case .policyViolated: return 1008 case .messageTooBig: return 1009 case .missingExtension: return 1010 case .internalError: return 1011 case .serviceRestart: return 1012 case .tryAgainLater: return 1013 case .tlsHandshake: return 1015 case let .other(value): return value } } } /** WebSocket の通信で送受信されるメッセージを表します。 */ public enum WebSocketMessage { /// テキスト case text(String) /// バイナリ case binary(Data) } /** WebSocket チャネルのイベントハンドラです。 */ public final class WebSocketChannelHandlers { /// 初期化します。 public init() {} /// このプロパティは onReceive に置き換えられました。 @available(*, deprecated, renamed: "onReceive", message: "このプロパティは onReceive に置き換えられました。") public var onMessageHandler: ((WebSocketMessage) -> Void)? { get { onReceive } set { onReceive = newValue } } /// メッセージ受信時に呼ばれるクロージャー public var onReceive: ((WebSocketMessage) -> Void)? // MARK: - 廃止された API /// onDisconnectHandler は廃止されました。 @available(*, unavailable, message: "onDisconnectHandler は廃止されました。") public var onDisconnectHandler: ((Error?) -> Void)? /// onPongHandler は廃止されました。 @available(*, unavailable, message: "onPongHandler は廃止されました。") public var onPongHandler: ((Data?) -> Void)? /// onSendHandler は廃止されました。 @available(*, unavailable, message: "onSendHandler は廃止されました。") public var onSendHandler: ((WebSocketMessage) -> WebSocketMessage)? /// 接続解除時に呼ばれるクロージャー @available(*, unavailable, message: "onDisconnect は廃止されました。") public var onDisconnect: ((Error?) -> Void)? /// pong の送信時に呼ばれるクロージャー @available(*, unavailable, message: "onPong は廃止されました。") public var onPong: ((Data?) -> Void)? /// メッセージ送信時に呼ばれるクロージャー @available(*, unavailable, message: "onSend は廃止されました。") public var onSend: ((WebSocketMessage) -> WebSocketMessage)? } final class WebSocketChannelInternalHandlers { public var onConnect: ((URLSessionWebSocketChannel) -> Void)? public var onDisconnectWithError: ((URLSessionWebSocketChannel, Error) -> Void)? public var onReceive: ((WebSocketMessage) -> Void)? public init() {} } /** WebSocket による通信を行うチャネルの機能を定義したプロトコルです。 デフォルトの実装は非公開 (`internal`) であり、 通信処理のカスタマイズはイベントハンドラでのみ可能です。 ソースコードは公開していますので、実装の詳細はそちらを参照してください。 WebSocket チャネルはシグナリングチャネル `SignalingChannel` により使用されます。 */ @available(*, unavailable, message: "WebSocketChannel プロトコルは廃止されました。") public protocol WebSocketChannel: AnyObject {}
apache-2.0
0ade3fe34836fd98f506c35088720fcc
21.825871
84
0.598954
3.779242
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Authentication/PinFlow/PinInteractor.swift
1
12832
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import FeatureAuthenticationDomain import PlatformKit import RxSwift import ToolKit import WalletPayloadKit /// Interactor for the pin. This component interacts with the Blockchain API and the local /// pin data store. When the pin is updated, the pin is also stored on the keychain. final class PinInteractor: PinInteracting { // MARK: - Type private enum Constant { enum IncorrectPinAlertLockTimeTrigger { /// 60 seconds lock time to trigger too many attempts alert static let tooManyAttempts = 60000 /// 24 hours lock time to trigger cannot log in alert static let cannotLogin = 86400000 } } // MARK: - Properties /// In case the user attempted to logout while the pin was being sent to the server /// the app needs to disragard any future response var hasLogoutAttempted = false private let pinClient: PinClientAPI private let maintenanceService: MaintenanceServicing private let passwordRepository: PasswordRepositoryAPI private let wallet: WalletProtocol private let appSettings: AppSettingsAuthenticating private let recorder: ErrorRecording private let cacheSuite: CacheSuite private let loginService: PinLoginServiceAPI private let walletCryptoService: WalletCryptoServiceAPI private let disposeBag = DisposeBag() // MARK: - Setup init( passwordRepository: PasswordRepositoryAPI = resolve(), pinClient: PinClientAPI = PinClient(), maintenanceService: MaintenanceServicing = resolve(), wallet: WalletProtocol = WalletManager.shared.wallet, appSettings: AppSettingsAuthenticating = resolve(), recorder: Recording = CrashlyticsRecorder(), cacheSuite: CacheSuite = resolve(), walletRepository: WalletRepositoryAPI = resolve(), walletCryptoService: WalletCryptoServiceAPI = resolve() ) { loginService = PinLoginService( settings: appSettings, service: DIKit.resolve() ) self.passwordRepository = passwordRepository self.pinClient = pinClient self.maintenanceService = maintenanceService self.wallet = wallet self.appSettings = appSettings self.recorder = recorder self.cacheSuite = cacheSuite self.walletCryptoService = walletCryptoService } // MARK: - API // TODO: Re-enable this once we have isolated the source of the crash // func serverStatus() -> Observable<ServerIncidents> { // maintenanceService.serverStatus // .filter { $0.hasActiveMajorIncident } // .asObservable() // .catch { [weak self] (error) -> Observable<ServerIncidents> in // self?.recorder.error(error) // return .empty() // } // } /// Creates a pin code in the remote pin store /// - Parameter payload: the pin payload /// - Returns: Completable indicating completion func create(using payload: PinPayload) -> Completable { maintenanceService.serverUnderMaintenanceMessage .flatMap(weak: self) { (self, message) -> Single<PinStoreResponse> in if let message = message { throw PinError.serverMaintenance(message: message) } return self.pinClient.create(pinPayload: payload).asSingle() } .flatMapCompletable(weak: self) { (self, response) in self.handleCreatePinResponse(response: response, payload: payload) } .catch { error in throw PinError.map(from: error) } .observe(on: MainScheduler.instance) } /// Validates if the provided pin payload (i.e. pin code and pin key combination) is correct. /// Calling this method will also fetch the WalletOptions to see if the server is under maintenance, /// then, handle updating the local pin store (i.e. the keychain), /// depending on the response for the remote pin store. /// - Parameter payload: the pin payload /// - Returns: Single warpping the pin decryption key func validate(using payload: PinPayload) -> Single<String> { maintenanceService.serverUnderMaintenanceMessage .flatMap(weak: self) { (self, message) -> Single<PinStoreResponse> in if let message = message { throw PinError.serverMaintenance(message: message) } return self.pinClient.validate(pinPayload: payload).asSingle() } .do( onSuccess: { [weak self] response in guard let self = self else { return } try self.updateCacheIfNeeded(response: response, pinPayload: payload) } ) .map { [weak self] response -> String in guard let self = self else { throw PinError.unretainedSelf } return try self.pinValidationStatus(from: response) } .catch { [weak self] error in if let response = error as? PinStoreResponse { // TODO: Check for invalid numerical value error by string comparison for now, should revisit when backend make necessary changes if let error = response.error, error.contains("Invalid Numerical Value") { throw PinError.invalid } let pinError = response.toPinError() switch pinError { case .incorrectPin(let message, let remaining, _): let pinAlert = self?.getPinAlertIfNeeded(remaining) throw PinError.incorrectPin(message, remaining, pinAlert) case .backoff(let message, let remaining, _): let pinAlert = self?.getPinAlertIfNeeded(remaining) throw PinError.backoff(message, remaining, pinAlert) default: throw pinError } } else { throw PinError.map(from: error) } } .observe(on: MainScheduler.instance) } func password(from pinDecryptionKey: String) -> Single<String> { loginService.password(from: pinDecryptionKey) .observe(on: MainScheduler.instance) } /// Keep the PIN value on the local pin store (i.e the keychain), for biometrics auth. /// - Parameter pin: the pin value func persist(pin: Pin) { pin.save(using: appSettings) appSettings.set(biometryEnabled: true) } // MARK: - Accessors private func getPinAlertIfNeeded(_ remaining: Int) -> PinError.PinAlert? { switch remaining { case Constant.IncorrectPinAlertLockTimeTrigger.tooManyAttempts: return .tooManyAttempts case let time where time >= Constant.IncorrectPinAlertLockTimeTrigger.cannotLogin: return .cannotLogin default: return nil } } private func handleCreatePinResponse(response: PinStoreResponse, payload: PinPayload) -> Completable { passwordRepository.password .asObservable() .take(1) .asSingle() .flatMap { [weak self] password -> Single<(pin: String, password: String)> in // Wallet must have password at the stage guard let password = password else { let error = PinError.serverError(LocalizationConstants.Pin.cannotSaveInvalidWalletState) self?.recorder.error(error) return .error(error) } guard response.error == nil else { self?.recorder.error(PinError.serverError("")) return .error(PinError.serverError(response.error!)) } guard response.isSuccessful else { let message = String( format: LocalizationConstants.Errors.invalidStatusCodeReturned, response.statusCode?.rawValue ?? -1 ) let error = PinError.serverError(message) self?.recorder.error(error) return .error(error) } guard let pinValue = payload.pinValue, !payload.pinKey.isEmpty, !pinValue.isEmpty else { let error = PinError.serverError(LocalizationConstants.Pin.responseKeyOrValueLengthZero) self?.recorder.error(error) return .error(error) } return .just((pin: pinValue, password: password)) } .flatMap(weak: self) { (self, data) -> Single<(encryptedPinPassword: String, password: String)> in self.walletCryptoService .encrypt( pair: KeyDataPair(key: data.pin, data: data.password), pbkdf2Iterations: WalletCryptoPBKDF2Iterations.pinLogin ) .map { (encryptedPinPassword: $0, password: data.password) } .asObservable() .take(1) .asSingle() } .flatMapCompletable(weak: self) { (self, data) -> Completable in // Once the pin has been created successfully, the wallet is not longer marked as new. self.wallet.isNew = false // Update the cache self.appSettings.set(encryptedPinPassword: data.encryptedPinPassword) self.appSettings.set(pinKey: payload.pinKey) self.appSettings.set(passwordPartHash: data.password.passwordPartHash) try self.updateCacheIfNeeded(response: response, pinPayload: payload) return Completable.empty() } } /// Persists the pin if needed or deletes it according to the response code received from the backend private func updateCacheIfNeeded( response: PinStoreResponse, pinPayload: PinPayload ) throws { // Make sure the user has not logout guard !hasLogoutAttempted else { throw PinError.receivedResponseWhileLoggedOut } guard let responseCode = response.statusCode else { return } switch responseCode { case .success where pinPayload.persistsLocally: // Optionally save the pin to the keychain to enable biometric authenticators persist(pin: pinPayload.pin!) case .deleted: // Clear pin from keychain if the user exceeded the number of retries when entering the pin. appSettings.set(pin: nil) appSettings.set(biometryEnabled: false) default: break } } // Returns the pin decryption key, or throws error if cannot private func pinValidationStatus(from response: PinStoreResponse) throws -> String { // TODO: Check for invalid numerical value error by string comparison for now, should revisit when backend make necessary changes if let error = response.error, error.contains("Invalid Numerical Value") { throw PinError.invalid } // Verify that the status code was received guard let statusCode = response.statusCode else { let error = PinError.serverError(LocalizationConstants.Errors.genericError) recorder.error(error) throw error } switch statusCode { case .success: guard let pinDecryptionKey = response.pinDecryptionValue, !pinDecryptionKey.isEmpty else { throw PinError.custom(LocalizationConstants.Errors.genericError) } return pinDecryptionKey case .deleted: throw PinError.tooManyAttempts case .incorrect: guard let remaining = response.remaining else { fatalError("Incorrect PIN should have an remaining field") } let message = LocalizationConstants.Pin.incorrect throw PinError.incorrectPin(message, remaining, nil) case .backoff: guard let remaining = response.remaining else { fatalError("Backoff should have an remaining field") } let message = LocalizationConstants.Pin.backoff throw PinError.backoff(message, remaining, nil) case .duplicateKey, .unknown: throw PinError.custom(LocalizationConstants.Errors.genericError) } } }
lgpl-3.0
bf9adf088871aa3a49eccfb81d2b6eaf
42.20202
149
0.60346
5.280247
false
false
false
false
iosyaowei/Weibo
WeiBo/Classes/Utils(工具)/YWRefreshControl/YWRefreshControl.swift
1
6006
// // YWRefreshControl.swift // WeiBo // // Created by 姚巍 on 16/9/23. // Copyright © 2016年 yao wei. All rights reserved. // 刷新控件 import UIKit /// 刷新状态切换的临界点 /// /// - Normal: 普通状态(还未到达临界点) /// - Pulling: 超过临界点,如果放手,开始刷新 /// - WillRefresh: 超过临界点,并且刷新 enum YWRefreshStaus { case Normal case Pulling case WillRefresh } /// 刷新状态切换的临界点 fileprivate let YWRefreshOffset: CGFloat = 122 class YWRefreshControl: UIControl { //刷新控件的父视图,下拉刷新控件应该适用于 tableView 和collectionView //父视图addSubView 强引用了self,所以使用weak fileprivate weak var scrollView: UIScrollView? fileprivate lazy var refrershView: YWRefreshView = YWRefreshView.refreshView() // MARK: - 构造函数 init() { super.init(frame: CGRect()) steupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) steupUI() } /** willMove addSubView 方法会调用 当添加到父视图的时候 newSuperView 是父视图 当父视图移除的时候 newSuperView 是 nil */ override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) //判断父视图类型 guard let sv = newSuperview as? UIScrollView else { return } //记录父视图 scrollView = sv //KVO监听父视图 contentOffset scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil) } //KVO 方法会统一调用此方法 //观察者模式 在不需要的时候都需要释放 //通知中心:如果不释放 什么也不会发生,但是会有内存泄漏,会有多次注册的可能! //KVO 如果不释放会崩溃 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let sv = scrollView else { return } //初始高度 为0 crollView?.contentInset.top = 64, scrollView?.contentOffset.y = -64 let height = -(sv.contentInset.top + sv.contentOffset.y); if height < 0 { return } //传递高度 如果是在正在舒心状态,就不传递高度 改变大小 if refrershView.refreshStatus != .WillRefresh { refrershView.parentViewHeight = height } //根据高度设置刷新控件的frame self.frame = CGRect(x: 0, y: -height, width: sv.bounds.width, height: height) if sv.isDragging { if height > YWRefreshOffset && refrershView.refreshStatus == .Normal{ print("放手刷新") refrershView.refreshStatus = .Pulling }else if height <= YWRefreshOffset && refrershView.refreshStatus == .Pulling{ print("继续拽") refrershView.refreshStatus = .Normal } }else { //放手 不在拖拽状态 判断是否超过临界点 if refrershView.refreshStatus == .Pulling { print("刷新数据----") beginRefreshing() //发送刷新数据事件 sendActions(for: .valueChanged) } } } //本视在父视图上移除 override func removeFromSuperview() { //superView还在 superview?.removeObserver(self, forKeyPath: "contentOffset") //superView不存在 super.removeFromSuperview() } //开始刷新 func beginRefreshing(){ print("开始刷新") //判断父视图 guard let sv = scrollView else { return } //判断是否正在刷新,如果正在刷新,直接返回 if refrershView.refreshStatus == .WillRefresh { return } //设置表格间距 要放在设置间距前面 refrershView.refreshStatus = .WillRefresh //设置新视图的间距 var inset1 = sv.contentInset inset1.top += YWRefreshOffset sv.contentInset = inset1 refrershView.parentViewHeight = YWRefreshOffset } //结束刷新 func endRefreshing(){ print("结束刷新") guard let sv = scrollView else { return } //判断状态 是否正在刷新,如果不是,直接返回 if refrershView.refreshStatus != .WillRefresh { return } //恢复刷新视图的状态 refrershView.refreshStatus = .Normal //恢复表格的 contentInset var inset = sv.contentInset inset.top -= YWRefreshOffset sv.contentInset = inset } } extension YWRefreshControl { fileprivate func steupUI(){ backgroundColor = superview?.backgroundColor addSubview(refrershView) //自动布局 refrershView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: refrershView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: refrershView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: refrershView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refrershView.bounds.width)) addConstraint(NSLayoutConstraint(item: refrershView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refrershView.bounds.height)) } }
mit
6dc79293bd07b22ee1be4ae54ac5ed0f
28.764368
196
0.599923
4.280165
false
false
false
false
gouyz/GYZBaking
baking/Classes/Mine/Controller/GYZMineAddressVC.swift
1
8682
// // GYZMineAddressVC.swift // baking // 我的地址 // Created by gouyz on 2017/4/2. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD private let mineAddressCell = "mineAddressCell" class GYZMineAddressVC: GYZBaseVC,UITableViewDelegate,UITableViewDataSource { /// 修改/保存按钮 var rightBtn: UIButton? /// 是否编辑状态 var isEditEnble: Bool = false ///是否是选择地址 var isSelected: Bool = false var addressModels: [GYZAddressModel] = [GYZAddressModel]() override func viewDidLoad() { super.viewDidLoad() self.title = "收货地址" rightBtn = UIButton(type: .custom) rightBtn?.setTitle("管理", for: .normal) rightBtn?.titleLabel?.font = k14Font rightBtn?.frame = CGRect.init(x: 0, y: 0, width: kTitleHeight, height: kTitleHeight) rightBtn?.addTarget(self, action: #selector(manageClick), for: .touchUpInside) navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBtn!) view.addSubview(tableView) view.addSubview(bottomView) tableView.snp.makeConstraints { (make) in make.edges.equalTo(UIEdgeInsetsMake(0, 0, kTitleAndStateHeight, 0)) } bottomView.snp.makeConstraints { (make) in make.bottom.equalTo(view) make.top.equalTo(tableView.snp.bottom) make.left.right.equalTo(view) } bottomView.addBtn.addTarget(self, action: #selector(clickedAddBtn), for: .touchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { addressModels.removeAll() requestAddressData() } /// 管理 func manageClick(){ isEditEnble = !isEditEnble if isEditEnble { rightBtn?.setTitle("完成", for: .normal) }else{ rightBtn?.setTitle("管理", for: .normal) } tableView.reloadData() } ///新增地址 func clickedAddBtn(){ goEditVC(isEdit: true) } /// 编辑/新增地址 /// /// - Parameter isEdit: 是增加还是编辑 func goEditVC(isEdit: Bool,addressInfo : GYZAddressModel? = nil){ let editVC = GYZEditAddressVC() editVC.isAdd = isEdit editVC.addressInfo = addressInfo navigationController?.pushViewController(editVC, animated: true) } /// 懒加载UITableView lazy var tableView : UITableView = { let table = UITableView(frame: CGRect.zero, style: .grouped) table.dataSource = self table.delegate = self table.tableFooterView = UIView() table.separatorColor = kGrayLineColor table.register(GYZAddressCell.self, forCellReuseIdentifier: mineAddressCell) return table }() /// 增加地址 lazy var bottomView: GYZAddAddressView = GYZAddAddressView() ///获取地址数据 func requestAddressData(){ weak var weakSelf = self showLoadingView() GYZNetWork.requestNetwork("Address/addressList",parameters: ["user_id":userDefaults.string(forKey: "userId") ?? ""], success: { (response) in weakSelf?.hiddenLoadingView() // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 let data = response["result"] guard let info = data["info"].array else { return } for item in info{ guard let itemInfo = item.dictionaryObject else { return } let model = GYZAddressModel.init(dict: itemInfo) weakSelf?.addressModels.append(model) } weakSelf?.tableView.reloadData() }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hiddenLoadingView() GYZLog(error) }) } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return addressModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: mineAddressCell) as! GYZAddressCell let item = addressModels[indexPath.row] cell.dataModel = item if isEditEnble { cell.deleteIconView.isHidden = false cell.editIconView.isHidden = false cell.contractLab.snp.updateConstraints({ (make) in make.left.equalTo(cell.deleteIconView.snp.right).offset(5) }) cell.editIconView.addOnClickListener(target: self, action: #selector(editAddressClick(sender:))) cell.editIconView.tag = 100 + indexPath.row cell.deleteIconView.addOnClickListener(target: self, action: #selector(deleteAddressClick(sender:))) cell.deleteIconView.tag = 100 + indexPath.row } else { cell.deleteIconView.isHidden = true cell.editIconView.isHidden = true cell.contractLab.snp.updateConstraints({ (make) in make.left.equalTo(cell.deleteIconView.snp.right).offset(-25) }) } cell.selectionStyle = .none return cell } ///MARK : UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return kTitleAndStateHeight } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return kMargin } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.00001 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if isSelected { backOrderVC(index: indexPath.row) } } /// 提交订单选择地址 /// /// - Parameter index: func backOrderVC(index: Int){ for i in 0..<(navigationController?.viewControllers.count)!{ if navigationController?.viewControllers[i].isKind(of: GYZSubmitOrderVC.self) == true { let vc = navigationController?.viewControllers[i] as! GYZSubmitOrderVC vc.addressModel = addressModels[index] _ = navigationController?.popToViewController(vc, animated: true) break } } } /// 编辑地址 /// /// - Parameter sender: func editAddressClick(sender: UITapGestureRecognizer){ let tag = sender.view?.tag goEditVC(isEdit: false, addressInfo: addressModels[tag! - 100]) } ///删除地址 func deleteAddressClick(sender: UITapGestureRecognizer){ let tag = sender.view?.tag weak var weakSelf = self GYZAlertViewTools.alertViewTools.showAlert(title: "提示", message: "确定要删除该地址?", cancleTitle: "取消", viewController: self, buttonTitles: "删除") { (index) in if index != -1{ weakSelf?.requestDeleteAddress(index: tag!) } } } func requestDeleteAddress(index: Int){ let addId: String = addressModels[index - 100].add_id! weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("Address/del", parameters: ["add_id":addId], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 weakSelf?.addressModels.remove(at: index - 100) weakSelf?.tableView.reloadData() } MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } }
mit
48af7d31ab652aaa45c38d6cede07b67
32.326772
159
0.585351
4.973561
false
false
false
false
nitrado/NitrAPI-Swift
Pod/Classes/order/Pricing.swift
1
4826
import ObjectMapper open class Pricing { var nitrapi: Nitrapi var product: String! var locationId: Int var additionals: Dictionary<String, String> var prices: [String: PriceList] public init(nitrapi: Nitrapi, locationId: Int) { self.nitrapi = nitrapi self.locationId = locationId self.prices = [:] self.additionals = [:] } /// returns a list of locations this service is available in open func getLocations() throws -> [Location] { if product == nil { // TODO: Exception return [] } let data = try nitrapi.client.dataGet("order/order/locations", parameters: [:]) let locations = Mapper<Location>().mapArray(JSONArray: data?["locations"] as! [[String : Any]]) var avaiable: [Location] = [] for loc in locations { if loc.hasService(product!) { avaiable.append(loc) } } return avaiable } open func setLocationId(_ id: Int) { locationId = id } open func getPrices() throws -> PriceList { return try getPrices(nil) } open func getPrices(_ service: Service?) throws -> PriceList { var cacheName = "\(locationId)" if let service = service { cacheName += "/\(service.id as Int)" } if prices.keys.contains(cacheName) { return prices[cacheName]! } var parameters: [String:String] = ["location": "\(locationId)"] if let service = service { parameters["sale_service"] = "\(service.id as Int)" } let data = try nitrapi.client.dataGet("order/pricing/\(product as String)", parameters: parameters) prices[cacheName] = Mapper<PriceList>().map(JSON: data?["prices"] as! [String : Any]) return prices[cacheName]! } open func getExtendPricesForService(_ service: Int) throws -> [Int: Int]? { let data = try nitrapi.client.dataGet("order/pricing/\(product as String)", parameters: [ "method": "extend", "service_id": "\(service)"]) if let obj = data?["extend"] as? Dictionary<String, AnyObject> { let pricesRaw = obj["prices"] if let prices = obj["prices"]! as? Dictionary<String, AnyObject> { var results: [Int: Int] = [:] for (key, value) in prices { results[Int(key)!] = value as! Int } return results } } return nil } open func getExtendPricesForService(_ service: Int, rentalTime: Int) throws -> Int? { let data = try nitrapi.client.dataGet("order/pricing/\(product as String)", parameters: [ "method": "extend", "service_id": "\(service)", "rental_time": "\(rentalTime)" ]) if let obj = data?["extend"] as? Dictionary<String, AnyObject> { if let prices = obj["prices"]! as? Dictionary<String, AnyObject> { return prices["\(rentalTime)"] as? Int } } return nil } open func doExtendService(_ service: Int, rentalTime: Int, price: Int) throws -> Int? { let data = try nitrapi.client.dataPost("order/order/\(product as String)", parameters: [ "price": "\(price)", "rental_time": "\(rentalTime)", "service_id": "\(service)", "method": "extend" ]) if let obj = data?["order"] as? Dictionary<String, AnyObject> { return obj["service_id"] as? Int } return nil } open func calcAdvicePrice(price: Double, advice: Double, service: Service?) -> Int { // Dynamic cloud servers return 100% of advice. if let cloudserver = service as? CloudServer, cloudserver.dynamic == true { return Int(price - advice) } var advice2 = advice if advice2 > price { advice2 -= round((advice2 - price) / 2) } return Int(price - advice2) } open func getPrice(_ rentalTime: Int) throws -> Int { return try getPrice(nil, rentalTime: rentalTime) } open func getPrice(_ service: Service?, rentalTime: Int) throws -> Int { return -1 } open func orderService(_ rentalTime: Int) throws -> Int? { return nil } open func getSwitchPrice(_ service: Service?, rentalTime: Int) throws -> Int { return try getPrice(service, rentalTime: rentalTime) } open func switchService(_ service: Service, rentalTime: Int) throws -> Int? { return nil } }
mit
8d4620c9f4442889b50030916be2f44e
31.608108
107
0.538956
4.489302
false
false
false
false
LawrenceHan/iOS-project-playground
Homepwner_swift/Homepwner/ItemCell.swift
1
550
// // Copyright © 2015 Big Nerd Ranch // import UIKit class ItemCell: UITableViewCell { @IBOutlet var nameLabel: UILabel! @IBOutlet var serialNumberLabel: UILabel! @IBOutlet var valueLabel: UILabel! func updateLabels() { let bodyFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) nameLabel.font = bodyFont valueLabel.font = bodyFont let caption1Font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) serialNumberLabel.font = caption1Font } }
mit
a7f7d547dbd4d7275e786a80aeb0ad89
23.954545
84
0.684882
5.330097
false
false
false
false
joelconnects/FlipTheBlinds
FlipTheBlinds/FTBExtensions.swift
1
2374
// // FTBExtensions.swift // FlipTheBlinds // // Created by Joel Bell on 1/2/17. // Copyright © 2017 Joel Bell. All rights reserved. // import UIKit // MARK: Image slice type enum FTBSliceType { case horizontal case vertical } // MARK: Generate image slices extension UIImage { func generateImage(slices: Int, type: FTBSliceType) -> [UIImage] { var imageSlices: [UIImage] = [] let imageRef = self.cgImage let multiplier = CGFloat(imageRef!.width) / self.size.width switch type { case .horizontal: let rectHeight = self.size.height * multiplier / CGFloat(slices) let rectWidth = self.size.width * multiplier for i in 0..<slices { let rectY: CGFloat = rectHeight * CGFloat(i) let frame = CGRect(x: 0, y: rectY, width: rectWidth, height: rectHeight) let slicedImageRef = imageRef?.cropping(to: frame) let imageSlice = UIImage(cgImage: slicedImageRef!) imageSlices.append(imageSlice) } case .vertical: let rectHeight = self.size.height * multiplier let rectWidth = self.size.width * multiplier / CGFloat(slices) for i in 0..<slices { let rectX: CGFloat = rectWidth * CGFloat(i) let frame = CGRect(x: rectX, y: 0, width: rectWidth, height: rectHeight) let slicedImageRef = imageRef?.cropping(to: frame) let imageSlice = UIImage(cgImage: slicedImageRef!) imageSlices.append(imageSlice) } } return imageSlices } } // MARK: Draw/Render Image extension UIView { func drawImage() -> UIImage { let renderer = UIGraphicsImageRenderer(size: (self.bounds.size)) return renderer.image { ctx in self.drawHierarchy(in: self.bounds, afterScreenUpdates: true) } } func renderImage() -> UIImage { let renderer = UIGraphicsImageRenderer(size: (self.bounds.size)) return renderer.image { ctx in self.layer.render(in: ctx.cgContext) } } }
mit
5d9908979049c826c0198c3208f67ed7
25.076923
88
0.540244
4.746
false
false
false
false
lanjing99/RxSwiftDemo
11-time-based-operators/final/RxSwiftPlayground/RxSwift.playground/Pages/buffer.xcplaygroundpage/Contents.swift
2
3671
//: Please build the scheme 'RxSwiftPlayground' first import UIKit import RxSwift import RxCocoa let bufferTimeSpan: RxTimeInterval = 4 let bufferMaxCount = 2 let sourceObservable = PublishSubject<String>() let sourceTimeline = TimelineView<String>.make() let bufferedTimeline = TimelineView<Int>.make() let stack = UIStackView.makeVertical([ UILabel.makeTitle("buffer"), UILabel.make("Emitted elements:"), sourceTimeline, UILabel.make("Buffered elements (at most \(bufferMaxCount) every \(bufferTimeSpan) seconds):"), bufferedTimeline]) _ = sourceObservable.subscribe(sourceTimeline) sourceObservable .buffer(timeSpan: bufferTimeSpan, count: bufferMaxCount, scheduler: MainScheduler.instance) .map { $0.count } .subscribe(bufferedTimeline) let hostView = setupHostView() hostView.addSubview(stack) hostView let elementsPerSecond = 0.7 let timer = DispatchSource.timer(interval: 1.0 / Double(elementsPerSecond), queue: .main) { sourceObservable.onNext("🐱") } // Support code -- DO NOT REMOVE class TimelineView<E>: TimelineViewBase, ObserverType where E: CustomStringConvertible { static func make() -> TimelineView<E> { let view = TimelineView(frame: CGRect(x: 0, y: 0, width: 400, height: 100)) view.setup() return view } public func on(_ event: Event<E>) { switch event { case .next(let value): add(.Next(String(describing: value))) case .completed: add(.Completed()) case .error(_): add(.Error()) } } } /*: Copyright (c) 2014-2016 Razeware LLC 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. */ /*: Copyright (c) 2014-2016 Razeware LLC 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. */
mit
9fd6832fd7e9cfab636ca5188956bc0b
37.208333
97
0.759269
4.517241
false
false
false
false
Aaron-zheng/SwiftTips
swifttips/swifttips/PreCalculateTextHeight.swift
1
765
// // PreCalculateTextHeight.swift // swifttips // // Created by Aaron on 26/7/2016. // Copyright © 2016 sightcorner. All rights reserved. // import Foundation import UIKit /** 计算在给定的文字类型和宽度限制下,文本将会占到的高度 - parameter text: 文本文字 - parameter font: 字体类型 - parameter width: 宽度 - returns: 文本的高度 */ func preCalculateTextHeight(text: String, font: UIFont, width: CGFloat) -> CGFloat { let label:UILabel = UILabel(frame: CGRect.init(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)) label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.font = font label.text = text label.sizeToFit() return label.frame.height }
apache-2.0
4c9e74aac78c68ffec088742d8f7a550
22.517241
118
0.702346
3.515464
false
false
false
false
PavelGnatyuk/SimplePurchase
SimplePurchase/SimplePurchase/in-app purchase/AppPaymentTransactionObserver.swift
1
2183
// // AppPaymentTransactionObserver.swift // // Payment transaction observer - actually a wrapper for SKPaymentQueue adding new payment to it // and handling all states of this payment in the queue. // // The class allows to write unit-test for the purchase controller. // // Created by Pavel Gnatyuk on 29/04/2017. // // import StoreKit @objc class AppPaymentTransactionObserver: NSObject, PaymentTransactionObserver { private(set) var active: Bool = false fileprivate weak var delegate: PaymentTransactionObserverDelegate? required init(delegate: PaymentTransactionObserverDelegate?) { self.delegate = delegate } deinit { delegate = nil } var canMakePayments: Bool { return SKPaymentQueue.canMakePayments() } func start() { if active == false { SKPaymentQueue.default().add(self) active = true } } func stop() { SKPaymentQueue.default().remove(self) } func add(_ payment: SKPayment) { SKPaymentQueue.default().add(payment) } func finish(_ transaction: SKPaymentTransaction) { SKPaymentQueue.default().finishTransaction(transaction) } func restoreTransactions() { if canMakePayments { SKPaymentQueue.default().restoreCompletedTransactions() } } } extension AppPaymentTransactionObserver: SKPaymentTransactionObserver { func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { transactions.forEach { transaction in switch transaction.transactionState { case .purchasing: self.delegate?.onPurchasing?(transaction) case .purchased: self.delegate?.onPurchased(transaction) case .failed: self.delegate?.onFailed(transaction) case .restored: self.delegate?.onRestored(transaction) case .deferred: self.delegate?.onDeferred?(transaction) } } } }
apache-2.0
2f58868d1ce77325fc55a8ae323957cf
26.2875
106
0.612918
5.484925
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteAuth/model.User200Entities.swift
1
2506
import OpenbuildExtensionPerfect public class ModelUser200Entities: ResponseModel200Entities, DocumentationProtocol { public var descriptions = [ "error": "An error has occurred, will always be false", "message": "Will always be 'Successfully fetched the entities.'", "entities": "Object describing the users." ] public init(entities: ModelUsersPlainMin) { super.init(entities: entities) } public static func describeRAML() -> [String] { if let docs = ResponseDocumentation.getRAML(key: "RouteAuth.ModelUser200Entities") { return docs } else { let entities = ModelUsersPlainMin(users: []) var rolesAdmin = [[String:Any]]() var rolesEditor = [[String:Any]]() let roleAdmin = ["role_id": UInt32(1), "role": "Admin"] as [String : Any] let roleEditor = ["role_id": UInt32(2), "role": "Editor"] as [String : Any] rolesAdmin.append(roleAdmin) rolesAdmin.append(roleEditor) rolesEditor.append(roleEditor) entities.addUser( ModelUserPlainMin( user_id: 1, username: "admin", email: "[email protected]", passwordUpdate: false, created: "2016-12-25 17:56:31", roles: rolesAdmin ) ) entities.addUser( ModelUserPlainMin( user_id: 2, username: "editor", email: "[email protected]", passwordUpdate: false, created: "2016-12-25 17:57:51", roles: rolesEditor ) ) let model = ModelUser200Entities(entities: entities) let aMirror = Mirror(reflecting: model) let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions) ResponseDocumentation.setRAML(key: "RouteAuth.ModelUser200Entities", lines: docs) return docs } } } extension ModelUser200Entities: CustomReflectable { open var customMirror: Mirror { return Mirror( self, children: [ "error": self.error, "message": self.message, "entities": self.entities ], displayStyle: Mirror.DisplayStyle.class ) } }
gpl-2.0
a46bd1f1e8f84e2411b95ab92e5af7ce
28.151163
103
0.534717
4.866019
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ChannelRecentPostRowItem.swift
1
10092
// // ChannelRecentPostRowItem.swift // Telegram // // Created by Mikhail Filimonov on 12.03.2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import Postbox import SwiftSignalKit import TelegramCore class ChannelRecentPostRowItem: GeneralRowItem { fileprivate let viewsCountLayout: TextViewLayout fileprivate let sharesCountLayout: TextViewLayout fileprivate let titleLayout: TextViewLayout fileprivate let dateLayout: TextViewLayout fileprivate let message: Message fileprivate let contentImageMedia: TelegramMediaImage? fileprivate let context: AccountContext init(_ initialSize: NSSize, stableId: AnyHashable, context: AccountContext, message: Message, interactions: ChannelStatsMessageInteractions?, viewType: GeneralViewType, action: @escaping()->Void) { self.context = context self.message = message var contentImageMedia: TelegramMediaImage? for media in message.media { if let image = media as? TelegramMediaImage { contentImageMedia = image break } else if let file = media as? TelegramMediaFile { if file.isVideo && !file.isInstantVideo { let iconImageRepresentation:TelegramMediaImageRepresentation? = smallestImageRepresentation(file.previewRepresentations) if let iconImageRepresentation = iconImageRepresentation { contentImageMedia = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: [iconImageRepresentation], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: []) } break } } else if let webpage = media as? TelegramMediaWebpage, case let .Loaded(content) = webpage.content { if let image = content.image { contentImageMedia = image break } else if let file = content.file { if file.isVideo && !file.isInstantVideo { let iconImageRepresentation:TelegramMediaImageRepresentation? = smallestImageRepresentation(file.previewRepresentations) if let iconImageRepresentation = iconImageRepresentation { contentImageMedia = TelegramMediaImage(imageId: MediaId(namespace: 0, id: 0), representations: [iconImageRepresentation], immediateThumbnailData: nil, reference: nil, partialReference: nil, flags: []) } break } } } } self.contentImageMedia = contentImageMedia self.titleLayout = TextViewLayout(NSAttributedString.initialize(string: pullText(from: message) as String, color: theme.colors.text, font: .medium(.text)), maximumNumberOfLines: 1) self.dateLayout = TextViewLayout(NSAttributedString.initialize(string: stringForFullDate(timestamp: message.timestamp), color: theme.colors.grayText, font: .normal(.text)), maximumNumberOfLines: 1) let views = Int(max(message.channelViewsCount ?? 0, interactions?.views ?? 0)) let shares = Int(interactions?.forwards ?? 0) let viewsString = strings().channelStatsViewsCountCountable(views).replacingOccurrences(of: "\(views)", with: views.formattedWithSeparator) let sharesString = strings().channelStatsSharesCountCountable(shares).replacingOccurrences(of: "\(shares)", with: shares.formattedWithSeparator) viewsCountLayout = TextViewLayout(NSAttributedString.initialize(string: viewsString, color: theme.colors.text, font: .normal(.short)),maximumNumberOfLines: 1) sharesCountLayout = TextViewLayout(NSAttributedString.initialize(string: sharesString, color: theme.colors.grayText, font: .normal(.short)),maximumNumberOfLines: 1) super.init(initialSize, height: 46, stableId: stableId, viewType: viewType, action: action) } override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool { _ = super.makeSize(width, oldWidth: oldWidth) viewsCountLayout.measure(width: .greatestFiniteMagnitude) sharesCountLayout.measure(width: .greatestFiniteMagnitude) let titleAndDateWidth: CGFloat = blockWidth - viewType.innerInset.left - (contentImageMedia != nil ? 34 + 10 : 0) - max(viewsCountLayout.layoutSize.width, sharesCountLayout.layoutSize.width) - 10 - viewType.innerInset.right titleLayout.measure(width: titleAndDateWidth) dateLayout.measure(width: titleAndDateWidth) return true } override func viewClass() -> AnyClass { return ChannelRecentPostRowView.self } } private final class ChannelRecentPostRowView : GeneralContainableRowView { private let viewCountView = TextView() private let sharesCountView = TextView() private let titleView = TextView() private let dateView = TextView() private let fetchDisposable = MetaDisposable() private var imageView: TransformImageView? required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(viewCountView) addSubview(sharesCountView) addSubview(titleView) addSubview(dateView) sharesCountView.userInteractionEnabled = false sharesCountView.isSelectable = false sharesCountView.isEventLess = true titleView.userInteractionEnabled = false titleView.isSelectable = false titleView.isEventLess = true viewCountView.userInteractionEnabled = false viewCountView.isSelectable = false viewCountView.isEventLess = true dateView.userInteractionEnabled = false dateView.isSelectable = false dateView.isEventLess = true containerView.set(handler: { [weak self] _ in self?.updateColors() }, for: .Highlight) containerView.set(handler: { [weak self] _ in self?.updateColors() }, for: .Normal) containerView.set(handler: { [weak self] _ in self?.updateColors() }, for: .Hover) containerView.set(handler: { [weak self] _ in guard let item = self?.item as? ChannelRecentPostRowItem else { return } item.action() }, for: .Click) } override func layout() { super.layout() guard let item = item as? ChannelRecentPostRowItem else { return } viewCountView.setFrameOrigin(NSMakePoint(item.blockWidth - viewCountView.frame.width - item.viewType.innerInset.right, 5)) sharesCountView.setFrameOrigin(NSMakePoint(item.blockWidth - sharesCountView.frame.width - item.viewType.innerInset.right, containerView.frame.height - sharesCountView.frame.height - 5)) let leftOffset: CGFloat = (imageView != nil ? 34 + 10 : 0) + item.viewType.innerInset.left titleView.setFrameOrigin(NSMakePoint(leftOffset, 5)) dateView.setFrameOrigin(NSMakePoint(leftOffset, containerView.frame.height - dateView.frame.height - 5)) imageView?.centerY(x: item.viewType.innerInset.left) } override var backdorColor: NSColor { return isSelect ? theme.colors.accentSelect : theme.colors.background } override func updateColors() { super.updateColors() if let item = item as? GeneralRowItem { self.background = item.viewType.rowBackground let highlighted = isSelect ? self.backdorColor : theme.colors.grayHighlight titleView.backgroundColor = containerView.controlState == .Highlight && !isSelect ? .clear : self.backdorColor dateView.backgroundColor = containerView.controlState == .Highlight && !isSelect ? .clear : self.backdorColor viewCountView.backgroundColor = containerView.controlState == .Highlight && !isSelect ? .clear : self.backdorColor sharesCountView.backgroundColor = containerView.controlState == .Highlight && !isSelect ? .clear : self.backdorColor containerView.set(background: self.backdorColor, for: .Normal) containerView.set(background: highlighted, for: .Highlight) } } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? ChannelRecentPostRowItem else { return } viewCountView.update(item.viewsCountLayout) sharesCountView.update(item.sharesCountLayout) dateView.update(item.dateLayout) titleView.update(item.titleLayout) if let media = item.contentImageMedia { if imageView == nil { self.imageView = TransformImageView(frame: NSMakeRect(0, 0, 34, 34)) imageView?.set(arguments: TransformImageArguments(corners: .init(radius: 4), imageSize: NSMakeSize(34, 34), boundingSize: NSMakeSize(34, 34), intrinsicInsets: NSEdgeInsets())) addSubview(self.imageView!) } let updateIconImageSignal = chatWebpageSnippetPhoto(account: item.context.account, imageReference: ImageMediaReference.message(message: MessageReference(item.message), media: media), scale: backingScaleFactor, small:true) imageView?.setSignal(updateIconImageSignal) fetchDisposable.set(chatMessagePhotoInteractiveFetched(account: item.context.account, imageReference: ImageMediaReference.message(message: MessageReference(item.message), media: media)).start()) } else { imageView?.removeFromSuperview() imageView = nil fetchDisposable.set(nil) } } deinit { fetchDisposable.dispose() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
1389b6b82f5c221a2e9985db7afe7a29
45.288991
233
0.662174
5.214987
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/NSUserDefaults+WMFExtensions.swift
1
18655
let WMFAppResignActiveDateKey = "WMFAppResignActiveDateKey" let WMFShouldRestoreNavigationStackOnResume = "WMFShouldRestoreNavigationStackOnResume" let WMFAppSiteKey = "Domain" let WMFSearchURLKey = "WMFSearchURLKey" let WMFFeedRefreshDateKey = "WMFFeedRefreshDateKey" let WMFLocationAuthorizedKey = "WMFLocationAuthorizedKey" let WMFPlacesDidPromptForLocationAuthorization = "WMFPlacesDidPromptForLocationAuthorization" let WMFExploreDidPromptForLocationAuthorization = "WMFExploreDidPromptForLocationAuthorization" let WMFPlacesHasAppeared = "WMFPlacesHasAppeared" let WMFAppThemeName = "WMFAppThemeName" let WMFIsImageDimmingEnabled = "WMFIsImageDimmingEnabled" let WMFIsAutomaticTableOpeningEnabled = "WMFIsAutomaticTableOpeningEnabled" let WMFDidShowThemeCardInFeed = "WMFDidShowThemeCardInFeed" let WMFDidShowReadingListCardInFeed = "WMFDidShowReadingListCardInFeed" let WMFDidShowEnableReadingListSyncPanelKey = "WMFDidShowEnableReadingListSyncPanelKey" let WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey = "WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey" let WMFDidShowThankRevisionAuthorEducationPanelKey = "WMFDidShowThankRevisionAuthorEducationPanelKey" let WMFDidShowLimitHitForUnsortedArticlesPanel = "WMFDidShowLimitHitForUnsortedArticlesPanel" let WMFDidShowSyncDisabledPanel = "WMFDidShowSyncDisabledPanel" let WMFDidShowSyncEnabledPanel = "WMFDidShowSyncEnabledPanel" let WMFDidSplitExistingReadingLists = "WMFDidSplitExistingReadingLists" let WMFDidShowTitleDescriptionEditingIntro = "WMFDidShowTitleDescriptionEditingIntro" let WMFDidShowFirstEditPublishedPanelKey = "WMFDidShowFirstEditPublishedPanelKey" let WMFIsSyntaxHighlightingEnabled = "WMFIsSyntaxHighlightingEnabled" let WMFSearchLanguageKey = "WMFSearchLanguageKey" let WMFAppInstallId = "WMFAppInstallId" let WMFSendUsageReports = "WMFSendUsageReports" let WMFShowNotificationsExploreFeedCard = "WMFShowNotificationsExploreFeedCard" let WMFUserHasOnboardedToNotificationsCenter = "WMFUserHasOnboardedToNotificationsCenter" let WMFUserHasOnboardedToContributingToTalkPages = "WMFUserHasOnboardedToContributingToTalkPages" let WMFDidShowNotificationsCenterPushOptInPanel = "WMFDidShowNotificationsCenterPushOptInPanel" let WMFSubscribedToEchoNotifications = "WMFSubscribedToEchoNotifications" let WMFTappedToImportSharedReadingListSurvey = "WMFTappedToImportSharedReadingListSurvey" @objc public enum WMFAppDefaultTabType: Int { case explore case settings } @objc public extension UserDefaults { @objc(WMFUserDefaultsKey) class Key: NSObject { @objc static let defaultTabType = "WMFDefaultTabTypeKey" static let isUserUnawareOfLogout = "WMFIsUserUnawareOfLogout" static let didShowDescriptionPublishedPanel = "WMFDidShowDescriptionPublishedPanel" static let didShowEditingOnboarding = "WMFDidShowEditingOnboarding" static let autoSignTalkPageDiscussions = "WMFAutoSignTalkPageDiscussions" static let talkPageForceRefreshRevisionIDs = "WMFTalkPageForceRefreshRevisionIDs" } @objc func wmf_dateForKey(_ key: String) -> Date? { return self.object(forKey: key) as? Date } @objc func wmf_appResignActiveDate() -> Date? { return self.wmf_dateForKey(WMFAppResignActiveDateKey) } @objc func wmf_setAppResignActiveDate(_ date: Date?) { if let date = date { self.set(date, forKey: WMFAppResignActiveDateKey) } else { self.removeObject(forKey: WMFAppResignActiveDateKey) } } @objc var shouldRestoreNavigationStackOnResume: Bool { get { return bool(forKey: WMFShouldRestoreNavigationStackOnResume) } set { set(newValue, forKey: WMFShouldRestoreNavigationStackOnResume) } } @objc var wmf_lastAppVersion: String? { get { return string(forKey: "WMFLastAppVersion") } set { set(newValue, forKey: "WMFLastAppVersion") } } @objc var wmf_appInstallId: String? { get { var appInstallId = string(forKey: WMFAppInstallId) if appInstallId == nil { appInstallId = UUID().uuidString set(appInstallId, forKey: WMFAppInstallId) } return appInstallId } set { set(newValue, forKey: WMFAppInstallId) } } @objc var wmf_sendUsageReports: Bool { get { return bool(forKey: WMFSendUsageReports) } set { set(newValue, forKey: WMFSendUsageReports) } } @objc var wmf_isSubscribedToEchoNotifications: Bool { get { return bool(forKey: WMFSubscribedToEchoNotifications) } set { set(newValue, forKey: WMFSubscribedToEchoNotifications) } } @objc func wmf_setFeedRefreshDate(_ date: Date) { self.set(date, forKey: WMFFeedRefreshDateKey) } @objc func wmf_feedRefreshDate() -> Date? { return self.wmf_dateForKey(WMFFeedRefreshDateKey) } @objc func wmf_setLocationAuthorized(_ authorized: Bool) { self.set(authorized, forKey: WMFLocationAuthorizedKey) } @objc var themeAnalyticsName: String { let name = string(forKey: WMFAppThemeName) let systemDarkMode = systemDarkModeEnabled guard name != nil, name != Theme.defaultThemeName else { return systemDarkMode ? Theme.black.analyticsName : Theme.light.analyticsName } if Theme.withName(name)?.name == Theme.light.name { return Theme.defaultAnalyticsThemeName } return Theme.withName(name)?.analyticsName ?? Theme.light.analyticsName } @objc var themeDisplayName: String { let name = string(forKey: WMFAppThemeName) guard name != nil, name != Theme.defaultThemeName else { return CommonStrings.defaultThemeDisplayName } return Theme.withName(name)?.displayName ?? Theme.light.displayName } @objc(themeCompatibleWith:) func theme(compatibleWith traitCollection: UITraitCollection) -> Theme { let name = string(forKey: WMFAppThemeName) let systemDarkMode = traitCollection.userInterfaceStyle == .dark systemDarkModeEnabled = systemDarkMode guard name != nil, name != Theme.defaultThemeName else { return systemDarkMode ? Theme.black.withDimmingEnabled(wmf_isImageDimmingEnabled) : .light } let theme = Theme.withName(name) ?? Theme.light return theme.isDark ? theme.withDimmingEnabled(wmf_isImageDimmingEnabled) : theme } @objc var themeName: String { get { string(forKey: WMFAppThemeName) ?? Theme.defaultThemeName } set { set(newValue, forKey: WMFAppThemeName) } } @objc var wmf_isImageDimmingEnabled: Bool { get { return bool(forKey: WMFIsImageDimmingEnabled) } set { set(newValue, forKey: WMFIsImageDimmingEnabled) } } @objc var wmf_IsSyntaxHighlightingEnabled: Bool { get { if object(forKey: WMFIsSyntaxHighlightingEnabled) == nil { return true // default to highlighting enabled } return bool(forKey: WMFIsSyntaxHighlightingEnabled) } set { set(newValue, forKey: WMFIsSyntaxHighlightingEnabled) } } @objc var wmf_isAutomaticTableOpeningEnabled: Bool { get { return bool(forKey: WMFIsAutomaticTableOpeningEnabled) } set { set(newValue, forKey: WMFIsAutomaticTableOpeningEnabled) } } @objc var wmf_didShowThemeCardInFeed: Bool { get { return bool(forKey: WMFDidShowThemeCardInFeed) } set { set(newValue, forKey: WMFDidShowThemeCardInFeed) } } @objc var wmf_didShowReadingListCardInFeed: Bool { get { return bool(forKey: WMFDidShowReadingListCardInFeed) } set { set(newValue, forKey: WMFDidShowReadingListCardInFeed) } } @objc func wmf_locationAuthorized() -> Bool { return self.bool(forKey: WMFLocationAuthorizedKey) } @objc func wmf_setPlacesHasAppeared(_ hasAppeared: Bool) { self.set(hasAppeared, forKey: WMFPlacesHasAppeared) } @objc func wmf_placesHasAppeared() -> Bool { return self.bool(forKey: WMFPlacesHasAppeared) } @objc func wmf_setPlacesDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFPlacesDidPromptForLocationAuthorization) } @objc func wmf_placesDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFPlacesDidPromptForLocationAuthorization) } @objc func wmf_setExploreDidPromptForLocationAuthorization(_ didPrompt: Bool) { self.set(didPrompt, forKey: WMFExploreDidPromptForLocationAuthorization) } @objc func wmf_exploreDidPromptForLocationAuthorization() -> Bool { return self.bool(forKey: WMFExploreDidPromptForLocationAuthorization) } @objc func wmf_setShowSearchLanguageBar(_ enabled: Bool) { self.set(NSNumber(value: enabled as Bool), forKey: "ShowLanguageBar") } @objc func wmf_showSearchLanguageBar() -> Bool { if let enabled = self.object(forKey: "ShowLanguageBar") as? NSNumber { return enabled.boolValue } else { return false } } @objc var wmf_openAppOnSearchTab: Bool { get { return bool(forKey: "WMFOpenAppOnSearchTab") } set { set(newValue, forKey: "WMFOpenAppOnSearchTab") } } @objc func wmf_currentSearchContentLanguageCode() -> String? { self.string(forKey: WMFSearchLanguageKey) } @objc func wmf_setCurrentSearchContentLanguageCode(_ code: String?) { if let code = code { set(code, forKey: WMFSearchLanguageKey) } else { removeObject(forKey: WMFSearchLanguageKey) } } @objc func wmf_setDidShowWIconPopover(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowWIconPopover") } @objc func wmf_didShowWIconPopover() -> Bool { if let enabled = self.object(forKey: "ShowWIconPopover") as? NSNumber { return enabled.boolValue } else { return false } } @objc func wmf_setDidShowMoreLanguagesTooltip(_ shown: Bool) { self.set(NSNumber(value: shown as Bool), forKey: "ShowMoreLanguagesTooltip") } @objc func wmf_didShowMoreLanguagesTooltip() -> Bool { if let enabled = self.object(forKey: "ShowMoreLanguagesTooltip") as? NSNumber { return enabled.boolValue } else { return false } } @objc func wmf_setTableOfContentsIsVisibleInline(_ visibleInline: Bool) { self.set(NSNumber(value: visibleInline as Bool), forKey: "TableOfContentsIsVisibleInline") } @objc func wmf_isTableOfContentsVisibleInline() -> Bool { if let enabled = self.object(forKey: "TableOfContentsIsVisibleInline") as? NSNumber { return enabled.boolValue } else { return true } } @objc func wmf_setDidFinishLegacySavedArticleImageMigration(_ didFinish: Bool) { self.set(didFinish, forKey: "DidFinishLegacySavedArticleImageMigration2") } @objc func wmf_didFinishLegacySavedArticleImageMigration() -> Bool { return self.bool(forKey: "DidFinishLegacySavedArticleImageMigration2") } @objc func wmf_setDidShowEnableReadingListSyncPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowEnableReadingListSyncPanelKey) } @objc func wmf_didShowEnableReadingListSyncPanel() -> Bool { return self.bool(forKey: WMFDidShowEnableReadingListSyncPanelKey) } @objc func wmf_setDidShowLoginToSyncSavedArticlesToReadingListPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) } @objc func wmf_didShowLoginToSyncSavedArticlesToReadingListPanel() -> Bool { return self.bool(forKey: WMFDidShowLoginToSyncSavedArticlesToReadingListPanelKey) } @objc func wmf_setDidShowThankRevisionAuthorEducationPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowThankRevisionAuthorEducationPanelKey) } @objc func wmf_didShowThankRevisionAuthorEducationPanel() -> Bool { return self.bool(forKey: WMFDidShowThankRevisionAuthorEducationPanelKey) } @objc func wmf_setDidShowFirstEditPublishedPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowFirstEditPublishedPanelKey) } @objc func wmf_didShowFirstEditPublishedPanel() -> Bool { return self.bool(forKey: WMFDidShowFirstEditPublishedPanelKey) } @objc func wmf_didShowLimitHitForUnsortedArticlesPanel() -> Bool { return self.bool(forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) } @objc func wmf_setDidShowLimitHitForUnsortedArticlesPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowLimitHitForUnsortedArticlesPanel) } @objc func wmf_didShowSyncDisabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncDisabledPanel) } @objc func wmf_setDidShowSyncDisabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncDisabledPanel) } @objc func wmf_didShowSyncEnabledPanel() -> Bool { return self.bool(forKey: WMFDidShowSyncEnabledPanel) } @objc func wmf_setDidShowSyncEnabledPanel(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowSyncEnabledPanel) } @objc func wmf_didSplitExistingReadingLists() -> Bool { return self.bool(forKey: WMFDidSplitExistingReadingLists) } @objc func wmf_setDidSplitExistingReadingLists(_ didSplit: Bool) { self.set(didSplit, forKey: WMFDidSplitExistingReadingLists) } @objc var defaultTabType: WMFAppDefaultTabType { get { guard let defaultTabType = WMFAppDefaultTabType(rawValue: integer(forKey: UserDefaults.Key.defaultTabType)) else { let explore = WMFAppDefaultTabType.explore set(explore.rawValue, forKey: UserDefaults.Key.defaultTabType) return explore } return defaultTabType } set { set(newValue.rawValue, forKey: UserDefaults.Key.defaultTabType) wmf_openAppOnSearchTab = newValue == .settings } } @objc func wmf_didShowTitleDescriptionEditingIntro() -> Bool { return self.bool(forKey: WMFDidShowTitleDescriptionEditingIntro) } @objc func wmf_setDidShowTitleDescriptionEditingIntro(_ didShow: Bool) { self.set(didShow, forKey: WMFDidShowTitleDescriptionEditingIntro) } @objc var wmf_userHasOnboardedToNotificationsCenter: Bool { get { return bool(forKey: WMFUserHasOnboardedToNotificationsCenter) } set { set(newValue, forKey: WMFUserHasOnboardedToNotificationsCenter) } } @objc var wmf_userHasOnboardedToContributingToTalkPages: Bool { get { return bool(forKey: WMFUserHasOnboardedToContributingToTalkPages) } set { set(newValue, forKey: WMFUserHasOnboardedToContributingToTalkPages) } } @objc var wmf_didShowNotificationsCenterPushOptInPanel: Bool { get { return bool(forKey: WMFDidShowNotificationsCenterPushOptInPanel) } set { set(newValue, forKey: WMFDidShowNotificationsCenterPushOptInPanel) } } var isUserUnawareOfLogout: Bool { get { return bool(forKey: UserDefaults.Key.isUserUnawareOfLogout) } set { set(newValue, forKey: UserDefaults.Key.isUserUnawareOfLogout) } } var didShowDescriptionPublishedPanel: Bool { get { return bool(forKey: UserDefaults.Key.didShowDescriptionPublishedPanel) } set { set(newValue, forKey: UserDefaults.Key.didShowDescriptionPublishedPanel) } } @objc var didShowEditingOnboarding: Bool { get { return bool(forKey: UserDefaults.Key.didShowEditingOnboarding) } set { set(newValue, forKey: UserDefaults.Key.didShowEditingOnboarding) } } var autoSignTalkPageDiscussions: Bool { get { return bool(forKey: UserDefaults.Key.autoSignTalkPageDiscussions) } set { set(newValue, forKey: UserDefaults.Key.autoSignTalkPageDiscussions) } } var talkPageForceRefreshRevisionIDs: Set<Int>? { get { guard let arrayValue = array(forKey: UserDefaults.Key.talkPageForceRefreshRevisionIDs) as? [Int], !arrayValue.isEmpty else { return nil } return Set<Int>(arrayValue) } set { guard let newValue = newValue, !newValue.isEmpty else { removeObject(forKey: UserDefaults.Key.talkPageForceRefreshRevisionIDs) return } let arrayValue = Array(newValue) set(arrayValue, forKey: UserDefaults.Key.talkPageForceRefreshRevisionIDs) } } private var systemDarkModeEnabled: Bool { get { return bool(forKey: "SystemDarkMode") } set { set(newValue, forKey: "SystemDarkMode") } } @objc var wmf_shouldShowNotificationsExploreFeedCard: Bool { get { return bool(forKey: WMFShowNotificationsExploreFeedCard) } set { set(newValue, forKey: WMFShowNotificationsExploreFeedCard) } } @objc var wmf_tappedToImportSharedReadingListSurvey: Bool { get { return bool(forKey: WMFTappedToImportSharedReadingListSurvey) } set { set(newValue, forKey: WMFTappedToImportSharedReadingListSurvey) } } #if UI_TEST @objc func wmf_isFastlaneSnapshotInProgress() -> Bool { return bool(forKey: "FASTLANE_SNAPSHOT") } #endif }
mit
a8b233b3b0ffcb2a056a1cdb74b2c696
34.198113
126
0.669365
4.63824
false
false
false
false
SpectralDragon/LightRoute
Example/Source/Helpers/Pressable.swift
1
5228
// // Pressable.swift // iOS Example // // Created by v.a.prusakov on 12/04/2018. // Copyright © 2018 v.a.prusakov. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass protocol PressStateAnimatable: class { var pressStateAnimationMinScale: CGFloat { get } var pressStateAnimationDuration: TimeInterval { get } var isPressStateAnimationEnabled: Bool { get set } } extension PressStateAnimatable where Self: UIView { var pressStateAnimationMinScale: CGFloat { return 0.95 } var pressStateAnimationDuration: TimeInterval { return 0.1 } fileprivate var highlightRecognizer: TouchHandlerGestureRecognizer? { return self.gestureRecognizers?.first { $0 is TouchHandlerGestureRecognizer } as? TouchHandlerGestureRecognizer } var isPressStateAnimationEnabled: Bool { get { return self.highlightRecognizer != nil } set { newValue ? self.enablePressStateAnimation() : disablePressStateAnimation() } } fileprivate func enablePressStateAnimation() { let minScale = self.pressStateAnimationMinScale let duration = self.pressStateAnimationDuration guard minScale < 1, minScale >= 0, duration > 0 else { return } self.disablePressStateAnimation() let touchUpGesture = TouchHandlerGestureRecognizer { [weak self] (gesture) in if gesture.state == .began { self?.animatePressStateChange(pressed: true, minScale: minScale, duration: duration) } if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed { self?.animatePressStateChange(pressed: false, minScale: minScale, duration: duration) } } touchUpGesture.cancelsTouchesInView = false self.addGestureRecognizer(touchUpGesture) } fileprivate func animatePressStateChange(pressed: Bool, minScale: CGFloat, duration: TimeInterval) { let toValue = pressed ? CATransform3DMakeScale(minScale, minScale, 1) : CATransform3DMakeScale(1, 1, 1) let scaleAnimation = CABasicAnimation(keyPath: "transform") if let presentationLayer = layer.presentation() { scaleAnimation.fromValue = presentationLayer.transform // Процент выполнения текущей анимации let animationProgress = Double((presentationLayer.transform.m11 - minScale) / (1 - minScale)) // Если вью не нажата, то анимация в обратную сторону let durationMultiplier = pressed ? animationProgress : (1 - animationProgress) scaleAnimation.duration = duration * durationMultiplier } else { scaleAnimation.fromValue = layer.transform scaleAnimation.duration = duration } scaleAnimation.toValue = toValue scaleAnimation.duration = duration // Remove previous animation, is she executed now layer.removeAnimation(forKey: "scale") layer.add(scaleAnimation, forKey: "scale") layer.transform = toValue } fileprivate func disablePressStateAnimation() { if let recognizer = self.highlightRecognizer { self.removeGestureRecognizer(recognizer) } } } // MARK: - Gestures final class TouchHandlerGestureRecognizer: TouchGestureRecognizer { typealias StateChangeHandler = ((UIGestureRecognizer) -> Void) private let stateChangeHandler: StateChangeHandler public required init(stateChangeHandler: @escaping StateChangeHandler) { self.stateChangeHandler = stateChangeHandler super.init() self.addTarget(self, action: #selector(handleStateChange(_:))) } // MARK: - Handler @objc private func handleStateChange(_ gestureRecognizer: UIGestureRecognizer) { self.stateChangeHandler(gestureRecognizer) } } class TouchGestureRecognizer: UIGestureRecognizer { init() { super.init(target: nil, action: nil) } override func canPrevent(_ preventedGestureRecognizer: UIGestureRecognizer) -> Bool { return false } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesBegan(touches, with: event) self.state = .began } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) guard let view = view, let point = Array(touches).last?.location(in: view) else { return } if view.bounds.contains(point) { self.state = .possible } else { self.state = .ended } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesEnded(touches, with: event) self.state = .ended } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesCancelled(touches, with: event) self.state = .cancelled } }
mit
56c2aaef879e2059bbc795357ce1d77c
33.824324
119
0.651727
5.072835
false
false
false
false
kickstarter/ios-ksapi
KsApi/models/lenses/MessageThreadLenses.swift
1
1602
import Prelude extension MessageThread { public enum lens { public static let id = Lens<MessageThread, Int>( view: { $0.id }, set: { MessageThread(backing: $1.backing, closed: $1.closed, id: 0, lastMessage: $1.lastMessage, participant: $1.participant, project: $1.project, unreadMessagesCount: $1.unreadMessagesCount) } ) public static let participant = Lens<MessageThread, User>( view: { $0.participant }, set: { MessageThread(backing: $1.backing, closed: $1.closed, id: $0.id, lastMessage: $1.lastMessage, participant: $0, project: $1.project, unreadMessagesCount: $1.unreadMessagesCount) } ) public static let project = Lens<MessageThread, Project>( view: { $0.project }, set: { MessageThread(backing: $1.backing, closed: $1.closed, id: $0.id, lastMessage: $1.lastMessage, participant: $1.participant, project: $0, unreadMessagesCount: $1.unreadMessagesCount) } ) public static let lastMessage = Lens<MessageThread, Message>( view: { $0.lastMessage }, set: { .init(backing: $1.backing, closed: $1.closed, id: $0.id, lastMessage: $0, participant: $1.participant, project: $1.project, unreadMessagesCount: $1.unreadMessagesCount) } ) public static let unreadMessagesCount = Lens<MessageThread, Int>( view: { $0.unreadMessagesCount }, set: { .init(backing: $1.backing, closed: $1.closed, id: $1.id, lastMessage: $1.lastMessage, participant: $1.participant, project: $1.project, unreadMessagesCount: $0) } ) } }
apache-2.0
99f467dbd7079852a67a225b6c2cc0aa
43.5
106
0.646067
3.725581
false
false
false
false
YunsChou/LovePlay
LovePlay-Swift3/LovePlay/Class/Zone/Controller/ZoneListViewController.swift
1
4983
// // ZoneListViewController.swift // LovePlay-UIKit-Swift // // Created by weiying on 2017/3/10. // Copyright © 2017年 yuns. All rights reserved. // import UIKit import Alamofire class ZoneListViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var zoneDatas : [ZoneListModel]? = [ZoneListModel]() override func viewDidLoad() { super.viewDidLoad() self.addSubViews() self.loadData() } // MARK: - private private func addSubViews() { self.view.addSubview(self.colletionView) } private func loadData() { let urlStr = BaseURL + ZoneDiscussURL Alamofire.request(urlStr).responseJSON { (response) in print(response) switch response.result.isSuccess { case true : if let value = response.result.value as? NSDictionary { let info = value["info"] as? NSDictionary let discuzList = info?["discuzList"] as? [NSDictionary] for detailList in discuzList! { let listModel = ZoneListModel.deserialize(from: detailList) self.zoneDatas?.append(listModel!) } self.colletionView.reloadData() } case false : print(response.result.error!) } } } // MARK: - collectionView dataSource func numberOfSections(in collectionView: UICollectionView) -> Int { if (self.zoneDatas?.isEmpty)! { return 0 } return (self.zoneDatas?.count)! } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let detailList = self.zoneDatas?[section].detailList { return detailList.count } return 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = ZoneListCell.cellWithCollectionView(collectionView: collectionView, indexPath: indexPath) let detailList = self.zoneDatas?[indexPath.section].detailList let discussItem = detailList?[indexPath.row] cell.listModel = discussItem return cell } // MARK: - collectionView delegate func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let listModel = self.zoneDatas?[indexPath.section] let sectionHeader : ZoneListSectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: NSStringFromClass(ZoneListSectionHeader.self), for: indexPath) as! ZoneListSectionHeader sectionHeader.titleTextLabel.text = listModel?.type?.typeName return sectionHeader } return UICollectionReusableView() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: self.view.bounds.size.width, height: 30) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let detailList = self.zoneDatas?[indexPath.section].detailList let discussItem = detailList?[indexPath.row] let listViewController : DiscussListViewController = DiscussListViewController() listViewController.fid = discussItem?.fid self.navigationController?.pushViewController(listViewController, animated: true) } // MARK: - setter / getter lazy var colletionView : UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: (self.view.bounds.size.width - 1) / 2, height: 70.0) flowLayout.minimumLineSpacing = 1 flowLayout.minimumInteritemSpacing = 1 let colletionView : UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout) colletionView.backgroundColor = RGB(r: 245, g: 245, b: 245) colletionView.delegate = self colletionView.dataSource = self colletionView.alwaysBounceVertical = true colletionView.register(ZoneListCell.self, forCellWithReuseIdentifier: NSStringFromClass(ZoneListCell.self)) colletionView.register(ZoneListSectionHeader.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: NSStringFromClass(ZoneListSectionHeader.self)) return colletionView }() override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
e969ffac19aa9bba14edaffce38173c5
41.20339
227
0.673494
5.496689
false
false
false
false
gregomni/swift
test/Generics/concrete_contraction_unrelated_typealias.swift
2
3330
// RUN: %target-swift-frontend -typecheck -verify %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s // Another GenericSignatureBuilder oddity, reduced from RxSwift. // // The requirements 'Proxy.Parent == P' and 'Proxy.Delegate == D' in the // init() below refer to both the typealias and the associated type, // despite the class being unrelated to the protocol; it just happens to // define typealiases with the same name. // // In the Requirement Machine, the concrete contraction pre-processing // pass would eagerly substitute the concrete type into these two // requirements, producing the useless requirements 'P == P' and 'D == D'. // // Make sure concrete contraction keeps these requirements as-is by // checking the generic signature with and without concrete contraction. class GenericDelegateProxy<P : AnyObject, D> { typealias Parent = P typealias Delegate = D // Here if we resolve Proxy.Parent and Proxy.Delegate to the typealiases, // we get vacuous requirements 'P == P' and 'D == D'. By keeping both // the substituted and original requirement, we ensure that the // unrelated associated type 'Parent' is constrained instead. // CHECK-LABEL: .GenericDelegateProxy.init(_:)@ // CHECK-NEXT: <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : GenericDelegateProxy<P, D>, Proxy : DelegateProxyType> init<Proxy: DelegateProxyType>(_: Proxy.Type) where Proxy: GenericDelegateProxy<P, D>, Proxy.Parent == P, // expected-warning {{redundant same-type constraint 'GenericDelegateProxy<P, D>.Parent' (aka 'P') == 'P'}} Proxy.Delegate == D {} // expected-warning {{redundant same-type constraint 'GenericDelegateProxy<P, D>.Delegate' (aka 'D') == 'D'}} } class SomeClass {} struct SomeStruct {} class ConcreteDelegateProxy { typealias Parent = SomeClass typealias Delegate = SomeStruct // An even more esoteric edge case. Note that this one I made up; only // the first one is relevant for compatibility with RxSwift. // // Here unfortunately we produce a different result from the GSB, because // the hack for keeping both the substituted and original requirement means // the substituted requirements become 'P == SomeClass' and 'D == SomeStruct'. // // The GSB does not constrain P and D in this way and instead produced the // following minimized signature: // // <P, D, Proxy where P == Proxy.[DelegateProxyType]Parent, D == Proxy.[DelegateProxyType]Delegate, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType>! // CHECK-LABEL: .ConcreteDelegateProxy.init(_:_:_:)@ // CHECK-NEXT: <P, D, Proxy where P == SomeClass, D == SomeStruct, Proxy : ConcreteDelegateProxy, Proxy : DelegateProxyType, Proxy.[DelegateProxyType]Delegate == SomeStruct, Proxy.[DelegateProxyType]Parent == SomeClass> // expected-warning@+2 {{same-type requirement makes generic parameter 'P' non-generic}} // expected-warning@+1 {{same-type requirement makes generic parameter 'D' non-generic}} init<P, D, Proxy: DelegateProxyType>(_: P, _: D, _: Proxy.Type) where Proxy: ConcreteDelegateProxy, Proxy.Parent == P, Proxy.Delegate == D {} } protocol DelegateProxyType { associatedtype Parent : AnyObject associatedtype Delegate }
apache-2.0
f038345cc7859beba402f3ad04f9f822
48.701493
221
0.722823
4.428191
false
false
false
false
cipriancaba/SwiftFSM
Example/SwiftFSM/ViewController.swift
1
2290
// // ViewController.swift // SwiftFSM // // Created by Ciprian Caba on 08/01/2015. // Copyright (c) 2015 Ciprian Caba. All rights reserved. // import UIKit import SwiftFSM class ViewController: UIViewController { fileprivate let fsm = SwiftFSM<TurnstileState, TurnstileTransition>(id: "TurnstileFSM", willLog: false) @IBOutlet var stateTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() stateTextView.isEditable = false // add new states and get a reference to them so you can map handlers and define transitions let locked = fsm.addState(.Locked) // Define an inline onEnter handler locked.onEnter = { (transition: TurnstileTransition) -> Void in self.append("Entered the \(self.fsm.currentState) state with the \(transition) transition") } // Define as many transitions to any states (including itself) locked.addTransition(.Push, to: .Locked) locked.addTransition(.Coin, to: .Unlocked) let unlocked = fsm.addState(.Unlocked) // Define handlers as reference unlocked.onEnter = handleUnlocked // Listen to onExit event unlocked.onExit = handleUnlockedExit unlocked.addTransition(.Coin, to: .Unlocked) unlocked.addTransition(.Push, to: .Locked) // Start the fsm in a specific state.. Please note that this will not trigger the initial onEnter callback fsm.startFrom(.Locked) } func handleUnlocked(_ transition: TurnstileTransition) { append("Entered the \(self.fsm.currentState) state with the \(transition) transition") } func handleUnlockedExit(_ transition: TurnstileTransition) { append("Turnstile fsm exited the Unlocked state with the \(transition) transition") } func append(_ message: String) { guard let text = self.stateTextView.text else { return } stateTextView.text = "\(text)\n\(message)" stateTextView.scrollRangeToVisible(NSMakeRange(stateTextView.text.characters.count - 1, 1)) } @IBAction func onCoin(_ sender: AnyObject) { if let _ = fsm.transitionWith(.Coin) { // state change happened } else { // transition was not valid } } @IBAction func onPush(_ sender: AnyObject) { fsm.transitionWith(.Push) } }
mit
d072e20663116a70a2b9f3403c6a9fee
28.358974
110
0.68559
4.361905
false
false
false
false
Wolox/wolmo-core-ios
WolmoCoreTests/Utilities/AssociatedObjectSpec.swift
1
3646
// // AssociatedObjectSpec.swift // WolmoCore // // Created by Francisco Depascuali on 7/18/16. // Copyright © 2016 Wolox. All rights reserved. // import Foundation import Quick import Nimble import WolmoCore private class AssociatableObjectClassMock { var x: Int init(x: Int = 4) { self.x = x } } private struct AssociatableObjectStructMock { let x: Int init(x: Int = 4) { self.x = x } } private var key: Int = 0 public class AssociatedObjectSpec: QuickSpec { override public func spec() { var associatableObject: AssociatableObjectClassMock! // It has to be an AnyObject (AKA: class) var classToAssociate: AssociatableObjectClassMock! var structToAssociate: AssociatableObjectStructMock! beforeEach { associatableObject = AssociatableObjectClassMock() classToAssociate = AssociatableObjectClassMock() structToAssociate = AssociatableObjectStructMock() } afterEach { setAssociatedObject(associatableObject, key: &key, value: Optional<Int>.none) } describe("setAssociatedObject") { context("When the value to associate the object to is a class") { it("should set an associated object") { setAssociatedObject(associatableObject, key: &key, value: classToAssociate) let associated: AssociatableObjectClassMock = getAssociatedObject(associatableObject, key: &key)! expect(associated.x).to(equal(classToAssociate.x)) } } context("When the value to associate the object to is a struct") { it("should set an associated object") { setAssociatedObject(associatableObject, key: &key, value: structToAssociate) let associated: AssociatableObjectStructMock = getAssociatedObject(associatableObject, key: &key)! expect(associated.x).to(equal(structToAssociate.x)) } } } describe("#getAssociatedObject") { context("When there is no associated value") { it("should return nil") { let value: Int? = getAssociatedObject(associatableObject, key: &key) expect(value).to(beNil()) } } context("when there is an associated value") { beforeEach { setAssociatedObject(associatableObject, key: &key, value: classToAssociate) } it("should return the associated value") { let a: AssociatableObjectClassMock = getAssociatedObject(associatableObject, key: &key)! expect(a.x).to(equal(classToAssociate.x)) } context("when there is a new associated value") { var newObjectToAssociate: AssociatableObjectClassMock! beforeEach { newObjectToAssociate = AssociatableObjectClassMock(x: 2) setAssociatedObject(associatableObject, key: &key, value: newObjectToAssociate) } it("should return the new associated value") { let a: AssociatableObjectClassMock = getAssociatedObject(associatableObject, key: &key)! expect(a.x).to(equal(newObjectToAssociate.x)) } } } } } }
mit
a4cb3cfe0ea915949359f566d4c15aa4
36.193878
118
0.566804
5.229555
false
false
false
false
williamFalcon/WFLocationService
WFLocationService/Extensions/LocationManagerDelegate/LocationService+LocationManagerDelegate.swift
1
2894
// // LocationService+LocationManagerDelegate.swift // // // Created by William Falcon on 6/17/15. // Copyright (c) 2015 William Falcon. All rights reserved. // import Foundation import CoreLocation extension LocationService : CLLocationManagerDelegate { func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { //update own coordinates let (loc, wasBetter) = mostAccurateLocation(newLocation) //update user only if the location is better if wasBetter { let lat = loc.coordinate.latitude let lon = loc.coordinate.longitude let accuracy = loc.horizontalAccuracy progressBlock?(latitude: lat, longitude: lon, accuracy: accuracy, locationObject: loc) //Print the new coordinates print("LocationService: Location updated:\nLat \(lat)\nLon \(lon)\n") } } ///Called when user updates authorization func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { startUpdatingLocationIfAuthorized(status) } ///Returns the most accurate location we've seen so far. Updates the last known loc. private func mostAccurateLocation(newLocation: CLLocation) -> (mostAccurateLocation :CLLocation, wasBetterLocation : Bool) { //get last location from manager. //if no last set, then use the newLocation let manager = LocationService.sharedInstance var wasBetter = (manager.updateCount == 0) if wasBetter { manager.updateCount += 1 } var lastKnown = manager.lastKnownLocation ?? newLocation //update if more accurate if lastKnown.horizontalAccuracy < newLocation.horizontalAccuracy { lastKnown = newLocation wasBetter = true manager.updateCount += 1 } //update manager manager.lastKnownLocation = lastKnown return (mostAccurateLocation :newLocation, wasBetterLocation : wasBetter) } ///Starts updating location if authorized private func startUpdatingLocationIfAuthorized(status: CLAuthorizationStatus) { //CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways // Update delegate's location if user allows authorization print("LocationService: Authorization status changed") if canAccessLocation() { self.startUpdatingLocation() }else if (status == CLAuthorizationStatus.Denied) { let error = NSError(domain: "LocationService", code: 1, userInfo: [NSLocalizedFailureReasonErrorKey:"User did not enable location services!"]) failUpdateBlock?(error: error) } } }
mit
c72f530c9a9b9ef3fc749263208092b1
37.586667
154
0.667243
5.753479
false
false
false
false
trill-lang/LLVMSwift
Sources/LLVM/BasicBlock.swift
1
7986
#if SWIFT_PACKAGE import cllvm #endif /// A `BasicBlock` represents a basic block in an LLVM IR program. A basic /// block contains a sequence of instructions, a pointer to its parent block and /// its follower block, and an optional label that gives the basic block an /// entry in the symbol table. Because of this label, the type of every basic /// block is `LabelType`. /// /// A basic block can be thought of as a sequence of instructions, and indeed /// its member instructions may be iterated over with a `for-in` loop. A well- /// formed basic block has as its last instruction a "terminator" that produces /// a transfer of control flow and possibly yields a value. All other /// instructions in the middle of the basic block may not be "terminator" /// instructions. Basic blocks are not required to be well-formed until /// code generation is complete. /// /// Creating a Basic Block /// ====================== /// /// By default, the initializer for a basic block merely creates the block but /// does not associate it with a function. /// /// let module = Module(name: "Example") /// let fun = builder.addFunction("example", /// type: FunctionType([], VoidType())) /// /// // This basic block is "floating" outside of a function. /// let floatingBB = BasicBlock(name: "floating") /// // Until we associate it with a function by calling `Function.append(_:)`. /// fun.append(floatingBB) /// /// A basic block may be created and automatically inserted at the end of a /// function by calling `Function.appendBasicBlock(named:in:)`. /// /// let module = Module(name: "Example") /// let fun = builder.addFunction("example", /// type: FunctionType([], VoidType())) /// /// // This basic block is "attached" to the example function. /// let attachedBB = fun.appendBasicBlock(named: "attached") /// /// The Address of a Basic Block /// ============================ /// /// Basic blocks (except the entry block) may have their labels appear in the /// symbol table. Naturally, these labels are associated with address values /// in the final object file. The value of that address may be accessed for the /// purpose of an indirect call or a direct comparisson by calling /// `Function.address(of:)` and providing one of the function's child blocks as /// an argument. Providing any other basic block outside of the function as an /// argument value is undefined. /// /// The Entry Block /// =============== /// /// The first basic block (the entry block) in a `Function` is special: /// /// - The entry block is immediately executed when the flow of control enters /// its parent function. /// - The entry block is not allowed to have predecessor basic blocks /// (i.e. there cannot be any branches to the entry block of a function). /// - The address of the entry block is not a well-defined value. /// - The entry block cannot have PHI nodes. This is enforced structurally, /// as the entry block can have no predecessor blocks to serve as operands /// to the PHI node. /// - Static `alloca` instructions situated in the entry block are treated /// specially by most LLVM backends. For example, FastISel keeps track of /// static `alloca` values in the entry block to more efficiently reference /// them from the base pointer of the stack frame. public struct BasicBlock: IRValue { internal let llvm: LLVMBasicBlockRef /// Creates a `BasicBlock` from an `LLVMBasicBlockRef` object. public init(llvm: LLVMBasicBlockRef) { self.llvm = llvm } /// Creates a new basic block without a parent function. /// /// The basic block should be inserted into a function or destroyed before /// the IR builder is finalized. public init(context: Context = .global, name: String = "") { self.llvm = LLVMCreateBasicBlockInContext(context.llvm, name) } /// Given that this block and a given block share a parent function, move this /// block before the given block in that function's basic block list. /// /// - Parameter position: The basic block that acts as a position before /// which this block will be moved. public func move(before position: BasicBlock) { LLVMMoveBasicBlockBefore(self.asLLVM(), position.asLLVM()) } /// Given that this block and a given block share a parent function, move this /// block after the given block in that function's basic block list. /// /// - Parameter position: The basic block that acts as a position after /// which this block will be moved. public func move(after position: BasicBlock) { LLVMMoveBasicBlockAfter(self.asLLVM(), position.asLLVM()) } /// Retrieves the underlying LLVM value object. public func asLLVM() -> LLVMValueRef { return llvm } /// Retrieves the name of this basic block. public var name: String { let cstring = LLVMGetBasicBlockName(self.llvm) return String(cString: cstring!) } /// Returns the first instruction in the basic block, if it exists. public var firstInstruction: IRInstruction? { guard let val = LLVMGetFirstInstruction(llvm) else { return nil } return Instruction(llvm: val) } /// Returns the first instruction in the basic block, if it exists. public var lastInstruction: IRInstruction? { guard let val = LLVMGetLastInstruction(llvm) else { return nil } return Instruction(llvm: val) } /// Returns the terminator instruction if this basic block is well formed or /// `nil` if it is not well formed. public var terminator: TerminatorInstruction? { guard let term = LLVMGetBasicBlockTerminator(llvm) else { return nil } return TerminatorInstruction(llvm: term) } /// Returns the parent function of this basic block, if it exists. public var parent: Function? { guard let functionRef = LLVMGetBasicBlockParent(llvm) else { return nil } return Function(llvm: functionRef) } /// Returns the basic block following this basic block, if it exists. public func next() -> BasicBlock? { guard let blockRef = LLVMGetNextBasicBlock(llvm) else { return nil } return BasicBlock(llvm: blockRef) } /// Returns the basic block before this basic block, if it exists. public func previous() -> BasicBlock? { guard let blockRef = LLVMGetPreviousBasicBlock(llvm) else { return nil } return BasicBlock(llvm: blockRef) } /// Returns a sequence of the Instructions that make up this basic block. public var instructions: AnySequence<IRInstruction> { var current = firstInstruction return AnySequence<IRInstruction> { return AnyIterator<IRInstruction> { defer { current = current?.next() } return current } } } /// Removes this basic block from a function but keeps it alive. /// /// - note: To ensure correct removal of the block, you must invalidate any /// references to it and its child instructions. The block must also /// have no successor blocks that make reference to it. public func removeFromParent() { LLVMRemoveBasicBlockFromParent(llvm) } /// Moves this basic block before the given basic block. public func moveBefore(_ block: BasicBlock) { LLVMMoveBasicBlockBefore(llvm, block.llvm) } /// Moves this basic block after the given basic block. public func moveAfter(_ block: BasicBlock) { LLVMMoveBasicBlockAfter(llvm, block.llvm) } } extension BasicBlock { /// An `Address` represents a function-relative address of a basic block for /// use with the `indirectbr` instruction. public struct Address: IRValue { internal let llvm: LLVMValueRef internal init(llvm: LLVMValueRef) { self.llvm = llvm } /// Retrieves the underlying LLVM value object. public func asLLVM() -> LLVMValueRef { return llvm } } } extension BasicBlock: Equatable { public static func == (lhs: BasicBlock, rhs: BasicBlock) -> Bool { return lhs.asLLVM() == rhs.asLLVM() } }
mit
474762066252dc070207d9dcdf7d48c4
37.76699
82
0.690834
4.312095
false
false
false
false
jonnguy/HSTracker
HSTracker/Core/SizeHelper.swift
1
11550
// // SizeHelper.swift // HSTracker // // Created by Benjamin Michotte on 28/02/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import AppKit struct SizeHelper { static let BaseWidth: CGFloat = 1440.0 static let BaseHeight: CGFloat = 922.0 class HearthstoneWindow { var _frame = NSRect.zero var windowId: CGWindowID? var screenRect = NSRect() init() { reload() } private func area(dict: NSDictionary) -> Int { let h = (dict["kCGWindowBounds"] as? NSDictionary)?["Height"] as? Int ?? 0 let w = (dict["kCGWindowBounds"] as? NSDictionary)?["Height"] as? Int ?? 0 return w * h } func reload() { let options = CGWindowListOption(arrayLiteral: .excludeDesktopElements) let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0)) if let info = (windowListInfo as? [NSDictionary])?.filter({dict in dict["kCGWindowOwnerName"] as? String == CoreManager.applicationName }).sorted(by: { return area(dict: $1) > area(dict: $0) }).last { if let id = info["kCGWindowNumber"] as? Int { self.windowId = CGWindowID(id) } // swiftlint:disable force_cast let bounds = info["kCGWindowBounds"] as! CFDictionary // swiftlint:enable force_cast if let rect = CGRect(dictionaryRepresentation: bounds) { var frame = rect // Warning: this function assumes that the // first screen in the list is the active one if let screen = NSScreen.screens.first { screenRect = screen.frame frame.origin.y = screen.frame.maxY - rect.maxY } //logger.debug("HS Frame is : \(rect)") self._frame = frame } } } fileprivate var width: CGFloat { return _frame.width } fileprivate var height: CGFloat { let height = _frame.height return isFullscreen() ? height : max(height - 22, 0) } fileprivate var left: CGFloat { return _frame.minX } fileprivate var top: CGFloat { return _frame.minY } fileprivate func isFullscreen() -> Bool { return _frame.minX == 0.0 && _frame.minY == 0.0 && (Int(_frame.height) & 22) != 22 } var frame: NSRect { return NSRect(x: left, y: top, width: width, height: height) } var scaleX: CGFloat { return width / SizeHelper.BaseWidth } var scaleY: CGFloat { return height / SizeHelper.BaseHeight } // // Get a frame relative to Hearthstone window // All size are taken from a resolution of BaseWidth*BaseHeight (my MBA resolution) // and translated to your resolution // func relativeFrame(_ frame: NSRect, relative: Bool = true) -> NSRect { var pointX = frame.minX var pointY = frame.minY let width = frame.width let height = frame.height if relative { pointX *= scaleX pointY *= scaleY } let x = self.frame.minX + pointX let y = self.frame.minY + pointY let relativeFrame = NSRect(x: x, y: y, width: width, height: height) //logger.verbose("FR:\(frame) -> HS:\(hearthstoneFrame) -> POS:\(relativeFrame)") return relativeFrame } func screenshot() -> NSImage? { guard let windowId = self.windowId else { return nil } if let image = CGWindowListCreateImage(CGRect.null, .optionIncludingWindow, windowId, [.nominalResolution, .boundsIgnoreFraming]) { return NSImage(cgImage: image, size: NSSize(width: image.width, height: image.height)) } return nil } } static let hearthstoneWindow = HearthstoneWindow() static func overHearthstoneFrame() -> NSRect { let frame = hearthstoneWindow.frame return hearthstoneWindow.relativeFrame(frame) } static fileprivate var trackerWidth: CGFloat { let width: Double switch Settings.cardSize { case .tiny: width = kTinyFrameWidth case .small: width = kSmallFrameWidth case .medium: width = kMediumFrameWidth case .big: width = kFrameWidth case .huge: width = kHighRowFrameWidth } return CGFloat(width) } static fileprivate func trackerFrame(xOffset: CGFloat, yOffset: CGFloat = 0) -> NSRect { // game menu let offset: CGFloat = hearthstoneWindow.isFullscreen() ? 0 : 50 let width: CGFloat switch Settings.cardSize { case .tiny: width = CGFloat(kTinyFrameWidth) case .small: width = CGFloat(kSmallFrameWidth) case .medium: width = CGFloat(kMediumFrameWidth) case .big: width = CGFloat(kFrameWidth) case .huge: width = CGFloat(kHighRowFrameWidth) } let frame = NSRect(x: xOffset, y: offset, width: max(trackerWidth, width), height: max(100, hearthstoneWindow.frame.height - offset - yOffset)) return hearthstoneWindow.relativeFrame(frame, relative: false) } fileprivate static func getScaledXPos(_ left: CGFloat, width: CGFloat, ratio: CGFloat) -> CGFloat { return ((width) * ratio * left) + (width * (1 - ratio) / 2) } static func searchLocation() -> NSPoint { let hsRect = hearthstoneWindow.frame let ratio = (4.0 / 3.0) / (hsRect.width / hsRect.height) let exportSearchBoxX: CGFloat = 0.5 let exportSearchBoxY: CGFloat = 0.915 var loc = NSPoint(x: getScaledXPos(exportSearchBoxX, width: hsRect.width, ratio: ratio), y: exportSearchBoxY * hsRect.height) // correct location with window origin. loc.x += hsRect.origin.x loc.y += ( hearthstoneWindow.screenRect.height - hsRect.origin.y - hsRect.size.height) return loc } static func firstCardFrame() -> NSRect { let location = firstCardLocation() return NSRect(x: location.x - 100, y: location.y + 180, width: 300, height: 100) } static func firstCardLocation() -> NSPoint { let hsRect = hearthstoneWindow.frame let ratio = (4.0 / 3.0) / (hsRect.width / hsRect.height) let cardPosOffset: CGFloat = 50 let exportCard1X: CGFloat = 0.04 let exportCard1Y: CGFloat = 0.168 let cardPosX = getScaledXPos(exportCard1X, width: hsRect.width, ratio: ratio) let cardPosY = exportCard1Y * hsRect.height var loc = NSPoint(x: cardPosX + cardPosOffset, y: cardPosY + cardPosOffset) // correct location with window origin. loc.x += hsRect.origin.x loc.y += (hearthstoneWindow.screenRect.height - hsRect.origin.y - hsRect.size.height) return loc } static func secondCardLocation() -> NSPoint { var loc = firstCardLocation() loc.x += 190 return loc } static func playerTrackerFrame() -> NSRect { return trackerFrame(xOffset: hearthstoneWindow.frame.width - trackerWidth) } static func opponentTrackerFrame() -> NSRect { var yOffset: CGFloat = 0 if Settings.preventOpponentNameCovering { yOffset = hearthstoneWindow.frame.height * 0.125 // name height ratio } return trackerFrame(xOffset: 0, yOffset: yOffset) } static func playerBoardDamageFrame() -> NSRect { let frame = NSRect(x: 923.0, y: 225.0, width: 50.0, height: 50.0) return hearthstoneWindow.relativeFrame(frame) } static func opponentBoardDamageFrame() -> NSRect { let frame = NSRect(x: 915.0, y: 667.0, width: 50.0, height: 50.0) return hearthstoneWindow.relativeFrame(frame) } static func arenaHelperFrame() -> NSRect { let height: CGFloat = 450 let frame = NSRect(x: 0, y: (hearthstoneWindow.frame.height / 2) - (height / 2), width: trackerWidth, height: height) return hearthstoneWindow.relativeFrame(frame) } static func secretTrackerFrame(height: CGFloat) -> NSRect { let yOffset: CGFloat = hearthstoneWindow.isFullscreen() ? 0 : 50 let frame = NSRect(x: trackerWidth + 25, y: hearthstoneWindow.frame.height - height - yOffset, width: trackerWidth, height: height) return hearthstoneWindow.relativeFrame(frame, relative: false) } static func timerHudFrame() -> NSRect { let frame = NSRect(x: 999.0, y: 423.0, width: 160.0, height: 115.0) return hearthstoneWindow.relativeFrame(frame) } static func battlegroundsOverlayFrame() -> NSRect { let top = 0.85 * hearthstoneWindow.height let bottom = 0.15 * hearthstoneWindow.height // Looks like the HS board ratio is 1.5, the rest is padding let boardWidth = hearthstoneWindow.height * 1.5 let left = 0.05 * boardWidth + (hearthstoneWindow.width - boardWidth)/2 let right = 0.125 * boardWidth + (hearthstoneWindow.width - boardWidth)/2 return NSRect(x: left, y: bottom, width: right - left, height: top - bottom) } static func battlegroundsDetailsFrame() -> NSRect { let w: CGFloat = BaseWidth - 2 * (trackerWidth + 20) let h: CGFloat = 120 let frame = NSRect(x: trackerWidth + 20, y: BaseHeight - h, width: w, height: h) return hearthstoneWindow.relativeFrame(frame) } static func collectionFeedbackFrame() -> NSRect { let w: CGFloat = 450.0 let h: CGFloat = 80.0 let offset: CGFloat = 20.0 let frame = NSRect(x: (BaseWidth - w)/2, y: (BaseHeight - offset - h), width: w, height: h) return hearthstoneWindow.relativeFrame(frame) } static let cardHudContainerWidth: CGFloat = 400 static let cardHudContainerHeight: CGFloat = 80 static func cardHudContainerFrame() -> NSRect { let w = SizeHelper.cardHudContainerWidth * hearthstoneWindow.scaleX let h = SizeHelper.cardHudContainerHeight * hearthstoneWindow.scaleY let frame = NSRect(x: (hearthstoneWindow.frame.width / 2) - (w / 2), y: hearthstoneWindow.frame.height - h, width: w, height: h) return hearthstoneWindow.relativeFrame(frame, relative: false) } }
mit
12fcbdc286a3cedb4625a3bf722c7c6c
35.547468
99
0.555113
4.666263
false
false
false
false
googlecreativelab/justaline-ios
RoomManager.swift
1
26557
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Firebase import FirebaseAuth import FirebaseDatabase import FirebaseAnalytics protocol RoomManagerDelegate { func localStrokeRemoved(_ stroke: Stroke) func updatePartnerAnchorReadiness(partnerReady: Bool, isHost: Bool) func partnerJoined(isHost: Bool, isPairing: Bool?) func pairingFailed() func partnerLost() func partnerStrokeUpdated(_ stroke: Stroke, id key: String) func partnerStrokeRemoved(id key: String) func anchorIdCreated(_ id: String) func anchorNotAvailable() func anchorResolved() func roomCreated(_ roomData: RoomData) func leaveRoom() } class RoomManager: StrokeUploaderDelegate { // MARK: Variables /// Auth var firebaseAuth: Auth? /// User ID var userUid: String? /// Store anchor id after it is added to prevent repeatedely resolving var anchorId: String? /// Delegate property for PairingManager var delegate: RoomManagerDelegate? var strokeUploader: StrokeUploadManager var hasStrokeData: Bool = false var isHost: Bool = false private let ROOT_FIREBASE_ROOMS = "rooms" var ROOT_GLOBAL_ROOM = "global_room_0" private let DISPLAY_NAME_VALUE = "Just a Line" private var app: FirebaseApp? private var roomRef: DatabaseReference? private var roomKey: String? private var roomCodeRef: DatabaseReference? private var hotspotListRef: DatabaseReference? private var roomsListRef: DatabaseReference? private var participantsRef: DatabaseReference? private var strokesRef: DatabaseReference? private var globalRoomRef: DatabaseReference? var isRoomResolved: Bool = false private var anchorValueHandle: UInt? private var anchorRemovedHandle: UInt? private var lineAddedHandle: UInt? private var partners = [String]() private var partnerAddedHandle: UInt? private var partnerUpdatedHandle: UInt? private var partnerRemovedHandle: UInt? private var partnerMovedHandle: UInt? private var strokeAddedHandle: UInt? private var strokeUpdatedHandle: UInt? private var strokeRemovedHandle: UInt? private var strokeMovedHandle: UInt? private var localStrokeUids = [String: Stroke]() /// Flag to indicate that we are using the global room, but pairing and resolving an anchor private var pairing: Bool = false var isRetrying = false // private var stroke // MARK: - Initialization init() { strokeUploader = StrokeUploadManager() strokeUploader.delegate = self // Firebase setup firebaseAuth = Auth.auth() firebaseLogin() app = FirebaseApp.app() if (app != nil) { let rootRef = Database.database().reference() roomsListRef = rootRef.child(ROOT_FIREBASE_ROOMS) globalRoomRef = rootRef.child(ROOT_GLOBAL_ROOM) DatabaseReference.goOnline(); } else { print("RoomManager: Could not connect to Firebase Database!") roomsListRef = nil globalRoomRef = nil } } func updateGlobalRoomName(_ name: String) { let rootRef = Database.database().reference() ROOT_GLOBAL_ROOM = name globalRoomRef = rootRef.child(ROOT_GLOBAL_ROOM) } /// Login with existing id or create a new one private func firebaseLogin() { if let currentUser = firebaseAuth?.currentUser { userUid = currentUser.uid print("firebaseLogin: user uid \(String(describing:userUid))") } else { loginAnonymously(); } } /// Create new user id with anonymous sign-in private func loginAnonymously() { firebaseAuth?.signInAnonymously(completion: { (user, error) in // need to handle error states if (error == nil) { if let currentUser = self.firebaseAuth?.currentUser { self.userUid = currentUser.uid print("loginAnonymously: user uid \(String(describing: self.userUid))") } } }) } // MARK: - Room Flow /// When pairing both users create a room func createRoom() { print("RoomManager:createRoom") if let room = roomsListRef?.childByAutoId() { updateRoomReference(room) } print("RoomManager:createRoom: Trying Room Number: \(String(describing:(roomRef?.key)))") let timestamp = Int64(Date().timeIntervalSince1970 * 1000) self.roomRef?.child(FBKey.val(.updated_at_timestamp)).setValue(timestamp) self.roomRef?.child(FBKey.val(.displayName)).setValue(self.DISPLAY_NAME_VALUE) pairing = true participateInRoom() if let roomString = roomKey { let roomData = RoomData(code: roomString, timestamp: timestamp) self.delegate?.roomCreated(roomData) } else { StateManager.updateState(.UNKNOWN_ERROR) } } /// Takes database ref for either new or joined room and updates the key and participants ref /// /// - Parameter room: Database Reference for firebase room func updateRoomReference(_ room: DatabaseReference) { roomRef = room roomKey = room.key } /// Add self as a participant in the current room func participateInRoom() { if let uid = self.userUid, let partnersRef = roomRef?.child(FBKey.val(.participants)) { participantsRef = partnersRef // Add to participants list with false value until room is resolved for the originating user to discover let participant = FBParticipant(readyToSetAnchor: false) participant.isPairing = pairing partnersRef.child(uid).setValue(participant.dictionaryValue()) partnersRef.child(uid).onDisconnectSetValue(nil) self.partnerJoinedCallbacks(uid:uid, reference:partnersRef) } } /// RoomData conveyed via Nearby func roomFound(_ roomData: RoomData) { if (shouldJoinRoom(roomData)) { self.delegate?.leaveRoom() joinRoom(roomKey: roomData.code) } } func findGlobalRoom(_ withPairing: Bool = false) { guard let globalRoom = globalRoomRef else { return } pairing = withPairing globalRoom.observeSingleEvent(of: .value) { (snapshot) in if let roomString = snapshot.value as? String { self.joinRoom(roomKey: roomString) } } } /// If no room has been created, join, otherwise only choose if my room number is lower private func shouldJoinRoom(_ roomData: RoomData)->Bool { guard let roomString = self.roomKey else { return true } return roomString.compare(roomData.code) == ComparisonResult.orderedDescending } /// Adds user id to participants list, and begins watching for an anchor func joinRoom(roomKey: String) { print("RoomManager:joinRoom: Joining Room: \(roomKey)") guard let _ = app, let _ = userUid else { return } if let room = roomsListRef?.child(roomKey) { updateRoomReference(room) participateInRoom() #if JOIN_GLOBAL_ROOM // if pairing with another device, remove anchor to start fresh // otherwise try to obtain an existing anchor id if pairing == false { self.observeAnchor() } #endif } } func resumeRoom() { guard let _ = roomRef else { return } participateInRoom() } /// Sets Firebase flags for participant and anchor, begins observing stroke ref for child changes func resolveRoom() { guard let room = roomRef, let uid = userUid else { return } self.isRoomResolved = true let participant = FBParticipant(anchorResolved: true, isPairing: false) participantsRef?.child(uid).setValue(participant.dictionaryValue()) room.child(FBKey.val(.anchor)).child(FBKey.val(.anchorResolutionError)).setValue(false) } func stopObservingLines() { print("Stopped observing lines") if let handle = strokeAddedHandle { strokesRef?.removeObserver(withHandle: handle) } if let handle = strokeUpdatedHandle { print ("stroke update handle removed for \(String(describing: strokesRef))") strokesRef?.removeObserver(withHandle: handle) } if let handle = strokeRemovedHandle { strokesRef?.removeObserver(withHandle: handle) } if let handle = strokeMovedHandle { strokesRef?.removeObserver(withHandle: handle) } strokesRef?.removeAllObservers() } func leaveRoom() { isRoomResolved = false isHost = false partners.removeAll() localStrokeUids.removeAll() if let handle = partnerAddedHandle { participantsRef?.removeObserver(withHandle: handle) } if let handle = partnerUpdatedHandle { participantsRef?.removeObserver(withHandle: handle) } if let handle = partnerRemovedHandle { participantsRef?.removeObserver(withHandle: handle) } if let handle = partnerMovedHandle { participantsRef?.removeObserver(withHandle: handle) } stopObservingLines() participantsRef?.removeAllObservers() anchorId = nil anchorValueHandle = nil anchorRemovedHandle = nil partnerAddedHandle = nil partnerUpdatedHandle = nil partnerRemovedHandle = nil partnerMovedHandle = nil strokeAddedHandle = nil strokeUpdatedHandle = nil strokeRemovedHandle = nil strokeMovedHandle = nil strokesRef = nil guard let room = roomRef, let uid = userUid else { return } // remove user from participants list participantsRef?.child(uid).removeValue() participantsRef = nil if let handle = anchorValueHandle { room.removeObserver(withHandle: handle) } if let handle = anchorRemovedHandle { room.removeObserver(withHandle: handle) } room.removeAllObservers() roomRef = nil roomKey = nil } // MARK: Partner Callbacks /// Observers for "participants" DatabaseReference. When participant is initially added, their id is the key, /// and the value indicates whether the anchor has been resolved /// /// - Parameters: /// - uid: userUid value /// - reference: path to participants in FB func partnerJoinedCallbacks(uid: String, reference: DatabaseReference) { print("Partner Callbacks Reference: \(reference)") // Partner Added self.partnerAddedHandle = reference.observe(.childAdded, with: { (snapshot) in print("RoomManager:partnerJoinedCallbacks: Partner Added Observer") if snapshot.key != uid { if let participantDict = snapshot.value as? [String: Any?] { self.partners.append(snapshot.key) let participant = FBParticipant.from(participantDict) if participant?.isPairing == true && self.pairing == true { // Host for global room pairing is alphabetical since we don't establish with Nearby pub/sub let keyComparison = uid.compare(snapshot.key) self.isHost = (keyComparison == ComparisonResult.orderedDescending) ? false : true #if JOIN_GLOBAL_ROOM let state:State = (self.isHost) ? .HOST_CONNECTED : .PARTNER_CONNECTED StateManager.updateState(state) #endif } self.delegate?.partnerJoined(isHost: self.isHost, isPairing: participant?.isPairing) } } }) { (error) in print("Partner Added Observer Cancelled") } // Partner Changed self.partnerUpdatedHandle = reference.observe(.childChanged, with: { (snapshot) in print("RoomManager:partnerJoinedCallbacks: Partner Changed Observer") if let participantDict = snapshot.value as? [String: Any?], let participant = FBParticipant.from(participantDict) , snapshot.key != uid { self.delegate?.updatePartnerAnchorReadiness(partnerReady: participant.readyToSetAnchor, isHost: self.isHost) // if host is true, we are pairing (when partner finishes resolving room, they set isPairing to false) and can resolve room // if partner, host still hasn't resolved room, so isPairing is still true if (participant.anchorResolved == true && (self.isHost == true)) { // || participant.isPairing == true)) { self.delegate?.anchorResolved() } } }) { (error) in print("Partner Changed Observer Cancelled") } // Partner Removed self.partnerRemovedHandle = reference.observe(.childRemoved, with: { (snapshot) in print("RoomManager:partnerJoinedCallbacks: Partner Removed Observer") if let partnerIndex = self.partners.index(of: snapshot.key) { self.partners.remove(at: partnerIndex) if self.partners.count < 1 { self.delegate?.partnerLost() } } if let participantDict = snapshot.value as? [String: Any?], snapshot.key != uid { let participant = FBParticipant.from(participantDict) if participant?.isPairing == true { StateManager.updateState(.CONNECTION_LOST) } } }) { (error) in print("Partner Removed Observer Cancelled") } // Unused self.partnerMovedHandle = reference.child(uid).observe(.childMoved, with: { (snapshot) in }) { (error) in print("RoomManager:partnerJoinedCallbacks: Partner Moved Observer Cancelled") } } // MARK: - Anchor Flow func observeAnchor() { guard let room = roomRef else { return } let anchorUpdateRef = room.child(FBKey.val(.anchor)) // Clear anchor before adding creation listener, except in global room when not pairing #if !JOIN_GLOBAL_ROOM anchorUpdateRef.removeValue() #else if pairing == true { anchorUpdateRef.removeValue() } #endif anchorValueHandle = anchorUpdateRef.observe(.value, with: { (dataSnapshot) in print("Anchor Value Callback Reference: \(anchorUpdateRef)") if let anchorValue = dataSnapshot.value as? [String: Any?] { print("RoomManager:observeAnchor: FBAnchor object found") // Create anchor object from Firebase model if let anchor = FBAnchor.from(anchorValue) { // Return anchor if anchor.anchorResolutionError == true { // When Joining a global room, if there is a pre-exisintg anchor error, need to show special error var shouldUseGlobalError = false #if JOIN_GLOBAL_ROOM if (self.pairing == false) { shouldUseGlobalError = true } #endif // Even in global pairing (not global joining), we want to set state to host or partner errors if self.isHost || !shouldUseGlobalError { StateManager.updateState(.HOST_RESOLVE_ERROR) } else if !shouldUseGlobalError { StateManager.updateState(.PARTNER_RESOLVE_ERROR) } else { StateManager.updateState(.GLOBAL_NO_ANCHOR) } self.delegate?.pairingFailed() // If there's an anchor error, reset readyToSetAnchor value if let uid = self.userUid { self.participantsRef?.child(uid).child(FBKey.val(.readyToSetAnchor)).setValue(false) } } else if let anchorId = anchor.anchorId, self.isHost == false, self.anchorId != anchorId { print("RoomManager:observeAnchor: Anchor ID found: \(String(describing:anchor.anchorId))") self.anchorId = anchorId var state: State = .PARTNER_CONNECTING #if JOIN_GLOBAL_ROOM if self.pairing == false { state = .GLOBAL_CONNECTING } #endif StateManager.updateState(state) self.delegate?.anchorIdCreated(anchorId) } // Stop watching for anchor changes // anchorUpdateRef.removeAllObservers() } } else { #if JOIN_GLOBAL_ROOM if (self.pairing == false) { StateManager.updateState(.GLOBAL_NO_ANCHOR) } #endif } }) { (error) in print("RoomManager:observeAnchor: Anchor Observe Cancelled") } print("Anchor Removed Callback Reference: \(room)") anchorRemovedHandle = room.observe(.childRemoved, with: { (snapshot) in if snapshot.key == FBKey.val(.anchor) { print("RoomManager:observeAnchor: Anchor object removed") self.delegate?.anchorNotAvailable() } }) } func setReadyToSetAnchor() { guard let partnersRef = participantsRef, let uid = userUid else { return } self.observeAnchor() let participant = FBParticipant(readyToSetAnchor: true) partnersRef.child(uid).setValue(participant.dictionaryValue()) } /// After resolving cloud anchor, set cloud identifier in Firebase for partner to discover func setAnchorId(_ identifier: String) { guard let room = roomRef else { return } self.anchorId = identifier let fbAnchor = FBAnchor(anchorId: identifier) room.child(FBKey.val(.anchor)).setValue(fbAnchor.dictionaryValue()) } func retryResolvingAnchor() { isRoomResolved = false if let anchor = self.anchorId { isRetrying = true localStrokeUids.removeAll() delegate?.anchorIdCreated(anchor) } else { delegate?.pairingFailed() } } func anchorResolved() { if (isRoomResolved == false) { self.resolveRoom() self.observeLines() isHost = false } } func anchorFailedToResolve() { guard let room = roomRef else { return } print("RoomManager: anchorFailedToResolve") if (!isRetrying) { // For global rooms, only send failure to Firebase if it is a hosting failure #if JOIN_GLOBAL_ROOM if (pairing) { let fbAnchor = FBAnchor(anchorResolutionError: true) room.child(FBKey.val(.anchor)).setValue(fbAnchor.dictionaryValue()) } #else let fbAnchor = FBAnchor(anchorResolutionError: true) room.child(FBKey.val(.anchor)).setValue(fbAnchor.dictionaryValue()) #endif } } // MARK: - Strokes /// Watch for changes to lines db ref func observeLines() { guard let room = roomRef, let uid = userUid else { return } strokesRef = room.child(FBKey.val(.lines)) self.strokeUpdateCallbacks(uid: uid, reference: strokesRef!) } /// Gateway for all stroke changes besides clear all /// Updates locally drawn strokes or adds them if they do not already exist func updateStroke(_ stroke: Stroke, shouldRemove: Bool = false) { let localStrokeMatch = localStrokeUids.contains { (key, localStroke) -> Bool in localStroke == stroke } if localStrokeMatch == false { addStroke(stroke) } strokeUploader.queueStroke(stroke, remove: shouldRemove) } private func addStroke(_ stroke: Stroke) { guard let room = roomRef, let uid = userUid else { return } let strokeRef = room.child(FBKey.val(.lines)).childByAutoId() localStrokeUids[strokeRef.key] = stroke stroke.creatorUid = uid stroke.fbReference = strokeRef } func clearAllStrokes() { guard let room = roomRef else { return } room.child(FBKey.val(.lines)).removeValue() } // MARK: StrokeUploadManager Delegate methods func uploadStroke(_ stroke: Stroke, completion: @escaping ((Error?, DatabaseReference) -> Void)) { guard let fbStrokeRef = stroke.fbReference else { return } if(stroke.previousPoints == nil){ let dictValue = stroke.dictionaryValue() print("New Stroke dict: \(dictValue)") if (dictValue.count == 0 || stroke.node == nil) { print("RoomManager: uploadStroke: Stroke new upload cancelled, stroke removed") delegate?.localStrokeRemoved(stroke) } else { fbStrokeRef.setValue(dictValue, withCompletionBlock: completion) } } else { let dictValue = stroke.pointsUpdateDictionaryValue() print("Stroke update dict: \(dictValue)") if (dictValue.count == 0 || stroke.node == nil) { print("RoomManager: uploadStroke: Stroke update upload cancelled, stroke removed") delegate?.localStrokeRemoved(stroke) } else { fbStrokeRef.child(FBKey.val(.points)).updateChildValues(dictValue, withCompletionBlock: completion) } } } func removeStroke(_ stroke: Stroke) { delegate?.localStrokeRemoved(stroke) stroke.fbReference?.removeValue() } // MARK: Stroke Callbacks /// Observers for changes to partner's lines private func strokeUpdateCallbacks(uid: String, reference: DatabaseReference) { print("Stroke Update Callbacks Reference: \(reference)") self.strokeAddedHandle = reference.observe(.childAdded, with: { (snapshot) in if let strokeValue = snapshot.value as? [String: Any?], self.localStrokeUids[snapshot.key] == nil, let stroke = Stroke.from(strokeValue) { print("RoomManager:strokeUpdateCallbacks: Partner Stroke Added Observer") stroke.drawnLocally = false self.delegate?.partnerStrokeUpdated(stroke, id: snapshot.key) } else if let _ = snapshot.value as? [String: Any?], self.localStrokeUids[snapshot.key] != nil { self.hasStrokeData = true } else { print("RoomManager:strokeUpdateCallbacks: Added Observer has wrong value: \(String(describing: snapshot.value))") } }) { (error) in print("Partner Stroke Added Observer Cancelled") } self.strokeUpdatedHandle = reference.observe(.childChanged, with: { (snapshot) in if let strokeValue = snapshot.value as? [String: Any?], self.localStrokeUids[snapshot.key] == nil, let stroke = Stroke.from(strokeValue) { // print("RoomManager:strokeUpdateCallbacks: Partner Stroke Changed Observer") stroke.drawnLocally = false self.delegate?.partnerStrokeUpdated(stroke, id: snapshot.key) } }) { (error) in print("Partner Stroke Changed Observer Cancelled") } self.strokeRemovedHandle = reference.observe(.childRemoved, with: { (snapshot) in print("Partner Stroke Removed Observer") if let stroke = self.localStrokeUids[snapshot.key] { self.delegate?.localStrokeRemoved(stroke) self.localStrokeUids[snapshot.key] = nil } else { self.delegate?.partnerStrokeRemoved(id: snapshot.key) } }) { (error) in print("RoomManager:strokeUpdateCallbacks: Partner Stroke Removed Observer Cancelled") } self.strokeMovedHandle = reference.observe(.childMoved, with: { (snapshot) in }) { (error) in print("Partner Stroke Moved Observer Cancelled") } } }
apache-2.0
471f79cca2667e17f2d007bece2510a8
34.791105
139
0.577738
5.12189
false
false
false
false
craaron/ioscreator
IOS8SwiftPrototypeCellsTutorial/IOS8SwiftPrototypeCellsTutorial/ViewController.swift
37
1238
// // ViewController.swift // IOS8SwiftPrototypeCellsTutorial // // Created by Arthur Knopper on 10/08/14. // Copyright (c) 2014 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UITableViewController { let transportItems = ["Bus","Helicopter","Truck","Boat","Bicycle","Motorcycle","Plane","Train","Car","Scooter","Caravan"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return transportItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("transportCell") as! UITableViewCell cell.textLabel?.text = transportItems[indexPath.row] var imageName = UIImage(named: transportItems[indexPath.row]) cell.imageView?.image = imageName return cell } }
mit
472e480229c8af828d72a857fc428013
24.791667
123
0.695477
4.932271
false
false
false
false
hengchengfei/PrivateCocoaPods
Sources/Extensions.swift
1
2301
import UIKit public extension String { /** 计算height - parameter font: 字体 - parameter width: 约束的宽度 - returns: size */ func sizeWithFont(font:UIFont!,constrainedToWidth width: CGFloat) -> CGSize { return NSString(string: self).boundingRect(with: CGSize(width: width, height: 9999), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:font], context: nil).size } /** 计算width - parameter font: 字体 - parameter height: 约束的高度 - returns: size */ func sizeWithFont(font:UIFont!,constrainedToHeight height: CGFloat) -> CGSize { return NSString(string: self).boundingRect(with: CGSize(width: 9999, height: height), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:font], context: nil).size } /** 删除字符串前后空格 - returns: 处理后的结果 */ func trimSpacesBeforeAndAfter() -> String{ return self.trimmingCharacters(in: .whitespacesAndNewlines) } /** 是否为数字 **/ func isNumber() -> Bool { let number = NSCharacterSet.decimalDigits.inverted if !self.isEmpty && self.rangeOfCharacter(from: number) == nil { return true } return false } /** 处理时间字符串格式化 例如: 2016-11-08 10:10:00 inputFormat: "yyyy-MM-dd HH:mm:ss" outFormat: 想要的格式 例如: "MM-dd" 则输出 11-08 - returns: 处理后的结果 */ func dealTimeString(_ inputFormat:String,outFormat:String,timeString:String) -> String { let inputFormatter = DateFormatter() inputFormatter.locale = Locale(identifier: "en_US") inputFormatter.dateFormat = inputFormat let inputDate = inputFormatter.date(from: timeString) let outputFormatter = DateFormatter() outputFormatter.locale = Locale.current outputFormatter.dateFormat = outFormat let dateString:String = outputFormatter.string(from: inputDate!) return dateString } func toDouble() -> Double { return (self as NSString).doubleValue } }
mit
1c773b7f199f3dcdeda26a37d666d40b
28.712329
208
0.627939
4.654506
false
false
false
false
Teleglobal/MHQuickBlockLib
Example/MHQuickBlockLib/ChatViewController.swift
1
4189
// // ChatViewController.swift // MHQuickBlockLib // // Created by Muhammad Adil on 10/18/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import UIKit import MHQuickBlockLib import RealmSwift open class ChatViewController: UIViewController { internal var dialogId: String! @IBOutlet weak var chatTableView: UITableView! override open func viewDidLoad() { self.navigationItem.title = Messenger.dialogServiceManager.dialogInMemory(self.dialogId)?.name } override open func viewWillAppear(_ animated: Bool) { Messenger.messageServiceManager.addMessageDelegate(self) self.chatTableView.reloadData() } open override func viewWillDisappear(_ animated: Bool) { Messenger.messageServiceManager.removeMessageDelegate(self) } @objc fileprivate func showSendMessageAlertController() { let alertController = UIAlertController(title: "Enter Message", message: "", preferredStyle: UIAlertControllerStyle.alert) let sendAction = UIAlertAction(title: "Send", style: UIAlertActionStyle.default, handler: { _ -> Void /*alert -> Void*/ in let firstTextField = alertController.textFields![0] as UITextField Messenger.messageServiceManager.sendMessage(firstTextField.text!, toDialog: self.dialogId, params: nil, completionBlock: { (_) in }) }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { /*(action : UIAlertAction!)*/ (_ : UIAlertAction!) -> Void in }) alertController.addTextField { (textField: UITextField!) -> Void in textField.placeholder = "Message" } alertController.addAction(sendAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } } extension ChatViewController : MessageServiceDelegate { public func messagesUpdatedForDialog(_ dialogId: String) { if dialogId == self.dialogId { self.chatTableView.reloadData() } } } extension ChatViewController : UITableViewDataSource, UITableViewDelegate { // MARK: - DataSource func messages() -> [Message]? { // Returns dialogs sorted by updatedAt date. if self.dialogId == nil { return nil } return Messenger.messageServiceManager.messegesInMemory(self.dialogId) } // MARK: - UITableViewDataSource public func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let messages = self.messages() { return messages.count } return 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell", for: indexPath) let message: Message = (self.messages()![indexPath.row]) cell.textLabel?.text = message.value(forKey: "text") as? String cell.detailTextLabel?.text = "From: " return cell } // MARK: - UITableViewDelegate public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
bba8426b14c93fb1b84925867d6375e0
30.022222
116
0.553009
6.158824
false
false
false
false
SwiftOnTheServer/DrinkChooser
lib/Redis/RedisMulti+List.swift
1
15914
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /// Extend RedisMulti by adding the List operations extension RedisMulti { /// Add a BLPOP command to the "transaction" /// /// - Parameter keys: The keys of the lists to check for an element. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func blpop(_ keys: String..., timeout: TimeInterval) -> RedisMulti { return blpopArrayofKeys(keys, timeout: timeout) } /// Add a BLPOP command to the "transaction" /// /// - Parameter keys: The array of keys of the lists to check for an element. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func blpopArrayofKeys(_ keys: [String], timeout: TimeInterval) -> RedisMulti { var command = [RedisString("BLPOP")] for key in keys { command.append(RedisString(key)) } command.append(RedisString(Int(timeout))) queuedCommands.append(command) return self } /// Add a BRPOP command to the "transaction" /// /// - Parameter keys: The keys of the lists to check for an element. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func brpop(_ keys: String..., timeout: TimeInterval) -> RedisMulti { return brpopArrayOfKeys(keys, timeout: timeout) } /// Add a BRPOP command to the "transaction" /// /// - Parameter keys: The array of keys of the lists to check for an element. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func brpopArrayOfKeys(_ keys: [String], timeout: TimeInterval) -> RedisMulti { var command = [RedisString("BRPOP")] for key in keys { command.append(RedisString(key)) } command.append(RedisString(Int(timeout))) queuedCommands.append(command) return self } /// Add a BRPOPLPUSH command to the "transaction" /// /// - Parameter source: The list to pop an item from. /// - Parameter destination: The list to push the poped item onto. /// - Parameter timeout: The amount of time to wait or zero to wait forever. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func brpoplpush(_ source: String, destination: String, timeout: TimeInterval) -> RedisMulti { queuedCommands.append([RedisString("BRPOPLPUSH"), RedisString(source), RedisString(destination), RedisString(Int(timeout))]) return self } /// Add a LINDEX command to the "transaction" /// /// - Parameter key: The key. /// - Parameter index: The index of the element to retrieve. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lindex(_ key: String, index: Int) -> RedisMulti { queuedCommands.append([RedisString("LINDEX"), RedisString(key), RedisString(index)]) return self } /// Add a LINSERT command to the "transaction" /// /// - Parameter key: The key. /// - Parameter before: If true, the value is inserted before the pivot. /// - Parameter pivot: The pivot around which the value will be inserted. /// - Parameter value: The value to be inserted. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func linsert(_ key: String, before: Bool, pivot: String, value: String) -> RedisMulti { queuedCommands.append([RedisString("LINSERT"), RedisString(key), RedisString(before ? "BEFORE" : "AFTER"), RedisString(pivot), RedisString(value)]) return self } /// Add a LINSERT command to the "transaction" /// /// - Parameter key: The key. /// - Parameter before: If true, the value is inserted before the pivot. /// - Parameter pivot: The pivot, in the form of a `RedisString`, around which /// the value will be inserted. /// - Parameter value: The value, in the form of a `RedisString`, to be inserted. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func linsert(_ key: String, before: Bool, pivot: RedisString, value: RedisString) -> RedisMulti { queuedCommands.append([RedisString("LINSERT"), RedisString(key), RedisString(before ? "BEFORE" : "AFTER"), pivot, value]) return self } /// Add a LLEN command to the "transaction" /// /// - Parameter key: The key. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func llen(_ key: String) -> RedisMulti { queuedCommands.append([RedisString("LLEN"), RedisString(key)]) return self } /// Add a LPOP command to the "transaction" /// /// - Parameter key: The key. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lpop(_ key: String) -> RedisMulti { queuedCommands.append([RedisString("LPOP"), RedisString(key)]) return self } /// Add a LPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The set of the values to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lpush(_ key: String, values: String...) -> RedisMulti { return lpushArrayOfValues(key, values: values) } /// Add a LPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: An array of values to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lpushArrayOfValues(_ key: String, values: [String]) -> RedisMulti { var command = [RedisString("LPUSH"), RedisString(key)] for value in values { command.append(RedisString(value)) } queuedCommands.append(command) return self } /// Add a LPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The array of the values, in the form of `RedisString`s, /// to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lpush(_ key: String, values: RedisString...) -> RedisMulti { return lpushArrayOfValues(key, values: values) } /// Add a LPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The array of the values, in the form of `RedisString`s, /// to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lpushArrayOfValues(_ key: String, values: [RedisString]) -> RedisMulti { var command = [RedisString("LPUSH"), RedisString(key)] for value in values { command.append(value) } queuedCommands.append(command) return self } /// Add a LPUSHX command to the "transaction" /// /// - Parameter key: The key. /// - Parameter value: The value to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lpushx(_ key: String, value: String) -> RedisMulti { queuedCommands.append([RedisString("LPUSHX"), RedisString(key), RedisString(value)]) return self } /// Add a LPUSHX command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The value, in the form of `RedisString`, to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lpushx(_ key: String, value: RedisString) -> RedisMulti { queuedCommands.append([RedisString("LPUSHX"), RedisString(key), value]) return self } /// Add a LRANGE command to the "transaction" /// /// - Parameter key: The key. /// - Parameter start: The index to start retrieving from. /// - Parameter end: The index to stop retrieving at. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lrange(_ key: String, start: Int, end: Int) -> RedisMulti { queuedCommands.append([RedisString("LRANGE"), RedisString(key), RedisString(start), RedisString(end)]) return self } /// Add a LREM command to the "transaction" /// /// - Parameter key: The key. /// - Parameter count: The number of elements to remove. /// - Parameter value: The value of the elements to remove. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lrem(_ key: String, count: Int, value: String) -> RedisMulti { queuedCommands.append([RedisString("LREM"), RedisString(key), RedisString(count), RedisString(value)]) return self } /// Add a LREM command to the "transaction" /// /// - Parameter key: The key. /// - Parameter count: The number of elements to remove. /// - Parameter value: The value of the elemnts to remove in the form of a `RedisString`. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lrem(_ key: String, count: Int, value: RedisString) -> RedisMulti { queuedCommands.append([RedisString("LREM"), RedisString(key), RedisString(count), value]) return self } /// Add a LSET command to the "transaction" /// /// - Parameter key: The key. /// - Parameter index: The index of the value in the list to be updated. /// - Parameter value: The new value for the element of the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lset(_ key: String, index: Int, value: String) -> RedisMulti { queuedCommands.append([RedisString("LSET"), RedisString(key), RedisString(index), RedisString(value)]) return self } /// Add a LSET command to the "transaction" /// /// - Parameter key: The key. /// - Parameter index: The index of the value in the list to be updated. /// - Parameter value: The new value for the element of the list in the form of a `RedisString`. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func lset(_ key: String, index: Int, value: RedisString) -> RedisMulti { queuedCommands.append([RedisString("LSET"), RedisString(key), RedisString(index), value]) return self } /// Add a LTRIM command to the "transaction" /// /// - Parameter key: The key. /// - Parameter start: The index of the first element of the list to keep. /// - Parameter end: The index of the last element of the list to keep. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func ltrim(_ key: String, start: Int, end: Int) -> RedisMulti { queuedCommands.append([RedisString("LTRIM"), RedisString(key), RedisString(start), RedisString(end)]) return self } /// Add a RPOP command to the "transaction" /// /// - Parameter key: The key. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpop(_ key: String) -> RedisMulti { queuedCommands.append([RedisString("RPOP"), RedisString(key)]) return self } /// Add a RPOPLPUSH command to the "transaction" /// /// - Parameter source: The list to pop an item from. /// - Parameter destination: The list to push the poped item onto. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpoplpush(_ source: String, destination: String) -> RedisMulti { queuedCommands.append([RedisString("RPOPLPUSH"), RedisString(source), RedisString(destination)]) return self } /// Add a RPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The list of values to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpush(_ key: String, values: String...) -> RedisMulti { return rpushArrayOfValues(key, values: values) } /// Add a RPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: An array of values to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpushArrayOfValues(_ key: String, values: [String]) -> RedisMulti { var command = [RedisString("RPUSH"), RedisString(key)] for value in values { command.append(RedisString(value)) } queuedCommands.append(command) return self } /// Add a RPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The list of `RedisString` values to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpush(_ key: String, values: RedisString...) -> RedisMulti { return rpushArrayOfValues(key, values: values) } /// Add a RPUSH command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: An array of `RedisString` values to be pushed on to the list /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpushArrayOfValues(_ key: String, values: [RedisString]) -> RedisMulti { var command = [RedisString("RPUSH"), RedisString(key)] for value in values { command.append(value) } queuedCommands.append(command) return self } /// Add a RPUSHX command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The value to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpushx(_ key: String, value: String) -> RedisMulti { queuedCommands.append([RedisString("RPUSHX"), RedisString(key), RedisString(value)]) return self } /// Add a RPUSHX command to the "transaction" /// /// - Parameter key: The key. /// - Parameter values: The `RedisString` value to be pushed on to the list. /// /// - Returns: The `RedisMulti` object being added to. @discardableResult public func rpushx(_ key: String, value: RedisString) -> RedisMulti { queuedCommands.append([RedisString("RPUSHX"), RedisString(key), value]) return self } }
mit
59d33c4ec4666d69fcbb38c5de519eee
37.626214
155
0.626492
4.25508
false
false
false
false
rtoal/polyglot
swift/arc_fail.swift
2
500
class Person { var name: String var boss: Person? var assistant: Person? // CAUSES A MEMORY LEAK init(name: String, boss: Person? = nil) { initCount += 1 self.name = name self.boss = boss } deinit { deinitCount += 1 } } func main() { let alice = Person(name: "Alice") let bob = Person(name: "Bob", boss: alice) alice.assistant = bob } var (initCount, deinitCount) = (0, 0) main() assert(initCount == 2 && deinitCount == 0)
mit
9346598c977cfe391b2b7bf7165dd74e
19.833333
52
0.568
3.355705
false
false
false
false
KaushalElsewhere/AllHandsOn
TryMadhu/TryMadhu/DetailController.swift
1
2070
// // DetailController.swift // TryMadhu // // Created by Kaushal Elsewhere on 15/05/2017. // Copyright © 2017 Elsewhere. All rights reserved. // import UIKit import Foundation protocol DetailControllerDelegate: class { func detailControllerDidSelectNext() func detailControllerDidSelectBack() } //MARK:- Actions extension DetailController { func didSelectButton() { delegate?.detailControllerDidSelectNext() } func didSelectBack() { delegate?.detailControllerDidSelectBack() } } //MARK:- Network Manager Delegate extension DetailController: NetworkManagerDelegate { func networkManagerDidRecieveData(items: [Product]) { // } } //MARK:- Base class DetailController: UIViewController { weak var delegate: DetailControllerDelegate? lazy var button: UIButton = { let button = UIButton() button.setTitle("Goto next", forState: .Normal) button.setTitleColor(.grayColor(), forState: .Normal) button.setTitleColor(.lightGrayColor(), forState: .Highlighted) button.addTarget(self, action: #selector(didSelectButton), forControlEvents: .TouchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() requestData() setupViews() } func setupViews() { self.view.backgroundColor = .whiteColor() self.title = "Detail" view.addSubview(button) navigationItem.setHidesBackButton(true, animated: false) let back = UIBarButtonItem(title: "Back", style: .Done, target: self, action: #selector(didSelectBack)) navigationItem.leftBarButtonItem = back setupConstraints() } func setupConstraints() { button.snp_makeConstraints { (make) in make.center.equalTo(view.snp_center) } } func requestData() { let manager = NetworkManager() manager.delegate = self manager.getItems() } }
mit
648220aa1e84abb11a13e8d97a7e22bd
23.05814
111
0.632673
5.133995
false
false
false
false
ahoppen/swift
test/Constraints/opened_existentials.swift
2
7490
// RUN: %target-typecheck-verify-swift -enable-experimental-opened-existential-types protocol Q { } protocol P { associatedtype A: Q } extension Int: P { typealias A = Double } extension Array: P where Element: P { typealias A = String } extension Double: Q { } extension String: Q { } func acceptGeneric<T: P>(_: T) -> T.A? { nil } func acceptCollection<C: Collection>(_ c: C) -> C.Element { c.first! } // --- Simple opening of existential values func testSimpleExistentialOpening(p: any P, pq: any P & Q, c: any Collection) { let pa = acceptGeneric(p) let _: Int = pa // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}} let pqa = acceptGeneric(pq) let _: Int = pqa // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}} let element = acceptCollection(c) let _: Int = element // expected-error{{cannot convert value of type 'Any' to specified type 'Int'}} } // --- Requirements on nested types protocol CollectionOfPs: Collection where Self.Element: P { } func takeCollectionOfPs<C: Collection>(_: C) -> C.Element.A? where C.Element: P { nil } func testCollectionOfPs(cp: any CollectionOfPs) { let e = takeCollectionOfPs(cp) let _: Int = e // expected-error{{cannot convert value of type '(any Q)?' to specified type 'Int'}} } // --- Multiple opened existentials in the same expression func takeTwoGenerics<T1: P, T2: P>(_ a: T1, _ b: T2) -> (T1, T2) { (a, b) } extension P { func combineThePs<T: P & Q>(_ other: T) -> (A, T.A)? { nil } } func testMultipleOpened(a: any P, b: any P & Q) { let r1 = takeTwoGenerics(a, b) let _: Int = r1 // expected-error{{cannot convert value of type '(any P, any P & Q)' to specified type 'Int'}} let r2 = a.combineThePs(b) let _: Int = r2 // expected-error{{cannot convert value of type '(any Q, any Q)?' to specified type 'Int'}} } // --- Opening existential metatypes func conjureValue<T: P>(of type: T.Type) -> T? { nil } func testMagic(pt: any P.Type) { let pOpt = conjureValue(of: pt) let _: Int = pOpt // expected-error{{cannot convert value of type '(any P)?' to specified type 'Int'}} } // --- With primary associated types and opaque parameter types protocol CollectionOf<Element>: Collection { } extension Array: CollectionOf { } extension Set: CollectionOf { } // expected-note@+2{{required by global function 'reverseIt' where 'some CollectionOf<T>' = 'any CollectionOf'}} @available(SwiftStdlib 5.1, *) func reverseIt<T>(_ c: some CollectionOf<T>) -> some CollectionOf<T> { return c.reversed() } @available(SwiftStdlib 5.1, *) func useReverseIt(_ c: any CollectionOf) { // Can't type-erase the `T` from the result. _ = reverseIt(c) // expected-error{{type 'any CollectionOf' cannot conform to 'CollectionOf'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } /// --- Opening existentials when returning opaque types. @available(SwiftStdlib 5.1, *) extension P { func getQ() -> some Q { let a: A? = nil return a! } func getCollectionOf() -> some CollectionOf<A> { return [] as [A] } } @available(SwiftStdlib 5.1, *) func getPQ<T: P>(_: T) -> some Q { let a: T.A? = nil return a! } // expected-note@+2{{required by global function 'getCollectionOfP' where 'T' = 'any P'}} @available(SwiftStdlib 5.1, *) func getCollectionOfP<T: P>(_: T) -> some CollectionOf<T.A> { return [] as [T.A] } func funnyIdentity<T: P>(_ value: T) -> T? { value } func arrayOfOne<T: P>(_ value: T) -> [T] { [value] } struct X<T: P> { // expected-note@-1{{required by generic struct 'X' where 'T' = 'any P'}} func f(_: T) { } } // expected-note@+1{{required by global function 'createX' where 'T' = 'any P'}} func createX<T: P>(_ value: T) -> X<T> { X<T>() } func doNotOpenOuter(p: any P) { _ = X().f(p) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } func takesVariadic<T: P>(_ args: T...) { } // expected-note@-1 2{{required by global function 'takesVariadic' where 'T' = 'any P'}} // expected-note@-2{{in call to function 'takesVariadic'}} func callVariadic(p1: any P, p2: any P) { takesVariadic() // expected-error{{generic parameter 'T' could not be inferred}} takesVariadic(p1) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} takesVariadic(p1, p2) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } func takesInOut<T: P>(_ value: inout T) { } func passesInOut(i: Int) { var p: any P = i takesInOut(&p) } @available(SwiftStdlib 5.1, *) func testReturningOpaqueTypes(p: any P) { let q = p.getQ() let _: Int = q // expected-error{{cannot convert value of type 'any Q' to specified type 'Int'}} p.getCollectionOf() // expected-error{{member 'getCollectionOf' cannot be used on value of type 'any P'; consider using a generic constraint instead}} let q2 = getPQ(p) let _: Int = q2 // expected-error{{cannot convert value of type 'any Q' to specified type 'Int'}} getCollectionOfP(p) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} let fi = funnyIdentity(p) let _: Int = fi // expected-error{{cannot convert value of type '(any P)?' to specified type 'Int'}} _ = arrayOfOne(p) // okay, arrays are covariant in their argument _ = createX(p) // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} } // Type-erasing vs. opening for parameters after the opened one. func takeValueAndClosure<T: P>(_ value: T, body: (T) -> Void) { } func takeValueAndClosureBackwards<T: P>(body: (T) -> Void, _ value: T) { } // expected-note@-1{{required by global function 'takeValueAndClosureBackwards(body:_:)' where 'T' = 'any P'}} func genericFunctionTakingP<T: P>(_: T) { } func genericFunctionTakingPQ<T: P & Q>(_: T) { } func overloadedGenericFunctionTakingP<T: P>(_: T) -> Int { 0 } func overloadedGenericFunctionTakingP<T: P>(_: T) { } func testTakeValueAndClosure(p: any P) { // Type-erase when not provided with a generic function. takeValueAndClosure(p) { x in print(x) let _: Int = x // expected-error{{cannot convert value of type 'any P' to specified type 'Int'}} } // Do not erase when referring to a generic function. takeValueAndClosure(p, body: genericFunctionTakingP) takeValueAndClosure(p, body: overloadedGenericFunctionTakingP) takeValueAndClosure(p, body: genericFunctionTakingPQ) // expected-error{{global function 'genericFunctionTakingPQ' requires that 'T' conform to 'Q'}} // Do not allow opening if there are any uses of the type parameter before // the opened parameter. This maintains left-to-right evaluation order. takeValueAndClosureBackwards( // expected-error{{type 'any P' cannot conform to 'P'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} body: { x in x as Int }, // expected-error{{'any P' is not convertible to 'Int'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} p) }
apache-2.0
fdfc685101a882255b13afe028c785e6
34.330189
152
0.674366
3.41853
false
false
false
false
wangrui460/WRNavigationBar_swift
WRNavigationBar_swift/WRNavigationBar_swift/WRNavigationBar/WRCycleScrollView/WRCycleScrollView.swift
2
12416
// // WRCycleScrollView.swift // WRCycleScrollViewDemo // // Created by wangrui on 2017/5/12. // Copyright © 2017年 wangrui. All rights reserved. // // Github地址:https://github.com/wangrui460/WRCycleScrollView import UIKit private let KEndlessScrollTimes = 128 @objc protocol WRCycleScrollViewDelegate { /// 点击图片回调 @objc optional func cycleScrollViewDidSelect(at index:Int, cycleScrollView:WRCycleScrollView) /// 图片滚动回调 @objc optional func cycleScrollViewDidScroll(to index:Int, cycleScrollView:WRCycleScrollView) } class WRCycleScrollView: UIView { //======================================================= // MARK: 对外提供的属性 //======================================================= weak var delegate:WRCycleScrollViewDelegate? /// 数据相关 var imgsType:ImgType = .SERVER var localImgArray :[String]? { didSet { if let local = localImgArray { proxy = Proxy(type: .LOCAL, array: local) reloadData() } } } var serverImgArray:[String]? { didSet { if let server = serverImgArray { proxy = Proxy(type: .SERVER, array: server) reloadData() } } } var descTextArray :[String]? /// WRCycleCell相关 var descLabelFont: UIFont? var descLabelTextColor: UIColor? var descLabelHeight: CGFloat? var descLabelTextAlignment:NSTextAlignment? var bottomViewBackgroundColor: UIColor? /// 主要功能需求相关 override var frame: CGRect { didSet { flowLayout?.itemSize = frame.size collectionView?.frame = bounds } } var isAutoScroll:Bool = true { didSet { timer?.invalidate() timer = nil if isAutoScroll == true { setupTimer() } } } var isEndlessScroll:Bool = true { didSet { reloadData() } } var autoScrollInterval: Double = 1.5 /// pageControl相关 var showPageControl: Bool = true { didSet { setupPageControl() } } var currentDotColor: UIColor = UIColor.orange { didSet { self.pageControl?.currentPageIndicatorTintColor = currentDotColor } } var otherDotColor: UIColor = UIColor.gray { didSet { self.pageControl?.pageIndicatorTintColor = otherDotColor } } //======================================================= // MARK: 对外提供的方法 //======================================================= func reloadData() { timer?.invalidate() timer = nil collectionView?.reloadData() setupPageControl() changeToFirstCycleCell(animated: false) if isAutoScroll == true { setupTimer() } } //======================================================= // MARK: 内部属性 //======================================================= fileprivate var imgsCount:Int { return (isEndlessScroll == true) ? (itemsInSection / KEndlessScrollTimes) : itemsInSection } fileprivate var itemsInSection:Int { guard let imgs = proxy?.imgArray else { return 0 } return (isEndlessScroll == true) ? (imgs.count * KEndlessScrollTimes) : imgs.count } fileprivate var firstItem:Int { return (isEndlessScroll == true) ? (itemsInSection / 2) : 0 } fileprivate var canChangeCycleCell:Bool { guard itemsInSection != 0 , let _ = collectionView, let _ = flowLayout else { return false } return true } fileprivate var indexOnPageControl:Int { var curIndex = Int((collectionView!.contentOffset.x + flowLayout!.itemSize.width * 0.5) / flowLayout!.itemSize.width) curIndex = max(0, curIndex) return curIndex % imgsCount } fileprivate var proxy:Proxy! fileprivate var flowLayout:UICollectionViewFlowLayout? fileprivate var collectionView:UICollectionView? fileprivate let CellID = "WRCycleCell" fileprivate var pageControl:UIPageControl? fileprivate var timer:Timer? // 标识子控件是否布局完成,布局完成后在layoutSubviews方法中就不执行 changeToFirstCycleCell 方法 fileprivate var isLoadOver = false //======================================================= // MARK: 构造方法 //======================================================= /// 构造方法 /// /// - Parameters: /// - frame: frame /// - type: ImagesType default:Server /// - imgs: localImgArray / serverImgArray default:nil /// - descs: descTextArray default:nil init(frame: CGRect, type:ImgType = .SERVER, imgs:[String]? = nil, descs:[String]? = nil) { super.init(frame: frame) setupCollectionView() imgsType = type if imgsType == .SERVER { if let server = imgs { proxy = Proxy(type: .SERVER, array: server) } } else { if let local = imgs { proxy = Proxy(type: .LOCAL, array: local) } } if let descTexts = descs { descTextArray = descTexts } reloadData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { collectionView?.delegate = nil print("WRCycleScrollView deinit") } //======================================================= // MARK: 内部方法(layoutSubviews、willMove) //======================================================= override func layoutSubviews() { super.layoutSubviews() // 解决WRCycleCell自动偏移问题 collectionView?.contentInset = .zero if isLoadOver == false { changeToFirstCycleCell(animated: false) } if showPageControl == true { setupPageControlFrame() } } override func willMove(toSuperview newSuperview: UIView?) { // 解决定时器导致的循环引用 super.willMove(toSuperview: newSuperview) // 展现的时候newSuper不为nil,离开的时候newSuper为nil guard let _ = newSuperview else { timer?.invalidate() timer = nil return } } } //======================================================= // MARK: - 无限轮播相关(定时器、切换图片、scrollView代理方法) //======================================================= extension WRCycleScrollView { func setupTimer() { timer = Timer(timeInterval: autoScrollInterval, target: self, selector: #selector(changeCycleCell), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .commonModes) } fileprivate func changeToFirstCycleCell(animated:Bool) { if canChangeCycleCell == true { let indexPath = IndexPath(item: firstItem, section: 0) collectionView!.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: animated) } } // 执行这个方法的前提是 isAutoScroll = true @objc func changeCycleCell() { if canChangeCycleCell == true { let curItem = Int(collectionView!.contentOffset.x / flowLayout!.itemSize.width) if curItem == itemsInSection - 1 { let animated = (isEndlessScroll == true) ? false : true changeToFirstCycleCell(animated: animated) } else { let indexPath = IndexPath(item: curItem + 1, section: 0) collectionView!.scrollToItem(at: indexPath, at: .init(rawValue: 0), animated: true) } } } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { timer?.invalidate() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if isAutoScroll == true { setupTimer() } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewDidEndScrollingAnimation(scrollView) } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { guard canChangeCycleCell else { return } delegate?.cycleScrollViewDidScroll?(to: indexOnPageControl, cycleScrollView: self) if indexOnPageControl >= firstItem { isLoadOver = true } } func scrollViewDidScroll(_ scrollView: UIScrollView) { guard canChangeCycleCell else { return } pageControl?.currentPage = indexOnPageControl } } //======================================================= // MARK: - pageControl页面 //======================================================= extension WRCycleScrollView { fileprivate func setupPageControl() { pageControl?.removeFromSuperview() if showPageControl == true { pageControl = UIPageControl() pageControl?.numberOfPages = imgsCount pageControl?.hidesForSinglePage = true pageControl?.currentPageIndicatorTintColor = self.currentDotColor pageControl?.pageIndicatorTintColor = self.otherDotColor pageControl?.isUserInteractionEnabled = false addSubview(pageControl!) } } fileprivate func setupPageControlFrame() { let pageW = bounds.width let pageH:CGFloat = 20 let pageX = bounds.origin.x let pageY = bounds.height - pageH self.pageControl?.frame = CGRect(x:pageX, y:pageY, width:pageW, height:pageH) } } //======================================================= // MARK: - WRCycleCell 相关 //======================================================= extension WRCycleScrollView: UICollectionViewDelegate,UICollectionViewDataSource { fileprivate func setupCollectionView() { flowLayout = UICollectionViewFlowLayout() flowLayout?.itemSize = frame.size flowLayout?.minimumLineSpacing = 0 flowLayout?.scrollDirection = .horizontal collectionView = UICollectionView(frame: bounds, collectionViewLayout: flowLayout!) collectionView?.register(WRCycleCell.self, forCellWithReuseIdentifier: CellID) collectionView?.isPagingEnabled = true collectionView?.bounces = false collectionView?.showsVerticalScrollIndicator = false collectionView?.showsHorizontalScrollIndicator = false collectionView?.delegate = self collectionView?.dataSource = self addSubview(collectionView!) } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemsInSection } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let curIndex = indexPath.item % imgsCount let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellID, for: indexPath) as! WRCycleCell cell.imgSource = proxy[curIndex] cell.descText = descTextArray?[curIndex] if let _ = descTextArray { cell.descLabelFont = (descLabelFont == nil) ? cell.descLabelFont : descLabelFont! cell.descLabelTextColor = (descLabelTextColor == nil) ? cell.descLabelTextColor : descLabelTextColor! cell.descLabelHeight = (descLabelHeight == nil) ? cell.descLabelHeight : descLabelHeight! cell.descLabelTextAlignment = (descLabelTextAlignment == nil) ? cell.descLabelTextAlignment : descLabelTextAlignment! cell.bottomViewBackgroundColor = (bottomViewBackgroundColor == nil) ? cell.bottomViewBackgroundColor : bottomViewBackgroundColor! } return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.cycleScrollViewDidSelect?(at: indexOnPageControl, cycleScrollView: self) } }
mit
c2b444916febe8b322da1af2c2ed340d
31.162234
141
0.56909
5.372279
false
false
false
false
bert589998/IOSUtils
IOSUtils/IOSUtils/extension/UIImage+Extensions.swift
1
1954
// // Created by 赵磊 on 2017/1/9. // Copyright © 2017年 赵磊. All rights reserved. // import UIKit extension UIImage { /// 转化圆形图像 /// /// - parameter size: 尺寸 /// - parameter backColor: 背景颜色 /// /// - returns: 裁切后的图像 func zl_circleImage(size: CGSize?, backColor: UIColor = UIColor.white, lineColor: UIColor = UIColor.lightGray) -> UIImage? { var size = size if size == nil { size = self.size } let rect = CGRect(origin: CGPoint(), size: size!) UIGraphicsBeginImageContextWithOptions(rect.size, true, 0); //背景的颜色填充 backColor.setFill() UIRectFill(rect) //圆形裁切 let path = UIBezierPath(ovalIn: rect) path.addClip() draw(in: rect) // 边界线宽度 //let ovalPath = UIBezierPath(ovalIn: rect) path.lineWidth = 2 lineColor.setStroke() path.stroke() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } /// 生成指定大小的不透明图象 /// /// - parameter size: 尺寸 /// - parameter backColor: 背景颜色 /// /// - returns: 图像 func cz_image(size: CGSize? = nil, backColor: UIColor = UIColor.white) -> UIImage? { var size = size if size == nil { size = self.size } let rect = CGRect(origin: CGPoint(), size: size!) UIGraphicsBeginImageContextWithOptions(rect.size, true, 0) backColor.setFill() UIRectFill(rect) draw(in: rect) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } }
mit
e694036d9ba59b9e0be0b7398e88d13b
23.144737
128
0.525886
4.803665
false
false
false
false
xxxAIRINxxx/ARNZoomImageTransition
ARNZoomImageTransition/ARNZoomImageTransition/Controller/MainViewController.swift
1
8555
// // MainViewController.swift // ARNZoomImageTransition // // Created by xxxAIRINxxx on 2015/08/08. // Copyright (c) 2015 xxxAIRINxxx. All rights reserved. // import UIKit import ARNTransitionAnimator class MainViewController: ImageZoomAnimationVC, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var collectionView : UICollectionView! @IBOutlet weak var tableView : UITableView! weak var selectedImageView : UIImageView? var animator : ARNTransitionAnimator? var isModeModal : Bool = false var isModeInteractive : Bool = false override func viewDidLoad() { super.viewDidLoad() self.extendedLayoutIncludesOpaqueBars = false self.collectionView.register(UINib(nibName: "CollectionCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell") self.tableView.register(UINib(nibName: "TableCell", bundle: nil), forCellReuseIdentifier: "TableCell") self.updateNavigationItem() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("MainViewController viewWillAppear") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("MainViewController viewWillDisappear") } func updateNavigationItem() { if isModeModal { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Modal", style: .done, target: self, action: #selector(self.modePush)) } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Push", style: .done, target: self, action: #selector(self.modeModal)) } if isModeInteractive { self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Interactive", style: .done, target: self, action: #selector(self.modeNormal)) } else { self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Normal", style: .done, target: self, action: #selector(self.modeInteractive)) } } @objc func modePush() { self.isModeModal = false self.updateNavigationItem() } @objc func modeModal() { self.isModeModal = true self.updateNavigationItem() } @objc func modeInteractive() { self.isModeInteractive = true self.updateNavigationItem() } @objc func modeNormal() { self.isModeInteractive = false self.updateNavigationItem() } func handleTransition() { if isModeInteractive { self.showInteractive() } else { if isModeModal { let storyboard = UIStoryboard(name: "ModalViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "ModalViewController") as! ModalViewController let animation = ImageZoomAnimation<ImageZoomAnimationVC>(rootVC: self, modalVC: controller, rootNavigation: self.navigationController) let animator = ARNTransitionAnimator(duration: 0.5, animation: animation) controller.transitioningDelegate = animator self.animator = animator self.present(controller, animated: true, completion: nil) } else { let storyboard = UIStoryboard(name: "DetailViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController let animation = ImageZoomAnimation<ImageZoomAnimationVC>(rootVC: self, modalVC: controller) let animator = ARNTransitionAnimator(duration: 0.5, animation: animation) self.navigationController?.delegate = animator self.animator = animator self.navigationController?.pushViewController(controller, animated: true) } } } func showInteractive() { if isModeModal { let storyboard = UIStoryboard(name: "ModalViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "ModalViewController") as! ModalViewController let animation = ImageZoomAnimation<ImageZoomAnimationVC>(rootVC: self, modalVC: controller, rootNavigation: self.navigationController) let animator = ARNTransitionAnimator(duration: 0.5, animation: animation) let gestureHandler = TransitionGestureHandler(targetView: controller.view, direction: .bottom) animator.registerInteractiveTransitioning(.dismiss, gestureHandler: gestureHandler) controller.transitioningDelegate = animator self.animator = animator self.present(controller, animated: true, completion: nil) } else { let storyboard = UIStoryboard(name: "DetailViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController let animation = ImageZoomAnimation<ImageZoomAnimationVC>(rootVC: self, modalVC: controller) let animator = ARNTransitionAnimator(duration: 0.5, animation: animation) let gestureHandler = TransitionGestureHandler(targetView: controller.view, direction: .bottom) animator.registerInteractiveTransitioning(.pop, gestureHandler: gestureHandler) self.navigationController?.delegate = animator self.animator = animator self.navigationController?.pushViewController(controller, animated: true) } } // MARK: - ImageTransitionZoomable override func createTransitionImageView() -> UIImageView { let imageView = UIImageView(image: self.selectedImageView!.image) imageView.contentMode = self.selectedImageView!.contentMode imageView.clipsToBounds = true imageView.isUserInteractionEnabled = false imageView.frame = self.selectedImageView!.convert(self.selectedImageView!.frame, to: self.view) return imageView } @objc override func presentationBeforeAction() { self.selectedImageView?.isHidden = true } override func presentationCompletionAction(didComplete: Bool) { self.selectedImageView?.isHidden = true } @objc override func dismissalBeforeAction() { self.selectedImageView?.isHidden = true } override func dismissalCompletionAction(didComplete: Bool) { self.selectedImageView?.isHidden = false } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 20 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell return cell } // MARK: - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! CollectionCell self.selectedImageView = cell.cellImageView self.handleTransition() } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell return cell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath) as! TableCell self.selectedImageView = cell.cellImageView self.handleTransition() } }
mit
a581f49f821791d8793e4299ee86c111
39.164319
153
0.665459
5.815772
false
false
false
false
DavidSteuber/QRTest
QRTest/QRCode.swift
1
1009
// // QRCode.swift // QRTest // // Created by David Steuber on 4/8/15. // Copyright (c) 2015 David Steuber. // import UIKit import CoreImage extension UIImage { class func qrCodeWithMessage(message: String) -> UIImage? { let data: NSData = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! let qrEncoder = CIFilter(name: "CIQRCodeGenerator", withInputParameters: ["inputMessage":data, "inputCorrectionLevel":"H"]) let ciImage = qrEncoder!.outputImage return UIImage(CIImage: ciImage!) } func scaleQRCodeWithNoInterpolation(size: CGFloat) -> UIImage? { UIGraphicsBeginImageContext(CGSizeMake(size, size)); let context = UIGraphicsGetCurrentContext(); CGContextSetInterpolationQuality(context, CGInterpolationQuality.None) self.drawInRect(CGRectMake(0, 0, size, size)) let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image } }
unlicense
296567267b6347b1f6aa284016d15715
31.580645
131
0.704658
4.99505
false
false
false
false
mcxiaoke/learning-ios
swift-language-guide/14_Initialization.playground/Contents.swift
1
7960
//: Playground - noun: a place where people can play // https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-ID203 // http://wiki.jikexueyuan.com/project/swift/chapter2/14_Initialization.html import UIKit struct Fahrenheit { // var temperature = 32.0 var temperature:Double init(){ temperature = 32.0 } } var f = Fahrenheit() f.temperature struct Celsius { var temperatureInCellsius:Double init(fromFahrenheit fahrenheit:Double){ temperatureInCellsius = (fahrenheit - 32.0)/1.8 } init(fromKelvin kelvin:Double){ temperatureInCellsius = kelvin - 273.15 } init(_ celsius :Double){ temperatureInCellsius = celsius } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) let freezingPointOfWater = Celsius(fromKelvin: 273.15) let freezingPointOfWater2 = Celsius(0.0) struct Color { var red, green, blue:Double init(red:Double, green:Double, blue:Double){ self.red = red self.green = green self.blue = blue } init(white:Double){ red = white green = white blue = white } } let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) let halfGray = Color(white: 0.5) // let veryGreen = Color(0.0,1.0,0.0) // error class SurveyQuestion { let text:String // cannot modify var response:String? init(text:String){ self.text = text } func ask(){ print(text) } } let cheeseQustion = SurveyQuestion(text: "Do you like cheese?") cheeseQustion.ask() cheeseQustion.response = "Yes, I do like cheese." class ShoppingListItem { var name:String? var quantity = 1 var purchased = false var notes:[Int]? } var item = ShoppingListItem() item.name item.quantity item.purchased item.notes struct Size { var width = 0.0, height = 0.0 } let twoByTwo = Size(width: 2.0, height: 2.0) twoByTwo struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() init() {} init(origin:Point, size:Size){ self.origin = origin self.size = size } init(center:Point, size:Size){ let originX = center.x - (size.width/2) let originY = center.y - (size.height/2) self.init(origin:Point(x:originX,y:originY),size:size) } } let basicRect = Rect() let originRect = Rect(origin: Point(x:2.0,y:2.0), size: Size(width: 5.0, height: 5.0)) let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) print("basiceRect:\(basicRect) originRect:\(originRect) centerRect:\(centerRect)") class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheel(s)" } } let vehicle = Vehicle() print("Vehicle: \(vehicle.description)") class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } let bicycle = Bicycle() print("Bicycle: \(bicycle.description)") class Food { var name:String init(name:String){ self.name = name } convenience init(){ self.init(name:"[Unnamed]") } } let namedMeat = Food(name: "Bacon") let mysteryMeat = Food() class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } } let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "Bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) class TheShoppingListItem: RecipeIngredient { var purchased = false var description: String { var output = "\(quantity) x \(name)" output += purchased ? " ✔" : " ✘" return output } } var breakfastList = [ TheShoppingListItem(), TheShoppingListItem(name: "Bacon"), TheShoppingListItem(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") someCreature.dynamicType if let giraffe = someCreature { print("An animal was initialized with a species of \(giraffe.species)") } let anonymousCreature = Animal(species: "") if anonymousCreature == nil { print("The anonymous creature could not be initialized") } enum TemperatureUnit { case Kelvin, Celsius, Fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .Kelvin case "C": self = .Celsius case "F": self = .Fahrenheit default: return nil } } } let fahrenheitUnit = TemperatureUnit(symbol: "F") fahrenheitUnit.dynamicType if fahrenheitUnit != nil { print("This is a defined temperature unit, so initialization succeeded.") } let unknownUnit = TemperatureUnit(symbol: "X") unknownUnit.dynamicType if unknownUnit == nil { print("This is not a defined temperature unit, so initialization failed.") } enum TemperatureUnit2: Character { case Kelvin = "K", Celsius = "C", Fahrenheit = "F" } let fahrenheitUnit2 = TemperatureUnit2(rawValue: "F") fahrenheitUnit2.dynamicType if fahrenheitUnit2 != nil { print("This is a defined temperature unit, so initialization succeeded.") } // prints "This is a defined temperature unit, so initialization succeeded." let unknownUnit2 = TemperatureUnit2(rawValue: "X") unknownUnit2.dynamicType if unknownUnit2 == nil { print("This is not a defined temperature unit, so initialization failed.") } class Product { let name:String! init?(name:String){ self.name = name if name.isEmpty { return nil } } } if let bowTie = Product(name: "bow tie") { // bowTie.name != nil, always print("The product's name is \(bowTie.name)") } class CartItem: Product { let quantity: Int! init?(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) if quantity < 1 { return nil } } } if let twoSocks = CartItem(name: "sock", quantity: 2) { print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)") } if let zeroShirts = CartItem(name: "shirt", quantity: 0) { print("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)") } else { print("Unable to initialize zero shirts") } if let oneUnnamed = CartItem(name: "", quantity: 1) { print("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)") } else { print("Unable to initialize one unnamed product") } class Document { var name: String? // this initializer creates a document with a nil name value init() {} // this initializer creates a document with a non-empty name value init?(name: String) { self.name = name if name.isEmpty { return nil } } } class AutomaticallyNamedDocument: Document { override init() { super.init() self.name = "[Untitled]" } override init(name: String) { super.init() if name.isEmpty { self.name = "[Untitled]" } else { self.name = name } } } class UntitledDocument: Document { override init() { super.init(name: "[Untitled]")! // ! unwrapped } } class SomeClass { required init() { // initializer implementation goes here } } class SomeSubclass: SomeClass { required init() { // subclass implementation of the required initializer goes here } } struct Checkerboard { let boardColors: [Bool] = { var temporaryBoard = [Bool]() var isBlack = false for i in 1...10 { for j in 1...10 { temporaryBoard.append(isBlack) isBlack = !isBlack } isBlack = !isBlack } return temporaryBoard }() func squareIsBlackAtRow(row: Int, column: Int) -> Bool { return boardColors[(row * 10) + column] } } let board = Checkerboard() print(board.squareIsBlackAtRow(0, column: 1)) // prints "true" print(board.squareIsBlackAtRow(9, column: 9)) // prints "false"
apache-2.0
4e5ea064fff162fef32420eb1d66a303
20.216
162
0.672197
3.507937
false
false
false
false
mcxiaoke/learning-ios
cocoa_programming_for_osx/28_WebServices/RanchForecast/RanchForecast/MainWindowController.swift
1
1613
// // MainWindowController.swift // RanchForecast // // Created by mcxiaoke on 16/5/23. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Cocoa class MainWindowController: NSWindowController { @IBOutlet var spinner: NSProgressIndicator! @IBOutlet var scrollView: NSScrollView! @IBOutlet var tableView: NSTableView! @IBOutlet var arrayController: NSArrayController! let fetcher = ScheduleFetcher() dynamic var courses: [Course] = [] override var windowNibName: String? { return "MainWindowController" } func openClass(sender: AnyObject!) { if let course = arrayController.selectedObjects.first as? Course { NSWorkspace.sharedWorkspace().openURL(course.url) } } func showProgress(){ scrollView.hidden = true spinner.hidden = false spinner.indeterminate = true spinner.startAnimation(nil) } func showContent() { scrollView.hidden = false spinner.stopAnimation(nil) spinner.hidden = true } override func windowDidLoad() { super.windowDidLoad() tableView.target = self tableView.doubleAction = #selector(openClass(_:)) fetcher.fetchCoursesUsingCompletionHandler { (result) -> (Void) in switch result { case .Success(let courses): print("Got courses: \(courses)") self.courses = courses self.showContent() case .Failure(let error): print("Got error: \(error)") NSAlert(error: error).runModal() self.courses = [] self.showContent() } } showProgress() } }
apache-2.0
2d455e6918b49ecbead398ce9cd87a45
24.15625
72
0.649689
4.707602
false
false
false
false
adrfer/swift
test/IDE/complete_with_closure_param.swift
14
1798
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COMPLETE | FileCheck %s typealias FunctionTypealias = (Int, Int) -> Bool typealias OptionalFunctionTypealias = ((Int, Int) -> Bool)? struct FooStruct { func instanceMethod1(callback: (Int, Int) -> Void) {} func instanceMethod2(callback: ((Int, Int) -> Void)?) {} func instanceMethod3(callback: ((Int, Int) -> Void)??) {} func instanceMethod4(callback: ((Int, Int) -> Void)!) {} func instanceMethod5(callback: FunctionTypealias) {} func instanceMethod6(callback: FunctionTypealias?) {} func instanceMethod7(callback: OptionalFunctionTypealias) {} } FooStruct().#^COMPLETE^# // CHECK: Begin completions, 7 items // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod1({#(callback): (Int, Int) -> Void##(Int, Int) -> Void#})[#Void#]; name=instanceMethod1(callback: (Int, Int) -> Void){{$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod2({#(callback): ((Int, Int) -> Void)?##(Int, Int) -> Void#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod3({#(callback): ((Int, Int) -> Void)??##(Int, Int) -> Void#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod4({#(callback): ((Int, Int) -> Void)!##(Int, Int) -> Void#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod5({#(callback): FunctionTypealias##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod6({#(callback): FunctionTypealias?##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}} // CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod7({#(callback): OptionalFunctionTypealias##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}} // CHECK: End completions
apache-2.0
25a289ceb198a5206df34e2c486e0b83
68.153846
184
0.673526
4.040449
false
false
false
false
werner-freytag/DockTime
ClockBundle-White/Layers/FaceBackgroundLayer.swift
1
722
// // Created by Werner on 02.02.18. // Copyright © 2018-2021 Werner Freytag. All rights reserved. // import AppKit.NSBezierPath import QuartzCore.CAGradientLayer class FaceBackgroundLayer: CAGradientLayer { let renderBounds = CGRect(x: 0, y: 0, width: 280, height: 280) override init() { super.init() frame = renderBounds colors = [NSColor(white: 1, alpha: 1).cgColor, NSColor(white: 0.93, alpha: 0.9).cgColor] let maskLayer = CAShapeLayer() maskLayer.path = NSBezierPath(ovalIn: frame).cgPath mask = maskLayer } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
5b7cc33fc09a9629ac24547583ff88f0
24.75
96
0.649098
4.005556
false
false
false
false
1amageek/Bleu
Bleu/Bleu.swift
1
9611
// // Bleu.swift // Bleu // // Created by 1amageek on 2017/03/12. // Copyright © 2017年 Stamp inc. All rights reserved. // import Foundation import CoreBluetooth /** # Bleu Bleu can easily control complex control of `CoreBluetooth` with Server client model. */ public class Bleu { /// Bleu is singleton class. public static var shared: Bleu = Bleu() /// Bleu Error's enum BleuError: Error { case invalidGetReceiver case invalidPostReceiver case invalidNotifyReceiver } /// Services handled by Bleu public var services: [CBMutableService] = [] // MARK: - /// It is a server for responding to clients. public let server: Beacon = Beacon() /// It is a receiver managed by Bleu. private(set) var receivers: Set<Receiver> = [] // MARK: - /// It is a radar for exploring the server. private var radars: Set<Radar> = [] /// Initialize public init() { server.delegate = self } // MARK: - Advertising /// Returns whether the server (peripheral) is advertising. public class var isAdvertising: Bool { return shared.server.isAdvertising } /// Start advertising. public class func startAdvertising() { shared.server.startAdvertising() } /// Stop advertising. public class func stopAdvertising() { shared.server.stopAdvertising() } // MARK: - Serivce /// Add services managed by Bleu. private class func addService(_ service: CBMutableService) { shared.services.append(service) } /// Delete the service managed by Bleu. private class func removeService(_ service: CBMutableService) { if let index: Int = shared.services.index(of: service) { shared.services.remove(at: index) } } // MARK: - Request /** Send the request to the nearby server. The server is called Peripheral in CoreBluetooth. Multiple Requests can be sent at once. The Request is controlled by the Rader. Rader is called CentralManager in Corebluetooth. - parameter requests: Set an array of Request. - parameter options: Set Rader options. It is possible to change to the operation of Rader. - parameter completionBlock: Callback is called when all requests are completed. Since there may be more than one Peripheral, each Dictionary is returned. - returns: Radar */ @discardableResult public class func send(_ requests: [Request], options: Radar.Options = Radar.Options(), completionBlock: (([CBPeripheral: Set<Request>], Error?) -> Void)?) -> Radar? { let radar = Radar(requests: requests, options: options) shared.radars.insert(radar) radar.completionHandler = { [weak radar] (completedRequests, error) in shared.radars.remove(radar!) completionBlock?(completedRequests, error) } radar.resume() return radar } // MARK: - Receiver /** Add a receiver. - parameter receiver: Set the receiver to respond to the request. */ public class func addReceiver(_ receiver: Receiver) { do { try shared.validateReceiver(receiver) let isAdvertising = Bleu.isAdvertising if isAdvertising { Bleu.stopAdvertising() } shared.receivers.insert(receiver) if case .broadcast(_) = receiver.method { if isAdvertising { Bleu.startAdvertising() } return } let serviceUUIDs: [CBUUID] = shared.services.map({ return $0.uuid }) if !serviceUUIDs.contains(receiver.serviceUUID) { let service: CBMutableService = CBMutableService(type: receiver.serviceUUID, primary: true) service.characteristics = [] Bleu.addService(service) } shared.services.forEach({ (service) in if service.uuid == receiver.serviceUUID { service.characteristics?.append(receiver.characteristic) } }) if isAdvertising { Bleu.startAdvertising() } } catch BleuError.invalidGetReceiver { print("*** Error: When RequestMethod is `get`, it must have get receiver.") } catch BleuError.invalidPostReceiver { print("*** Error: When RequestMethod is `post`, it must have post receiver.") } catch BleuError.invalidNotifyReceiver { print("*** Error: When RequestMethod is `notify`, it must have post receiver.") } catch { print("*** Error: Receiver unkown error.") } } /** This function validates the receiver. - parameter receiver: Set the target receiver. */ private func validateReceiver(_ receiver: Receiver) throws { switch receiver.method { case .get(let isNotify): guard let _: Receiver.ReceiveGetHandler = receiver.get else { throw BleuError.invalidGetReceiver } if isNotify { guard let _: Receiver.ReceiveNotifyHandler = receiver.subscribe else { throw BleuError.invalidNotifyReceiver } guard let _: Receiver.ReceiveNotifyHandler = receiver.unsubscribe else { throw BleuError.invalidNotifyReceiver } } case .post: guard let _: Receiver.ReceivePostHandler = receiver.post else { throw BleuError.invalidPostReceiver } case .broadcast: break } } /** This function deletes the receiver. - parameter receiver: Set the target receiver. */ public class func removeReceiver(_ receiver: Receiver) { shared.receivers.remove(receiver) shared.services.forEach({ (service) in if service.uuid == receiver.serviceUUID { if let index: Int = service.characteristics?.index(where: { (characteristic) -> Bool in return characteristic.uuid == receiver.characteristicUUID }) { service.characteristics?.remove(at: index) } } }) } /** This function deletes all receivers. */ public class func removeAllReceivers() { shared.receivers.forEach { (receiver) in Bleu.removeReceiver(receiver) } } // MARK: - /** Update the value of characteristic. - parameter value: Set the data to be updated. - parameter characteristic: Set the target characteristic. - parameter centrals: Set the target centrals. - returns: `true` if the update could be sent, or `false` if the underlying transmit queue is full. If `false` was returned, the delegate method peripheralManagerIsReadyToUpdateSubscribers: will be called once space has become available, and the update should be re-sent if so desired. */ @discardableResult public class func updateValue(_ value: Data, for characteristic: CBMutableCharacteristic, onSubscribedCentrals centrals: [CBCentral]?) -> Bool { return shared.server.updateValue(value, for: characteristic, onSubscribedCentrals: centrals) } } protocol BleuServerDelegate: class { var services: [CBMutableService] { get } var receivers: Set<Receiver> { get } func get(peripheralManager: CBPeripheralManager, request: CBATTRequest) func post(peripheralManager: CBPeripheralManager, requests: [CBATTRequest]) func subscribe(peripheralManager: CBPeripheralManager, central: CBCentral, characteristic: CBCharacteristic) func unsubscribe(peripheralManager: CBPeripheralManager, central: CBCentral, characteristic: CBCharacteristic) } extension Bleu: BleuServerDelegate { func get(peripheralManager: CBPeripheralManager, request: CBATTRequest) { self.receivers.forEach { (receiver) in if receiver.characteristicUUID == request.characteristic.uuid { DispatchQueue.main.async { receiver.get?(peripheralManager, request) } } } } func post(peripheralManager: CBPeripheralManager, requests: [CBATTRequest]) { self.receivers.forEach { (receiver) in requests.forEach({ (request) in if receiver.characteristicUUID == request.characteristic.uuid { DispatchQueue.main.async { receiver.post?(peripheralManager, request) } } }) } } func subscribe(peripheralManager: CBPeripheralManager, central: CBCentral, characteristic: CBCharacteristic) { self.receivers.forEach { (receiver) in if receiver.characteristicUUID == receiver.characteristic.uuid { DispatchQueue.main.async { receiver.subscribe?(peripheralManager, central, characteristic) } } } } func unsubscribe(peripheralManager: CBPeripheralManager, central: CBCentral, characteristic: CBCharacteristic) { self.receivers.forEach { (receiver) in if receiver.characteristicUUID == receiver.characteristic.uuid { DispatchQueue.main.async { receiver.unsubscribe?(peripheralManager, central, characteristic) } } } } }
mit
8432b430ecd1b5c08352b38d5772c77a
32.594406
171
0.613447
5.054182
false
false
false
false
kfix/MacPin
Sources/MacPin_stub/main.swift
1
3630
import Foundation import AppKit #if canImport(os) import os.log // `log stream --predicate "category=='main'"` // `log stream --predicate "subsystem like 'com.github.kfix.MacPin'"` func warn(_ msg: String) { if #available(OSX 10.12, *) { let log = OSLog(subsystem: "com.github.kfix.MacPin", category: "main") os_log("%{public}s", log: log, type: .error, msg) } print(msg) } // import os.signpost // let signpostID = OSSignpostID(log: log) #else func warn(_ msg: String) { print(msg); } #endif func loadMPframework(fromBundle: Bundle, frameworkName: String = "MacPin") -> Bool { if let frames = fromBundle.sharedFrameworksPath, let MPdir = Bundle.path(forResource: frameworkName, ofType: "framework", inDirectory: frames), let MPframe = Bundle(path: MPdir), MPframe.load() { print("loaded \(MPdir)") return true } else if let frames = fromBundle.privateFrameworksPath, let MPdir = Bundle.path(forResource: frameworkName, ofType: "framework", inDirectory: frames), let MPframe = Bundle(path: MPdir), MPframe.load() { print("loaded \(MPdir)") return true } return false } let mainBundle = Bundle.main // bundle directory that contains the current executable. This method may return a valid bundle object even for unbundled apps // lets you access the resources in the same directory as the currently running executable. // For a running app, the main bundle offers access to the app’s bundle directory. // For code running in a framework, the main bundle offers access to the framework’s bundle directory. print(mainBundle.executablePath ?? "no exec path") print(mainBundle.resourcePath ?? "no resource path") print(mainBundle.sharedFrameworksPath ?? "no frameworks path") print(mainBundle.privateFrameworksPath ?? "no frameworks path") if let sharedURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "com.github.kfix.MacPin") { // https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_application-groups // print("\(sharedURL)") // could load self-modified, user customized, main.js's from here } if !loadMPframework(fromBundle: mainBundle) { // not found locally, so search for the LaunchServices-registered MacPin.app // https://github.com/chromium/chromium/blob/master/chrome/app_shim/chrome_main_app_mode_mac.mm // https://github.com/chromium/chromium/blob/master/chrome/browser/apps/app_shim/app_shim_host_manager_mac.mm if let MPappPath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: "com.github.kfix.MacPin.MacPin"), let MPappBundle = Bundle(path: MPappPath), loadMPframework(fromBundle: MPappBundle) { // Chromium Web Apps just use dlopen: https://github.com/chromium/chromium/blob/master/chrome/app_shim/app_mode_loader_mac.mm#L139 // and parses info.plists itself: https://github.com/chromium/chromium/blob/master/chrome/common/mac/app_mode_chrome_locator.mm print("loaded \(MPappPath)!!") } else { warn("Could not find & load MacPin.framework locally or from [com.github.kfix.MacPin.MacPin].app") } } guard NSClassFromString("MacPin.MacPinApp") != nil else { warn("Could not find MacPinApp() in MacPin.framework!") exit(1) } print("initializing MacPinApp()") let app = (NSClassFromString("MacPin.MacPinApp") as! NSApplication.Type).shared print("initializing MacPinAppDelegateOSX()") guard let appDelCls = NSClassFromString("MacPin.MacPinAppDelegateOSX") as? NSObject.Type, let applicationDelegate = appDelCls.init() as? NSApplicationDelegate else { warn("failed to initialize MacPinAppDelegateOSX()") exit(1) } app.delegate = applicationDelegate app.run()
gpl-3.0
aafa10686d561fcd3ecd6aa2b5efd25b
43.765432
165
0.753172
3.47651
false
false
false
false
galacemiguel/bluehacks2017
Project Civ-1/Project Civ/ProjectCoverSectionController.swift
1
2070
// // ProjectCoverSectionController.swift // Project Civ // // Created by Carlos Arcenas on 2/18/17. // Copyright © 2017 Rogue Three. All rights reserved. // import UIKit import IGListKit class ProjectCoverSectionController: IGListSectionController, ProjectCoverViewCellDelegate { var project: Project! var delegate: ProjectCoverSectionControllerDelegate? } extension ProjectCoverSectionController: IGListSectionType { func numberOfItems() -> Int { return 2 } func sizeForItem(at index: Int) -> CGSize { guard let context = collectionContext, let _ = project else { return .zero } let width = context.containerSize.width if index == 0 { return CGSize(width: context.containerSize.width, height: context.containerSize.height) } else { return CGSize(width: width, height: 70) } } func cellForItem(at index: Int) -> UICollectionViewCell { if index == 0 { let cell = collectionContext!.dequeueReusableCell(of: ProjectCoverViewCell.self, for: self, at: index) as! ProjectCoverViewCell // image cell.nameLabel.text = project.name cell.locationLabel.text = project.location.uppercased() cell.delegate = self return cell } else { let cell = collectionContext!.dequeueReusableCell(of: VoteCell.self, for: self, at: index) as! VoteCell cell.upvoteButton.setTitle("+" + String(describing: project.upvotes), for: .normal) cell.downvoteButton.setTitle("-" + String(describing: project.downvotes), for: .normal) return cell } } func didUpdate(to object: Any) { project = object as? Project } func closeTapped() { delegate?.closeTapped() } func infoTapped() { delegate?.infoTapped() } func didSelectItem(at index: Int) { // nothing happens } } protocol ProjectCoverSectionControllerDelegate { func closeTapped() func infoTapped() }
mit
7441f6af63d436e8500949bc45db7da4
28.557143
135
0.638956
4.69161
false
false
false
false
tectijuana/iOS
FernandoDominguez/p7.swift
2
561
import Foundation print("Ingresar los 3 digitos enteros") var n=readLine() var nu1=Int(n!) print("Ingresar los 2 digitos enteros") let n2=readLine() var nu2=Int(n2!) print("Ingresar los 4 digitos enteros") let n3=readLine() var nu3=Int(n3!) var num1=nu1! var num2=nu2! var num3=nu3! var cn1=n!.characters.count var cn2=n2!.characters.count var cn3=n3!.characters.count print(cn1,cn2,cn3) if(cn1==3&&cn2==2&&cn3==4) { print("Su numero de IMSS es: ",num1,num2,num3) } else { print("Revisar la cantidad de digitos.Total de digitos permitidos 9") }
mit
27e85147c35f298b8d44b0150f310f66
12.682927
69
0.709447
2.377119
false
false
false
false
devandsev/theTVDB-iOS
tvShows/Source/Models/SeriesDetails.swift
1
1431
// // SeriesDetails.swift // tvShows // // Created by Andrey Sevrikov on 24/07/2017. // Copyright © 2017 devandsev. All rights reserved. // import Foundation import ObjectMapper struct SeriesDetails: ImmutableMappable { var added: String var addedBy: String? var airsDayOfWeek: String var airsTime: String var genre: [String] var imdbId: String var lastUpdated: Date var networkId: String var rating: String var runtime: String var seriesId: String var siteRating: Float var siteRatingCount: Int var zap2itId: String init(map: Map) throws { added = try map.value("added") addedBy = try? map.value("addedBy") airsDayOfWeek = try map.value("airsDayOfWeek") airsTime = try map.value("airsTime") genre = try map.value("genre") imdbId = try map.value("imdbId") // lastUpdated = try map.value("lastUpdated") lastUpdated = try map.value("lastUpdated", nested: nil, delimiter: "", using: DateTransform()) // birthday <- (map["birthday"], DateTransform()) networkId = try map.value("networkId") rating = try map.value("rating") runtime = try map.value("runtime") seriesId = try map.value("seriesId") siteRating = try map.value("siteRating") siteRatingCount = try map.value("siteRatingCount") zap2itId = try map.value("zap2itId") } }
mit
9dc33b1964a80b15b299357dcd8e76fe
29.425532
102
0.637762
3.950276
false
false
false
false
mac-cain13/DocumentStore
DocumentStore/Index/StorageInformation.swift
1
853
// // StorageInformation.swift // DocumentStore // // Created by Mathijs Kadijk on 07-07-17. // Copyright © 2017 Mathijs Kadijk. All rights reserved. // import Foundation struct StorageInformation: Equatable, Validatable { let documentNameResolver: () -> String let propertyName: PropertyName let storageType: StorageType let isOptional: Bool let sourceKeyPath: AnyKeyPath? var documentName: String { return documentNameResolver() } func validate() -> [ValidationIssue] { return propertyName.validate() } static func == (lhs: StorageInformation, rhs: StorageInformation) -> Bool { return lhs.documentName == rhs.documentName && lhs.propertyName == rhs.propertyName && lhs.storageType == rhs.storageType && lhs.isOptional == rhs.isOptional && lhs.sourceKeyPath == rhs.sourceKeyPath } }
mit
f2d44b347bd56b9109fc95a88029df2f
24.818182
77
0.705399
4.55615
false
false
false
false
TonyJin99/SinaWeibo
SinaWeibo/SinaWeibo/TJStatus.swift
1
1408
// // TJStatus.swift // SinaWeibo // // Created by Tony.Jin on 8/1/16. // Copyright © 2016 Innovatis Tech. All rights reserved. // import UIKit class TJStatus: NSObject{ var created_at: String? //微博创建时间 var idstr: String? //字符串型的微博ID var text: String? //微博信息内容 var source: String? //微博来源 var user: TJUser? //微博作者的用户信息 var pic_urls: [[String: AnyObject]]? //配图数组 var retweeted_status : TJStatus? //转发微博 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } //KVC的setValuesForKeysWithDictionary方法内部会调用setValue方法 override func setValue(value: AnyObject?, forKey key: String) { if key == "user"{ user = TJUser(dict: value as! [String : AnyObject]) return } if key == "retweeted_status"{ retweeted_status = TJStatus(dict: value as! [String : AnyObject]) return } super.setValue(value, forKey: key) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } override var description: String { let property = ["created_at", "idstr", "text", "source"] let dict = dictionaryWithValuesForKeys(property) return "\(dict)" } }
apache-2.0
74933361e2e19e0dcd21a093206a2dd9
24.627451
77
0.594491
4.097179
false
false
false
false
naokits/my-programming-marathon
RxSwiftDemo/Carthage/Checkouts/RxSwift/Rx.playground/Pages/Transforming_Observables.xcplaygroundpage/Contents.swift
2
1925
//: [<< Previous](@previous) - [Index](Index) import RxSwift /*: ## Transforming Observables Operators that transform items that are emitted by an Observable. */ /*: ### `map` / `select` Transform the items emitted by an Observable by applying a function to each item ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/map.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/map.html ) */ example("map") { let originalSequence = Observable.of(1, 2, 3) _ = originalSequence .map { number in number * 2 } .subscribe { print($0) } } /*: ### `flatMap` Transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/flatmap.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/flatmap.html ) */ example("flatMap") { let sequenceInt = Observable.of(1, 2, 3) let sequenceString = Observable.of("A", "B", "C", "D", "E", "F", "--") _ = sequenceInt .flatMap { (x:Int) -> Observable<String> in print("from sequenceInt \(x)") return sequenceString } .subscribe { print($0) } } /*: ### `scan` Apply a function to each item emitted by an Observable, sequentially, and emit each successive value ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/scan.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/scan.html ) */ example("scan") { let sequenceToSum = Observable.of(0, 1, 2, 3, 4, 5) _ = sequenceToSum .scan(0) { acum, elem in acum + elem } .subscribe { print($0) } } //: [Index](Index) - [Next >>](@next)
mit
20662232ad5ad51c175b915d90ddd755
23.367089
125
0.637922
3.796844
false
false
false
false
BObereder/Bureaucracy
Bureaucracy/Fields/SegmentedFormField.swift
1
2613
// // SegmentedFormField.swift // Bureaucracy // // Created by Alexander Kolov on 20.10.14. // Copyright (c) 2014 Alexander Kolov. All rights reserved. // import Foundation import SwiftHelpers public class SegmentedFormField<Type: Equatable, Internal, Representation>: FormField<Type, Internal, Representation> { public typealias Internal = Int public typealias Representation = String public init(_ name: String, value: Type, values: [Type], transformer: Type -> Internal, reverse: Internal -> Type) { super.init(name, value: value, cellClass: SegmentedFormCell.self, transformer: transformer, reverse: reverse) self.values = values self.accessibilityLabel = "SegmentedFormField" self.representationTransformer = { (var x) -> Representation in if let theRepresentation = self.representation { if let idx = find(values, x) { return theRepresentation[idx] } } return "\(x)" } } public convenience init(_ name: String, value: Type, values: [Type]) { let transformer: Type -> Internal = { (var x) -> Internal in return find(values, x)! } let reverse: Internal -> Type = { (var idx) -> Type in return values[idx] } self.init(name, value: value, values: values, transformer: transformer, reverse: reverse) } public var representation: [Representation]? public override func registerReusableView(tableView: UITableView) { let bundle = NSBundle(forClass: self.cellClass) let nib: UINib! = UINib(nibName: "SegmentedFormCell", bundle: bundle) tableView.registerNib(nib, forCellReuseIdentifier: self.cellClass.description()) } public override func update(cell: FormCell) { if let realCell = cell as? SegmentedFormCell { realCell.segmentedControl.accessibilityLabel = accessibilityLabel realCell.segmentedControl.removeAllSegments() if let field = cell.formElement as? SegmentedFormField<Type, Int, String> { if let realValues = field.representationValues { for v in realValues { realCell.segmentedControl.insertSegmentWithTitle(v, atIndex: realCell.segmentedControl.numberOfSegments, animated: false) } if let index = field.internalValue { realCell.segmentedControl.selectedSegmentIndex = index } } } } } public override func didChangeInternalValue(cell: FormCell) { if let field = cell.formElement as? SegmentedFormField { field.internalValue = (cell as SegmentedFormCell).segmentedControl.selectedSegmentIndex } super.didChangeInternalValue(cell) } }
mit
ac29f39557d37db53596ade4e7ea820d
35.802817
133
0.699196
4.584211
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/CoreStore/Sources/SetupResult.swift
2
3955
// // SetupResult.swift // CoreStore // // Copyright © 2014 John Rommel Estropia // // 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 CoreData // MARK: - SetupResult /** The `SetupResult` indicates the result of an asynchronous initialization of a persistent store. The `SetupResult` can be treated as a boolean: ``` try! CoreStore.addStorage( SQLiteStore(), completion: { (result: SetupResult) -> Void in if result { // succeeded } else { // failed } } ) ``` or as an `enum`, where the resulting associated object can also be inspected: ``` try! CoreStore.addStorage( SQLiteStore(), completion: { (result: SetupResult) -> Void in switch result { case .success(let storage): // storage is the related StorageInterface instance case .failure(let error): // error is the CoreStoreError enum value for the failure } } ) ``` */ public enum SetupResult<T: StorageInterface>: Hashable { /** `SetupResult.success` indicates that the storage setup succeeded. The associated object for this `enum` value is the related `StorageInterface` instance. */ case success(T) /** `SetupResult.failure` indicates that the storage setup failed. The associated object for this value is the related `CoreStoreError` enum value. */ case failure(CoreStoreError) /** Returns `true` if the result indicates `.success`, `false` if the result is `.failure`. */ public var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } // MARK: Equatable public static func == <T: StorageInterface, U: StorageInterface>(lhs: SetupResult<T>, rhs: SetupResult<U>) -> Bool { switch (lhs, rhs) { case (.success(let storage1), .success(let storage2)): return storage1 === storage2 case (.failure(let error1), .failure(let error2)): return error1 == error2 default: return false } } // MARK: Hashable public var hashValue: Int { switch self { case .success(let storage): return true.hashValue ^ ObjectIdentifier(storage).hashValue case .failure(let error): return false.hashValue ^ error.hashValue } } // MARK: Internal internal init(_ storage: T) { self = .success(storage) } internal init(_ error: CoreStoreError) { self = .failure(error) } internal init(_ error: Error) { self = .failure(CoreStoreError(error)) } }
mit
aa3b8fa0542846c7061e1adaa5e4c223
27.652174
158
0.614315
4.781137
false
false
false
false
mischarouleaux/Smack
Smack/Pods/Socket.IO-Client-Swift/Source/SocketIOClient.swift
2
21693
// // SocketIOClient.swift // Socket.IO-Client-Swift // // Created by Erik Little on 11/23/14. // // 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 Dispatch import Foundation /// The main class for SocketIOClientSwift. /// /// **NOTE**: The client is not thread/queue safe, all interaction with the socket should be done on the `handleQueue` /// /// Represents a socket.io-client. Most interaction with socket.io will be through this class. open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, SocketParsable { // MARK: Properties /// The engine for this client. public private(set) var engine: SocketEngineSpec? /// The status of this client. public private(set) var status = SocketIOClientStatus.notConnected { didSet { switch status { case .connected: reconnecting = false currentReconnectAttempt = 0 default: break } handleClientEvent(.statusChange, data: [status]) } } /// If `true` then every time `connect` is called, a new engine will be created. public var forceNew = false /// The queue that all interaction with the client should occur on. This is the queue that event handlers are /// called on. public var handleQueue = DispatchQueue.main /// The namespace for this client. public var nsp = "/" /// The configuration for this client. public var config: SocketIOClientConfiguration /// If `true`, this client will try and reconnect on any disconnects. public var reconnects = true /// The number of seconds to wait before attempting to reconnect. public var reconnectWait = 10 /// The session id of this client. public var sid: String? { return engine?.sid } /// The URL of the socket.io server. /// /// If changed after calling `init`, `forceNew` must be set to `true`, or it will only connect to the url set in the /// init. public var socketURL: URL var ackHandlers = SocketAckManager() var waitingPackets = [SocketPacket]() private(set) var currentAck = -1 private(set) var reconnectAttempts = -1 private let logType = "SocketIOClient" private var anyHandler: ((SocketAnyEvent) -> ())? private var currentReconnectAttempt = 0 private var handlers = [SocketEventHandler]() private var reconnecting = false // MARK: Initializers /// Type safe way to create a new SocketIOClient. `opts` can be omitted. /// /// - parameter socketURL: The url of the socket.io server. /// - parameter config: The config for this socket. public init(socketURL: URL, config: SocketIOClientConfiguration = []) { self.config = config self.socketURL = socketURL if socketURL.absoluteString.hasPrefix("https://") { self.config.insert(.secure(true)) } for option in config { switch option { case let .reconnects(reconnects): self.reconnects = reconnects case let .reconnectAttempts(attempts): reconnectAttempts = attempts case let .reconnectWait(wait): reconnectWait = abs(wait) case let .nsp(nsp): self.nsp = nsp case let .log(log): DefaultSocketLogger.Logger.log = log case let .logger(logger): DefaultSocketLogger.Logger = logger case let .handleQueue(queue): handleQueue = queue case let .forceNew(force): forceNew = force default: continue } } self.config.insert(.path("/socket.io/"), replacing: false) super.init() } /// Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity. /// If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)` /// /// - parameter socketURL: The url of the socket.io server. /// - parameter config: The config for this socket. public convenience init(socketURL: NSURL, config: NSDictionary?) { self.init(socketURL: socketURL as URL, config: config?.toSocketConfiguration() ?? []) } deinit { DefaultSocketLogger.Logger.log("Client is being released", type: logType) engine?.disconnect(reason: "Client Deinit") } // MARK: Methods private func addEngine() { DefaultSocketLogger.Logger.log("Adding engine", type: logType, args: "") engine?.client = nil engine = SocketEngine(client: self, url: socketURL, config: config) } /// Connect to the server. open func connect() { connect(timeoutAfter: 0, withHandler: nil) } /// Connect to the server. If we aren't connected after `timeoutAfter` seconds, then `withHandler` is called. /// /// - parameter timeoutAfter: The number of seconds after which if we are not connected we assume the connection /// has failed. Pass 0 to never timeout. /// - parameter withHandler: The handler to call when the client fails to connect. open func connect(timeoutAfter: Double, withHandler handler: (() -> ())?) { assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)") guard status != .connected else { DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType) return } status = .connecting if engine == nil || forceNew { addEngine() } engine?.connect() guard timeoutAfter != 0 else { return } handleQueue.asyncAfter(deadline: DispatchTime.now() + timeoutAfter) {[weak self] in guard let this = self, this.status == .connecting || this.status == .notConnected else { return } this.status = .disconnected this.engine?.disconnect(reason: "Connect timeout") handler?() } } private func createOnAck(_ items: [Any]) -> OnAckCallback { currentAck += 1 return OnAckCallback(ackNumber: currentAck, items: items, socket: self) } func didConnect(toNamespace namespace: String) { DefaultSocketLogger.Logger.log("Socket connected", type: logType) status = .connected handleClientEvent(.connect, data: [namespace]) } func didDisconnect(reason: String) { guard status != .disconnected else { return } DefaultSocketLogger.Logger.log("Disconnected: %@", type: logType, args: reason) reconnecting = false status = .disconnected // Make sure the engine is actually dead. engine?.disconnect(reason: reason) handleClientEvent(.disconnect, data: [reason]) } /// Disconnects the socket. open func disconnect() { DefaultSocketLogger.Logger.log("Closing socket", type: logType) didDisconnect(reason: "Disconnect") } /// Send an event to the server, with optional data items. /// /// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error` /// will be emitted. The structure of the error data is `[eventName, items, theError]` /// /// - parameter event: The event to send. /// - parameter items: The items to send with this event. May be left out. open func emit(_ event: String, _ items: SocketData...) { do { try emit(event, with: items.map({ try $0.socketRepresentation() })) } catch let err { DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)", type: logType) handleClientEvent(.error, data: [event, items, err]) } } /// Same as emit, but meant for Objective-C /// /// - parameter event: The event to send. /// - parameter with: The items to send with this event. May be left out. open func emit(_ event: String, with items: [Any]) { guard status == .connected else { handleClientEvent(.error, data: ["Tried emitting \(event) when not connected"]) return } _emit([event] + items) } /// Sends a message to the server, requesting an ack. /// /// **NOTE**: It is up to the server send an ack back, just calling this method does not mean the server will ack. /// Check that your server's api will ack the event being sent. /// /// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error` /// will be emitted. The structure of the error data is `[eventName, items, theError]` /// /// Example: /// /// ```swift /// socket.emitWithAck("myEvent", 1).timingOut(after: 1) {data in /// ... /// } /// ``` /// /// - parameter event: The event to send. /// - parameter items: The items to send with this event. May be left out. /// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent. open func emitWithAck(_ event: String, _ items: SocketData...) -> OnAckCallback { do { return emitWithAck(event, with: try items.map({ try $0.socketRepresentation() })) } catch let err { DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)", type: logType) handleClientEvent(.error, data: [event, items, err]) return OnAckCallback(ackNumber: -1, items: [], socket: self) } } /// Same as emitWithAck, but for Objective-C /// /// **NOTE**: It is up to the server send an ack back, just calling this method does not mean the server will ack. /// Check that your server's api will ack the event being sent. /// /// Example: /// /// ```swift /// socket.emitWithAck("myEvent", with: [1]).timingOut(after: 1) {data in /// ... /// } /// ``` /// /// - parameter event: The event to send. /// - parameter with: The items to send with this event. Use `[]` to send nothing. /// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent. open func emitWithAck(_ event: String, with items: [Any]) -> OnAckCallback { return createOnAck([event] + items) } func _emit(_ data: [Any], ack: Int? = nil) { guard status == .connected else { handleClientEvent(.error, data: ["Tried emitting when not connected"]) return } let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: false) let str = packet.packetString DefaultSocketLogger.Logger.log("Emitting: %@", type: logType, args: str) engine?.send(str, withData: packet.binary) } // If the server wants to know that the client received data func emitAck(_ ack: Int, with items: [Any]) { guard status == .connected else { return } let packet = SocketPacket.packetFromEmit(items, id: ack, nsp: nsp, ack: true) let str = packet.packetString DefaultSocketLogger.Logger.log("Emitting Ack: %@", type: logType, args: str) engine?.send(str, withData: packet.binary) } /// Called when the engine closes. /// /// - parameter reason: The reason that the engine closed. open func engineDidClose(reason: String) { handleQueue.async { self._engineDidClose(reason: reason) } } private func _engineDidClose(reason: String) { waitingPackets.removeAll() if status != .disconnected { status = .notConnected } if status == .disconnected || !reconnects { didDisconnect(reason: reason) } else if !reconnecting { reconnecting = true tryReconnect(reason: reason) } } /// Called when the engine errors. /// /// - parameter reason: The reason the engine errored. open func engineDidError(reason: String) { handleQueue.async { self._engineDidError(reason: reason) } } private func _engineDidError(reason: String) { DefaultSocketLogger.Logger.error("%@", type: logType, args: reason) handleClientEvent(.error, data: [reason]) } /// Called when the engine opens. /// /// - parameter reason: The reason the engine opened. open func engineDidOpen(reason: String) { DefaultSocketLogger.Logger.log(reason, type: "SocketEngineClient") } // Called when the socket gets an ack for something it sent func handleAck(_ ack: Int, data: [Any]) { guard status == .connected else { return } DefaultSocketLogger.Logger.log("Handling ack: %@ with data: %@", type: logType, args: ack, data) ackHandlers.executeAck(ack, with: data, onQueue: handleQueue) } /// Causes an event to be handled, and any event handlers for that event to be called. /// /// - parameter event: The event that is to be handled. /// - parameter data: the data associated with this event. /// - parameter isInternalMessage: If `true` event handlers for this event will be called regardless of status. /// - parameter withAck: The ack number for this event. May be left out. open func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int = -1) { guard status == .connected || isInternalMessage else { return } DefaultSocketLogger.Logger.log("Handling event: %@ with data: %@", type: logType, args: event, data) anyHandler?(SocketAnyEvent(event: event, items: data)) for handler in handlers where handler.event == event { handler.executeCallback(with: data, withAck: ack, withSocket: self) } } func handleClientEvent(_ event: SocketClientEvent, data: [Any]) { handleEvent(event.rawValue, data: data, isInternalMessage: true) } /// Leaves nsp and goes back to the default namespace. open func leaveNamespace() { if nsp != "/" { engine?.send("1\(nsp)", withData: []) nsp = "/" } } /// Joins `namespace`. /// /// **Do not use this to join the default namespace.** Instead call `leaveNamespace`. /// /// - parameter namespace: The namespace to join. open func joinNamespace(_ namespace: String) { nsp = namespace if nsp != "/" { DefaultSocketLogger.Logger.log("Joining namespace", type: logType) engine?.send("0\(nsp)", withData: []) } } /// Removes handler(s) based on an event name. /// /// If you wish to remove a specific event, call the `off(id:)` with the UUID received from its `on` call. /// /// - parameter event: The event to remove handlers for. open func off(_ event: String) { DefaultSocketLogger.Logger.log("Removing handler for event: %@", type: logType, args: event) handlers = handlers.filter({ $0.event != event }) } /// Removes a handler with the specified UUID gotten from an `on` or `once` /// /// If you want to remove all events for an event, call the off `off(_:)` method with the event name. /// /// - parameter id: The UUID of the handler you wish to remove. open func off(id: UUID) { DefaultSocketLogger.Logger.log("Removing handler with id: %@", type: logType, args: id) handlers = handlers.filter({ $0.id != id }) } /// Adds a handler for an event. /// /// - parameter event: The event name for this handler. /// - parameter callback: The callback that will execute when this event is received. /// - returns: A unique id for the handler that can be used to remove it. @discardableResult open func on(_ event: String, callback: @escaping NormalCallback) -> UUID { DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event) let handler = SocketEventHandler(event: event, id: UUID(), callback: callback) handlers.append(handler) return handler.id } /// Adds a handler for a client event. /// /// Example: /// /// ```swift /// socket.on(clientEvent: .connect) {data, ack in /// ... /// } /// ``` /// /// - parameter event: The event for this handler. /// - parameter callback: The callback that will execute when this event is received. /// - returns: A unique id for the handler that can be used to remove it. @discardableResult open func on(clientEvent event: SocketClientEvent, callback: @escaping NormalCallback) -> UUID { DefaultSocketLogger.Logger.log("Adding handler for event: %@", type: logType, args: event) let handler = SocketEventHandler(event: event.rawValue, id: UUID(), callback: callback) handlers.append(handler) return handler.id } /// Adds a single-use handler for an event. /// /// - parameter event: The event name for this handler. /// - parameter callback: The callback that will execute when this event is received. /// - returns: A unique id for the handler that can be used to remove it. @discardableResult open func once(_ event: String, callback: @escaping NormalCallback) -> UUID { DefaultSocketLogger.Logger.log("Adding once handler for event: %@", type: logType, args: event) let id = UUID() let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in guard let this = self else { return } this.off(id: id) callback(data, ack) } handlers.append(handler) return handler.id } /// Adds a handler that will be called on every event. /// /// - parameter handler: The callback that will execute whenever an event is received. open func onAny(_ handler: @escaping (SocketAnyEvent) -> ()) { anyHandler = handler } /// Called when the engine has a message that must be parsed. /// /// - parameter msg: The message that needs parsing. public func parseEngineMessage(_ msg: String) { DefaultSocketLogger.Logger.log("Should parse message: %@", type: "SocketIOClient", args: msg) handleQueue.async { self.parseSocketMessage(msg) } } /// Called when the engine receives binary data. /// /// - parameter data: The data the engine received. public func parseEngineBinaryData(_ data: Data) { handleQueue.async { self.parseBinaryData(data) } } /// Tries to reconnect to the server. /// /// This will cause a `disconnect` event to be emitted, as well as an `reconnectAttempt` event. open func reconnect() { guard !reconnecting else { return } engine?.disconnect(reason: "manual reconnect") } /// Removes all handlers. /// Can be used after disconnecting to break any potential remaining retain cycles. open func removeAllHandlers() { handlers.removeAll(keepingCapacity: false) } private func tryReconnect(reason: String) { guard reconnecting else { return } DefaultSocketLogger.Logger.log("Starting reconnect", type: logType) handleClientEvent(.reconnect, data: [reason]) _tryReconnect() } private func _tryReconnect() { guard reconnects && reconnecting && status != .disconnected else { return } if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts { return didDisconnect(reason: "Reconnect Failed") } DefaultSocketLogger.Logger.log("Trying to reconnect", type: logType) handleClientEvent(.reconnectAttempt, data: [(reconnectAttempts - currentReconnectAttempt)]) currentReconnectAttempt += 1 connect() handleQueue.asyncAfter(deadline: DispatchTime.now() + Double(reconnectWait), execute: _tryReconnect) } // Test properties var testHandlers: [SocketEventHandler] { return handlers } func setTestable() { status = .connected } func setTestStatus(_ status: SocketIOClientStatus) { self.status = status } func setTestEngine(_ engine: SocketEngineSpec?) { self.engine = engine } func emitTest(event: String, _ data: Any...) { _emit([event] + data) } }
mit
ea5bfcc2bf4b5bcc63ddea5ff14adba7
34.679276
120
0.625086
4.605732
false
false
false
false
zhuzhengwei/ResearchKit
Testing/ORKTest/ORKTest/Charts/ChartDataSources.swift
5
7416
/* Copyright (c) 2015, James Cox. All rights reserved. Copyright (c) 2015, Ricardo Sánchez-Sáez. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import ResearchKit func randomColorArray(number: Int) -> [UIColor] { func random() -> CGFloat { return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) } var colors: [UIColor] = [] for _ in 0 ..< number { colors.append(UIColor(red: random(), green: random(), blue: random(), alpha: 1)) } return colors } let NumberOfPieChartSegments = 8 class ColorlessPieChartDataSource: NSObject, ORKPieChartViewDataSource { func numberOfSegmentsInPieChartView(pieChartView: ORKPieChartView ) -> Int { return NumberOfPieChartSegments } func pieChartView(pieChartView: ORKPieChartView, valueForSegmentAtIndex index: Int) -> CGFloat { return CGFloat(index + 1) } func pieChartView(pieChartView: ORKPieChartView, titleForSegmentAtIndex index: Int) -> String { return "Title \(index + 1)" } } class RandomColorPieChartDataSource: ColorlessPieChartDataSource { lazy var backingStore: [UIColor] = { return randomColorArray(NumberOfPieChartSegments) }() func pieChartView(pieChartView: ORKPieChartView, colorForSegmentAtIndex index: Int) -> UIColor { return backingStore[index] } } class BaseGraphChartDataSource: NSObject, ORKGraphChartViewDataSource { var plotPoints: [[ORKRangedPoint]] = [[]] func numberOfPlotsInGraphChartView(graphChartView: ORKGraphChartView) -> Int { return plotPoints.count } func graphChartView(graphChartView: ORKGraphChartView, pointForPointIndex pointIndex: Int, plotIndex: Int) -> ORKRangedPoint { return plotPoints[plotIndex][pointIndex] } func graphChartView(graphChartView: ORKGraphChartView, numberOfPointsForPlotIndex plotIndex: Int) -> Int { return plotPoints[plotIndex].count } } class LineGraphChartDataSource: BaseGraphChartDataSource { override init() { super.init() plotPoints = [ [ ORKRangedPoint(), ORKRangedPoint(value: 20), ORKRangedPoint(value: 25), ORKRangedPoint(), ORKRangedPoint(value: 30), ORKRangedPoint(value: 40), ORKRangedPoint(), ], [ ORKRangedPoint(value: 2), ORKRangedPoint(value: 4), ORKRangedPoint(value: 8), ORKRangedPoint(value: 16), ORKRangedPoint(value: 32), ORKRangedPoint(value: 50), ORKRangedPoint(value: 64), ], [ ORKRangedPoint(), ORKRangedPoint(), ORKRangedPoint(), ORKRangedPoint(value: 20), ORKRangedPoint(value: 25), ORKRangedPoint(), ORKRangedPoint(value: 30), ORKRangedPoint(value: 40), ORKRangedPoint(), ], ] } func maximumValueForGraphChartView(graphChartView: ORKGraphChartView) -> CGFloat { return 70 } func minimumValueForGraphChartView(graphChartView: ORKGraphChartView) -> CGFloat { return 0 } func numberOfDivisionsInXAxisForGraphChartView(graphChartView: ORKGraphChartView) -> Int { return 10 } func graphChartView(graphChartView: ORKGraphChartView, titleForXAxisAtPointIndex pointIndex: Int) -> String { return "\(pointIndex + 1)" } func scrubbingPlotIndexForGraphChartView(graphChartView: ORKGraphChartView) -> Int { return 2 } } class ColoredLineGraphChartDataSource: LineGraphChartDataSource { func graphChartView(graphChartView: ORKGraphChartView, colorForPlotIndex plotIndex: Int) -> UIColor { let color: UIColor switch plotIndex { case 0: color = UIColor.cyanColor() case 1: color = UIColor.magentaColor() case 2: color = UIColor.yellowColor() default: color = UIColor.redColor() } return color } } class DiscreteGraphChartDataSource: BaseGraphChartDataSource { override init() { super.init() plotPoints = [ [ ORKRangedPoint(), ORKRangedPoint(minimumValue: 0, maximumValue: 2), ORKRangedPoint(minimumValue: 1, maximumValue: 3), ORKRangedPoint(minimumValue: 2, maximumValue: 6), ORKRangedPoint(minimumValue: 3, maximumValue: 9), ORKRangedPoint(minimumValue: 4, maximumValue: 13), ], [ ORKRangedPoint(value: 1), ORKRangedPoint(minimumValue: 2, maximumValue: 4), ORKRangedPoint(minimumValue: 3, maximumValue: 8), ORKRangedPoint(minimumValue: 5, maximumValue: 11), ORKRangedPoint(minimumValue: 7, maximumValue: 13), ORKRangedPoint(minimumValue: 10, maximumValue: 13), ORKRangedPoint(minimumValue: 12, maximumValue: 15), ], ] } func numberOfDivisionsInXAxisForGraphChartView(graphChartView: ORKGraphChartView) -> Int { return 8 } func graphChartView(graphChartView: ORKGraphChartView, titleForXAxisAtPointIndex pointIndex: Int) -> String { return "\(pointIndex + 1)" } func scrubbingPlotIndexForGraphChartView(graphChartView: ORKGraphChartView) -> Int { return 1 } }
bsd-3-clause
f869768e11288d824a1ec10f1a5c12f2
35.343137
130
0.631643
5.395924
false
false
false
false
an23lm/Player
Player/MediaApplication.swift
1
2489
// // YouTube.swift // Player // // Created by Ansèlm Joseph on 15/07/2017. // Copyright © 2017 Ansèlm Joseph. All rights reserved. // import Cocoa enum MediaApplication: String { case iTunes = "com.apple.iTunes" case spotify = "com.spotify.client" case chrome = "com.google.Chrome" } enum PlayerState: String { case playing = "Playing" case paused = "Paused" case stopped = "Stopped" case unknown = "Unknown" } class Track { var name: String var artist: String var album: String var albumArtwork: Data init(name: String, artist: String, album: String, albumArtwork: Data) { self.name = name self.album = album self.artist = artist self.albumArtwork = albumArtwork } } class CurrentMediaApplication { static var shared: CurrentMediaApplication = CurrentMediaApplication(withAppleScript: Script.shared.appleScript) private var script: AppleScript! = nil var bundleIdentifier: MediaApplication { return BundleIdentifierManager.shared.currentBundleID } var name: String { switch bundleIdentifier { case .iTunes: return "iTunes" case .chrome: return "Google Chrome" default: return "Unknown" } } var track: Track { switch bundleIdentifier { case .iTunes: let trackName = ITunes.shared.currentTrack!.name let album = ITunes.shared.currentTrack!.album let artist = ITunes.shared.currentTrack!.artist let artwork = ITunes.shared.currentTrack!.albumArtwork return Track(name: trackName, artist: album, album: artist, albumArtwork: artwork) case .chrome: return Track(name: YouTube.shared.title, artist: "", album: "", albumArtwork: Data()) default: return Track(name: "", artist: "", album: "", albumArtwork: Data()) } } var state: PlayerState { switch bundleIdentifier { case .iTunes: return ITunes.shared.state case .chrome: return YouTube.shared.state default: return .unknown } } init (withAppleScript appleScript: AppleScript) { self.script = appleScript // YouTube.init(withAppleScript: appleScript) // iTunes.init(withAppleScript: appleScript) } }
apache-2.0
645c9641f407779c375905c3210e8d7e
25.446809
116
0.599356
4.690566
false
false
false
false
daisysomus/swift-algorithm-club
Linear Regression/LinearRegression.playground/Contents.swift
3
1401
// Linear Regression import Foundation let carAge: [Double] = [10, 8, 3, 3, 2, 1] let carPrice: [Double] = [500, 400, 7000, 8500, 11000, 10500] var intercept = 0.0 var slope = 0.0 func predictedCarPrice(_ carAge: Double) -> Double { return intercept + slope * carAge } // An iterative approach let numberOfCarAdvertsWeSaw = carPrice.count let numberOfIterations = 100 let alpha = 0.0001 for n in 1...numberOfIterations { for i in 0..<numberOfCarAdvertsWeSaw { let difference = carPrice[i] - predictedCarPrice(carAge[i]) intercept += alpha * difference slope += alpha * difference * carAge[i] } } print("A car age of 4 years is predicted to be worth £\(Int(predictedCarPrice(4)))") // A closed form solution func average(_ input: [Double]) -> Double { return input.reduce(0, +) / Double(input.count) } func multiply(_ a: [Double], _ b: [Double]) -> [Double] { return zip(a,b).map(*) } func linearRegression(_ xs: [Double], _ ys: [Double]) -> (Double) -> Double { let sum1 = average(multiply(xs, ys)) - average(xs) * average(ys) let sum2 = average(multiply(xs, xs)) - pow(average(xs), 2) let slope = sum1 / sum2 let intercept = average(ys) - slope * average(xs) return { x in intercept + slope * x } } let result = linearRegression(carAge, carPrice)(4) print("A car of age 4 years is predicted to be worth £\(Int(result))")
mit
63eb0767bc31786a4787fdaee0842b20
26.98
84
0.653324
3.223502
false
false
false
false
1000copy/fin
Model/TopicCommentModel.swift
1
13935
import UIKit import Alamofire import Ji import YYText import Kingfisher protocol V2CommentAttachmentImageTapDelegate : class { func V2CommentAttachmentImageSingleTap(_ imageView:V2CommentAttachmentImage) } /// 评论中的图片 class V2CommentAttachmentImage:AnimatedImageView { /// 父容器中第几张图片 var index:Int = 0 /// 图片地址 var imageURL:String? weak var delegate : V2CommentAttachmentImageTapDelegate? init(){ super.init(frame: CGRect(x: 0, y: 0, width: 80, height: 80)) self.autoPlayAnimatedImage = false; self.contentMode = .scaleAspectFill self.clipsToBounds = true self.isUserInteractionEnabled = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if self.image != nil { return } if let imageURL = self.imageURL , let URL = URL(string: imageURL) { self.kf.setImage(with: URL, placeholder: nil, options: nil, completionHandler: { (image, error, cacheType, imageURL) -> () in if let image = image { if image.size.width < 80 && image.size.height < 80 { self.contentMode = .bottomLeft } } }) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let tapCount = touch?.tapCount if let tapCount = tapCount { if tapCount == 1 { self.handleSingleTap(touch!) } } //取消后续的事件响应 self.next?.touchesCancelled(touches, with: event) } func handleSingleTap(_ touch:UITouch){ self.delegate?.V2CommentAttachmentImageSingleTap(self) } } class TopicCommentModel:TopicCommentModel_{ // fileprivate var textLayout:YYTextLayout? var textLayout_:YYTextLayout? fileprivate var textLayout:YYTextLayout?{ get{ if textLayout_ == nil { textLayout_ = getTextLayout(textAttributedString) } return textLayout_ } set { textLayout_ = newValue } } func getHeight()-> CGFloat{ let layout = textLayout! return layout.textBoundingRect.size.height + 12 + 35 + 12 + 12 + 1 } func getText()-> String?{ return textLayout?.text.string } func getTextLayout(_ str:NSMutableAttributedString?)->YYTextLayout?{ let textContainer = YYTextContainer(size: CGSize(width: SCREEN_WIDTH - 24, height: 9999)) return YYTextLayout(container: textContainer, text: str!) } func getTextLayout()->YYTextLayout?{ let str = textAttributedString let textContainer = YYTextContainer(size: CGSize(width: SCREEN_WIDTH - 24, height: 9999)) return YYTextLayout(container: textContainer, text: str!) } func toDict()->TJTableDataSourceItem{ var item = TJTableDataSourceItem() item["replyId"] = replyId item["avata"] = avata item["userName"] = userName item["date"] = date item["favorites"] = favorites item["textLayout"] = textLayout item["images"] = images item["number"] = number item["textAttributedString"] = textAttributedString return item } func fromDict(_ item : TJTableDataSourceItem){ if let r = item["replyId"] as? String{ replyId = r } avata = item["avata"] as! String userName = item["userName"] as! String date = item["date"] as! String favorites = item["favorites"] as! Int textLayout = item["textLayout"] as! YYTextLayout images = item["images"] as! NSMutableArray number = item["number"] as! Int textAttributedString = item["textAttributedString"] as! NSMutableAttributedString } } class TopicCommentModel_: NSObject,BaseHtmlModelProtocol { var replyId:String? var avata: String? var userName: String? var date: String? // var comment: String? var favorites: Int = 0 var images:NSMutableArray = NSMutableArray() //楼层 var number:Int = 0 var textAttributedString:NSMutableAttributedString? override init() { super.init() } required init(rootNode: JiNode) { super.init() let id = rootNode.xPath("table/tr/td[3]/div[1]/div[attribute::id]").first?["id"] if let id = id { if id.hasPrefix("thank_area_") { self.replyId = id.replacingOccurrences(of: "thank_area_", with: "") } } self.avata = rootNode.xPath("table/tr/td[1]/img").first?["src"] self.userName = rootNode.xPath("table/tr/td[3]/strong/a").first?.content self.date = rootNode.xPath("table/tr/td[3]/span").first?.content if let str = rootNode.xPath("table/tr/td[3]/div[@class='fr']/span").first?.content , let no = Int(str){ self.number = no; } if let favorite = rootNode.xPath("table/tr/td[3]/span[2]").first?.content { let array = favorite.components(separatedBy: " ") if array.count == 2 { if let i = Int(array[1]){ self.favorites = i } } } self.textAttributedString = NSMutableAttributedString(string: "") let nodes = rootNode.xPath("table/tr/td[3]/div[@class='reply_content']/node()") self.preformAttributedString(textAttributedString!, nodes: nodes) // //构造评论内容 // let commentAttributedString:NSMutableAttributedString = NSMutableAttributedString(string: "") // let nodes = rootNode.xPath("table/tr/td[3]/div[@class='reply_content']/node()") // self.preformAttributedString(commentAttributedString, nodes: nodes) // let textContainer = YYTextContainer(size: CGSize(width: SCREEN_WIDTH - 24, height: 9999)) // self.textLayout = YYTextLayout(container: textContainer, text: commentAttributedString) // // self.textAttributedString = commentAttributedString } func preformAttributedString(_ commentAttributedString:NSMutableAttributedString,nodes:[JiNode]) { for element in nodes { if element.name == "text" , let content = element.content{//普通文本 commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSFontAttributeName:v2ScaleFont(14) , NSForegroundColorAttributeName:V2EXColor.colors.v2_TopicListTitleColor])) commentAttributedString.yy_lineSpacing = 5 } else if element.name == "img" ,let imageURL = element["src"] {//图片 let image = V2CommentAttachmentImage() image.imageURL = imageURL let imageAttributedString = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit , attachmentSize: CGSize(width: 80,height: 80), alignTo: v2ScaleFont(14), alignment: .bottom) commentAttributedString.append(imageAttributedString) image.index = self.images.count self.images.add(imageURL) } else if element.name == "a" ,let content = element.content,let url = element["href"]{//超链接 //递归处理所有子节点,主要是处理下 a标签下包含的img标签 let subNodes = element.xPath("./node()") if subNodes.first?.name != "text" && subNodes.count > 0 { self.preformAttributedString(commentAttributedString, nodes: subNodes) } if content.Lenght > 0 { let attr = NSMutableAttributedString(string: content ,attributes: [NSFontAttributeName:v2ScaleFont(14)]) attr.yy_setTextHighlight(NSMakeRange(0, content.Lenght), color: V2EXColor.colors.v2_LinkColor, backgroundColor: UIColor(white: 0.95, alpha: 1), userInfo: ["url":url], tapAction: { (view, text, range, rect) -> Void in if let highlight = text.yy_attribute(YYTextHighlightAttributeName, at: UInt(range.location)) ,let url = (highlight as AnyObject).userInfo["url"] as? String { AnalyzeURLHelper.Analyze(url) } }, longPressAction: nil) commentAttributedString.append(attr) } } else if let content = element.content{//其他 commentAttributedString.append(NSMutableAttributedString(string: content,attributes: [NSForegroundColorAttributeName:V2EXColor.colors.v2_TopicListTitleColor])) } } } } //MARK: - Request class TopicCommentModelHTTP { class func replyWithTopicId(_ topic:TopicDetailModel, content:String, completionHandler: @escaping (V2Response) -> Void){ let url = V2EXURL + "t/" + topic.topicId! User.shared.getOnce(url) { (response) -> Void in if response.success { let prames = [ "content":content, "once":User.shared.once! ] as [String:Any] Alamofire.request(url, method: .post, parameters: prames, headers: MOBILE_CLIENT_HEADERS).responseJiHtml { (response) -> Void in if let location = response.response?.allHeaderFields["Etag"] as? String{ if location.Lenght > 0 { completionHandler(V2Response(success: true)) } else { completionHandler(V2Response(success: false, message: "回帖失败")) } //不管成功还是失败,更新一下once if let jiHtml = response .result.value{ User.shared.once = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"] } return } completionHandler(V2Response(success: false,message: "请求失败")) } } else{ completionHandler(V2Response(success: false,message: "获取once失败,请重试")) } } } class func replyThankWithReplyId(_ replyId:String , token:String ,completionHandler: @escaping (V2Response) -> Void) { let url = V2EXURL + "thank/reply/" + replyId + "?t=" + token Alamofire.request(url, method: .post, headers: MOBILE_CLIENT_HEADERS).responseString { (response: DataResponse<String>) -> Void in if response.result.isSuccess { if let result = response.result.value { if result.Lenght == 0 { completionHandler(V2Response(success: true)) return; } } } completionHandler(V2Response(success: false)) } } } //MARK: - Method extension TopicCommentModel { /** 用某一条评论,获取和这条评论有关的所有评论 - parameter array: 所有的评论数组 - parameter firstComment: 这条评论 - returns: 某一条评论相关的评论,里面包含它自己 */ class func getRelevantCommentsInArray(_ allCommentsArray:[TopicCommentModel], firstComment:TopicCommentModel) -> [TopicCommentModel] { var relevantComments:[TopicCommentModel] = [] var users = getUsersOfComment(firstComment) users.insert(firstComment.userName!) for comment in allCommentsArray { //判断评论中是否只@了其他用户,是的话则证明这条评论是和别人讲的,不属于当前对话 let commentUsers = getUsersOfComment(comment) let intersectUsers = commentUsers.intersection(users) if commentUsers.count > 0 && intersectUsers.count <= 0 { continue; } if let username = comment.userName { if users.contains(username) { relevantComments.append(comment) } } //只找到点击的位置,之后就不找了 if comment == firstComment { break; } } return relevantComments } //获取评论中 @ 了多少用户 class func getUsersOfComment(_ comment:TopicCommentModel) -> Set<String> { //获取到所有YYTextHighlight ,用以之后获取 这条评论@了多少用户 var textHighlights:[YYTextHighlight] = [] comment.textAttributedString!.enumerateAttribute(YYTextHighlightAttributeName, in: NSMakeRange(0, comment.textAttributedString!.length), options: []) { (attribute, range, stop) -> Void in if let highlight = attribute as? YYTextHighlight { textHighlights.append(highlight) } } //获取这条评论 @ 了多少用户 var users:Set<String> = [] for highlight in textHighlights { if let url = highlight.userInfo?["url"] as? String{ let result = AnalyzURLResultType(url: url) if case .member(let member) = result { users.insert(member.username) } } } return users } }
mit
73624d11b4c0427afddd86fcd2ef9d99
43.674419
232
0.574403
4.711633
false
false
false
false
lkzhao/YetAnotherAnimationLibrary
Sources/YetAnotherAnimationLibrary/Animator/DisplayLink.swift
1
2381
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[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 UIKit private let minDeltaTime = 1.0 / 30.0 /// The `update(dt:)` function will be called on every screen refresh if started internal class DisplayLink: NSObject { private var displayLink: CADisplayLink? private var lastUpdateTime: TimeInterval = 0 internal var isRunning: Bool { return displayLink != nil } @objc internal func _update() { guard let _ = displayLink else { return } let currentTime = CACurrentMediaTime() defer { lastUpdateTime = currentTime } var dt = currentTime - lastUpdateTime while dt > minDeltaTime { update(dt: minDeltaTime) dt -= minDeltaTime } update(dt: dt) } open func update(dt: TimeInterval) {} internal func start() { guard !isRunning else { return } lastUpdateTime = CACurrentMediaTime() displayLink = CADisplayLink(target: self, selector: #selector(_update)) displayLink!.add(to: .main, forMode: .common) } internal func stop() { guard let displayLink = displayLink else { return } displayLink.isPaused = true displayLink.remove(from: .main, forMode: .common) self.displayLink = nil } }
mit
6e12fd43a9f3729ed0785176721744e2
37.403226
80
0.693406
4.659491
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/Image/Resolution.swift
1
4292
// // Resolution.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct Resolution: Hashable { public var horizontal: Double public var vertical: Double public var unit: Unit @inlinable public init(horizontal: Double, vertical: Double, unit: Unit) { self.horizontal = horizontal self.vertical = vertical self.unit = unit } @inlinable public init(resolution: Double, unit: Unit) { self.horizontal = resolution self.vertical = resolution self.unit = unit } } extension Resolution { @inlinable public static var `default`: Resolution { return Resolution(resolution: 1, unit: .point) } } extension Resolution { public enum Unit: CaseIterable { case point case pica case meter case centimeter case millimeter case inch } } extension Resolution.Unit { @usableFromInline var inchScale: Double { switch self { case .point: return 72 case .pica: return 6 case .meter: return 0.0254 case .centimeter: return 2.54 case .millimeter: return 25.4 case .inch: return 1 } } } extension Resolution { @inlinable public func convert(to toUnit: Resolution.Unit) -> Resolution { let scale = unit.inchScale / toUnit.inchScale return Resolution(horizontal: scale * horizontal, vertical: scale * vertical, unit: toUnit) } } extension Resolution.Unit { @inlinable public func convert(length: Double, from fromUnit: Resolution.Unit) -> Double { return fromUnit.convert(length: length, to: self) } @inlinable public func convert(point: Point, from fromUnit: Resolution.Unit) -> Point { return fromUnit.convert(point: point, to: self) } @inlinable public func convert(size: Size, from fromUnit: Resolution.Unit) -> Size { return fromUnit.convert(size: size, to: self) } @inlinable public func convert(rect: Rect, from fromUnit: Resolution.Unit) -> Rect { return fromUnit.convert(rect: rect, to: self) } @inlinable public func convert(length: Double, to toUnit: Resolution.Unit) -> Double { let scale = toUnit.inchScale / self.inchScale return length * scale } @inlinable public func convert(point: Point, to toUnit: Resolution.Unit) -> Point { let scale = toUnit.inchScale / self.inchScale return point * scale } @inlinable public func convert(size: Size, to toUnit: Resolution.Unit) -> Size { let scale = toUnit.inchScale / self.inchScale return size * scale } @inlinable public func convert(rect: Rect, to toUnit: Resolution.Unit) -> Rect { let scale = toUnit.inchScale / self.inchScale return rect * scale } } extension Resolution: CustomStringConvertible { @inlinable public var description: String { return "Resolution(horizontal: \(horizontal), vertical: \(vertical), unit: \(unit))" } }
mit
34d434b0fa3bc6eaa83361b3f823ce4d
28.39726
99
0.654473
4.415638
false
false
false
false
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/BE/SessionBE.swift
1
3637
// // SessionBE.swift // AllStarsV2 // // Created by Kenyi Rodriguez Vergara on 20/07/17. // Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved. // import UIKit class SessionBE: NSObject, NSCoding { var session_pwd_reset_required : NSNumber = false var session_base_profile_complete : NSNumber = false var session_user_id : NSNumber = 0 var session_token : String = "" var session_user : String? var session_password : String? var session_state : SessionState = .session_profileComplete enum SessionState: NSNumber { case session_profileComplete = 1 case session_profileIncomplete = 2 case session_needResetPassword = 3 } public static var sharedInstance : SessionBE? override init() { super.init() } required public init(coder aDecoder: NSCoder) { self.session_pwd_reset_required = aDecoder.decodeObject(forKey:"session_pwd_reset_required") as! NSNumber self.session_base_profile_complete = aDecoder.decodeObject(forKey:"session_base_profile_complete") as! NSNumber self.session_user_id = aDecoder.decodeObject(forKey:"session_user_id") as! NSNumber self.session_token = aDecoder.decodeObject(forKey:"session_token") as! String self.session_user = aDecoder.decodeObject(forKey:"session_user") as? String self.session_password = aDecoder.decodeObject(forKey:"session_password") as? String // self.session_state = SessionState(rawValue: aDecoder.decodeObject(forKey:"session_state") as! NSNumber) ?? .session_profileComplete } public func encode(with aCoder: NSCoder) { aCoder.encode(self.session_pwd_reset_required, forKey: "session_pwd_reset_required") aCoder.encode(self.session_base_profile_complete, forKey: "session_base_profile_complete") aCoder.encode(self.session_user_id, forKey: "session_user_id") aCoder.encode(self.session_token, forKey: "session_token") aCoder.encode(self.session_user!, forKey: "session_user") aCoder.encode(self.session_password!, forKey: "session_password") aCoder.encode(self.session_state.rawValue, forKey: "SessionState") } class func parse(_ objDic : [String : Any]) -> SessionBE { let objBE = SessionBE() objBE.session_pwd_reset_required = NSNumber(booleanLiteral: CDMWebResponse.getBool(objDic["is_password_reset_required"])) objBE.session_base_profile_complete = NSNumber(booleanLiteral: CDMWebResponse.getBool(objDic["is_base_profile_complete"])) objBE.session_user_id = NSNumber(integerLiteral: CDMWebResponse.getInt(objDic["user_id"])) objBE.session_token = CDMWebResponse.getString(objDic["token"]) if objBE.session_pwd_reset_required.boolValue == false { if objBE.session_base_profile_complete.boolValue == true{ objBE.session_state = .session_profileComplete }else{ objBE.session_state = .session_profileIncomplete } }else{ objBE.session_state = .session_needResetPassword } return objBE } }
apache-2.0
4c282449f60c65182ee8b767f69d019f
40.793103
158
0.590759
4.596713
false
false
false
false
renxlWin/gege
swiftChuge/swiftChuge/Main/Home/Controller/RxNearVC.swift
1
2847
// // RxHomeVC.swift // swiftChuge // // Created by RXL on 17/3/21. // Copyright © 2017年 RXL. All rights reserved. // import UIKit class RxNearVC: RxBaseVC { override func viewDidLoad() { super.viewDidLoad() prepareUI(); } //MARK:懒加载 lazy var contentScroll : UIScrollView = { let scrollView = UIScrollView(); scrollView.backgroundColor = UIColor.white; scrollView.contentSize = CGSize(width: screenWidth * 3, height: 0) scrollView.delegate = self; scrollView.isPagingEnabled = true; scrollView.bounces = false; scrollView.showsHorizontalScrollIndicator = false; return scrollView; }(); lazy var titleSegment : UISegmentedControl = { let segment = UISegmentedControl(items: ["广场","人","颜值"]) segment.frame = CGRect(x: 0, y: 0, width: screenWidth * 0.5, height: 30); segment.tintColor = UIColor.white; segment.selectedSegmentIndex = 0; let font = UIFont.systemFont(ofSize: 16); segment.setTitleTextAttributes([NSFontAttributeName : font], for: .normal); segment.addTarget(self, action:#selector(RxNearVC.changeView), for: .valueChanged); return segment; }(); lazy var parkVC : RxParkVC = { let parkVC = RxParkVC(); return parkVC; }() } //MARK:界面布局 extension RxNearVC { func prepareUI() { setNav(); view.addSubview(contentScroll); contentScroll.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsetsMake(0, 0, 44, 0)); } contentScroll.addSubview(parkVC.view); parkVC.view.snp.makeConstraints { (make) in make.leading.height.top.equalToSuperview(); make.width.equalTo(screenWidth); }; } private func setNav(){ self.navigationItem.titleView = titleSegment; } } //MARK:按钮点击事件 extension RxNearVC { func changeView(){ let index : CGFloat = CGFloat(titleSegment.selectedSegmentIndex); contentScroll.setContentOffset(CGPoint(x: screenWidth * index , y : 0), animated: true); } } //MARK:代理 extension RxNearVC : UIScrollViewDelegate{ func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let index = scrollView.mj_offsetX / screenWidth; titleSegment.selectedSegmentIndex = Int(index); } }
mit
a19a3b4e58a6f0aaac7dc3ba8cd7b954
21.253968
96
0.543866
5.135531
false
false
false
false
izotx/iTenWired-Swift
Conference App/AppDelegate.swift
1
11796
// Copyright (c) 2016, Izotx // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Izotx nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // AppDelegate.swift // Conference App // Created by B4TH Administrator on 4/1/16. import UIKit import CoreData import FBSDKCoreKit import Fabric import TwitterKit enum NotificationObserver:String { case APPBecameActive case RemoteNotificationReceived } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate{ var window: UIWindow? func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { let notificationController = NotificationController() let data = userInfo.first!.1 as? NSDictionary let alert = data!["alert"] let date = NSDate() let notification = Notification(message: (alert!["body"] as? String)!, title: (alert!["title"] as? String)!, date: date) if application.applicationState == UIApplicationState.Active { notification.setDone(true) let alertView = SCLAlertView() let alertViewIcon = UIImage(named: "AnnouncementsFilled-50.png") alertView.showNotification(notification.title, subTitle: notification.message, circleIconImage: alertViewIcon) } notificationController.addNotification(notification) NSNotificationCenter.defaultCenter().postNotificationName(NotificationObserver.RemoteNotificationReceived.rawValue, object: self) UIApplication.sharedApplication().applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1 completionHandler(UIBackgroundFetchResult.NewData) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { _ = OneSignal(launchOptions: launchOptions, appId: "d7ae9182-b319-4654-a5e1-9107872f2a2b") { (message, additionalData, isActive) in NSLog("OneSignal Notification opened:\nMessage: %@", message) } OneSignal.defaultClient().enableInAppAlertNotification(false) let appData = AppData() if NetworkConnection.isConnected(){ appData.saveData() } // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.navigationBar.translucent = true splitViewController.maximumPrimaryColumnWidth = 320 splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.managedObjectContext //FBSDKApplication Delegate FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) //Twitter Fabric.with([Twitter.self]) return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { //Facebook return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], completionHandler: () -> Void) { } func applicationDidBecomeActive(application: UIApplication) { NSNotificationCenter.defaultCenter().postNotificationName(NotificationObserver.APPBecameActive.rawValue, object: self) //Facebook FBSDKAppEvents.activateApp() } 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. let notificationController = NotificationController() UIApplication.sharedApplication().applicationIconBadgeNumber = notificationController.getNumberOfUnReadNotifications() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() let notificationController = NotificationController() UIApplication.sharedApplication().applicationIconBadgeNumber = notificationController.getNumberOfUnReadNotifications() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.booksforthehungry.chrystechsystems.Conference_App" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Conference_App", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } } //Mark: - UISplitViewControllerDelegate extension AppDelegate: UISplitViewControllerDelegate { func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { //return true guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. //return true return true } return false } }
bsd-2-clause
acfc286953f9afff057c2df787de4fa0
48.772152
291
0.713377
6.096124
false
false
false
false
iadmir/Signal-iOS
Signal/src/views/AttachmentPointerView.swift
1
5996
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation class AttachmentPointerView: UIView { let TAG = "[AttachmentPointerView]" let progressView = OWSProgressView() let nameLabel = UILabel() let statusLabel = UILabel() let isIncoming: Bool let filename: String let attachmentPointer: TSAttachmentPointer let genericFilename = NSLocalizedString("ATTACHMENT_DEFAULT_FILENAME", comment: "Generic filename for an attachment with no known name") var progress: CGFloat = 0 { didSet { self.progressView.progress = progress } } required init(attachmentPointer: TSAttachmentPointer, isIncoming: Bool) { self.isIncoming = isIncoming self.attachmentPointer = attachmentPointer let attachmentPointerFilename = attachmentPointer.sourceFilename if let filename = attachmentPointerFilename, !filename.isEmpty { self.filename = filename } else { self.filename = genericFilename } super.init(frame: CGRect.zero) createSubviews() updateViews() if attachmentPointer.state == .downloading { NotificationCenter.default.addObserver(self, selector:#selector(attachmentDownloadProgress(_:)), name:NSNotification.Name.attachmentDownloadProgress, object:nil) } } deinit { NotificationCenter.default.removeObserver(self) } internal func attachmentDownloadProgress(_ notification: Notification) { guard let attachmentId = attachmentPointer.uniqueId else { owsFail("Missing attachment id.") return } guard let progress = (notification as NSNotification).userInfo?[kAttachmentDownloadProgressKey] as? NSNumber else { owsFail("Attachment download notification missing progress.") return } guard let notificationAttachmentId = (notification as NSNotification).userInfo?[kAttachmentDownloadAttachmentIDKey] as? String else { owsFail("Attachment download notification missing attachment id.") return } guard notificationAttachmentId == attachmentId else { return } self.progress = CGFloat(progress.floatValue) } @available(*, unavailable) override init(frame: CGRect) { owsFail("invalid constructor") // This initializer should never be called, but we assign some bogus values to keep the compiler happy. self.filename = genericFilename self.isIncoming = false self.attachmentPointer = TSAttachmentPointer() super.init(frame: frame) self.createSubviews() self.updateViews() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { owsFail("Invalid constructor") // This initializer should never be called, but we assign some bogus values to keep the compiler happy. self.filename = genericFilename self.isIncoming = false self.attachmentPointer = TSAttachmentPointer() super.init(coder: aDecoder) self.createSubviews() self.updateViews() } func createSubviews() { self.addSubview(nameLabel) // truncate middle to be sure we include file extension nameLabel.lineBreakMode = .byTruncatingMiddle nameLabel.textAlignment = .center nameLabel.textColor = self.textColor nameLabel.font = UIFont.ows_dynamicTypeBody() nameLabel.autoPinWidthToSuperview() nameLabel.autoPinEdge(toSuperviewEdge: .top) self.addSubview(progressView) progressView.autoPinWidthToSuperview() progressView.autoPinEdge(.top, to: .bottom, of: nameLabel, withOffset: 6) progressView.autoSetDimension(.height, toSize: 8) self.addSubview(statusLabel) statusLabel.textAlignment = .center statusLabel.adjustsFontSizeToFitWidth = true statusLabel.textColor = self.textColor statusLabel.font = UIFont.ows_footnote() statusLabel.autoPinWidthToSuperview() statusLabel.autoPinEdge(.top, to: .bottom, of: progressView, withOffset: 4) statusLabel.autoPinEdge(toSuperviewEdge: .bottom) } func emojiForContentType(_ contentType: String) -> String { if MIMETypeUtil.isImage(contentType) { return "📷" } else if MIMETypeUtil.isVideo(contentType) { return "📽" } else if MIMETypeUtil.isAudio(contentType) { return "📻" } else if MIMETypeUtil.isAnimated(contentType) { return "🎡" } else { // generic file return "📁" } } func updateViews() { let emoji = self.emojiForContentType(self.attachmentPointer.contentType) nameLabel.text = "\(emoji) \(self.filename)" statusLabel.text = { switch self.attachmentPointer.state { case .enqueued: return NSLocalizedString("ATTACHMENT_DOWNLOADING_STATUS_QUEUED", comment: "Status label when an attachment is enqueued, but hasn't yet started downloading") case .downloading: return NSLocalizedString("ATTACHMENT_DOWNLOADING_STATUS_IN_PROGRESS", comment: "Status label when an attachment is currently downloading") case .failed: return NSLocalizedString("ATTACHMENT_DOWNLOADING_STATUS_FAILED", comment: "Status label when an attachment download has failed.") } }() if attachmentPointer.state == .downloading { progressView.isHidden = false } else { progressView.isHidden = true } } var textColor: UIColor { return self.isIncoming ? UIColor.darkText : UIColor.white } }
gpl-3.0
5325502fd1c773d5f28c531ee0575626
35.03012
172
0.638689
5.5023
false
false
false
false
bradhowes/SynthInC
SwiftMIDI/SoundFont.swift
1
6536
// SoundFonts.swift // SynthInC // // Created by Brad Howes // Copyright (c) 2016 Brad Howes. All rights reserved. import UIKit import GameKit let systemFontAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: UIFont.systemFontSize)] /** Representation of a sound font library. NOTE: all sound font files must have 'sf2' extension. */ public final class SoundFont { /** Mapping of registered sound fonts. Add additional sound font entries here to make them available to the SoundFont code. NOTE: the value of this mapping is manipulated by the Python script `catalog.py` found in the `Extras` folder. In particular, it expects to find the -BEGIN- and -END- comments. */ public static let library: [String:SoundFont] = [ // -BEGIN- FreeFontGMVer32SoundFont.name: FreeFontGMVer32SoundFont, GeneralUserGSMuseScoreversion1442SoundFont.name: GeneralUserGSMuseScoreversion1442SoundFont, FluidR3GMSoundFont.name: FluidR3GMSoundFont, UserBankSoundFont.name: UserBankSoundFont, // -END- ] /** Array of registered sound font names sorted in alphabetical order. Generated from `library` entries. */ public static let keys: [String] = library.keys.sorted() /** Maximium width of all library names. */ public static let maxNameWidth: CGFloat = library.values.map { $0.nameWidth }.max() ?? 100.0 public static let patchCount: Int = library.reduce(0) { $0 + $1.1.patches.count } /** Obtain a random patch from all registered sound fonts. - returns: radom Patch object */ public static func randomPatch(randomSource: GKRandomDistribution) -> Patch { let namePos = randomSource.nextInt(upperBound: keys.count) let soundFont = getByIndex(namePos) let patchPos = randomSource.nextInt(upperBound: soundFont.patches.count) return soundFont.patches[patchPos] } /** Obtain a SoundFont using an index into the `keys` name array. If the index is out-of-bounds this will return the FreeFont sound font. - parameter index: the key to use - returns: found SoundFont object */ public static func getByIndex(_ index: Int) -> SoundFont { guard index >= 0 && index < keys.count else { return SoundFont.library[SoundFont.keys[0]]! } let key = keys[index] return library[key]! } /** Obtain the index in `keys` for the given sound font name. If not found, return 0 - parameter name: the name to look for - returns: found index or zero */ public static func indexForName(_ name: String) -> Int { return keys.index(of: name) ?? 0 } public let soundFontExtension = "sf2" /// Presentation name of the sound font public let name: String /// Width of the sound font name public lazy var nameWidth = { return (name as NSString).size(withAttributes: systemFontAttributes).width }() /// The file name of the sound font (sans extension) public let fileName: String /// The resolved URL for the sound font public let fileURL: URL /// The collection of Patches found in the sound font public let patches: [Patch] /// The max width of all of the patch names in the sound font public lazy var maxPatchNameWidth = { patches.map { $0.nameWidth }.max() ?? 100.0 }() /// The gain to apply to a patch in the sound font public let dbGain: Float32 /** Initialize new SoundFont instance. - parameter name: the display name for the sound font - parameter fileName: the file name of the sound font in the application bundle - parameter patches: the array of Patch objects for the sound font - parameter dbGain: AudioUnit attenuation to apply to patches from this sound font [-90, +12] */ init(_ name: String, fileName: String, _ patches: [Patch], _ dbGain: Float32 = 0.0 ) { self.name = name self.fileName = fileName self.fileURL = Bundle(for: SoundFont.self).url(forResource: fileName, withExtension: soundFontExtension)! self.patches = patches self.dbGain = min(max(dbGain, -90.0), 12.0) patches.forEach { $0.soundFont = self } } /** Locate a patch in the SoundFont using a display name. - parameter name: the display name to search for - returns: found Patch or nil */ public func findPatch(_ name: String) -> Patch? { guard let found = findPatchIndex(name) else { return nil } return patches[found] } /** Obtain the index to a Patch with a given name. - parameter name: the display name to search for - returns: index of found object or nil if not found */ public func findPatchIndex(_ name: String) -> Int? { return patches.index(where: { return $0.name == name }) } } /** Representation of a patch in a sound font. */ public final class Patch { /// Display name for the patch public let name: String /// Width of the name in the system font public lazy var nameWidth: CGFloat = { return (name as NSString).size(withAttributes: systemFontAttributes).width }() /// Bank number where the patch resides in the sound font public let bank: Int /// Program patch number where the patch resides in the sound font public let patch: Int /// Reference to the SoundFont parent (set by the SoundFont itself) public weak var soundFont: SoundFont! = nil /** Initialize Patch instance. - parameter name: the diplay name for the patch - parameter bank: the bank where the patch resides - parameter patch: the program ID of the patch in the sound font */ init(_ name: String, _ bank: Int, _ patch: Int) { self.name = name self.bank = bank self.patch = patch } } let FavoriteSoundFont = SoundFont.getByIndex(0) public let FavoritePatches = [ FavoriteSoundFont.patches[0], FavoriteSoundFont.patches[7], FavoriteSoundFont.patches[2], FavoriteSoundFont.patches[12], FavoriteSoundFont.patches[24], FavoriteSoundFont.patches[42], FavoriteSoundFont.patches[32], FavoriteSoundFont.patches[40], FavoriteSoundFont.patches[46], FavoriteSoundFont.patches[52], FavoriteSoundFont.patches[53], FavoriteSoundFont.patches[54], FavoriteSoundFont.patches[64], FavoriteSoundFont.patches[73], FavoriteSoundFont.patches[74], FavoriteSoundFont.patches[79], FavoriteSoundFont.patches[108], ]
mit
fd0e5b6fedb37be40458110cc04cce18
33.765957
117
0.674572
4.082448
false
false
false
false
mumbler/PReVo-iOS
PoshReVo/Subaj Paghoj/Agordoj/LingvoElektiloViewController.swift
1
8586
// // LingvoElektiloViewController.swift // PoshReVo // // Created by Robin Hill on 3/11/16. // Copyright © 2016 Robin Hill. All rights reserved. // import Foundation import UIKit import ReVoModeloj import ReVoDatumbazo let lingvoElektiloChelIdent = "lingvoElektiloChelo" /* Delegate por ke aliaj paghoj povos reagi al lingvo-elektado */ protocol LingvoElektiloDelegate { func elektisLingvon(lingvo: Lingvo) } /* Pagho por elekti lingvon. La unua sekcio povas montri lastaj elektitaj lingvoj, kaj sube videblas chiu lingvo */ final class LingvoElektiloViewController : UIViewController, Stilplena { @IBOutlet var serchTabulo: UISearchBar? @IBOutlet var lingvoTabelo: UITableView? private let chiujLingvoj = VortaroDatumbazo.komuna.chiujLingvoj() private var validajLingvoj: [Lingvo]? private var filtritajLingvoj: [Lingvo]? = nil private var suprajLingvoj: [Lingvo]? private var suprajTitolo: String? private var montriEsperanton: Bool = true var montrotajLingvoj: [Lingvo] { return filtritajLingvoj ?? validajLingvoj ?? chiujLingvoj } var delegate: LingvoElektiloDelegate? init() { super.init(nibName: "LingvoElektiloViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func starigi(titolo: String, suprajTitolo: String? = nil, montriEsperanton: Bool = true) { title = titolo self.suprajTitolo = suprajTitolo suprajLingvoj = UzantDatumaro.oftajSerchLingvoj self.montriEsperanton = montriEsperanton if !montriEsperanton { suprajLingvoj?.removeAll(where: { (lingvo) -> Bool in lingvo == Lingvo.esperanto }) validajLingvoj = chiujLingvoj validajLingvoj?.removeAll(where: { (lingvo) -> Bool in lingvo == Lingvo.esperanto }) } } override func viewDidLoad() { serchTabulo?.delegate = self lingvoTabelo?.delegate = self lingvoTabelo?.dataSource = self lingvoTabelo?.register(UITableViewCell.self, forCellReuseIdentifier: lingvoElektiloChelIdent) NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeDidChange(forChildContentContainer:)), name: UIContentSizeCategory.didChangeNotification, object: nil) efektivigiStilon() } // MARK: - Paĝ-informoj private func chiujSekcioj() -> Int { if suprajLingvoj == nil { return 0 } else { return 1 } } // MARK: - Paĝ-agoj func forigiSin() { if presentingViewController != nil { navigationController?.dismiss(animated: true, completion: nil) } else { navigationController?.popViewController(animated: true) } } // MARK: - Stiplena func efektivigiStilon() { serchTabulo?.backgroundColor = UzantDatumaro.stilo.bazKoloro serchTabulo?.barStyle = UzantDatumaro.stilo.serchTabuloKoloro serchTabulo?.keyboardAppearance = UzantDatumaro.stilo.klavaroKoloro serchTabulo?.tintColor = UzantDatumaro.stilo.tintKoloro lingvoTabelo?.indicatorStyle = UzantDatumaro.stilo.scrollKoloro lingvoTabelo?.backgroundColor = UzantDatumaro.stilo.fonKoloro lingvoTabelo?.separatorColor = UzantDatumaro.stilo.apartigiloKoloro lingvoTabelo?.reloadData() } } // MARK: - UISearchBarDelegate extension LingvoElektiloViewController : UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard let teksto = searchBar.text else { return true } // Ĉapeli literojn if text == "x" && teksto.count > 0 { let chapelita = Iloj.chapeliFinon(teksto) if chapelita != teksto { searchBar.text = chapelita self.searchBar(searchBar, textDidChange: teksto) return false } } return true } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { searchBar.text = searchBar.text?.lowercased() if let teksto = searchBar.text, !teksto.isEmpty { filtritajLingvoj = Iloj.filtriLingvojn(teksto: teksto, lingvoj: chiujLingvoj, montriEsperanton: montriEsperanton) } else { filtritajLingvoj = nil } lingvoTabelo?.reloadData() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } } // MARK: - UITableViewDelegate & UITableViewDataSource extension LingvoElektiloViewController : UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { if filtritajLingvoj == nil && suprajLingvoj != nil { return 2 } else { return 1 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let filtritajLingvoj = filtritajLingvoj { return filtritajLingvoj.count } else { if section == chiujSekcioj() { return montrotajLingvoj.count } else if let suprajLingvoj = suprajLingvoj { return suprajLingvoj.count } } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let novaChelo: UITableViewCell if let trovChelo = lingvoTabelo?.dequeueReusableCell(withIdentifier: lingvoElektiloChelIdent) { novaChelo = trovChelo } else { novaChelo = UITableViewCell() } novaChelo.backgroundColor = UzantDatumaro.stilo.bazKoloro novaChelo.textLabel?.textColor = UzantDatumaro.stilo.tekstKoloro let lingvo: Lingvo if let filtritajLingvoj = filtritajLingvoj { lingvo = filtritajLingvoj[indexPath.row] } else { if indexPath.section == chiujSekcioj() { lingvo = montrotajLingvoj[indexPath.row] } else if let suprajLingvoj = suprajLingvoj { lingvo = suprajLingvoj[indexPath.row] } else { fatalError("Mankas lingvo") } } novaChelo.textLabel?.text = lingvo.nomo novaChelo.isAccessibilityElement = true novaChelo.accessibilityLabel = novaChelo.textLabel?.text return novaChelo } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard suprajLingvoj != [] else { return nil } if filtritajLingvoj == nil { if section == 0 { return suprajTitolo } else if section == 1 { return NSLocalizedString("lingvo-elektilo chiuj etikedo", comment: "") } } return nil } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var lingvo: Lingvo? = nil if let filtritajLingvoj = filtritajLingvoj { lingvo = filtritajLingvoj[indexPath.row] } else { if indexPath.section == chiujSekcioj() { lingvo = montrotajLingvoj[indexPath.row] } else { lingvo = suprajLingvoj?[indexPath.row] } } if let veraLingvo = lingvo, let delegate = delegate { delegate.elektisLingvon(lingvo: veraLingvo) } lingvoTabelo?.deselectRow(at: indexPath, animated: true) forigiSin() } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } // MARK: - Helpiloj extension LingvoElektiloViewController { func didChangePreferredContentSize(notification: NSNotification) -> Void { lingvoTabelo?.reloadData() } }
mit
52ea0eec788e3e09d92d9c876c61ad2e
29.21831
195
0.613726
4.297446
false
false
false
false
wordpress-mobile/AztecEditor-iOS
WordPressEditor/WordPressEditor/Classes/Extensions/VideoAttachment+WordPress.swift
2
1050
import Foundation import Aztec // MARK: - VideoAttachment // extension VideoAttachment { @objc public var videoPressID: String? { get { return extraAttributes[VideoShortcodeProcessor.videoPressHTMLAttribute]?.toString() } set { if let nonNilValue = newValue { extraAttributes[VideoShortcodeProcessor.videoPressHTMLAttribute] = .string(nonNilValue) } else { extraAttributes.remove(named: VideoShortcodeProcessor.videoPressHTMLAttribute) } } } @objc public var isShortcode: Bool { get { return extraAttributes[VideoShortcodeProcessor.videoWPShortcodeHTMLAttribute]?.toString() == "true" } set { if newValue { extraAttributes[VideoShortcodeProcessor.videoWPShortcodeHTMLAttribute] = .string(String("true")) } else { extraAttributes.remove(named: VideoShortcodeProcessor.videoWPShortcodeHTMLAttribute) } } } }
mpl-2.0
95a0f7240efddfba783c872663555fd1
29.882353
112
0.622857
5.19802
false
false
false
false
ingresse/ios-sdk
IngresseSDK/Model/WalletInfoPaypal.swift
1
926
// // Copyright © 2019 Ingresse. All rights reserved. // public class WalletInfoPaypal: NSObject, Decodable { public var id: String = "" public var additional: WalletInfoPaypalAdditional? enum CodingKeys: String, CodingKey { case id case additional } public required init(from decoder: Decoder) throws { guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return } id = container.decodeKey(.id, ofType: String.self) additional = container.decodeKey(.additional, ofType: WalletInfoPaypalAdditional.self) } } public class WalletInfoPaypalAdditional: NSObject, Codable { public var email: String = "" public required init(from decoder: Decoder) throws { guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return } email = container.decodeKey(.email, ofType: String.self) } }
mit
4f480d79bb3e6e09cada143c1235b927
29.833333
94
0.690811
4.60199
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/Kingfisher/Sources/Views/Indicator.swift
3
7158
// // Indicator.swift // Kingfisher // // Created by João D. Moreira on 30/08/16. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !os(watchOS) #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit public typealias IndicatorView = NSView #else import UIKit public typealias IndicatorView = UIView #endif /// Represents the activity indicator type which should be added to /// an image view when an image is being downloaded. /// /// - none: No indicator. /// - activity: Uses the system activity indicator. /// - image: Uses an image as indicator. GIF is supported. /// - custom: Uses a custom indicator. The type of associated value should conform to the `Indicator` protocol. public enum IndicatorType { /// No indicator. case none /// Uses the system activity indicator. case activity /// Uses an image as indicator. GIF is supported. case image(imageData: Data) /// Uses a custom indicator. The type of associated value should conform to the `Indicator` protocol. case custom(indicator: Indicator) } /// An indicator type which can be used to show the download task is in progress. public protocol Indicator { /// Called when the indicator should start animating. func startAnimatingView() /// Called when the indicator should stop animating. func stopAnimatingView() /// Center offset of the indicator. Kingfisher will use this value to determine the position of /// indicator in the super view. var centerOffset: CGPoint { get } /// The indicator view which would be added to the super view. var view: IndicatorView { get } } extension Indicator { /// Default implementation of `centerOffset` of `Indicator`. The default value is `.zero`, means that there is /// no offset for the indicator view. public var centerOffset: CGPoint { return .zero } } // Displays a NSProgressIndicator / UIActivityIndicatorView final class ActivityIndicator: Indicator { #if os(macOS) private let activityIndicatorView: NSProgressIndicator #else private let activityIndicatorView: UIActivityIndicatorView #endif private var animatingCount = 0 var view: IndicatorView { return activityIndicatorView } func startAnimatingView() { if animatingCount == 0 { #if os(macOS) activityIndicatorView.startAnimation(nil) #else activityIndicatorView.startAnimating() #endif activityIndicatorView.isHidden = false } animatingCount += 1 } func stopAnimatingView() { animatingCount = max(animatingCount - 1, 0) if animatingCount == 0 { #if os(macOS) activityIndicatorView.stopAnimation(nil) #else activityIndicatorView.stopAnimating() #endif activityIndicatorView.isHidden = true } } init() { #if os(macOS) activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) activityIndicatorView.controlSize = .small activityIndicatorView.style = .spinning #else let indicatorStyle: UIActivityIndicatorView.Style #if os(tvOS) if #available(tvOS 13.0, *) { indicatorStyle = UIActivityIndicatorView.Style.large } else { indicatorStyle = UIActivityIndicatorView.Style.white } #else if #available(iOS 13.0, * ) { indicatorStyle = UIActivityIndicatorView.Style.medium } else { indicatorStyle = UIActivityIndicatorView.Style.gray } #endif #if swift(>=4.2) activityIndicatorView = UIActivityIndicatorView(style: indicatorStyle) #else activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle) #endif #endif } } #if canImport(UIKit) extension UIActivityIndicatorView.Style { #if compiler(>=5.1) #else static let large = UIActivityIndicatorView.Style.white #if !os(tvOS) static let medium = UIActivityIndicatorView.Style.gray #endif #endif } #endif // MARK: - ImageIndicator // Displays an ImageView. Supports gif final class ImageIndicator: Indicator { private let animatedImageIndicatorView: KFCrossPlatformImageView var view: IndicatorView { return animatedImageIndicatorView } init?( imageData data: Data, processor: ImageProcessor = DefaultImageProcessor.default, options: KingfisherParsedOptionsInfo? = nil) { var options = options ?? KingfisherParsedOptionsInfo(nil) // Use normal image view to show animations, so we need to preload all animation data. if !options.preloadAllAnimationData { options.preloadAllAnimationData = true } guard let image = processor.process(item: .data(data), options: options) else { return nil } animatedImageIndicatorView = KFCrossPlatformImageView() animatedImageIndicatorView.image = image #if os(macOS) // Need for gif to animate on macOS animatedImageIndicatorView.imageScaling = .scaleNone animatedImageIndicatorView.canDrawSubviewsIntoLayer = true #else animatedImageIndicatorView.contentMode = .center #endif } func startAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = true #else animatedImageIndicatorView.startAnimating() #endif animatedImageIndicatorView.isHidden = false } func stopAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = false #else animatedImageIndicatorView.stopAnimating() #endif animatedImageIndicatorView.isHidden = true } } #endif
mit
3db58c69e5195b5b15e2de9568b6e766
32.288372
114
0.665083
5.167509
false
false
false
false
victorlin/ReactiveCocoa
ReactiveCocoa.playground/Pages/SignalProducer.xcplaygroundpage/Contents.swift
1
21606
/*: > # IMPORTANT: To use `ReactiveCocoa.playground`, please: 1. Retrieve the project dependencies using one of the following terminal commands from the ReactiveCocoa project root directory: - `script/bootstrap` **OR**, if you have [Carthage](https://github.com/Carthage/Carthage) installed - `carthage checkout` 1. Open `ReactiveCocoa.xcworkspace` 1. Build `Result-Mac` scheme 1. Build `ReactiveCocoa-Mac` scheme 1. Finally open the `ReactiveCocoa.playground` 1. Choose `View > Show Debug Area` */ import Result import ReactiveCocoa import Foundation /*: ## SignalProducer A **signal producer**, represented by the [`SignalProducer`](https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/ReactiveCocoa/Swift/SignalProducer.swift) type, creates [signals](https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/ReactiveCocoa/Swift/Signal.swift) and performs side effects. They can be used to represent operations or tasks, like network requests, where each invocation of `start()` will create a new underlying operation, and allow the caller to observe the result(s). The `startWithSignal()` variant gives access to the produced signal, allowing it to be observed multiple times if desired. Because of the behavior of `start()`, each signal created from the same producer may see a different ordering or version of events, or the stream might even be completely different! Unlike a plain signal, no work is started (and thus no events are generated) until an observer is attached, and the work is restarted anew for each additional observer. Starting a signal producer returns a [disposable](#disposables) that can be used to interrupt/cancel the work associated with the produced signal. Just like signals, signal producers can also be manipulated via primitives like `map`, `filter`, etc. Every signal primitive can be “lifted” to operate upon signal producers instead, using the `lift` method. Furthermore, there are additional primitives that control _when_ and _how_ work is started—for example, `times`. */ /*: ### `Subscription` A SignalProducer represents an operation that can be started on demand. Starting the operation returns a Signal on which the result(s) of the operation can be observed. This behavior is sometimes also called "cold". This means that a subscriber will never miss any values sent by the SignalProducer. */ scopedExample("Subscription") { let producer = SignalProducer<Int, NoError> { observer, _ in print("New subscription, starting operation") observer.sendNext(1) observer.sendNext(2) } let subscriber1 = Observer<Int, NoError>(next: { print("Subscriber 1 received \($0)") }) let subscriber2 = Observer<Int, NoError>(next: { print("Subscriber 2 received \($0)") }) print("Subscriber 1 subscribes to producer") producer.start(subscriber1) print("Subscriber 2 subscribes to producer") // Notice, how the producer will start the work again producer.start(subscriber2) } /*: ### `empty` A producer for a Signal that will immediately complete without sending any values. */ scopedExample("`empty`") { let emptyProducer = SignalProducer<Int, NoError>.empty let observer = Observer<Int, NoError>( next: { _ in print("next not called") }, failed: { _ in print("error not called") }, completed: { print("completed called") } ) emptyProducer.start(observer) } /*: ### `never` A producer for a Signal that never sends any events to its observers. */ scopedExample("`never`") { let neverProducer = SignalProducer<Int, NoError>.never let observer = Observer<Int, NoError>( next: { _ in print("next not called") }, failed: { _ in print("error not called") }, completed: { print("completed not called") } ) neverProducer.start(observer) } /*: ### `startWithSignal` Creates a Signal from the producer, passes it into the given closure, then starts sending events on the Signal when the closure has returned. The closure will also receive a disposable which can be used to interrupt the work associated with the signal and immediately send an `Interrupted` event. */ scopedExample("`startWithSignal`") { var started = false var value: Int? SignalProducer<Int, NoError>(value: 42) .on(next: { value = $0 }) .startWithSignal { signal, disposable in print(value) } print(value) } /*: ### `startWithResult` Creates a Signal from the producer, then adds exactly one observer to the Signal, which will invoke the given callback when `next` or `failed` events are received. Returns a Disposable which can be used to interrupt the work associated with the Signal, and prevent any future callbacks from being invoked. */ scopedExample("`startWithResult`") { SignalProducer<Int, NoError>(value: 42) .startWithResult { result in print(result.value) } } /*: ### `startWithNext` Creates a Signal from the producer, then adds exactly one observer to the Signal, which will invoke the given callback when `next` events are received. This method is available only if the producer never emits error, or in other words, has an error type of `NoError`. Returns a Disposable which can be used to interrupt the work associated with the Signal, and prevent any future callbacks from being invoked. */ scopedExample("`startWithNext`") { SignalProducer<Int, NoError>(value: 42) .startWithNext { value in print(value) } } /*: ### `startWithCompleted` Creates a Signal from the producer, then adds exactly one observer to the Signal, which will invoke the given callback when a `completed` event is received. Returns a Disposable which can be used to interrupt the work associated with the Signal. */ scopedExample("`startWithCompleted`") { SignalProducer<Int, NoError>(value: 42) .startWithCompleted { print("completed called") } } /*: ### `startWithFailed` Creates a Signal from the producer, then adds exactly one observer to the Signal, which will invoke the given callback when a `failed` event is received. Returns a Disposable which can be used to interrupt the work associated with the Signal. */ scopedExample("`startWithFailed`") { SignalProducer<Int, NSError>(error: NSError(domain: "example", code: 42, userInfo: nil)) .startWithFailed { error in print(error) } } /*: ### `startWithInterrupted` Creates a Signal from the producer, then adds exactly one observer to the Signal, which will invoke the given callback when an `interrupted` event is received. Returns a Disposable which can be used to interrupt the work associated with the Signal. */ scopedExample("`startWithInterrupted`") { let disposable = SignalProducer<Int, NoError>.never .startWithInterrupted { print("interrupted called") } disposable.dispose() } /*: ### `lift` Lifts an unary Signal operator to operate upon SignalProducers instead. In other words, this will create a new SignalProducer which will apply the given Signal operator to _every_ created Signal, just as if the operator had been applied to each Signal yielded from start(). */ scopedExample("`lift`") { var counter = 0 let transform: (Signal<Int, NoError>) -> Signal<Int, NoError> = { signal in counter = 42 return signal } SignalProducer<Int, NoError>(value: 0) .lift(transform) .startWithNext { _ in print(counter) } } /*: ### `map` Maps each value in the producer to a new value. */ scopedExample("`map`") { SignalProducer<Int, NoError>(value: 1) .map { $0 + 41 } .startWithNext { value in print(value) } } /*: ### `mapError` Maps errors in the producer to a new error. */ scopedExample("`mapError`") { SignalProducer<Int, NSError>(error: NSError(domain: "mapError", code: 42, userInfo: nil)) .mapError { PlaygroundError.example($0.description) } .startWithFailed { error in print(error) } } /*: ### `filter` Preserves only the values of the producer that pass the given predicate. */ scopedExample("`filter`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .filter { $0 > 3 } .startWithNext { value in print(value) } } /*: ### `take(first:)` Returns a producer that will yield the first `count` values from the input producer. */ scopedExample("`take(first:)`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .take(first: 2) .startWithNext { value in print(value) } } /*: ### `observe(on:)` Forwards all events onto the given scheduler, instead of whichever scheduler they originally arrived upon. */ scopedExample("`observe(on:)`") { let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) let completion = { print("is main thread? \(Thread.current.isMainThread)") } baseProducer .observe(on: QueueScheduler(qos: .default, name: "test")) .startWithCompleted(completion) baseProducer .startWithCompleted(completion) } /*: ### `collect` Returns a producer that will yield an array of values until it completes. */ scopedExample("`collect`") { SignalProducer<Int, NoError> { observer, disposable in observer.sendNext(1) observer.sendNext(2) observer.sendNext(3) observer.sendNext(4) observer.sendCompleted() } .collect() .startWithNext { value in print(value) } } /*: ### `collect(count:)` Returns a producer that will yield an array of values until it reaches a certain count. */ scopedExample("`collect(count:)`") { SignalProducer<Int, NoError> { observer, disposable in observer.sendNext(1) observer.sendNext(2) observer.sendNext(3) observer.sendNext(4) observer.sendCompleted() } .collect(count: 2) .startWithNext { value in print(value) } } /*: ### `collect(_:)` matching values inclusively Returns a producer that will yield an array of values based on a predicate which matches the values collected. When producer completes any remaining values will be sent, the last values array may not match `predicate`. Alternatively, if were not collected any values will sent an empty array of values. */ scopedExample("`collect(_:)` matching values inclusively") { SignalProducer<Int, NoError> { observer, disposable in observer.sendNext(1) observer.sendNext(2) observer.sendNext(3) observer.sendNext(4) observer.sendCompleted() } .collect { values in values.reduce(0, +) == 3 } .startWithNext { value in print(value) } } /*: ### `collect(_:)` matching values exclusively Returns a producer that will yield an array of values based on a predicate which matches the values collected and the next value. When producer completes any remaining values will be sent, the last values array may not match `predicate`. Alternatively, if were not collected any values will sent an empty array of values. */ scopedExample("`collect(_:)` matching values exclusively") { SignalProducer<Int, NoError> { observer, disposable in observer.sendNext(1) observer.sendNext(2) observer.sendNext(3) observer.sendNext(4) observer.sendCompleted() } .collect { values, next in next == 3 } .startWithNext { value in print(value) } } /*: ### `combineLatest(with:)` Combines the latest value of the receiver with the latest value from the given producer. The returned producer will not send a value until both inputs have sent at least one value each. If either producer is interrupted, the returned producer will also be interrupted. */ scopedExample("`combineLatest(with:)`") { let producer1 = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) let producer2 = SignalProducer<Int, NoError>(values: [ 1, 2 ]) producer1 .combineLatest(with: producer2) .startWithNext { value in print("\(value)") } } /*: ### `skip(first:)` Returns a producer that will skip the first `count` values, then forward everything afterward. */ scopedExample("`skip(first:)`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .skip(first: 2) .startWithNext { value in print(value) } } /*: ### `materialize` Treats all Events from the input producer as plain values, allowing them to be manipulated just like any other value. In other words, this brings Events “into the monad.” When a Completed or Failed event is received, the resulting producer will send the Event itself and then complete. When an Interrupted event is received, the resulting producer will send the Event itself and then interrupt. */ scopedExample("`materialize`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .materialize() .startWithNext { value in print(value) } } /*: ### `sample(on:)` Forwards the latest value from `self` whenever `sampler` sends a Next event. If `sampler` fires before a value has been observed on `self`, nothing happens. Returns a producer that will send values from `self`, sampled (possibly multiple times) by `sampler`, then complete once both input producers have completed, or interrupt if either input producer is interrupted. */ scopedExample("`sample(on:)`") { let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) let sampledOnProducer = SignalProducer<Int, NoError>(values: [ 1, 2 ]) .map { _ in () } baseProducer .sample(on: sampledOnProducer) .startWithNext { value in print(value) } } /*: ### `combinePrevious` Forwards events from `self` with history: values of the returned producer are a tuple whose first member is the previous value and whose second member is the current value. `initial` is supplied as the first member when `self` sends its first value. */ scopedExample("`combinePrevious`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .combinePrevious(42) .startWithNext { value in print("\(value)") } } /*: ### `scan` Aggregates `self`'s values into a single combined value. When `self` emits its first value, `combine` is invoked with `initial` as the first argument and that emitted value as the second argument. The result is emitted from the producer returned from `scan`. That result is then passed to `combine` as the first argument when the next value is emitted, and so on. */ scopedExample("`scan`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .scan(0, +) .startWithNext { value in print(value) } } /*: ### `reduce` Like `scan`, but sends only the final value and then immediately completes. */ scopedExample("`reduce`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .reduce(0, +) .startWithNext { value in print(value) } } /*: ### `skipRepeats` Forwards only those values from `self` which do not pass `isRepeat` with respect to the previous value. The first value is always forwarded. */ scopedExample("`skipRepeats`") { SignalProducer<Int, NoError>(values: [ 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4 ]) .skipRepeats(==) .startWithNext { value in print(value) } } /*: ### `skip(while:)` Does not forward any values from `self` until `predicate` returns false, at which point the returned signal behaves exactly like `self`. */ scopedExample("`skip(while:)`") { // Note that trailing closure is used for `skip(while:)`. SignalProducer<Int, NoError>(values: [ 3, 3, 3, 3, 1, 2, 3, 4 ]) .skip { $0 > 2 } .startWithNext { value in print(value) } } /*: ### `take(untilReplacement:)` Forwards events from `self` until `replacement` begins sending events. Returns a producer which passes through `Next`, `Failed`, and `Interrupted` events from `self` until `replacement` sends an event, at which point the returned producer will send that event and switch to passing through events from `replacement` instead, regardless of whether `self` has sent events already. */ scopedExample("`take(untilReplacement:)`") { let (replacementSignal, incomingReplacementObserver) = Signal<Int, NoError>.pipe() let baseProducer = SignalProducer<Int, NoError> { incomingObserver, _ in incomingObserver.sendNext(1) incomingObserver.sendNext(2) incomingObserver.sendNext(3) incomingReplacementObserver.sendNext(42) incomingObserver.sendNext(4) incomingReplacementObserver.sendNext(42) } baseProducer .take(untilReplacement: replacementSignal) .startWithNext { value in print(value) } } /*: ### `take(last:)` Waits until `self` completes and then forwards the final `count` values on the returned producer. */ scopedExample("`take(last:)`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .take(last: 2) .startWithNext { value in print(value) } } /*: ### `skipNil` Unwraps non-`nil` values and forwards them on the returned signal, `nil` values are dropped. */ scopedExample("`skipNil`") { SignalProducer<Int?, NoError>(values: [ nil, 1, 2, nil, 3, 4, nil ]) .skipNil() .startWithNext { value in print(value) } } /*: ### `zip(with:)` Zips elements of two producers into pairs. The elements of any Nth pair are the Nth elements of the two input producers. */ scopedExample("`zip(with:)`") { let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) let zippedProducer = SignalProducer<Int, NoError>(values: [ 42, 43 ]) baseProducer .zip(with: zippedProducer) .startWithNext { value in print("\(value)") } } /*: ### `times` Repeats `self` a total of `count` times. Repeating `1` times results in an equivalent signal producer. */ scopedExample("`times`") { var counter = 0 SignalProducer<(), NoError> { observer, disposable in counter += 1 observer.sendCompleted() } .times(42) .start() print(counter) } /*: ### `retry(upTo:)` Ignores failures up to `count` times. */ scopedExample("`retry(upTo:)`") { var tries = 0 SignalProducer<Int, NSError> { observer, disposable in if tries == 0 { tries += 1 observer.sendFailed(NSError(domain: "retry", code: 0, userInfo: nil)) } else { observer.sendNext(42) observer.sendCompleted() } } .retry(upTo: 1) .startWithResult { result in print(result) } } /*: ### `then` Waits for completion of `producer`, *then* forwards all events from `replacement`. Any failure sent from `producer` is forwarded immediately, in which case `replacement` will not be started, and none of its events will be be forwarded. All values sent from `producer` are ignored. */ scopedExample("`then`") { let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) let thenProducer = SignalProducer<Int, NoError>(value: 42) baseProducer .then(thenProducer) .startWithNext { value in print(value) } } /*: ### `replayLazily(upTo:)` Creates a new `SignalProducer` that will multicast values emitted by the underlying producer, up to `capacity`. This means that all clients of this `SignalProducer` will see the same version of the emitted values/errors. The underlying `SignalProducer` will not be started until `self` is started for the first time. When subscribing to this producer, all previous values (up to `capacity`) will be emitted, followed by any new values. If you find yourself needing *the current value* (the last buffered value) you should consider using `PropertyType` instead, which, unlike this operator, will guarantee at compile time that there's always a buffered value. This operator is not recommended in most cases, as it will introduce an implicit relationship between the original client and the rest, so consider alternatives like `PropertyType`, `SignalProducer.buffer`, or representing your stream using a `Signal` instead. This operator is only recommended when you absolutely need to introduce a layer of caching in front of another `SignalProducer`. This operator has the same semantics as `SignalProducer.buffer`. */ scopedExample("`replayLazily(upTo:)`") { let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4, 42 ]) .replayLazily(upTo: 2) baseProducer.startWithNext { value in print(value) } baseProducer.startWithNext { value in print(value) } baseProducer.startWithNext { value in print(value) } } /*: ### `flatMap(.latest)` Maps each event from `self` to a new producer, then flattens the resulting producers (into a producer of values), according to the semantics of the given strategy. If `self` or any of the created producers fail, the returned producer will forward that failure immediately. */ scopedExample("`flatMap(.latest)`") { SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) .flatMap(.latest) { SignalProducer(value: $0 + 3) } .startWithNext { value in print(value) } } /*: ### `flatMapError` Catches any failure that may occur on the input producer, mapping to a new producer that starts in its place. */ scopedExample("`flatMapError`") { SignalProducer<Int, NSError>(error: NSError(domain: "flatMapError", code: 42, userInfo: nil)) .flatMapError { SignalProducer<Int, NoError>(value: $0.code) } .startWithNext { value in print(value) } } /*: ### `sample(with:)` Forwards the latest value from `self` with the value from `sampler` as a tuple, only when `sampler` sends a Next event. If `sampler` fires before a value has been observed on `self`, nothing happens. Returns a producer that will send values from `self` and `sampler`, sampled (possibly multiple times) by `sampler`, then complete once both input producers have completed, or interrupt if either input producer is interrupted. */ scopedExample("`sample(with:)`") { let producer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4 ]) let sampler = SignalProducer<String, NoError>(values: [ "a", "b" ]) let result = producer.sample(with: sampler) result.startWithNext { left, right in print("\(left) \(right)") } } /*: ### `logEvents` Logs all events that the receiver sends. By default, it will print to the standard output. */ scopedExample("`log events`") { let baseProducer = SignalProducer<Int, NoError>(values: [ 1, 2, 3, 4, 42 ]) baseProducer .logEvents(identifier: "Playground is fun!") .start() }
mit
9286ed69172dda5d2c6b81dbdf21300d
27.156454
215
0.723097
3.777506
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/LayoutKit/Sources/ViewRecycler.swift
2
6411
// Copyright 2016 LinkedIn Corp. // 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. import ObjectiveC import Foundation #if os(iOS) || os(tvOS) import UIKit #endif /** Provides APIs to recycle views by id. Initialize ViewRecycler with a root view whose subviews are eligible for recycling. Call `makeView(layoutId:)` to recycle or create a view of the desired type and id. Call `purgeViews()` to remove all unrecycled views from the view hierarchy. Call `markViewsAsRoot(views:)` to mark the top level views of generated view hierarchy */ class ViewRecycler { private var viewsById = [String: View]() private var unidentifiedViews = Set<View>() #if os(iOS) || os(tvOS) private let defaultLayerAnchorPoint = CGPoint(x: 0.5, y: 0.5) private let defaultTransform = CGAffineTransform.identity #endif /// Retains all subviews of rootView for recycling. init(rootView: View?) { guard let rootView = rootView else { return } // Mark all direct subviews from rootView as managed. // We are recreating the layout they were previously roots of. for view in rootView.subviews where view.type == .root { view.type = .managed } rootView.walkNonRootSubviews { (view) in if let viewReuseId = view.viewReuseId { self.viewsById[viewReuseId] = view } else { self.unidentifiedViews.insert(view) } } } /** Returns a view for the layout. It may recycle an existing view or create a new view. */ func makeOrRecycleView(havingViewReuseId viewReuseId: String?, viewProvider: () -> View) -> View? { // If we have a recyclable view that matches type and id, then reuse it. if let viewReuseId = viewReuseId, let view = viewsById[viewReuseId] { viewsById[viewReuseId] = nil #if os(iOS) || os(tvOS) // Reset affine transformation and layer anchor point to their default values. // Without this there will be an issue when their current value is not the default. // Take affine transformation for example, the issue goes like this. // 1. View has a non-identity transform. // 2. View gets retrieved from the viewsById map. // 3. View's frame gets set under the assumption that its transform is identity. // 4. View's transform gets set to a value. // 5. View's frame gets changed automatically when its transform gets set. As a result, view's frame will not match its transform. // Example: // 1. View has a scale transform of (0.001, 0.001). // 2. View gets reused so its transform is still (0.001, 0.001). // 3. View's frame gets set to (0, 0, 100, 100) which is its original size. // 4. View's transform gets set to identity in a config block. // 5. One would expect view's frame to be (0, 0, 100, 100) since its transform is now identity. But actually its frame will be // (-49950, -49950, 100000, 100000) because its scale has just gone up 1000-fold, i.e. from 0.001 to 1. if view.layer.anchorPoint != defaultLayerAnchorPoint { view.layer.anchorPoint = defaultLayerAnchorPoint } if view.transform != defaultTransform { view.transform = defaultTransform } #endif return view } let providedView = viewProvider() providedView.type = .managed // Remove the provided view from the list of cached views. if let viewReuseId = providedView.viewReuseId, let oldView = viewsById[viewReuseId], oldView == providedView { viewsById[viewReuseId] = nil } else { unidentifiedViews.remove(providedView) } providedView.viewReuseId = viewReuseId return providedView } /// Removes all unrecycled views from the view hierarchy. func purgeViews() { for view in viewsById.values { view.removeFromSuperview() } viewsById.removeAll() for view in unidentifiedViews where view.type == .managed { view.removeFromSuperview() } unidentifiedViews.removeAll() } func markViewsAsRoot(_ views: [View]) { views.forEach { $0.type = .root } } } private var viewReuseIdKey: UInt8 = 0 private var typeKey: UInt8 = 0 extension View { enum ViewType: UInt8 { // Indicates the view was not created by LayoutKit and should not be modified. case unmanaged // Indicates the view is managed by LayoutKit that can be safely removed. case managed // Indicates the view is managed by LayoutKit and is a root of a view hierarchy instantiated (or updated) by `makeViews`. // Used to separate such nested hierarchies so that updating the outer hierarchy doesn't disturb any nested hierarchies. case root } /// Calls visitor for each transitive subview. func walkNonRootSubviews(visitor: (View) -> Void) { for subview in subviews where subview.type != .root { visitor(subview) subview.walkNonRootSubviews(visitor: visitor) } } /// Identifies the layout that was used to create this view. public internal(set) var viewReuseId: String? { get { return objc_getAssociatedObject(self, &viewReuseIdKey) as? String } set { objc_setAssociatedObject(self, &viewReuseIdKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } var type: ViewType { get { return objc_getAssociatedObject(self, &typeKey) as? ViewType ?? .unmanaged } set { let type: ViewType? = (newValue == .unmanaged) ? nil : newValue objc_setAssociatedObject(self, &typeKey, type, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } }
mit
233021889377a6647d5e6acebbc2abbe
38.331288
142
0.635782
4.572753
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Home/Recommend/View/YSBanmikuShowCell.swift
1
1869
// // YSBanmikuShowCell.swift // ysbilibili // // Created by MOLBASE on 2017/8/7. // Copyright © 2017年 YangShen. All rights reserved. // import UIKit class YSBanmikuShowCell: YSNormalBaseCell { var sonStatusModel: YSItemDetailModel? { didSet{ detailLabel.text = createDetailString() } } // MARK: - 懒加载控件 lazy var detailLabel: UILabel = { let detailLabel = UILabel() detailLabel.textColor = UIColor.white detailLabel.font = kCellDetailFont return detailLabel }() // MARK: - 添加控件 override init(frame: CGRect) { super.init(frame: frame) self.addSubview(detailLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 初始化位置 override func layoutSubviews() { super.layoutSubviews() detailLabel.snp.makeConstraints { (make) in make.left.equalTo(maskImageView.snp.left).offset(5) make.bottom.equalTo(maskImageView.snp.bottom).offset(-5) } } } extension YSBanmikuShowCell { fileprivate func createDetailString() -> String { // 1.创建一个formatter let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY-MM-DD HH:mm:ss.s" // 2.判断数据存不存在 guard let timeString = sonStatusModel?.mtime else {return ""} guard let index = sonStatusModel?.index else {return ""} // 3. 返回需要展示的数据格式 let currentDate = dateFormatter.date(from: timeString) if let time = currentDate?.getCustomDateString(){ return "\(time) • 第\(index)话" }else{ return "" } } }
mit
511be52a9c42939e94e8cba994f82305
24.15493
69
0.583427
4.377451
false
false
false
false
KimDarren/FaceCropper
Example/FaceCropper/ExampleController.swift
1
5661
// Copyright (c) 2017 TAEJUN KIM <[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 UIKit import FaceCropper final class ExampleController: UIViewController { let imageView: UIImageView let collectionView: UICollectionView let pickButton: UIButton var faces: [UIImage] = [] override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } // MARK: Initializer init() { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: 100, height: 100) self.imageView = UIImageView() self.imageView.contentMode = .scaleAspectFit self.imageView.backgroundColor = .black self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) self.collectionView.backgroundColor = .white self.collectionView.contentInset = UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10) self.collectionView.register(FaceCollectionViewCell.self, forCellWithReuseIdentifier: "Cell") self.pickButton = UIButton() self.pickButton.backgroundColor = .black self.pickButton.setTitle("Pick the image", for: .normal) self.pickButton.setTitleColor(.white, for: .normal) self.pickButton.titleLabel?.font = UIFont.systemFont(ofSize: 20) super.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { fatalError("init(nibName:bundle:) has not been implemented") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white self.collectionView.dataSource = self self.pickButton.addTarget(self, action: #selector(pickImage), for: .touchUpInside) self.view.addSubview(self.imageView) self.view.addSubview(self.collectionView) self.view.addSubview(self.pickButton) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.imageView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 200) self.collectionView.frame = CGRect(x: 0, y: 200, width: self.view.frame.width, height: self.view.frame.height-200-50) self.pickButton.frame = CGRect(x: 0, y: self.view.frame.height-50, width: self.view.frame.width, height: 50) } // MARK: Action func pickImage() { let imagePicker = UIImagePickerController() imagePicker.sourceType = .photoLibrary imagePicker.delegate = self self.present(imagePicker, animated: true) } func configure(image: UIImage?) { self.imageView.image = image guard let image = image else { self.faces = [] self.collectionView.reloadData() return } image.face.crop { result in switch result { case .success(let faces): self.faces = faces self.collectionView.reloadData() case .notFound: self.showAlert("couldn't find any face") case .failure(let error): self.showAlert(error.localizedDescription) } } } func showAlert(_ message: String) { let alert = UIAlertController(title: "Oops", message: message, preferredStyle: .alert) let action = UIAlertAction(title: "Close", style: .cancel) alert.addAction(action) self.present(alert, animated: true) } } extension ExampleController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true) { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { self.configure(image: nil) return } self.configure(image: image) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true) { self.configure(image: nil) } } } extension ExampleController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! FaceCollectionViewCell let face = self.faces[indexPath.item] cell.configure(face: face) return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.faces.count } }
mit
839978943cd70012850721ba61c5806d
32.898204
121
0.708885
4.572698
false
false
false
false
alessiobrozzi/firefox-ios
SyncTests/StorageClientTests.swift
4
5048
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared @testable import Sync import XCTest import SwiftyJSON // Always return a gigantic encoded payload. func massivify(record: Record<CleartextPayloadJSON>) -> JSON? { return JSON([ "id": record.id, "foo": String(repeating: "X", count: Sync15StorageClient.maxRecordSizeBytes + 1) ]) } class StorageClientTests: XCTestCase { func testPartialJSON() { let body = "0" let o: Any? = try! JSONSerialization.jsonObject(with: body.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.allowFragments) XCTAssertTrue(JSON(object: o!).isInt()) } func testPOSTResult() { // Pulled straight from <http://docs.services.mozilla.com/storage/apis-1.5.html>. let r = "{" + "\"success\": [\"GXS58IDC_12\", \"GXS58IDC_13\", \"GXS58IDC_15\"," + "\"GXS58IDC_16\", \"GXS58IDC_18\", \"GXS58IDC_19\"]," + "\"failed\": {\"GXS58IDC_11\": \"invalid ttl\"," + "\"GXS58IDC_14\": \"invalid sortindex\"}" + "}" let p = POSTResult.fromJSON(JSON(parseJSON: r)) XCTAssertTrue(p != nil) XCTAssertEqual(p!.success[0], "GXS58IDC_12") XCTAssertEqual(p!.failed["GXS58IDC_14"]!, "invalid sortindex") XCTAssertTrue(nil == POSTResult.fromJSON(JSON(parseJSON: "{\"foo\": 5}"))) } func testNumeric() { let m = ResponseMetadata(status: 200, headers: [ "X-Last-Modified": "2174380461.12", ]) XCTAssertTrue(m.lastModifiedMilliseconds == 2174380461120) XCTAssertEqual("2174380461.12", millisecondsToDecimalSeconds(2174380461120)) } // Trivial test for struct semantics that we might want to pay attention to if they change, // and for response header parsing. func testResponseHeaders() { let v: JSON = JSON(parseJSON: "{\"a:\": 2}") let m = ResponseMetadata(status: 200, headers: [ "X-Weave-Timestamp": "1274380461.12", "X-Last-Modified": "2174380461.12", "X-Weave-Next-Offset": "abdef", ]) XCTAssertTrue(m.lastModifiedMilliseconds == 2174380461120) XCTAssertTrue(m.timestampMilliseconds == 1274380461120) XCTAssertTrue(m.nextOffset == "abdef") // Just to avoid consistent overflow allowing ==. XCTAssertTrue(m.lastModifiedMilliseconds?.description == "2174380461120") XCTAssertTrue(m.timestampMilliseconds.description == "1274380461120") let x: StorageResponse<JSON> = StorageResponse<JSON>(value: v, metadata: m) func doTesting(y: StorageResponse<JSON>) { // Make sure that reference fields in a struct are copies of the same reference, // not references to a copy. XCTAssertTrue(x.value == y.value) XCTAssertTrue(y.metadata.lastModifiedMilliseconds == x.metadata.lastModifiedMilliseconds, "lastModified is the same.") XCTAssertTrue(x.metadata.quotaRemaining == nil, "No quota.") XCTAssertTrue(y.metadata.lastModifiedMilliseconds == 2174380461120, "lastModified is correct.") XCTAssertTrue(x.metadata.timestampMilliseconds == 1274380461120, "timestamp is correct.") XCTAssertTrue(x.metadata.nextOffset == "abdef", "nextOffset is correct.") XCTAssertTrue(x.metadata.records == nil, "No X-Weave-Records.") } doTesting(y: x) } func testOverSizeRecords() { let delegate = MockSyncDelegate() // We can use these useless values because we're directly injecting decrypted // payloads; no need for real keys etc. let prefs = MockProfilePrefs() let scratchpad = Scratchpad(b: KeyBundle.random(), persistingTo: prefs) let synchronizer = IndependentRecordSynchronizer(scratchpad: scratchpad, delegate: delegate, basePrefs: prefs, collection: "foo") let jA = "{\"id\":\"aaaaaa\",\"histUri\":\"http://foo.com/\",\"title\": \"ñ\",\"visits\":[{\"date\":1222222222222222,\"type\":1}]}" let rA = Record<CleartextPayloadJSON>(id: "aaaaaa", payload: CleartextPayloadJSON(JSON(parseJSON: jA)), modified: 10000, sortindex: 123, ttl: 1000000) let storageClient = Sync15StorageClient(serverURI: "http://example.com/".asURL!, authorizer: identity, workQueue: DispatchQueue.main, resultQueue: DispatchQueue.main, backoff: MockBackoffStorage()) let collectionClient = storageClient.clientForCollection("foo", encrypter: RecordEncrypter<CleartextPayloadJSON>(serializer: massivify, factory: { CleartextPayloadJSON($0) })) let result = synchronizer.uploadRecords([rA], lastTimestamp: Date.now(), storageClient: collectionClient, onUpload: { _ in deferMaybe(Date.now()) }) XCTAssertTrue(result.value.failureValue is RecordTooLargeError) } }
mpl-2.0
d0feb5e6d2d9ad11a93294330f9f00ef
45.731481
205
0.656826
4.478261
false
true
false
false
mssun/passforios
pass/Controllers/SettingsTableViewController.swift
2
12621
// // SettingsTableViewController.swift // pass // // Created by Mingshen Sun on 18/1/2017. // Copyright © 2017 Bob Sun. All rights reserved. // import CoreData import passKit import SVProgressHUD import UIKit class SettingsTableViewController: UITableViewController, UITabBarControllerDelegate { @IBOutlet var pgpKeyTableViewCell: UITableViewCell! @IBOutlet var passcodeTableViewCell: UITableViewCell! @IBOutlet var passwordRepositoryTableViewCell: UITableViewCell! var setPasscodeLockAlert: UIAlertController? let keychain = AppKeychain.shared var passcodeLock = PasscodeLock.shared func tabBarController(_: UITabBarController, didSelect _: UIViewController) { navigationController?.popViewController(animated: true) } @IBAction private func savePGPKey(segue: UIStoryboardSegue) { guard let sourceController = segue.source as? PGPKeyImporter, sourceController.isReadyToUse() else { return } savePGPKey(using: sourceController) } private func savePGPKey(using keyImporter: PGPKeyImporter) { SVProgressHUD.setDefaultMaskType(.black) SVProgressHUD.setDefaultStyle(.light) SVProgressHUD.show(withStatus: "FetchingPgpKey".localize()) DispatchQueue.global(qos: .userInitiated).async { [unowned self] in Defaults.pgpKeySource = type(of: keyImporter).keySource do { // Remove exiting passphrase AppKeychain.shared.removeAllContent(withPrefix: Globals.pgpKeyPassphrase) try keyImporter.importKeys() try PGPAgent.shared.initKeys() DispatchQueue.main.async { self.setPGPKeyTableViewCellDetailText() SVProgressHUD.showSuccess(withStatus: "Success".localize()) SVProgressHUD.dismiss(withDelay: 1) keyImporter.doAfterImport() } } catch { DispatchQueue.main.async { self.pgpKeyTableViewCell.detailTextLabel?.text = "NotSet".localize() Utils.alert(title: "Error".localize(), message: error.localizedDescription, controller: self, completion: nil) } } } } @IBAction private func saveGitServerSetting(segue _: UIStoryboardSegue) { passwordRepositoryTableViewCell.detailTextLabel?.text = Defaults.gitURL.host } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(actOnPasswordStoreErasedNotification), name: .passwordStoreErased, object: nil) passwordRepositoryTableViewCell.detailTextLabel?.text = Defaults.gitURL.host setPGPKeyTableViewCellDetailText() setPasscodeLockCell() } override func viewWillAppear(_: Bool) { super.viewWillAppear(true) tabBarController!.delegate = self setPasswordRepositoryTableViewCellDetailText() } private func setPasscodeLockCell() { if passcodeLock.hasPasscode { passcodeTableViewCell.detailTextLabel?.text = "On".localize() } else { passcodeTableViewCell.detailTextLabel?.text = "Off".localize() } } private func setPGPKeyTableViewCellDetailText() { var label = "NotSet".localize() let keyID = (try? PGPAgent.shared.getShortKeyID()) ?? [] if keyID.count == 1 { label = keyID.first ?? "" } else if keyID.count > 1 { label = "Multiple" } if Defaults.isYubiKeyEnabled { label += "+YubiKey" } pgpKeyTableViewCell.detailTextLabel?.text = label } private func setPasswordRepositoryTableViewCellDetailText() { let host: String? = { let gitURL = Defaults.gitURL if gitURL.scheme == nil { return URL(string: "scheme://" + gitURL.absoluteString)?.host } return gitURL.host }() passwordRepositoryTableViewCell.detailTextLabel?.text = host } @objc func actOnPasswordStoreErasedNotification() { setPGPKeyTableViewCellDetailText() setPasswordRepositoryTableViewCellDetailText() setPasscodeLockCell() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.detailTextLabel?.font = UIFont.preferredFont(forTextStyle: .body) cell.textLabel?.adjustsFontForContentSizeCategory = true cell.detailTextLabel?.adjustsFontForContentSizeCategory = true return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) if cell == passcodeTableViewCell { if passcodeLock.hasPasscode { showPasscodeActionSheet() } else { setPasscodeLock() } } else if cell == pgpKeyTableViewCell { showPGPKeyActionSheet() } tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat { UITableView.automaticDimension } override func tableView(_: UITableView, estimatedHeightForRowAt _: IndexPath) -> CGFloat { UITableView.automaticDimension } func showPGPKeyActionSheet() { let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) optionMenu.addAction( UIAlertAction(title: PGPKeyURLImportTableViewController.menuLabel, style: .default) { _ in self.performSegue(withIdentifier: "setPGPKeyByURLSegue", sender: self) } ) optionMenu.addAction( UIAlertAction(title: PGPKeyArmorImportTableViewController.menuLabel, style: .default) { _ in self.performSegue(withIdentifier: "setPGPKeyByASCIISegue", sender: self) } ) optionMenu.addAction( UIAlertAction(title: PGPKeyFileImportTableViewController.menuLabel, style: .default) { _ in self.performSegue(withIdentifier: "setPGPKeyByFileSegue", sender: self) } ) if isReadyToUse() { optionMenu.addAction( UIAlertAction(title: "\(Self.menuLabel) (\("Import".localize()))", style: .default) { _ in self.saveImportedKeys() } ) } else { optionMenu.addAction( UIAlertAction(title: "\(Self.menuLabel) (\("Tips".localize()))", style: .default) { _ in let title = "Tips".localize() let message = "PgpCopyPublicAndPrivateKeyToPass.".localize() Utils.alert(title: title, message: message, controller: self) } ) } optionMenu.addAction( UIAlertAction(title: Defaults.isYubiKeyEnabled ? "✓ YubiKey" : "YubiKey", style: .default) { _ in Defaults.isYubiKeyEnabled.toggle() self.setPGPKeyTableViewCellDetailText() } ) if Defaults.pgpKeySource != nil { optionMenu.addAction( UIAlertAction(title: "RemovePgpKeys".localize(), style: .destructive) { _ in let alert = UIAlertController.removeConfirmationAlert(title: "RemovePgpKeys".localize(), message: "") { _ in self.keychain.removeContent(for: PGPKey.PUBLIC.getKeychainKey()) self.keychain.removeContent(for: PGPKey.PRIVATE.getKeychainKey()) PGPAgent.shared.uninitKeys() self.pgpKeyTableViewCell.detailTextLabel?.text = "NotSet".localize() Defaults.pgpKeySource = nil } self.present(alert, animated: true, completion: nil) } ) } optionMenu.addAction(UIAlertAction.cancel()) optionMenu.popoverPresentationController?.sourceView = pgpKeyTableViewCell optionMenu.popoverPresentationController?.sourceRect = pgpKeyTableViewCell.bounds present(optionMenu, animated: true) } func showPasscodeActionSheet() { let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let passcodeRemoveViewController = PasscodeLockViewController() let removePasscodeAction = UIAlertAction(title: "RemovePasscode".localize(), style: .destructive) { [weak self] _ in passcodeRemoveViewController.successCallback = { self?.passcodeLock.delete() self?.setPasscodeLockCell() } self?.present(passcodeRemoveViewController, animated: true, completion: nil) } let changePasscodeAction = UIAlertAction(title: "ChangePasscode".localize(), style: .default) { [weak self] _ in self?.setPasscodeLock() } optionMenu.addAction(removePasscodeAction) optionMenu.addAction(changePasscodeAction) optionMenu.addAction(UIAlertAction.cancel()) optionMenu.popoverPresentationController?.sourceView = passcodeTableViewCell optionMenu.popoverPresentationController?.sourceRect = passcodeTableViewCell.bounds present(optionMenu, animated: true, completion: nil) } @objc func alertTextFieldDidChange(_ sender: UITextField) { // check whether we should enable the Save button in setPasscodeLockAlert if let setPasscodeLockAlert = setPasscodeLockAlert, let setPasscodeLockAlertTextFields0 = setPasscodeLockAlert.textFields?[0], let setPasscodeLockAlertTextFields1 = setPasscodeLockAlert.textFields?[1] { if sender == setPasscodeLockAlertTextFields0 || sender == setPasscodeLockAlertTextFields1 { // two passwords should be the same, and length >= 4 let passcodeText = setPasscodeLockAlertTextFields0.text! let passcodeConfirmationText = setPasscodeLockAlertTextFields1.text! setPasscodeLockAlert.actions[0].isEnabled = passcodeText == passcodeConfirmationText && passcodeText.count >= 4 } } } func setPasscodeLock() { // prepare the alert for setting the passcode setPasscodeLockAlert = UIAlertController(title: "SetPasscode".localize(), message: "FillInAppPasscode.".localize(), preferredStyle: .alert) setPasscodeLockAlert?.addTextField { textField in textField.placeholder = "Passcode".localize() textField.isSecureTextEntry = true textField.addTarget(self, action: #selector(self.alertTextFieldDidChange), for: UIControl.Event.editingChanged) } setPasscodeLockAlert?.addTextField { textField in textField.placeholder = "PasswordConfirmation".localize() textField.isSecureTextEntry = true textField.addTarget(self, action: #selector(self.alertTextFieldDidChange), for: UIControl.Event.editingChanged) } // save action let saveAction = UIAlertAction(title: "Save".localize(), style: .default) { (_: UIAlertAction) in let passcode: String = self.setPasscodeLockAlert!.textFields![0].text! self.passcodeLock.save(passcode: passcode) // refresh the passcode lock cell ("On") self.setPasscodeLockCell() } saveAction.isEnabled = false // disable the Save button by default // cancel action let cancelAction = UIAlertAction.cancel() // present setPasscodeLockAlert?.addAction(saveAction) setPasscodeLockAlert?.addAction(cancelAction) present(setPasscodeLockAlert!, animated: true, completion: nil) } } extension SettingsTableViewController: PGPKeyImporter { static let keySource = KeySource.itunes static let label = "ITunesFileSharing".localize() func isReadyToUse() -> Bool { KeyFileManager.PublicPGP.doesKeyFileExist() && KeyFileManager.PrivatePGP.doesKeyFileExist() } func importKeys() throws { try KeyFileManager.PublicPGP.importKeyFromFileSharing() try KeyFileManager.PrivatePGP.importKeyFromFileSharing() } func saveImportedKeys() { savePGPKey(using: self) } }
mit
da53976f2872bdcd32deafc46a78279e
40.781457
152
0.64725
5.2575
false
false
false
false
Asura19/SwiftAlgorithm
SwiftAlgorithm/SwiftAlgorithm/LC054.swift
1
2548
// // LC054.swift // SwiftAlgorithm // // Created by phoenix on 2022/2/23. // Copyright © 2022 Phoenix. All rights reserved. // import Foundation struct MatrixSpiralIterator { typealias Index = (row: Int, col: Int, idx: Int) let rowCount: Int let colCount: Int private var top: Int private var left: Int private var bottom: Int private var right: Int private let total: Int init(rowCount: Int, colCount: Int) { assert(rowCount >= 1 && colCount >= 1) self.rowCount = rowCount self.colCount = colCount self.top = 0 self.left = 0 self.bottom = rowCount - 1 self.right = colCount - 1 total = rowCount * colCount } var current: Index? mutating func next() -> Index? { guard var c = current else { current = (0, 0, 0) return self.current } if c.idx == total - 1 { return nil } if rowCount == 1 { current = c.col < right ? (0, c.col + 1, c.idx + 1) : nil return current } if colCount == 1 { current = c.row < bottom ? (c.row + 1, 0, c.idx + 1) : nil return current } if c.row == top && c.col < right { c.col += 1 } else if c.col == right && c.row < bottom { c.row += 1 } else if c.row == bottom && c.col > left { c.col -= 1 } else if c.col == left && c.row > top { c.row -= 1 } if c.row == top, c.col == left { top += 1 left += 1 bottom -= 1 right -= 1 c.row = top c.col = left } c.idx += 1 current = c return current } } extension LeetCode { static func printMatrixBySpiral<T>(_ matrix: [[T]]) { guard isMatrix(matrix) else { assert(false, "not a matrix") return } let rowCount = matrix.count let colCount = matrix[0].count var iterator = MatrixSpiralIterator(rowCount: rowCount, colCount: colCount) while let index = iterator.next() { print("\(index.idx): \(matrix[index.row][index.col])") } } private static func isMatrix<T>(_ matrix: [[T]]) -> Bool { if matrix.count == 0 { return false } let colCount = matrix[0].count return matrix.filter { $0.count != colCount }.count == 0 } }
mit
96df5a80bcd1d4409f42aeec6fc2c7ae
23.257143
83
0.485669
4.023697
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/KCFloatingActionButton/Sources/KCFABManager.swift
2
2304
// // KCFABManager.swift // KCFloatingActionButton-Sample // // Created by LeeSunhyoup on 2015. 10. 13.. // Copyright © 2015년 kciter. All rights reserved. // import UIKit /** KCFloatingActionButton dependent on UIWindow. */ open class KCFABManager: NSObject { private static var __once: () = { StaticInstance.instance = KCFABManager() }() struct StaticInstance { static var dispatchToken: Int = 0 static var instance: KCFABManager? } open class func defaultInstance() -> KCFABManager { _ = KCFABManager.__once return StaticInstance.instance! } var _fabWindow: KCFABWindow? = nil var fabWindow: KCFABWindow { get { if _fabWindow == nil { _fabWindow = KCFABWindow(frame: UIScreen.main.bounds) _fabWindow?.rootViewController = fabController } return _fabWindow! } } var _fabController: KCFABViewController? = nil open var fabController: KCFABViewController { get { if _fabController == nil { _fabController = KCFABViewController() } return _fabController! } } open func getButton() -> KCFloatingActionButton { return fabController.fab } open func show(_ animated: Bool = true) { if animated == true { fabWindow.isHidden = false UIView.animate(withDuration: 0.3, animations: { () -> Void in self.fabWindow.alpha = 1 }) } else { fabWindow.isHidden = false } } open func hide(_ animated: Bool = true) { if animated == true { UIView.animate(withDuration: 0.3, animations: { () -> Void in self.fabWindow.alpha = 0 }, completion: { finished in self.fabWindow.isHidden = true }) } else { fabWindow.isHidden = true } } open func toggle(_ animated: Bool = true) { if fabWindow.isHidden == false { self.hide(animated) } else { self.show(animated) } } open func isHidden() -> Bool { return fabWindow.isHidden } }
mit
f3ae0c4befde5c69bca06da08817725a
25.448276
73
0.538462
4.476654
false
false
false
false
lstanii-magnet/ChatKitSample-iOS
ChatMessenger/Pods/ChatKit/ChatKit/source/src/Helpers/DateFormatter/DateFormatter.swift
1
2960
/* * Copyright (c) 2016 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ public class DateFormatter { //MARK: Public properties public let formatter = NSDateFormatter() //MARK: - Init init() { formatter.locale = NSLocale.currentLocale() formatter.timeZone = NSTimeZone(name: "GMT") } //MARK: - public Methods public func currentTimeStamp() -> String { formatter.dateFormat = "yyyyMMddHHmmss" return formatter.stringFromDate(NSDate()) } public func dateForStringTime(stringTime: String) -> NSDate? { formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" return formatter.dateFromString(stringTime) } public func dayOfTheWeek(date: NSDate) -> String { let dayFormatter = NSDateFormatter() dayFormatter.dateFormat = "EEEE" return dayFormatter.stringFromDate(date) } public func displayTime(stringTime: String) -> String! { let now = NSDate() let components = NSCalendar.currentCalendar().components([.Day , .Month, .Year ], fromDate: now) let midnight = NSCalendar.currentCalendar().dateFromComponents(components) let secondsInWeek: NSTimeInterval = 24 * 60 * 60 * 7 let aWeekago = NSDate(timeInterval: -secondsInWeek, sinceDate: NSDate()) let aMinutesAgo = NSDate(timeInterval: -(1 * 60), sinceDate: NSDate()) if let lastPublishedTime = dateForStringTime(stringTime) { if aMinutesAgo.compare(lastPublishedTime) == .OrderedAscending { return "Now" } else if midnight?.compare(lastPublishedTime) == .OrderedAscending { return timeForDate(lastPublishedTime) } else if aWeekago.compare(lastPublishedTime) == .OrderedAscending { return dayOfTheWeek(lastPublishedTime) } else { return relativeDateForDate(lastPublishedTime) } } return stringTime } public func relativeDateForDate(date: NSDate) -> String { return NSDateFormatter.localizedStringFromDate(date, dateStyle: .ShortStyle, timeStyle: .NoStyle) } public func timeForDate(date: NSDate) -> String { return NSDateFormatter.localizedStringFromDate(date, dateStyle: .NoStyle, timeStyle: .ShortStyle) } }
apache-2.0
c49b91e19c83f98bbdcee6b16e32e4f4
33.418605
105
0.651014
4.766506
false
false
false
false
argent-os/argent-ios
app-ios/LoginViewController.swift
1
17464
// // LoginViewController.swift // argent-ios // // Created by Sinan Ulkuatam on 2/9/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import UIKit import QuartzCore import Alamofire import SwiftyJSON import TextFieldEffects import UIColor_Hex_Swift import TransitionTreasury import TransitionAnimation import OnePasswordExtension import Crashlytics import WatchConnectivity class LoginViewController: UIViewController, UITextFieldDelegate, WCSessionDelegate { var window: UIWindow? @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var loginBox: UIView! @IBOutlet weak var loginButton: UIButton! let onePasswordButton = UIImageView() let imageView = UIImageView() weak var modalDelegate: ModalViewControllerDelegate? private let activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) override func viewDidAppear(animated: Bool) { NSUserDefaults.standardUserDefaults().setBool(false,forKey:"userLoggedIn"); NSUserDefaults.standardUserDefaults().synchronize(); } override func viewDidLoad() { super.viewDidLoad() configureView() } func configureView() { NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(LoginViewController.keyboardWillAppear(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(LoginViewController.keyboardWillDisappear(_:)), name: UIKeyboardWillHideNotification, object: nil) loginButton.layer.cornerRadius = 3 loginButton.layer.masksToBounds = true loginButton.backgroundColor = UIColor.pastelBlue().colorWithAlphaComponent(0.5) loginButton.setTitleColor(UIColor.whiteColor().colorWithAlphaComponent(0.3), forState: .Normal) loginButton.addTarget(LoginBoxTableViewController(), action: #selector(LoginBoxTableViewController.login(_:)), forControlEvents: .TouchUpInside) self.view.backgroundColor = UIColor.globalBackground() let screen = UIScreen.mainScreen().bounds let screenWidth = screen.size.width let screenHeight = screen.size.height // Set background image let backgroundView: UIImageView = UIImageView(image: UIImage(named: "BackgroundBlueDark")) backgroundView.contentMode = UIViewContentMode.ScaleToFill backgroundView.frame = self.view.bounds // self.view!.addSubview(backgroundView) // self.view.sendSubviewToBack(backgroundView) self.view.backgroundColor = UIColor.whiteColor() let signInLabel = UILabel() signInLabel.adjustAttributedString("SIGN IN", spacing: 2, fontName: "SFUIText-Regular", fontSize: 13, fontColor: UIColor.darkBlue().colorWithAlphaComponent(0.75)) signInLabel.textAlignment = .Center signInLabel.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 60) signInLabel.frame.origin.y = 200 // 12% down from the top // addSubviewWithFade(signInLabel, parentView: self, duration: 0.3) activityIndicator.center = self.view.center activityIndicator.startAnimating() activityIndicator.hidesWhenStopped = true self.view.addSubview(activityIndicator) activityIndicator.stopAnimating() NSUserDefaults.standardUserDefaults().setValue("", forKey: "userAccessToken") NSUserDefaults.standardUserDefaults().synchronize() UITextField.appearance().keyboardAppearance = .Light // Add action to close button to return to auth view closeButton.addTarget(self, action: #selector(LoginViewController.goToAuth(_:)), forControlEvents: UIControlEvents.TouchUpInside) closeButton.addTarget(self, action: #selector(LoginViewController.goToAuth(_:)), forControlEvents: UIControlEvents.TouchUpOutside) onePasswordButton.frame = CGRect(x: 0, y: screenHeight-140, width: screenWidth, height: 40) onePasswordButton.image = UIImage(named: "onepassword-button-dark") onePasswordButton.contentMode = .ScaleAspectFit onePasswordButton.userInteractionEnabled = true self.view.addSubview(onePasswordButton) self.view.bringSubviewToFront(onePasswordButton) // Set up OnePassword if OnePasswordExtension.sharedExtension().isAppExtensionAvailable() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.useOnePassword(_:))) self.onePasswordButton.addGestureRecognizer(tap) } else { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.checkOnePasswordExists(_:))) self.onePasswordButton.addGestureRecognizer(tap) } let resetPasswordButton = UIButton() resetPasswordButton.frame = CGRect(x: 0, y: screenHeight-60, width: screenWidth, height: 40) let str0 = NSAttributedString(string: "Forgot Password?", attributes: [ NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 12)!, NSForegroundColorAttributeName:UIColor.pastelBlue() ]) let str1 = NSAttributedString(string: "Forgot Password?", attributes: [ NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 12)!, NSForegroundColorAttributeName:UIColor.pastelBlue().colorWithAlphaComponent(0.5) ]) resetPasswordButton.setAttributedTitle(str0, forState: .Normal) resetPasswordButton.setAttributedTitle(str1, forState: .Highlighted) resetPasswordButton.addTarget(self, action: #selector(LoginViewController.goToReset(_:)), forControlEvents: .TouchUpInside) self.view.addSubview(resetPasswordButton) self.view.bringSubviewToFront(resetPasswordButton) // Login box, set height of container to match embedded tableview let containerFrame: CGRect = self.loginBox.frame loginBox.frame = containerFrame loginBox.layer.cornerRadius = 3 loginBox.layer.borderColor = UIColor.paleBlue().colorWithAlphaComponent(0.5).CGColor loginBox.layer.borderWidth = 1 loginBox.layer.masksToBounds = true // Border radius on uiview view.layer.cornerRadius = 0 view.layer.masksToBounds = true // Do any additional setup after loading the view. //Looks for single or multiple taps. let keyboardTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard)) view.addGestureRecognizer(keyboardTap) let image = UIImage(named: "LogoOutlineDark") imageView.image = image imageView.layer.masksToBounds = true imageView.tag = 42312 imageView.frame = CGRect(x: 0, y: 0, width: 70, height: 70) imageView.frame.origin.y = screenHeight*0.15 // 12% down from the top imageView.frame.origin.x = (self.view.bounds.size.width - imageView.frame.size.width) / 2.0 // centered left to right. addSubviewWithFade(imageView, parentView: self, duration: 0.3) if self.view.layer.frame.height <= 480.0 { imageView.removeFromSuperview() } } func goToReset(sender: AnyObject) { performSegueWithIdentifier("resetPasswordView", sender: sender) } // Set the ID in the storyboard in order to enable transition! func goToAuth(sender:AnyObject!) { // Normally identifiers are started with capital letters, exception being authViewController, make sure UIStoryboard name is Auth, not Main let viewController:AuthViewController = UIStoryboard(name: "Auth", bundle: nil).instantiateViewControllerWithIdentifier("authViewController") as! AuthViewController viewController.modalTransitionStyle = .CoverVertical self.presentViewController(viewController, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Changing Status Bar override func preferredStatusBarStyle() -> UIStatusBarStyle { return .Default } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } } extension LoginViewController { // one password func checkOnePasswordExists(sender: AnyObject) { if OnePasswordExtension.sharedExtension().isAppExtensionAvailable() == false { let alertController = UIAlertController(title: "1Password is not installed", message: "Get 1Password from the App Store", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "Get 1Password", style: .Default) { (action) in UIApplication.sharedApplication().openURL(NSURL(string: "https://itunes.apple.com/app/1password-password-manager/id568903335")!) } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true, completion: nil) } } func useOnePassword(sender: AnyObject) { OnePasswordExtension.sharedExtension().findLoginForURLString("https://www.argentapp.com", forViewController: self, sender: sender, completion: { (loginDictionary, error) -> Void in if loginDictionary == nil { if error!.code != Int(AppExtensionErrorCodeCancelledByUser) { print("Error invoking 1Password App Extension for find login: \(error)") Answers.logLoginWithMethod("1Password", success: false, customAttributes: [ "error": error! ]) } return } Answers.logLoginWithMethod("1Password", success: true, customAttributes: [ "user": (loginDictionary?[AppExtensionUsernameKey])! ]) let username = loginDictionary?[AppExtensionUsernameKey] as? String let password = loginDictionary?[AppExtensionPasswordKey] as? String self.activityIndicator.center = self.view.center self.activityIndicator.bounds.origin.y = 150 self.activityIndicator.startAnimating() self.activityIndicator.hidesWhenStopped = true self.view.addSubview(self.activityIndicator) Auth.login(username!, username: username!, password: password!) { (token, grant, username, err) in if(grant == true && token != "") { self.activityIndicator.stopAnimating() self.activityIndicator.hidden = true // Performs segue to home, repeats in LoginBoxTableViewController. @todo: DRY self.performSegueWithIdentifier("homeView", sender: self) // Sets access token on login, otherwise will log out userAccessToken = token Answers.logLoginWithMethod("Default", success: true, customAttributes: [ "user": username ]) // Send access token and Stripe key to Apple Watch if WCSession.isSupported() { //makes sure it's not an iPad or iPod let watchSession = WCSession.defaultSession() watchSession.delegate = self watchSession.activateSession() if watchSession.paired && watchSession.watchAppInstalled { do { try watchSession.updateApplicationContext( [ "token": token ] ) print("setting watch data") } catch let error as NSError { print(error.description) } } } } else { self.activityIndicator.stopAnimating() self.activityIndicator.hidden = true Answers.logLoginWithMethod("Default", success: false, customAttributes: [ "error": "Error using default login method" ]) self.displayAlertMessage("Error logging in") } } }) } } extension LoginViewController { func displayDefaultErrorAlertMessage(alertMessage:String) { let alertView: UIAlertController = UIAlertController(title: "Error", message: alertMessage, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertView, animated: true, completion: nil) } func displayAlertMessage(alertMessage:String) { let alertView: UIAlertController = UIAlertController(title: "Error", message: alertMessage, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertView, animated: true, completion: nil) } func displayErrorAlertMessage(alertMessage:String) { let alertView: UIAlertController = UIAlertController(title: "Error", message: alertMessage, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alertView, animated: true, completion: nil) } } class HTTPManager: Alamofire.Manager { static let sharedManager: HTTPManager = { //let configuration = Timberjack.defaultSessionConfiguration() let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders let serverTrustPolicies: [String: ServerTrustPolicy] = [ "192.168.1.182:": .DisableEvaluation ] var policy: ServerTrustPolicy = ServerTrustPolicy.DisableEvaluation let manager = HTTPManager(configuration: configuration,serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)) return manager }() } extension LoginViewController { func textFieldDidChange(textField: UITextField) { if textField.text?.characters.count > 0 { loginButton.userInteractionEnabled = true loginButton.setBackgroundColor(UIColor.pastelBlue(), forState: .Normal) loginButton.setBackgroundColor(UIColor.pastelBlue().darkerColor(), forState: .Highlighted) loginButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) } else { loginButton.userInteractionEnabled = false loginButton.setBackgroundColor(UIColor.pastelBlue().colorWithAlphaComponent(0.3), forState: .Normal) loginButton.setBackgroundColor(UIColor.pastelBlue().colorWithAlphaComponent(0.3), forState: .Highlighted) loginButton.setTitleColor(UIColor.whiteColor().colorWithAlphaComponent(0.5), forState: .Normal) } } } extension LoginViewController { //Calls this function when the tap is recognized. func dismissKeyboard() { loginButton.userInteractionEnabled = false //Causes the view (or one of its embedded text fields) to resign the first responder status. loginButton.setBackgroundColor(UIColor.pastelBlue().colorWithAlphaComponent(0.3), forState: .Normal) loginButton.setBackgroundColor(UIColor.pastelBlue().colorWithAlphaComponent(0.3), forState: .Highlighted) loginButton.setTitleColor(UIColor.whiteColor().colorWithAlphaComponent(0.5), forState: .Normal) view.endEditing(true) } func keyboardWillAppear(notification: NSNotification){ loginButton.userInteractionEnabled = true loginButton.setBackgroundColor(UIColor.pastelBlue(), forState: .Normal) loginButton.setBackgroundColor(UIColor.pastelBlue().darkerColor(), forState: .Highlighted) loginButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) } func keyboardWillDisappear(notification: NSNotification){ loginButton.userInteractionEnabled = false loginButton.setBackgroundColor(UIColor.pastelBlue().colorWithAlphaComponent(0.3), forState: .Normal) loginButton.setBackgroundColor(UIColor.pastelBlue().colorWithAlphaComponent(0.3), forState: .Highlighted) loginButton.setTitleColor(UIColor.whiteColor().colorWithAlphaComponent(0.5), forState: .Normal) } }
mit
d535bd066a0b391ffd3054d5a9a17750
47.243094
224
0.655328
5.774802
false
false
false
false
yimajo/MeetupTweet
MeetupTweet/Classes/DataSource/NicoNicoCommentFlowViewDataSource.swift
1
6403
// // TweetPresenter.swift // MeetupTweet // // Created by Yoshinori Imajo on 2016/03/03. // Copyright © 2016年 Yoshinori Imajo. All rights reserved. // import Foundation import RxSwift import AppKit import OAuthSwift import TwitterAPI class NicoNicoCommentFlowWindowDataSource: FlowWindowDataSource { var subscription: Disposable? fileprivate let tweetSearchUseCase: TwitterStraemAPIUseCase fileprivate let disposeBag = DisposeBag() fileprivate var comments: [String: (comment: CommentType, view: CommentView)] = [:] fileprivate var commentViews: [CommentView?] = [] fileprivate var window: NSWindow? init(oauthClient: OAuthClient) { self.tweetSearchUseCase = TwitterStraemAPIUseCase(oauthClient: oauthClient) } func search(_ search: String, screen: NSScreen) { refreshComments() window = makeTweetWindow(screen) let tweetStream = tweetSearchUseCase.startStream(search) .observeOn(MainScheduler.instance) .startWith(Announce(search: search)) .filter { !$0.message.hasPrefix("RT") } subscription = Observable.of(tweetStream, AnnounceUseCase.intervalTextStream(search)) .merge() .subscribe(onNext: { [unowned self] comment in self.addComment(comment) }) subscription?.disposed(by: disposeBag) } func stop() { window?.orderOut(nil) refreshComments() } } private extension NicoNicoCommentFlowWindowDataSource { func refreshComments() { tweetSearchUseCase.stopStream() subscription?.dispose() comments = [:] commentViews = [] } func addComment(_ comment: CommentType) { guard let window = window else { return } let view = makeCommentView(comment, from: window) window.contentView?.addSubview(view) comments[comment.identifier] = (comment: comment, view: view) startAnimationComment(comment, view: view) } func removeComment(_ comment: CommentType) { if let tweet = comments[comment.identifier] { tweet.view.removeFromSuperview() comments[comment.identifier] = nil } } func startAnimationComment(_ comment: CommentType, view: CommentView) { guard let window = window else { return } // TextFieldの移動開始 let windowFrame = window.frame let v: CGFloat = 200.0 let firstDuration = TimeInterval(view.frame.width / v) let len = windowFrame.width let secondDuration = TimeInterval(len / v) NSAnimationContext.runAnimationGroup( { context in context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) context.duration = firstDuration view.animator().frame = view.frame.offsetBy(dx: -view.frame.width, dy: 0) }, completionHandler: { [weak self] in guard let `self` = self else { return } for (index, v) in self.commentViews.enumerated() { if v == view { self.commentViews[index] = nil break; } } NSAnimationContext.runAnimationGroup({ context in context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) context.duration = secondDuration view.animator().frame = view.frame.offsetBy(dx: -len, dy: 0) }, completionHandler: { [weak self] in self?.removeComment(comment) }) } ) } func makeCommentView(_ comment: CommentType, from window: NSWindow) -> CommentView { let commentView: CommentView switch comment.type { case .tweet: commentView = CommentView.newCommentView(comment.message) if let url = comment.imageURL { URLSession.shared.rx.data(request: URLRequest(url: url)) .subscribe(onNext: { data in DispatchQueue.main.async { commentView.imageView.image = NSImage(data: data) } }) .disposed(by: disposeBag) } case .announce: commentView = CommentView.newCommentView(comment.message, fontColor: NSColor.red) commentView.imageView.image = NSApp.applicationIconImage } var space = 0 if commentViews.count == 0 { commentViews.append(commentView) } else { var add = false for (index, view) in commentViews.enumerated() { if view == nil { commentViews[index] = commentView space = index add = true break } } if !add { commentViews.append(commentView) space = commentViews.count } } commentView.layoutSubtreeIfNeeded() let windowFrame = window.frame let y = (windowFrame.height - commentView.frame.height) - (CGFloat(space) * commentView.frame.height) commentView.frame.origin = CGPoint(x: windowFrame.width, y: y) return commentView } func makeTweetWindow(_ screen: NSScreen) -> NSWindow { let menuHeight: CGFloat = 23.0 let size = CGSize(width: screen.frame.size.width, height: screen.frame.size.height - menuHeight) let frame = NSRect(origin: CGPoint.zero, size: size) let window = NSWindow(contentRect: frame, styleMask: .resizable, backing: .buffered, defer: false, screen: screen) window.isOpaque = false window.hasShadow = false window.isMovable = true window.isMovableByWindowBackground = true window.isReleasedWhenClosed = false window.backgroundColor = NSColor.clear window.level = NSWindow.Level(Int(CGWindowLevelForKey(.maximumWindow))) window.makeKeyAndOrderFront(nil) return window } }
mit
adf5d1bf6fa186c915dbaf162871ae25
32.455497
122
0.577778
5.149073
false
false
false
false
tndatacommons/Compass-iOS
Compass/src/Util/InitialDataLoader.swift
1
1450
// // InitialDataLoader.swift // Compass // // Created by Ismael Alonso on 4/25/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import Just import ObjectMapper class InitialDataLoader{ private static var user: User? = nil; private static var callback: ((Bool)) -> Void = { success in }; static func load(user: User, callback: ((Bool)) -> Void){ self.user = user; self.callback = callback; fetchCategories(); } private static func fetchCategories(){ Just.get(API.getCategoriesUrl(), headers: user!.getHeaderMap()){ (response) in if (response.ok && CompassUtil.isSuccessStatusCode(response.statusCode!)){ let result = String(data: response.content!, encoding:NSUTF8StringEncoding); SharedData.publicCategories = (Mapper<ParserModels.CategoryContentArray>().map(result)?.categories)!; //for category in SharedData.publicCategories{ // print(category.toString()); //} success(); } else{ failure(); } } } private static func success(){ dispatch_async(dispatch_get_main_queue(), { callback(true); }); } private static func failure(){ dispatch_async(dispatch_get_main_queue(), { callback(false); }); } }
mit
77176f10b0269dbc8a47882aa20cc447
26.865385
117
0.567978
4.704545
false
false
false
false
niilohlin/Fuzi
Sources/Element.swift
6
5743
// Element.swift // Copyright (c) 2015 Ce Zheng // // 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 libxml2 /// Represents an element in `XMLDocument` or `HTMLDocument` open class XMLElement: XMLNode { /// The element's namespace. open fileprivate(set) lazy var namespace: String? = { return ^-^(self.cNode.pointee.ns != nil ?self.cNode.pointee.ns.pointee.prefix :nil) }() /// The element's tag. open fileprivate(set) lazy var tag: String? = { return ^-^self.cNode.pointee.name }() // MARK: - Accessing Attributes /// All attributes for the element. open fileprivate(set) lazy var attributes: [String : String] = { var attributes = [String: String]() var attribute = self.cNode.pointee.properties while attribute != nil { if let key = ^-^attribute?.pointee.name, let value = self.attr(key) { attributes[key] = value } attribute = attribute?.pointee.next } return attributes }() /** Returns the value for the attribute with the specified key. - parameter name: The attribute name. - parameter ns: The namespace, or `nil` by default if not using a namespace - returns: The attribute value, or `nil` if the attribute is not defined. */ open func attr(_ name: String, namespace ns: String? = nil) -> String? { var value: String? = nil let xmlValue: UnsafeMutablePointer<xmlChar>? if let ns = ns { xmlValue = xmlGetNsProp(cNode, name, ns) } else { xmlValue = xmlGetProp(cNode, name) } if let xmlValue = xmlValue { value = ^-^xmlValue xmlFree(xmlValue) } return value } // MARK: - Accessing Children /// The element's children elements. open var children: [XMLElement] { return LinkedCNodes(head: cNode.pointee.children).flatMap { XMLElement(cNode: $0, document: self.document) } } /** Get the element's child nodes of specified types - parameter types: type of nodes that should be fetched (e.g. .Element, .Text, .Comment) - returns: all children of specified types */ open func childNodes(ofTypes types: [XMLNodeType]) -> [XMLNode] { return LinkedCNodes(head: cNode.pointee.children, types: types).flatMap { node in switch node.pointee.type { case XMLNodeType.Element: return XMLElement(cNode: node, document: self.document) default: return XMLNode(cNode: node, document: self.document) } } } /** Returns the first child element with a tag, or `nil` if no such element exists. - parameter tag: The tag name. - parameter ns: The namespace, or `nil` by default if not using a namespace - returns: The child element. */ open func firstChild(tag: String, inNamespace ns: String? = nil) -> XMLElement? { var nodePtr = cNode.pointee.children while let cNode = nodePtr { if cXMLNode(nodePtr, matchesTag: tag, inNamespace: ns) { return XMLElement(cNode: cNode, document: self.document) } nodePtr = cNode.pointee.next } return nil } /** Returns all children elements with the specified tag. - parameter tag: The tag name. - parameter ns: The namepsace, or `nil` by default if not using a namespace - returns: The children elements. */ open func children(tag: String, inNamespace ns: String? = nil) -> [XMLElement] { return LinkedCNodes(head: cNode.pointee.children).flatMap { cXMLNode($0, matchesTag: tag, inNamespace: ns) ? XMLElement(cNode: $0, document: self.document) : nil } } // MARK: - Accessing Content /// Whether the element has a value. open var isBlank: Bool { return stringValue.isEmpty } /// A number representation of the element's value, which is generated from the document's `numberFormatter` property. open fileprivate(set) lazy var numberValue: NSNumber? = { return self.document.numberFormatter.number(from: self.stringValue) }() /// A date representation of the element's value, which is generated from the document's `dateFormatter` property. open fileprivate(set) lazy var dateValue: Date? = { return self.document.dateFormatter.date(from: self.stringValue) }() /** Returns the child element at the specified index. - parameter idx: The index. - returns: The child element. */ open subscript (idx: Int) -> XMLElement? { return children[idx] } /** Returns the value for the attribute with the specified key. - parameter name: The attribute name. - returns: The attribute value, or `nil` if the attribute is not defined. */ open subscript (name: String) -> String? { return attr(name) } }
mit
19ec7fcff8b459134c344628a29cfc11
31.817143
120
0.679784
4.179767
false
false
false
false
mothule/RNMoVali
RNMoVali/RNConstraintNumeric.swift
1
782
// // RNConstraintNumeric.swift // RNMoVali // // Created by mothule on 2016/08/23. // Copyright © 2016年 mothule. All rights reserved. // import Foundation open class RNConstraintNumeric : RNConstraintable { fileprivate let errorMessage:String public init(errorMessage:String){ self.errorMessage = errorMessage } open func constrain(_ object:Any?) -> RNConstraintResult{ let ret = RNConstraintResult() if let string = object as? String{ guard !string.isEmpty else { return ret } if Regex.make("^[0-9]+$").isMatch(string) == false { ret.invalidate(errorMessage) } } return ret } }
apache-2.0
5a53a46b45a6499edc4abcf7de8e5fd7
22.606061
64
0.555841
4.609467
false
false
false
false
thoughtbend/mobile-ps-demo-poc
AboutTown/AboutTown/Constants.swift
1
678
// // Constants.swift // AboutTown // // Created by Mike Nolan on 8/18/16. // Copyright © 2016 Thoughtbend. All rights reserved. // import Foundation struct Constants { static let UserPoolName = "thoughtbend-ps-demo" static let ClientIdAuth = "1kmr1leb1kudn2pd7i72p42if3" static let ClientSecretAuth = "1vdbdo8e5qi326773c7etlepht2mqk0qoi1um1plfio25e9e3gbn" static let PoolId = "us-west-2_0Au6MRa5r" static let ClientIdRegistration = "4cdtlhgk5gp43idr1uen7rc5pf" static let CognitoIdentityPoolId = "us-west-2:54b12e61-7346-42d5-947d-7f32384740b5" } struct UserRecord { static let lastKnownUser = "[email protected]" }
mit
c1e3ff7582c1101a3b362dff4d1a7c89
24.111111
88
0.725258
2.686508
false
false
false
false