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
iAugux/Zoom-Contacts
Phonetic/TableViewHeaderFooterViewWithButton.swift
1
1572
// // TableViewHeaderFooterViewWithButton.swift // Phonetic // // Created by Augus on 2/15/16. // Copyright © 2016 iAugus. All rights reserved. // import UIKit protocol TableViewHeaderFooterViewWithButtonDelegate { func tableViewHeaderFooterViewWithButtonDidTap() } class TableViewHeaderFooterViewWithButton: UITableViewHeaderFooterView { var delegate: TableViewHeaderFooterViewWithButtonDelegate! private var button: UIButton! override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) } convenience init(buttonImageName name: String, twinkleInterval: NSTimeInterval = 0.7) { self.init(reuseIdentifier: nil) button = UIButton(type: .Custom) button.frame.size = CGSizeMake(18, 18) button.center = textLabel!.center button.frame.origin.x = textLabel!.frame.maxX + 8.0 button.setImage(UIImage(named: name), forState: .Normal) button.addTarget(self, action: #selector(buttonDidTap), forControlEvents: .TouchUpInside) addSubview(button) button?.twinkling(twinkleInterval, minAlpha: 0.2) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() button?.center = textLabel!.center button.frame.origin.x = textLabel!.frame.maxX + 8.0 } @objc private func buttonDidTap() { delegate?.tableViewHeaderFooterViewWithButtonDidTap() } }
mit
65215e1ffc7d85e764f569e980a7df53
29.211538
97
0.684914
4.593567
false
false
false
false
15221758864/TestKitchen_1606
TestKitchen/TestKitchen/classes/common/CBHeaderView.swift
1
1422
// // CBHeaderView.swift // TestKitchen // // Created by Ronie on 16/8/19. // Copyright © 2016年 Ronie. All rights reserved. // import UIKit class CBHeaderView: UIView { private var titleLabel: UILabel? private var imageView: UIImageView? override init(frame: CGRect) { super.init(frame: frame) //背景视图 let bgView = UIView.createView() bgView.frame = CGRectMake(0, 10, bounds.width, bounds.height-10) bgView.backgroundColor = UIColor.whiteColor() addSubview(bgView) //标题文字 let titleW: CGFloat = 300 let imageW: CGFloat = 30 let x = (bounds.width-titleW-imageW)/2 titleLabel = UILabel.createLabel(nil, font: UIFont.systemFontOfSize(18), textAlignment: .Center, textColor: UIColor.blackColor()) titleLabel?.frame = CGRectMake(x, 10, titleW, bounds.height-10) addSubview(titleLabel!) //右边图片 imageView = UIImageView.createImageView("more_icon") imageView?.frame = CGRectMake(x+titleW, 14, imageW, imageW) addSubview(imageView!) backgroundColor = UIColor(white: 0.8, alpha: 1.0) } //显示标题 func configTitle(title: String) { titleLabel?.text = title } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
13ff5a474276feeb6e55a6a81fa5e927
26.74
137
0.619322
4.228659
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/GCDMandelrotView.swift
1
3724
// // GCDMandelrotView.swift // ApiDemo-Swift // // Created by Jacob su on 8/4/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit let qkeyString = "label" as NSString let QKEY = qkeyString.utf8String let qvalString = "com.neuburg.mandeldraw" as NSString var QVAL = qvalString.utf8String class GCDMandelrotView: UIView { let MANDELBROT_STEPS = 200 let draw_queue : DispatchQueue = { let q = DispatchQueue(label: String(qvalString)) return q }() var bitmapContext: CGContext! var odd = false // jumping-off point: draw the Mandelbrot set func drawThatPuppy () { let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) var bti : UIBackgroundTaskIdentifier = 0 bti = UIApplication.shared .beginBackgroundTask(expirationHandler: { UIApplication.shared.endBackgroundTask(bti) }) if bti == UIBackgroundTaskInvalid { return } self.draw_queue.async { if let bitmap = self.makeBitmapContext(self.bounds.size) { self.drawAtCenter(center, zoom:1, context:bitmap) DispatchQueue.main.async { self.bitmapContext = bitmap self.setNeedsDisplay() UIApplication.shared.endBackgroundTask(bti) } } } } // create bitmap context func makeBitmapContext(_ size:CGSize) -> CGContext? { var bitmapBytesPerRow = Int(size.width * 4) bitmapBytesPerRow += (16 - (bitmapBytesPerRow % 16)) % 16 let colorSpace = CGColorSpaceCreateDeviceRGB() let prem = CGImageAlphaInfo.premultipliedLast.rawValue let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: prem) return context } // draw pixels of bitmap context func drawAtCenter(_ center:CGPoint, zoom:CGFloat, context: CGContext) { func isInMandelbrotSet(_ re:Float, _ im:Float) -> Bool { var fl = true var (x, y, nx, ny) : (Float,Float,Float,Float) = (0,0,0,0) for _ in 0 ..< MANDELBROT_STEPS { nx = x*x - y*y + re ny = 2*x*y + im if nx*nx + ny*ny > 4 { fl = false break } x = nx y = ny } return fl } context.setAllowsAntialiasing(false) context.setFillColor(red: 0, green: 0, blue: 0, alpha: 1) var re : CGFloat var im : CGFloat let maxi = Int(self.bounds.size.width) let maxj = Int(self.bounds.size.height) for i in 0 ..< maxi { for j in 0 ..< maxj { re = (CGFloat(i) - 1.33 * center.x) / 160 im = (CGFloat(j) - 1.0 * center.y) / 160 re /= zoom im /= zoom if (isInMandelbrotSet(Float(re), Float(im))) { context.fill (CGRect(x: CGFloat(i), y: CGFloat(j), width: 1.0, height: 1.0)) } } } } // turn pixels of bitmap context into CGImage, draw into ourselves override func draw(_ rect: CGRect) { if self.bitmapContext != nil { let context = UIGraphicsGetCurrentContext()! let im = self.bitmapContext.makeImage() context.draw(im!, in: self.bounds) self.odd = !self.odd self.backgroundColor = self.odd ? UIColor.green : UIColor.red } } }
apache-2.0
a0286c44e657a6865c1642e7f685e118
32.540541
182
0.547408
4.245154
false
false
false
false
dklinzh/NodeExtension
NodeExtension/Classes/Node/DLSwitchNode.swift
1
1906
// // DLSwitchNode.swift // NodeExtension // // Created by Daniel Lin on 24/08/2017. // Copyright (c) 2017 Daniel Lin. All rights reserved. // import AsyncDisplayKit /// The Node object of switch view open class DLSwitchNode: DLViewNode<UISwitch> { public typealias DLSwitchActionBlock = (_ isOn: Bool) -> Void public var isEnabled: Bool { get { return self.nodeView.isEnabled } set { self.appendViewAssociation { (view: UISwitch) in view.isEnabled = newValue } } } public var isOn: Bool { get { return self.nodeView.isOn } set { self.appendViewAssociation { (view: UISwitch) in view.isOn = newValue } } } open override var tintColor: UIColor! { didSet { let _tintColor = tintColor self.appendViewAssociation { (view: UISwitch) in view.onTintColor = _tintColor } } } private let _switchActionBlock: DLSwitchActionBlock public init(scale: CGFloat = 1.0, action: @escaping DLSwitchActionBlock) { _switchActionBlock = action super.init() self.setViewBlock { () -> UIView in let switchView = UISwitch() switchView.transform = CGAffineTransform(scaleX: scale, y: scale) return switchView } // FIXME: fit size self.style.preferredSize = CGSize(width: 51 * scale, height: 31 * scale) self.backgroundColor = .clear } override open func didLoad() { super.didLoad() self.nodeView.addTarget(self, action: #selector(switchAction), for: .valueChanged) } @objc private func switchAction(sender: UISwitch) { _switchActionBlock(sender.isOn) } }
mit
67b8b84c59fd2fe7c703fba5050551c2
25.109589
90
0.562434
4.717822
false
false
false
false
jessesquires/JSQCoreDataKit
Example/ExampleApp/EmployeeViewController.swift
1
2503
// // Created by Jesse Squires // https://www.jessesquires.com // // // Documentation // https://jessesquires.github.io/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015-present Jesse Squires // Released under an MIT license: https://opensource.org/licenses/MIT // import CoreData import ExampleModel import JSQCoreDataKit import UIKit final class EmployeeViewController: CollectionViewController { let stack: CoreDataStack let company: Company lazy var coordinator: FetchedResultsCoordinator<Employee, EmployeeCellConfig> = { let supplementaryViews = [ AnyFetchedResultsSupplementaryConfiguration(EmployeeHeaderConfig()), AnyFetchedResultsSupplementaryConfiguration(EmployeeFooterConfig()) ] return FetchedResultsCoordinator( fetchRequest: Employee.fetchRequest(for: self.company), context: self.stack.mainContext, sectionNameKeyPath: nil, cacheName: nil, collectionView: self.collectionView, cellConfiguration: EmployeeCellConfig(), supplementaryConfigurations: supplementaryViews ) }() // MARK: Init init(stack: CoreDataStack, company: Company) { self.stack = stack self.company = company super.init() } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = self.company.name self.collectionView.allowsSelection = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.coordinator.performFetch() } // MARK: Actions override func addAction() { self.stack.mainContext.performAndWait { _ = Employee.newEmployee(self.stack.mainContext, company: self.company) self.stack.mainContext.saveSync() } } override func deleteAction() { let backgroundChildContext = self.stack.childContext() backgroundChildContext.performAndWait { do { let objects = try backgroundChildContext.fetch(Employee.fetchRequest(for: self.company)) for each in objects { backgroundChildContext.delete(each) } backgroundChildContext.saveSync() } catch { print("Error deleting objects: \(error)") } } } }
mit
ca8e2bf7f940fd944970ad1114f14f82
27.11236
104
0.638689
5.245283
false
true
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Models/Milestone.swift
1
2957
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import Foundation struct Milestone { let sequence: Int let distance: Int let name: String let flagName: String let journeyMap: String let description: String let title: String let subtitle: String let media: String let content: String init?(json: JSON?) { guard let json = json, let sequence = json["sequence"]?.intValue, let distance = json["distance"]?.intValue, let name = json["name"]?.stringValue, let flagName = json["flagName"]?.stringValue, let journeyMap = json["journeyMap"]?.stringValue, let description = json["description"]?.stringValue, let title = json["title"]?.stringValue, let subtitle = json["subtitle"]?.stringValue, let media = json["media"]?.stringValue, let content = json["content"]?.stringValue else { return nil } self.sequence = sequence self.distance = distance self.name = name self.flagName = flagName self.journeyMap = journeyMap self.description = description self.title = title self.subtitle = subtitle self.media = media self.content = content } func getMediaURLs() -> [String] { var result = [String]() let splitMedia = self.media.split(separator: " ") for mediaURL in splitMedia { let url = mediaURL.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: true)[safe: 1] if let url = url { result.append(String(url)) } } return result } }
bsd-3-clause
c4e383123ef370cd29bd0fc2caea8ad2
35.04878
102
0.703654
4.506098
false
false
false
false
dsantosp12/DResume
Sources/App/Models/Language.swift
1
2538
// // Language.swift // App // // Created by Daniel Santos on 10/2/17. // import Vapor import FluentProvider import HTTP final class Language: Model { let storage = Storage() var name: String private var mLevel: Int var level: Skill.Level { get { return Skill.Level(level: self.mLevel) } set { mLevel = newValue.rawValue } } let userID: Identifier? static let nameKey = "name" static let levelKey = "level" static let userIDKey = "user_id" init( name: String, level: Int, user: User ) { self.name = name self.userID = user.id self.mLevel = level self.level = Skill.Level(level: level) } required init(row: Row) throws { self.name = try row.get(Language.nameKey) self.mLevel = try row.get(Language.levelKey) self.userID = try row.get(User.foreignIdKey) self.level = Skill.Level(level: self.mLevel) } func makeRow() throws -> Row { var row = Row() try row.set(Language.nameKey, self.name) try row.set(Language.levelKey, self.mLevel) try row.set(User.foreignIdKey, self.userID) return row } func update(with json: JSON) throws { self.name = try json.get(Language.nameKey) self.level = Skill.Level(level: try json.get(Language.levelKey)) try self.save() } } // MARK: Relationship extension Language { var owner: Parent<Language, User> { return parent(id: self.userID) } } // MARK: JSON extension Language: JSONConvertible { convenience init(json: JSON) throws { let userID: Identifier = try json.get(Language.userIDKey) guard let user = try User.find(userID) else { throw Abort.badRequest } try self.init( name: json.get(Language.nameKey), level: json.get(Language.levelKey), user: user ) } func makeJSON() throws -> JSON { var json = JSON() try json.set(Language.idKey, self.id) try json.set(Language.nameKey, self.name) try json.set(Language.levelKey, self.level.rawValue) try json.set(Language.userIDKey, self.userID) return json } } // MARK: HTTP extension Language: ResponseRepresentable { } extension Language: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string(Language.nameKey) builder.string(Language.levelKey) builder.parent(User.self) } } static func revert(_ database: Database) throws { try database.delete(self) } }
mit
422e41e21d23872cf1288cebebbc7873
20.15
68
0.646572
3.6
false
false
false
false
tuarua/WebViewANE
native_library/apple/WebViewANE/WebViewANE/Extensions/FreURLRequest.swift
1
1974
// Copyright 2018 Tua Rua Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Additional Terms // No part, or derivative of this Air Native Extensions's code is permitted // to be sold as the basis of a commercially packaged Air Native Extension which // undertakes the same purpose as this software. That is, a WebView for Windows, // OSX and/or iOS and/or Android. // All Rights Reserved. Tua Rua Ltd. import Foundation import WebKit import FreSwift public extension URLRequest { init?(_ freObject: FREObject?) { guard let rv = freObject else { return nil } let fre = FreObjectSwift(rv) guard let urlStr: String = fre.url, let url = URL(string: urlStr) else { return nil } self.init(url: url) for header in URLRequest.getCustomRequestHeaders(rv) { self.addValue(header.1, forHTTPHeaderField: header.0) } } static func getCustomRequestHeaders(_ freObject: FREObject?) -> [(String, String)] { var ret = [(String, String)]() guard let rv = freObject else { return ret } if let freRequestHeaders = rv["requestHeaders"] { let arr = FREArray(freRequestHeaders) for requestHeaderFre in arr { if let name = String(requestHeaderFre["name"]), let value = String(requestHeaderFre["value"]) { ret.append((name, value)) } } } return ret } }
apache-2.0
cb6b91c9feb2664766b61fa8014a68c1
37.705882
111
0.657042
4.173362
false
false
false
false
koba-uy/chivia-app-ios
src/Pods/Alamofire/Source/Response.swift
86
17819
// // Response.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DataResponse { /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result /// value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's /// result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension DownloadResponse { /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this /// instance's result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif }
lgpl-3.0
1a292d38b99414e135df62eacc47e7e1
37.32043
119
0.65823
4.806852
false
false
false
false
riehs/bitcoin-trainer
Bitcoin Trainer/Bitcoin Trainer/SendBitconViewController.swift
1
1951
// // SendBitconViewController.swift // Bitcoin Trainer // // Created by Daniel Riehs on 8/29/15. // Copyright (c) 2015 Daniel Riehs. All rights reserved. // import UIKit class SendBitcoinViewController: UIViewController { @IBOutlet weak var addressTextField: UITextField! @IBOutlet weak var amountTextField: UITextField! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! //The user presses the Cancel button. @IBAction func dismissSendBitcoin(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } @IBAction func sendBitcoinButton(_ sender: AnyObject) { sendBitcoin(addressTextField.text!, amount: amountTextField.text!) } override func viewDidLoad() { super.viewDidLoad() //The activity indicator is hidden when the view first loads. activityIndicator.isHidden = true } func sendBitcoin(_ address: String, amount: String) { //Make the activity indicator visible. activityIndicator.isHidden = false BitcoinAddress.sharedInstance().sendBitcoin(address, amount: amount) { (success, errorString) in if success { DispatchQueue.main.async(execute: { () -> Void in self.activityIndicator.isHidden = true self.dismiss(animated: true, completion: nil) }); } else { DispatchQueue.main.async(execute: { () -> Void in self.activityIndicator.isHidden = true self.errorAlert("Error", error: errorString!) }); } } } //Creates an Alert-style error message. func errorAlert(_ title: String, error: String) { let controller: UIAlertController = UIAlertController(title: title, message: error, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(controller, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3c37d71a3400a7c5835abb7e3594dff1
26.097222
109
0.713993
4.186695
false
false
false
false
Xiomara7/slackers
slackers/ProfileView.swift
1
6217
// // ProfileView.swift // slackers // // Created by Xiomara on 11/5/15. // Copyright © 2015 Xiomara. All rights reserved. // import Foundation import UIKit class ProfileView: UIView { var shouldUpdateConstraints = true var banner: UIView! var username: UILabel! var name: UILabel! var profileImage: UIImageView! var closeButton: UIButton! var skype: UILabel! var phone: UILabel! var email: UILabel! var title: UILabel! var skypeIcon: UIImageView! var phoneIcon: UIImageView! var emailIcon: UIImageView! init() { super.init(frame: CGRectZero) self.backgroundColor = UIColor.whiteColor() banner = UIView(frame: CGRectZero) banner.translatesAutoresizingMaskIntoConstraints = true banner.backgroundColor = UIColor.grayColor() banner.autoSetDimension(.Height, toSize: defaultCellHeight) self.addSubview(banner) self.sendSubviewToBack(banner) profileImage = UIImageView(frame: CGRectZero) profileImage.translatesAutoresizingMaskIntoConstraints = true profileImage.backgroundColor = UIColor.whiteColor() profileImage.contentMode = UIViewContentMode.ScaleAspectFill profileImage.layer.borderColor = UIColor.grayColor().CGColor profileImage.layer.cornerRadius = defaultCornerRadius profileImage.layer.borderWidth = defaultBorderWidth profileImage.layer.masksToBounds = true profileImage.autoSetDimension(.Height, toSize: profileImageSize) profileImage.autoSetDimension(.Width, toSize: profileImageSize) self.addSubview(profileImage) self.bringSubviewToFront(profileImage) name = UILabel(frame: CGRectZero) name.font = UIFont(name: nameFontName, size: 24.0) self.addSubview(name) username = UILabel(frame: CGRectZero) username.font = UIFont(name: userFontName, size: 14.0) self.addSubview(username) title = UILabel(frame: CGRectZero) self.addSubview(title) email = UILabel(frame: CGRectZero) email.font = UIFont(name: normalFontName, size: 14.0) self.addSubview(email) phone = UILabel(frame: CGRectZero) phone.font = UIFont(name: normalFontName, size: 14.0) self.addSubview(phone) skype = UILabel(frame: CGRectZero) skype.font = UIFont(name: normalFontName, size: 14.0) self.addSubview(skype) skypeIcon = UIImageView(image: UIImage(named: IMG_SKYPE)) skypeIcon.autoSetDimension(.Width, toSize: 24.0) skypeIcon.autoSetDimension(.Height, toSize: 24.0) skypeIcon.contentMode = UIViewContentMode.ScaleAspectFit skypeIcon.layer.masksToBounds = true self.addSubview(skypeIcon) emailIcon = UIImageView(image: UIImage(named: IMG_EMAIL)) emailIcon.autoSetDimension(.Width, toSize: 24.0) emailIcon.autoSetDimension(.Height, toSize: 24.0) emailIcon.contentMode = UIViewContentMode.ScaleAspectFit emailIcon.layer.masksToBounds = true self.addSubview(emailIcon) phoneIcon = UIImageView(image: UIImage(named: IMG_PHONE)) phoneIcon.autoSetDimension(.Width, toSize: 24.0) phoneIcon.autoSetDimension(.Height, toSize: 24.0) phoneIcon.contentMode = UIViewContentMode.ScaleAspectFit phoneIcon.layer.masksToBounds = true self.addSubview(phoneIcon) closeButton = UIButton(frame: CGRectZero) closeButton.setImage(UIImage(named: IMG_CLOSE), forState: .Normal) self.addSubview(closeButton) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func updateConstraints() { if shouldUpdateConstraints { banner.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero, excludingEdge: .Bottom) closeButton.autoPinEdgeToSuperviewEdge(.Top, withInset: 20.0) closeButton.autoPinEdgeToSuperviewEdge(.Left, withInset: 20.0) profileImage.autoAlignAxis(.Vertical, toSameAxisOfView: banner) profileImage.autoPinEdge(.Top, toEdge: .Bottom, ofView: banner, withOffset: -profileImageSize / 3) name.autoPinEdge(.Top, toEdge: .Bottom, ofView: profileImage, withOffset: 30.0) name.autoAlignAxis(.Vertical, toSameAxisOfView: profileImage) username.autoPinEdge(.Top, toEdge: .Bottom, ofView: name, withOffset: 5.0) username.autoAlignAxis(.Vertical, toSameAxisOfView: name) title.autoPinEdge(.Top, toEdge: .Bottom, ofView: username, withOffset: 5.0) title.autoAlignAxis(.Vertical, toSameAxisOfView: username) emailIcon.autoPinEdge(.Top, toEdge: .Bottom, ofView: title, withOffset: 44.0) emailIcon.autoPinEdgeToSuperviewEdge(.Left, withInset: 20.0) email.autoPinEdge(.Top, toEdge: .Bottom, ofView: title, withOffset: 44.0) email.autoPinEdge(.Left, toEdge: .Right, ofView: emailIcon, withOffset: 5.0) phoneIcon.autoPinEdge(.Top, toEdge: .Bottom, ofView: email, withOffset: 10.0) phoneIcon.autoPinEdgeToSuperviewEdge(.Left, withInset: 20.0) phone.autoPinEdge(.Top, toEdge: .Bottom, ofView: email, withOffset: 10.0) phone.autoPinEdge(.Left, toEdge: .Right, ofView: phoneIcon, withOffset: 5.0) skypeIcon.autoPinEdge(.Top, toEdge: .Bottom, ofView: phone, withOffset: 10.0) skypeIcon.autoPinEdgeToSuperviewEdge(.Left, withInset: 20.0) skype.autoPinEdge(.Top, toEdge: .Bottom, ofView: phone, withOffset: 10.0) skype.autoPinEdge(.Left, toEdge: .Right, ofView: skypeIcon, withOffset: 5.0) shouldUpdateConstraints = false } super.updateConstraints() } }
mit
20c999b95a7d4947c448a0f90f6fff37
35.781065
110
0.636261
5.033198
false
false
false
false
yonaskolb/XcodeGen
Sources/XcodeGenCLI/XcodeGenCLI.swift
1
816
import Foundation import ProjectSpec import SwiftCLI import Version public class XcodeGenCLI { let cli: CLI public init(version: Version) { let generateCommand = GenerateCommand(version: version) cli = CLI( name: "xcodegen", version: version.description, description: "Generates Xcode projects", commands: [ generateCommand, DumpCommand(version: version), ] ) cli.parser.routeBehavior = .searchWithFallback(generateCommand) } public func execute(arguments: [String]? = nil) { let status: Int32 if let arguments = arguments { status = cli.go(with: arguments) } else { status = cli.go() } exit(status) } }
mit
ff3442bfeea51be4c7eb89d9e1a53dc7
23.727273
71
0.566176
4.77193
false
false
false
false
sean915213/sgy-swift-json
SGYSwiftJSON/Classes/Deserialization/DeserializationExtensions.swift
2
5711
// // SGYDeserializationExtensions.swift // SGYSwiftJSON // // Created by Sean Young on 8/23/15. // Copyright © 2015 Sean Young. All rights reserved. // import Foundation // MARK: JSONCollectionCreatable Conformance - extension RangeReplaceableCollection where Self: JSONCollectionCreatable { /** Extends `RangeReplaceableCollectionType` types that implement `JSONCollectionCreatable`. Provides an automatic initializer that attempts casting the provided `Any` collection to the type's `Iterator.Element`. - parameter array: An array typed as `[Any]` but intended to contain instances that can be cast to the type's `Iterator.Element`. - returns: An initialized collection. */ public init(array: [Any]) { self.init() array.forEach { if let e = $0 as? Iterator.Element { append(e) } } } } extension Array: JSONCollectionCreatable { } extension Set: JSONCollectionCreatable { /** An initializer that extends `Set` to conform to `JSONCollectionCreatable`. - parameter array: An array typed as `[Any]` but intended to contain instances that can be cast to `Iterator.Element`. - returns: An initialized set. */ public init(array: [Any]) { self.init() array.forEach { if let e = $0 as? Iterator.Element { insert(e) } } } } // MARK: JSONDictionaryCreatable Conformance - extension Dictionary: JSONDictionaryCreatable { /** An initializer that extends `Dictionary` to conform to `JSONDictionaryCreatable`. - parameter dictionary: A dictionary typed as `[String: Any]` but intended to contain values that can be cast to `Value`. - returns: An initialized dictionary. */ public init(dictionary: [String: Any]) { self.init() dictionary.forEach { if let k = $0 as? Key, let v = $1 as? Value { self[k] = v } } } } // MARK: JSONLeafCreatable Conformance - // MARK: String extension String: JSONLeafCreatable { /** Extends `String` to conform to `JSONLeafCreatable`. Fails only on the `Null` case. - parameter jsonValue: A `JSONLeafCreatable` enum case. - returns: An initialized `String` value or `nil`. */ public init?(jsonValue: JSONLeafValue) { switch jsonValue { case .string(let string as String): self = string case .number(let number): self = "\(number)" default: return nil } } } // MARK: Numeric Structs extension Int: JSONLeafCreatable { /** Extends `Int` to conform to `JSONLeafCreatable`. Fails conditionally on the `String` case and always on the `Null` case. - parameter jsonValue: A `JSONLeafCreatable` enum case. - returns: An initialized `Int` value or `nil`. */ public init?(jsonValue: JSONLeafValue) { switch jsonValue { case .string(let string as String): guard let int = Int(string) else { return nil } self = int case .number(let number): self = number.intValue default: return nil } } } extension UInt: JSONLeafCreatable { /** Extends `UInt` to conform to `JSONLeafCreatable`. Fails conditionally on the `String` case and always on the `Null` case. - parameter jsonValue: A `JSONLeafCreatable` enum case. - returns: An initialized `UInt` value or `nil`. */ public init?(jsonValue: JSONLeafValue) { switch jsonValue { case .string(let string as String): guard let uint = UInt(string) else { return nil } self = uint case .number(let number): self = number.uintValue default: return nil } } } extension Float: JSONLeafCreatable { /** Extends `Float` to conform to `JSONLeafCreatable`. Fails conditionally on the `String` case and always on the `Null` case. - parameter jsonValue: A `JSONLeafCreatable` enum case. - returns: An initialized `Float` value or `nil`. */ public init?(jsonValue: JSONLeafValue) { switch jsonValue { case .string(let string as String): guard let float = Float(string) else { return nil } self = float case .number(let number): self = number.floatValue default: return nil } } } extension Double: JSONLeafCreatable { /** Extends `Double` to conform to `JSONLeafCreatable`. Fails conditionally on the `String` case and always on the `Null` case. - parameter jsonValue: A `JSONLeafCreatable` enum case. - returns: An initialized `Double` value or `nil`. */ public init?(jsonValue: JSONLeafValue) { switch jsonValue { case .string(let string as String): guard let double = Double(string) else { return nil } self = double case .number(let number): self = number.doubleValue default: return nil } } } extension Bool: JSONLeafCreatable { /** Extends `Bool` to conform to `JSONLeafCreatable`. Fails conditionally on the `String` case and always on the `Null` case. - parameter jsonValue: A `JSONLeafCreatable` enum case. - returns: An initialized `Bool` value or `nil`. */ public init?(jsonValue: JSONLeafValue) { switch jsonValue { case .string(let string): if let value = Bool(string as String) { self = value } return nil case .number(let number): self = Bool(number) case .null: return nil } } }
mit
e5e3a1d18901d3d78ef2577705e63427
28.895288
213
0.614011
4.382195
false
false
false
false
fcanas/FFCTextField
src/Validation.swift
1
2270
// // Validation.swift // FFCTextField // // Created by Fabian Canas on 1/21/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import Foundation public typealias Validation = (String?) -> (valid: Bool, reason: String) public let PermissiveValidation: Validation = { _ in (true, "")} public let RequiredString: (String) -> Validation = { name in { value in if value == nil { return (false, "\(name) can't be empty") } if let text = value { if text.isEmpty { return (false, "\(name) can't be empty") } return (true, "") } return (false, "\(name) must be a String") } } private extension String { func toDouble() -> Double? { let trimmedValue = (self as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) return self == trimmedValue ? (self as NSString).doubleValue : nil } } public let MinimumNumber: (String, Int) -> Validation = { name, min in { value in if let value = value { if let number = value.toDouble() { if number < Double(min) { return (false, "\(name) must be at least \(min)") } return (true, "") } } else { return (false, "\(name) must be at least \(min)") } return (false, "\(name) must be a number") } } public let MaximumNumber: (String, Int) -> Validation = { name, max in { value in if let value = value { if let number = value.toDouble() { if number > Double(max) { return (false, "\(name) must be at most \(max)") } return (true, "") } } else { return (false, "\(name) must be at most \(max)") } return (false, "\(name) must be a number") } } public func && (lhs: Validation, rhs: Validation) -> Validation { return { value in let lhsr = lhs(value) if !lhsr.valid { return lhsr } let rhsr = rhs(value) if !rhsr.valid { return rhsr } return (true, "") } }
mit
d4fc3a29d2c6dcf1466b64a142796ca4
23.673913
132
0.511013
4.235075
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Deal/CustomView/DealMarketCell.swift
4
1945
// // DealMarketCell.swift // iOSStar // // Created by J-bb on 17/5/23. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit class DealMarketCell: UITableViewCell { @IBOutlet weak var changePercentLabel: UILabel! @IBOutlet weak var changePriceLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() priceLabel.textColor = UIColor.init(hexString: AppConst.Color.orange) changePriceLabel.textColor = UIColor.init(hexString: AppConst.Color.main) changePercentLabel.textColor = UIColor.init(hexString: AppConst.Color.main) // Initialization code } func setRealTimeData(model:RealTimeModel?) { guard model != nil else { return } var colorString = AppConst.Color.up let percent = model!.pchg * 100 if model!.pchg < 0 { changePercentLabel.text = String(format: "%.2f%%", -percent) changePriceLabel.text = String(format: "%.2f", model!.change) colorString = AppConst.Color.down } else if model!.pchg == 0{ changePercentLabel.text = String(format: "%.2f%%", -percent) changePriceLabel.text = String(format: "%.2f", model!.change) colorString = "333333" } else { changePercentLabel.text = String(format: "+%.2f%%",percent) changePriceLabel.text = String(format: "%.2f",model!.change) } changePriceLabel.textColor = UIColor(hexString: colorString) changePercentLabel.textColor = UIColor(hexString: colorString) priceLabel.text = String(format: "%.2f", model!.currentPrice) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
7d6f2a6941378b2fcd1a0d30eca4aba3
29.825397
83
0.621009
4.484988
false
false
false
false
SoneeJohn/WWDC
WWDC/ModalLoadingView.swift
1
2359
// // ModalLoadingView.swift // WWDC // // Created by Guilherme Rambo on 20/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa class ModalLoadingView: NSView { private lazy var backgroundView: NSVisualEffectView = { let v = NSVisualEffectView() v.material = .ultraDark v.appearance = WWDCAppearance.appearance() v.blendingMode = .withinWindow v.translatesAutoresizingMaskIntoConstraints = false v.state = .active return v }() private lazy var spinner: NSProgressIndicator = { let p = NSProgressIndicator() p.isIndeterminate = true p.style = .spinning p.translatesAutoresizingMaskIntoConstraints = false return p }() override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true addSubview(backgroundView) backgroundView.addSubview(spinner) backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true backgroundView.topAnchor.constraint(equalTo: topAnchor).isActive = true backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true spinner.centerXAnchor.constraint(equalTo: backgroundView.centerXAnchor).isActive = true spinner.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor).isActive = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } static func show(attachedTo view: NSView) -> ModalLoadingView { let v = ModalLoadingView(frame: view.bounds) v.show(in: view) return v } func show(in view: NSView) { alphaValue = 0 autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] spinner.startAnimation(nil) view.addSubview(self) NSAnimationContext.runAnimationGroup({ _ in self.alphaValue = 1 }, completionHandler: nil) } func hide() { NSAnimationContext.runAnimationGroup({ _ in self.spinner.stopAnimation(nil) self.alphaValue = 0 }, completionHandler: { self.removeFromSuperview() }) } }
bsd-2-clause
d3b48a588dabdce66aa8c4bc935addc4
26.741176
95
0.659457
5.193833
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift
22
2766
// // HMAC.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 13/01/15. // Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. // public final class HMAC: Authenticator { public enum Error: Swift.Error { case authenticateError case invalidInput } public enum Variant { case sha1, sha256, sha384, sha512, md5 var digestLength: Int { switch (self) { case .sha1: return SHA1.digestLength case .sha256: return SHA2.Variant.sha256.digestLength case .sha384: return SHA2.Variant.sha384.digestLength case .sha512: return SHA2.Variant.sha512.digestLength case .md5: return MD5.digestLength } } func calculateHash(_ bytes: Array<UInt8>) -> Array<UInt8>? { switch (self) { case .sha1: return Digest.sha1(bytes) case .sha256: return Digest.sha256(bytes) case .sha384: return Digest.sha384(bytes) case .sha512: return Digest.sha512(bytes) case .md5: return Digest.md5(bytes) } } func blockSize() -> Int { switch self { case .md5: return MD5.blockSize case .sha1, .sha256: return 64 case .sha384, .sha512: return 128 } } } var key: Array<UInt8> let variant: Variant public init(key: Array<UInt8>, variant: HMAC.Variant = .md5) { self.variant = variant self.key = key if key.count > variant.blockSize() { if let hash = variant.calculateHash(key) { self.key = hash } } if key.count < variant.blockSize() { self.key = ZeroPadding().add(to: key, blockSize: variant.blockSize()) } } // MARK: Authenticator public func authenticate(_ bytes: Array<UInt8>) throws -> Array<UInt8> { var opad = Array<UInt8>(repeating: 0x5c, count: variant.blockSize()) for idx in key.indices { opad[idx] = key[idx] ^ opad[idx] } var ipad = Array<UInt8>(repeating: 0x36, count: variant.blockSize()) for idx in key.indices { ipad[idx] = key[idx] ^ ipad[idx] } guard let ipadAndMessageHash = variant.calculateHash(ipad + bytes), let result = variant.calculateHash(opad + ipadAndMessageHash) else { throw Error.authenticateError } // return Array(result[0..<10]) // 80 bits return result } }
mit
29e5863934619caa0b14ec340f3a3742
26.939394
81
0.522415
4.281734
false
false
false
false
neonichu/Clock
Tests/String.swift
1
948
import Spectre import Clock import Foundation extension NSDateComponents { func toDate() -> NSDate { let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) return calendar?.dateFromComponents(self) ?? NSDate() } } func describeDateToStringConversion() { describe("Converting dates to strings") { $0.it("can convert TM struct to an ISO8601 GMT string") { let actual = tm_struct(year: 1971, month: 2, day: 3, hour: 9, minute: 16, second: 6) try expect(actual.toISO8601GMTString()) == "1971-02-03T09:16:06Z" } #if !os(Linux) $0.it("can convert NSDate to an ISO8601 GMT string") { let input = components(year: 1971, month: 2, day: 3, hour: 9, minute: 16, second: 6) let actual = input.toDate() try expect(actual.toISO8601GMTString()) == "1971-02-03T09:16:06Z" } #endif } }
mit
cbf9e12ce64b9a0805230fc738b5edec
31.689655
100
0.603376
3.885246
false
false
false
false
NunoAlexandre/broccoli_mobile
ios/Carthage/Checkouts/Eureka/Source/Rows/PopoverSelectorRow.swift
7
2517
// PopoverSelectorRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class _PopoverSelectorRow<Cell: CellType> : SelectorRow<Cell, SelectorViewController<Cell.Value>> where Cell: BaseCell, Cell: TypedCellType { public required init(tag: String?) { super.init(tag: tag) onPresentCallback = { [weak self] (_, viewController) -> Void in guard let porpoverController = viewController.popoverPresentationController, let tableView = self?.baseCell.formViewController()?.tableView, let cell = self?.cell else { fatalError() } porpoverController.sourceView = tableView porpoverController.sourceRect = tableView.convert(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, from: cell) } presentationMode = .popover(controllerProvider: ControllerProvider.callback { return SelectorViewController<Cell.Value>(){ _ in } }, onDismiss: { [weak self] in $0.dismiss(animated: true) self?.reload() }) } open override func didSelect() { deselect() super.didSelect() } } public final class PopoverSelectorRow<T: Equatable> : _PopoverSelectorRow<PushSelectorCell<T>>, RowType { public required init(tag: String?) { super.init(tag: tag) } }
mit
12aefb98165d2249e257456ca206a14b
45.611111
181
0.706397
4.669759
false
false
false
false
maorongsen/injectionforxcode
InjectionPluginLite/XprobeSwift/XprobeSwift/Internals.swift
1
3185
// // Internals.swift // XprobeSwift // // Created by John Holdsworth on 22/12/2016. // Copyright © 2016 John Holdsworth. All rights reserved. // import Foundation /** pointer to a function implementing a Swift method */ public typealias SIMP = @convention(c) (_: AnyObject) -> Void /** Layout of a class instance. Needs to be kept in sync with ~swift/include/swift/Runtime/Metadata.h */ public struct ClassMetadataSwift { public let MetaClass: uintptr_t = 0, SuperClass: uintptr_t = 0 public let CacheData1: uintptr_t = 0, CacheData2: uintptr_t = 0 public let Data: uintptr_t = 0 /// Swift-specific class flags. public let Flags: UInt32 = 0 /// The address point of instances of this type. public let InstanceAddressPoint: UInt32 = 0 /// The required size of instances of this type. /// 'InstanceAddressPoint' bytes go before the address point; /// 'InstanceSize - InstanceAddressPoint' bytes go after it. public let InstanceSize: UInt32 = 0 /// The alignment mask of the address point of instances of this type. public let InstanceAlignMask: UInt16 = 0 /// Reserved for runtime use. public let Reserved: UInt16 = 0 /// The total size of the class object, including prefix and suffix /// extents. public let ClassSize: UInt32 = 0 /// The offset of the address point within the class object. public let ClassAddressPoint: UInt32 = 0 /// An out-of-line Swift-specific description of the type, or null /// if this is an artificial subclass. We currently provide no /// supported mechanism for making a non-artificial subclass /// dynamically. public let Description: uintptr_t = 0 /// A function for destroying instance variables, used to clean up /// after an early return from a constructor. public var IVarDestroyer: SIMP? = nil // After this come the class members, laid out as follows: // - class members for the superclass (recursively) // - metadata reference for the parent, if applicable // - generic parameters for this class // - class variables (if we choose to support these) // - "tabulated" virtual methods } #if swift(>=3.0) // not public in Swift3 @_silgen_name("swift_demangle") private func _stdlib_demangleImpl( mangledName: UnsafePointer<CChar>?, mangledNameLength: UInt, outputBuffer: UnsafeMutablePointer<UInt8>?, outputBufferSize: UnsafeMutablePointer<UInt>?, flags: UInt32 ) -> UnsafeMutablePointer<CChar>? public func _stdlib_demangleName(_ mangledName: String) -> String { return mangledName.utf8CString.withUnsafeBufferPointer { (mangledNameUTF8) in let demangledNamePtr = _stdlib_demangleImpl( mangledName: mangledNameUTF8.baseAddress, mangledNameLength: UInt(mangledNameUTF8.count - 1), outputBuffer: nil, outputBufferSize: nil, flags: 0) if let demangledNamePtr = demangledNamePtr { let demangledName = String(cString: demangledNamePtr) free(demangledNamePtr) return demangledName } return mangledName } } #endif
mit
9a1eefc3181f43fa27e208f640e7094d
31.161616
98
0.681533
4.373626
false
false
false
false
benoit-pereira-da-silva/Navet
Sources/navet/CommandFacade.swift
1
4585
// // CommandFacade.swift // navet // // Created by Benoit Pereira da silva on 27/10/2017. // Copyright © 2017 Pereira da Silva https://pereira-da-silva.com All rights reserved. // import Cocoa import NavetLib public struct CommandsFacade { static let args = Swift.CommandLine.arguments let executableName = NSString(string: args.first!).pathComponents.last! let firstArgumentAfterExecutablePath: String = (args.count >= 2) ? args[1] : "" let echo: String = args.joined(separator: " ") public func actOnArguments() { switch firstArgumentAfterExecutablePath { case nil: print(self._noArgMessage()) exit(EX_NOINPUT) case "-h", "-help", "h", "help": print(self._noArgMessage()) exit(EX_USAGE) case "-version", "--version", "v", "version": print("\n\"navet\" has been created by Benoit Pereira da Silva https://pereira-da-silva.com\nCurrent version of Navet is: \(Navet.version)") exit(EX_USAGE) case "echo", "--echo": print(echo) exit(EX_USAGE) case "generate": let _ = NavetGenerate() default: // We want to propose the best verb candidate let reference=[ "h", "help", "v","version", "echo", "generate" ] let bestCandidate=self.bestCandidate(string: firstArgumentAfterExecutablePath, reference: reference) print("Hey ...\"\(executableName) \(firstArgumentAfterExecutablePath)\" is unexpected!") print("Did you mean:\"\(executableName) \(bestCandidate)\"?") exit(EX__BASE) } } private func _noArgMessage() -> String { var s="" s += "Navet Command Line tool" s += "\nCreated by Benoit Pereira da Silva https://pereira-da-silva.com" s += "\nvalid calls are S.V.O sentences like:\"\(executableName) <verb> [options]\"" s += "\n" s += "\n\(executableName) help" s += "\n\(executableName) version" s += "\n\(executableName) echo <args>" s += "\n" s += "\nYou can call help for each verb e.g:\t\"\(executableName) generate help\"" s += "\n" s += "\nAvailable verbs:" s += "\n" s += "\n\(executableName) generate -d <duration> -f <fps> [options]" s += "\n" return s } // MARK: levenshtein distance private func bestCandidate(string: String, reference: [String]) -> String { guard string != "" else { return "help" } var selectedCandidate=string var minDistance: Int=Int.max for candidate in reference { let distance=self.levenshtein(string, candidate) if distance<minDistance { minDistance=distance selectedCandidate=candidate } } return selectedCandidate } private func min(numbers: Int...) -> Int { return numbers.reduce(numbers[0], {$0 < $1 ? $0 : $1}) } private class Array2D { var cols: Int, rows: Int var matrix: [Int] init(cols: Int, rows: Int) { self.cols = cols self.rows = rows matrix = Array(repeating:0, count:cols*rows) } subscript(col: Int, row: Int) -> Int { get { return matrix[cols * row + col] } set { matrix[cols*row+col] = newValue } } func colCount() -> Int { return self.cols } func rowCount() -> Int { return self.rows } } private func levenshtein(_ aStr: String, _ bStr: String) -> Int { let a = Array(aStr.utf16) let b = Array(bStr.utf16) let dist = Array2D(cols: a.count + 1, rows: b.count + 1) for i in 1...a.count { dist[i, 0] = i } for j in 1...b.count { dist[0, j] = j } for i in 1...a.count { for j in 1...b.count { if a[i-1] == b[j-1] { dist[i, j] = dist[i-1, j-1] // noop } else { dist[i, j] = min(numbers: dist[i-1, j] + 1, // deletion dist[i, j-1] + 1, // insertion dist[i-1, j-1] + 1 // substitution ) } } } return dist[a.count, b.count] } }
apache-2.0
f272eb014f6a873c1b73e1e5fe860888
29.56
152
0.499782
4.045896
false
false
false
false
haskellswift/swift-package-manager
Sources/Get/Git.swift
2
1494
/* This source file is part of the Swift.org open source project Copyright 2015 - 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 Swift project authors */ import class Foundation.ProcessInfo import Basic import Utility import func POSIX.realpath import enum POSIX.Error extension Git { class func clone(_ url: String, to dstdir: AbsolutePath) throws -> Repo { // Canonicalize URL. // // FIXME: This is redundant with the same code in the manifest loader. var url = url if URL.scheme(url) == nil { url = try realpath(url) } do { let env = ProcessInfo.processInfo.environment try system(Git.tool, "clone", "--recursive", // get submodules too so that developers can use these if they so choose "--depth", "10", url, dstdir.asString, environment: env, message: "Cloning \(url)") } catch POSIX.Error.exitStatus { // Git 2.0 or higher is required if let majorVersion = Git.majorVersionNumber, majorVersion < 2 { throw Utility.Error.obsoleteGitVersion } else { throw Error.gitCloneFailure(url, dstdir.asString) } } return Repo(path: dstdir)! //TODO no bangs } }
apache-2.0
c6a390785416d4e450823b88fc03f761
31.478261
112
0.618474
4.582822
false
false
false
false
ben-ng/swift
test/SILGen/switch_abstraction.swift
4
1539
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s | %FileCheck %s struct A {} enum Optionable<T> { case Summn(T) case Nuttn } // CHECK-LABEL: sil hidden @_TF18switch_abstraction18enum_reabstractionFT1xGOS_10OptionableFVS_1AS1__1aS1__T_ : $@convention(thin) (@owned Optionable<(A) -> A>, A) -> () // CHECK: switch_enum {{%.*}} : $Optionable<(A) -> A>, case #Optionable.Summn!enumelt.1: [[DEST:bb[0-9]+]] // CHECK: [[DEST]]([[ORIG:%.*]] : $@callee_owned (@in A) -> @out A): // CHECK: [[REABSTRACT:%.*]] = function_ref @_TTR // CHECK: [[SUBST:%.*]] = partial_apply [[REABSTRACT]]([[ORIG]]) func enum_reabstraction(x x: Optionable<(A) -> A>, a: A) { switch x { case .Summn(var f): f(a) case .Nuttn: () } } enum Wacky<A, B> { case Foo(A) case Bar((B) -> A) } // CHECK-LABEL: sil hidden @_TF18switch_abstraction45enum_addr_only_to_loadable_with_reabstraction{{.*}} : $@convention(thin) <T> (@in Wacky<T, A>, A) -> @out T { // CHECK: switch_enum_addr [[ENUM:%.*]] : $*Wacky<T, A>, {{.*}} case #Wacky.Bar!enumelt.1: [[DEST:bb[0-9]+]] // CHECK: [[DEST]]: // CHECK: [[ORIG_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM]] : $*Wacky<T, A>, #Wacky.Bar // CHECK: [[ORIG:%.*]] = load [take] [[ORIG_ADDR]] // CHECK: [[REABSTRACT:%.*]] = function_ref @_TTR // CHECK: [[SUBST:%.*]] = partial_apply [[REABSTRACT]]<T>([[ORIG]]) func enum_addr_only_to_loadable_with_reabstraction<T>(x x: Wacky<T, A>, a: A) -> T { switch x { case .Foo(var b): return b case .Bar(var f): return f(a) } }
apache-2.0
5c98948fc486a12c1915541bcc4252d7
33.2
169
0.582196
2.808394
false
false
false
false
Mrwerdo/Socket
Sources/Socket/Select.swift
2
5090
// // Select.swift // QuickShare // // Copyright (c) 2016 Andrew Thompson // // 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 Darwin import Support //private let __DARWIN_NFDBITS = Int32(sizeof(Int32)) * __DARWIN_NBBY //private let __DARWIN_NUMBER_OF_BITS_IN_SET: Int32 = { () -> Int32 in // func howmany(x: Int32, _ y: Int32) -> Int32 { // return (x % y) == 0 ? (x / y) : (x / (y + 1)) // } // return howmany(__DARWIN_FD_SETSIZE, __DARWIN_NFDBITS) //}() extension fd_set { /// Returns the index of the highest bit set. fileprivate func highestDescriptor() -> Int32 { return qs_fd_highest_fd(self) } /// Clears the `bit` index given. public mutating func clear(_ fd: Int32) { qs_fd_clear(&self, fd) } /// Sets the `bit` index given. public mutating func set(_ fd: Int32) { qs_fd_set(&self, fd) } /// Returns non-zero if `bit` is set. public func isset(_ fd: Int32) -> Bool { return qs_fd_isset(self, fd) != 0 } /// Zeros `self`, so no bits are set. public mutating func zero() { qs_fd_zero(&self) } } /// Waits efficiently until a file descriptor(s) specified is marked as having /// either pending data, a penidng error, or the ability to write. /// /// Any file descriptor's added to `read` will cause `select` to observer their /// status until one or more has any pending data available to read. This is /// similar for `write` and `error` too - `select` will return once some file /// descriptors have been flagged for writing or have an error pending. /// /// The `timeout` parameter will cause `select` to wait for the specified time, /// then return, if no file descriptors have changed state. If a file descriptor /// has changed its state, then select will return immediately and mark the file /// descriptors accordingly. /// /// - parameters: /// - read: Contains a set of file descriptors which have pending /// data ready to be read. /// - write: Contains any file descriptors which can be immediately /// written to. /// - error: Contains any file descriptors which have a pending error /// on them. /// - timeout: Contains the timeout period `select` will wait until /// returning if no changes are observed on the file /// descriptor. /// - Returns: /// The number of file descriptors who's status' have been /// changed. Select modifies the given sets to contain only /// a subset of those given, which have had their status' /// changed. If you pass nil to either `read`, `write` or /// `error`, then you will receive nil out the other end. /// - Throws: /// - `SocketError.SelectFailed` public func select(read: UnsafeMutablePointer<fd_set>?, write: UnsafeMutablePointer<fd_set>?, error: UnsafeMutablePointer<fd_set>?, timeout: UnsafeMutablePointer<timeval>?) throws -> Int32 { var highestFD: Int32 = 0 if let k = read?.pointee.highestDescriptor() { if k > highestFD { highestFD = k } } if let k = write?.pointee.highestDescriptor() { if k > highestFD { highestFD = k } } if let k = error?.pointee.highestDescriptor() { if k > highestFD { highestFD = k } } let result = select(highestFD, read, write, error, timeout) guard result != -1 else { throw SocketError.systemCallError(errno, .select) } return result } enum CError : Error { case cError(Int32) } public func pipe() throws -> (readfd: Int32, writefd: Int32) { var fds: [Int32] = [-1, -1] guard pipe(&fds) == 0 else { throw CError.cError(errno) } guard fds[0] > -1 && fds[1] > -1 else { fatalError("file descriptors are invalid and pipe failed to report an error!") } return (fds[0], fds[1]) }
mit
fc527f059382642c020f9664a3191fda
37.560606
190
0.62888
3.976563
false
false
false
false
zhubofei/IGListKit
Examples/Examples-tvOS/IGListKitExamples/Views/EmbeddedCollectionViewCell.swift
4
1380
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class EmbeddedCollectionViewCell: UICollectionViewCell { lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let view = UICollectionView(frame: .zero, collectionViewLayout: layout) view.backgroundColor = .clear view.alwaysBounceVertical = false view.alwaysBounceHorizontal = true self.contentView.addSubview(view) return view }() override func layoutSubviews() { super.layoutSubviews() collectionView.frame = contentView.frame } override var canBecomeFocused: Bool { return false } }
mit
aa0af4f05e4e81e3d5c10fde3286bbe8
33.5
80
0.733333
5.328185
false
false
false
false
OpenKitten/Meow
Sources/Meow/TypesafeQuerying.swift
1
4971
// // Querying.swift // App // // Created by Robbert Brandsma on 06/06/2018. // // Typesafe queries are currently only available if Vapor is available import MongoKitten import NIO public protocol KeyPathQueryable { static func makeQueryPath<T>(for key: KeyPath<Self, T>) throws -> String } public protocol QueryableModel: KeyPathQueryable, Model {} public protocol ConvertibleToQueryPath { func makeQueryPath() throws -> String } extension KeyPath: ConvertibleToQueryPath where Root: QueryableModel { public func makeQueryPath() throws -> String { return try Root.makeQueryPath(for: self) } } enum MeowQueryEncodingError: Error { case noResultingPrimitive } public struct ModelQuery<M: QueryableModel> { public var query: MongoKitten.Query public init(_ query: MongoKitten.Query = .init()) { self.query = query } } public extension AggregateCursor { public func match<T>(_ query: ModelQuery<T>) -> AggregateCursor<Element> { return self.match(query.query) } } fileprivate struct TargetValueEncodingWrapper<V: Encodable>: Encodable { var value: V } fileprivate extension QueryableModel { static func encode<V: Encodable>(value: V) throws -> Primitive { let wrapper = TargetValueEncodingWrapper(value: value) let document = try Self.encoder.encode(wrapper) guard let result = document["value"] else { throw MeowQueryEncodingError.noResultingPrimitive } return result } } public func == <M: QueryableModel, V: Encodable>(lhs: KeyPath<M, V>, rhs: V?) throws -> ModelQuery<M> { let path = try lhs.makeQueryPath() let compareValue: Primitive? if let rhs = rhs { compareValue = try M.encode(value: rhs) } else { compareValue = nil } return ModelQuery(path == compareValue) } public func == <M: QueryableModel, T: Model>(lhs: KeyPath<M, Reference<T>>, rhs: T?) throws -> ModelQuery<M> { let path = try lhs.makeQueryPath() let compareValue: Primitive? if let rhs = rhs { compareValue = try M.encode(value: rhs._id) } else { compareValue = nil } return ModelQuery(path == compareValue) } public func != <M: QueryableModel, V: Encodable>(lhs: KeyPath<M, V>, rhs: V?) throws -> ModelQuery<M> { let path = try lhs.makeQueryPath() let compareValue: Primitive? if let rhs = rhs { compareValue = try M.encode(value: rhs) } else { compareValue = nil } return ModelQuery(path != compareValue) } public func < <M: QueryableModel, V: Encodable>(lhs: KeyPath<M, V>, rhs: V) throws -> ModelQuery<M> { let path = try lhs.makeQueryPath() let compareValue = try M.encode(value: rhs) return ModelQuery(path < compareValue) } public func > <M: QueryableModel, V: Encodable>(lhs: KeyPath<M, V>, rhs: V) throws -> ModelQuery<M> { let path = try lhs.makeQueryPath() let compareValue = try M.encode(value: rhs) return ModelQuery(path > compareValue) } public func <= <M: QueryableModel, V: Encodable>(lhs: KeyPath<M, V>, rhs: V) throws -> ModelQuery<M> { let path = try lhs.makeQueryPath() let compareValue = try M.encode(value: rhs) return ModelQuery(path <= compareValue) } public func >= <M: QueryableModel, V: Encodable>(lhs: KeyPath<M, V>, rhs: V) throws -> ModelQuery<M> { let path = try lhs.makeQueryPath() let compareValue = try M.encode(value: rhs) return ModelQuery(path >= compareValue) } public func || <M>(lhs: ModelQuery<M>, rhs: ModelQuery<M>) -> ModelQuery<M> { return ModelQuery(lhs.query || rhs.query) } public func && <M>(lhs: ModelQuery<M>, rhs: ModelQuery<M>) -> ModelQuery<M> { return ModelQuery(lhs.query && rhs.query) } public prefix func ! <M>(query: ModelQuery<M>) -> ModelQuery<M> { return ModelQuery(!query.query) } extension KeyPath where Root: QueryableModel, Value: Sequence, Value.Element: Encodable { public func contains(_ element: Value.Element) throws -> ModelQuery<Root> { let path = try self.makeQueryPath() let compareValue = try Root.encode(value: element) return ModelQuery(path == compareValue) // MongoDB allows matching array contains with "$eq" } } extension KeyPath where Root: QueryableModel, Value: Encodable { public func `in`(_ options: [Value]) throws -> ModelQuery<Root> { let path = try self.makeQueryPath() let compareValue = try options.map { try Root.encode(value: $0) } return ModelQuery(.in(field: path, in: compareValue)) } } extension KeyPath where Root: QueryableModel, Value: Sequence, Value.Element: Encodable { public func `in`(_ options: [Value.Element]) throws -> ModelQuery<Root> { let path = try self.makeQueryPath() let compareValue = try options.map { try Root.encode(value: $0) } return ModelQuery(.in(field: path, in: compareValue)) } }
mit
45f39b35cdb3773268c9399cdf1ef165
29.127273
110
0.662643
3.835648
false
false
false
false
KrishMunot/swift
test/expr/closure/single_expr.swift
2
1211
// RUN: %target-parse-verify-swift func takeIntToInt(_ f: (Int) -> Int) { } func takeIntIntToInt(_ f: (Int, Int) -> Int) { } // Simple closures with anonymous arguments func simple() { takeIntToInt({$0 + 1}) takeIntIntToInt({$0 + $1 + 1}) } // Anonymous arguments with inference func myMap<T, U>(_ array: [T], _ f: (T) -> U) -> [U] {} func testMap(_ array: [Int]) { var farray = myMap(array, { Float($0) }) var _ : Float = farray[0] let farray2 = myMap(array, { (x : Int) in Float(x) }) farray = farray2 _ = farray } // Nested single-expression closures -- <rdar://problem/20931915> class NestedSingleExpr { private var b: Bool = false private func callClosure(_ callback: Void -> Void) {} func call() { callClosure { [weak self] in self?.callClosure { self?.b = true } } } } // Autoclosure nested inside single-expr closure should get discriminator // <rdar://problem/22441425> Swift compiler "INTERNAL ERROR: this diagnostic should not be produced" struct Expectation<T> {} func expect<T>(@autoclosure _ expression: () -> T) -> Expectation<T> { return Expectation<T>() } func describe(_ closure: () -> ()) {} func f() { describe { expect("what") } }
apache-2.0
f74cf2209dc4dcedad837faeab818531
26.522727
100
0.628406
3.430595
false
false
false
false
paulofaria/swift-apex
Sources/Apex/FileDescriptorStream/FileDescriptorStream.swift
1
1828
import CLibvenice public let standardInputStream = FileDescriptorStream(fileDescriptor: STDIN_FILENO) public let standardOutputStream = FileDescriptorStream(fileDescriptor: STDOUT_FILENO) public final class FileDescriptorStream : Stream { fileprivate var file: mfile? public fileprivate(set) var closed = false init(file: mfile) { self.file = file } public convenience init(fileDescriptor: FileDescriptor) { let file = fileattach(fileDescriptor) self.init(file: file!) } deinit { if let file = file, !closed { fileclose(file) } } } extension FileDescriptorStream { public func write(_ data: Data, length: Int, deadline: Double) throws -> Int { try ensureFileIsOpen() let bytesWritten = data.withUnsafeBytes { filewrite(file, $0, length, deadline.int64milliseconds) } if bytesWritten == 0 { try ensureLastOperationSucceeded() } return bytesWritten } public func read(into buffer: inout Data, length: Int, deadline: Double) throws -> Int { try ensureFileIsOpen() let bytesRead = buffer.withUnsafeMutableBytes { filereadlh(file, $0, 1, length, deadline.int64milliseconds) } if bytesRead == 0 { try ensureLastOperationSucceeded() } return bytesRead } public func flush(deadline: Double) throws { try ensureFileIsOpen() fileflush(file, deadline.int64milliseconds) try ensureLastOperationSucceeded() } public func close() { if !closed { fileclose(file) } closed = true } private func ensureFileIsOpen() throws { if closed { throw StreamError.closedStream } } }
mit
9015e8c55824a4b58cac9c011fcee6b8
23.702703
92
0.620897
4.967391
false
false
false
false
trungphamduc/Calendar
Pod/Classes/CalendarLogic.swift
2
4085
// // CalLogic.swift // CalendarLogic // // Created by Lancy on 01/06/15. // Copyright (c) 2015 Lancy. All rights reserved. // import Foundation class CalendarLogic: Hashable { var hashValue: Int { return baseDate.hashValue } // Mark: Public variables and methods. var baseDate: NSDate { didSet { calculateVisibleDays() } } private lazy var dateFormatter = NSDateFormatter() var currentMonthAndYear: NSString { dateFormatter.dateFormat = calendarSettings.monthYearFormat return dateFormatter.stringFromDate(baseDate) } var currentMonthDays: [Date]? var previousMonthVisibleDays: [Date]? var nextMonthVisibleDays: [Date]? init(date: NSDate) { baseDate = date.firstDayOfTheMonth calculateVisibleDays() } func retreatToPreviousMonth() { baseDate = baseDate.firstDayOfPreviousMonth } func advanceToNextMonth() { baseDate = baseDate.firstDayOfFollowingMonth } func moveToMonth(date: NSDate) { baseDate = date } func isVisible(date: NSDate) -> Bool { let internalDate = Date(date: date) if contains(currentMonthDays!, internalDate) { return true } else if contains(previousMonthVisibleDays!, internalDate) { return true } else if contains(nextMonthVisibleDays!, internalDate) { return true } return false } func containsDate(date: NSDate) -> Bool { let date = Date(date: date) let logicBaseDate = Date(date: baseDate) if (date.month == logicBaseDate.month) && (date.year == logicBaseDate.year) { return true } return false } //Mark: Private methods. private var numberOfDaysInPreviousPartialWeek: Int { return baseDate.weekDay - 1 } private var numberOfVisibleDaysforFollowingMonth: Int { // Traverse to the last day of the month. let parts = baseDate.monthDayAndYearComponents parts.day = baseDate.numberOfDaysInMonth let date = NSCalendar.currentCalendar().dateFromComponents(parts) // 7*6 = 42 :- 7 columns (7 days in a week) and 6 rows (max 6 weeks in a month) return 42 - (numberOfDaysInPreviousPartialWeek + baseDate.numberOfDaysInMonth) } private var calculateCurrentMonthVisibleDays: [Date] { var dates = [Date]() let numberOfDaysInMonth = baseDate.numberOfDaysInMonth let component = baseDate.monthDayAndYearComponents for var i = 1; i <= numberOfDaysInMonth; i++ { dates.append(Date(day: i, month: component.month, year: component.year)) } return dates } private var calculatePreviousMonthVisibleDays: [Date] { var dates = [Date]() let date = baseDate.firstDayOfPreviousMonth let numberOfDaysInMonth = date.numberOfDaysInMonth let numberOfVisibleDays = numberOfDaysInPreviousPartialWeek let parts = date.monthDayAndYearComponents for var i = numberOfDaysInMonth - (numberOfVisibleDays - 1); i <= numberOfDaysInMonth; i++ { dates.append(Date(day: i, month: parts.month, year: parts.year)) } return dates } private var calculateFollowingMonthVisibleDays: [Date] { var dates = [Date]() let date = baseDate.firstDayOfFollowingMonth let numberOfDays = numberOfVisibleDaysforFollowingMonth let parts = date.monthDayAndYearComponents for var i = 1; i <= numberOfVisibleDaysforFollowingMonth; i++ { dates.append(Date(day: i, month: parts.month, year: parts.year)) } return dates } private func calculateVisibleDays() { currentMonthDays = calculateCurrentMonthVisibleDays previousMonthVisibleDays = calculatePreviousMonthVisibleDays nextMonthVisibleDays = calculateFollowingMonthVisibleDays } } func ==(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool { return lhs.hashValue == rhs.hashValue } func <(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool { return (lhs.baseDate.compare(rhs.baseDate) == .OrderedAscending) } func >(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool { return (lhs.baseDate.compare(rhs.baseDate) == .OrderedDescending) }
mit
6683d2407df09c0f7b7e818bd7129b8f
26.789116
96
0.697674
4.295478
false
false
false
false
xwu/swift
stdlib/public/core/SequenceAlgorithms.swift
12
31716
//===--- SequenceAlgorithms.swift -----------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // enumerated() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a sequence of pairs (*n*, *x*), where *n* represents a /// consecutive integer starting at zero and *x* represents an element of /// the sequence. /// /// This example enumerates the characters of the string "Swift" and prints /// each character along with its place in the string. /// /// for (n, c) in "Swift".enumerated() { /// print("\(n): '\(c)'") /// } /// // Prints "0: 'S'" /// // Prints "1: 'w'" /// // Prints "2: 'i'" /// // Prints "3: 'f'" /// // Prints "4: 't'" /// /// When you enumerate a collection, the integer part of each pair is a counter /// for the enumeration, but is not necessarily the index of the paired value. /// These counters can be used as indices only in instances of zero-based, /// integer-indexed collections, such as `Array` and `ContiguousArray`. For /// other collections the counters may be out of range or of the wrong type /// to use as an index. To iterate over the elements of a collection with its /// indices, use the `zip(_:_:)` function. /// /// This example iterates over the indices and elements of a set, building a /// list consisting of indices of names with five or fewer letters. /// /// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// var shorterIndices: [Set<String>.Index] = [] /// for (i, name) in zip(names.indices, names) { /// if name.count <= 5 { /// shorterIndices.append(i) /// } /// } /// /// Now that the `shorterIndices` array holds the indices of the shorter /// names in the `names` set, you can use those indices to access elements in /// the set. /// /// for i in shorterIndices { /// print(names[i]) /// } /// // Prints "Sofia" /// // Prints "Mateo" /// /// - Returns: A sequence of pairs enumerating the sequence. /// /// - Complexity: O(1) @inlinable // protocol-only public func enumerated() -> EnumeratedSequence<Self> { return EnumeratedSequence(_base: self) } } //===----------------------------------------------------------------------===// // min(), max() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the minimum element in the sequence, using the given predicate as /// the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `min(by:)` method on a /// dictionary to find the key-value pair with the lowest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let leastHue = hues.min { a, b in a.value < b.value } /// print(leastHue) /// // Prints "Optional((key: "Coral", value: 16))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` /// if its first argument should be ordered before its second /// argument; otherwise, `false`. /// - Returns: The sequence's minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns /// `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func min( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(e, result) { result = e } } return result } /// Returns the maximum element in the sequence, using the given predicate /// as the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `max(by:)` method on a /// dictionary to find the key-value pair with the highest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let greatestHue = hues.max { a, b in a.value < b.value } /// print(greatestHue) /// // Prints "Optional((key: "Heliotrope", value: 296))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. /// - Returns: The sequence's maximum element if the sequence is not empty; /// otherwise, `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable // protocol-only @warn_unqualified_access public func max( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(result, e) { result = e } } return result } } extension Sequence where Element: Comparable { /// Returns the minimum element in the sequence. /// /// This example finds the smallest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let lowestHeight = heights.min() /// print(lowestHeight) /// // Prints "Optional(58.5)" /// /// - Returns: The sequence's minimum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func min() -> Element? { return self.min(by: <) } /// Returns the maximum element in the sequence. /// /// This example finds the largest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let greatestHeight = heights.max() /// print(greatestHeight) /// // Prints "Optional(67.5)" /// /// - Returns: The sequence's maximum element. If the sequence has no /// elements, returns `nil`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable @warn_unqualified_access public func max() -> Element? { return self.max(by: <) } } //===----------------------------------------------------------------------===// // starts(with:) //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are equivalent to the elements in another sequence, using /// the given predicate as the equivalence test. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - possiblePrefix: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if the initial elements of the sequence are equivalent /// to the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix, by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool ) rethrows -> Bool { var possiblePrefixIterator = possiblePrefix.makeIterator() for e0 in self { if let e1 = possiblePrefixIterator.next() { if try !areEquivalent(e0, e1) { return false } } else { return true } } return possiblePrefixIterator.next() == nil } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are the same as the elements in another sequence. /// /// This example tests whether one countable range begins with the elements /// of another countable range. /// /// let a = 1...3 /// let b = 1...10 /// /// print(b.starts(with: a)) /// // Prints "true" /// /// Passing a sequence with no elements or an empty collection as /// `possiblePrefix` always results in `true`. /// /// print(b.starts(with: [])) /// // Prints "true" /// /// - Parameter possiblePrefix: A sequence to compare to this sequence. /// - Returns: `true` if the initial elements of the sequence are the same as /// the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `possiblePrefix`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix ) -> Bool where PossiblePrefix.Element == Element { return self.starts(with: possiblePrefix, by: ==) } } //===----------------------------------------------------------------------===// // elementsEqual() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain equivalent elements in the same order, using the given /// predicate as the equivalence test. /// /// At least one of the sequences must be finite. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if this sequence and `other` contain equivalent items, /// using `areEquivalent` as the equivalence test; otherwise, `false.` /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence, by areEquivalent: (Element, OtherSequence.Element) throws -> Bool ) rethrows -> Bool { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { switch (iter1.next(), iter2.next()) { case let (e1?, e2?): if try !areEquivalent(e1, e2) { return false } case (_?, nil), (nil, _?): return false case (nil, nil): return true } } } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain the same elements in the same order. /// /// At least one of the sequences must be finite. /// /// This example tests whether one countable range shares the same elements /// as another countable range and an array. /// /// let a = 1...3 /// let b = 1...10 /// /// print(a.elementsEqual(b)) /// // Prints "false" /// print(a.elementsEqual([1, 2, 3])) /// // Prints "true" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence and `other` contain the same elements /// in the same order. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.elementsEqual(other, by: ==) } } //===----------------------------------------------------------------------===// // lexicographicallyPrecedes() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the given /// predicate to compare elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areInIncreasingOrder: A predicate that returns `true` if its first /// argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that perform /// localized comparison instead. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Bool where OtherSequence.Element == Element { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { if let e1 = iter1.next() { if let e2 = iter2.next() { if try areInIncreasingOrder(e1, e2) { return true } if try areInIncreasingOrder(e2, e1) { return false } continue // Equivalent } return false } return iter2.next() != nil } } } extension Sequence where Element: Comparable { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the /// less-than operator (`<`) to compare elements. /// /// This example uses the `lexicographicallyPrecedes` method to test which /// array of integers comes first in a lexicographical ordering. /// /// let a = [1, 2, 2, 2] /// let b = [1, 2, 3, 4] /// /// print(a.lexicographicallyPrecedes(b)) /// // Prints "true" /// print(b.lexicographicallyPrecedes(b)) /// // Prints "false" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that /// perform localized comparison. /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.lexicographicallyPrecedes(other, by: <) } } //===----------------------------------------------------------------------===// // contains() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence contains an /// element that satisfies the given predicate. /// /// You can use the predicate to check for an element of a type that /// doesn't conform to the `Equatable` protocol, such as the /// `HTTPResponse` enumeration in this example. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)] /// let hadError = lastThreeResponses.contains { element in /// if case .error = element { /// return true /// } else { /// return false /// } /// } /// // 'hadError' == true /// /// Alternatively, a predicate can be satisfied by a range of `Equatable` /// elements or a general condition. This example shows how you can check an /// array for an expense greater than $100. /// /// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41] /// let hasBigPurchase = expenses.contains { $0 > 100 } /// // 'hasBigPurchase' == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element represents a match. /// - Returns: `true` if the sequence contains an element that satisfies /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains( where predicate: (Element) throws -> Bool ) rethrows -> Bool { for e in self { if try predicate(e) { return true } } return false } /// Returns a Boolean value indicating whether every element of a sequence /// satisfies a given predicate. /// /// The following code uses this method to test whether all the names in an /// array have at least five characters: /// /// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 }) /// // allHaveAtLeastFive == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element satisfies a condition. /// - Returns: `true` if the sequence contains only elements that satisfy /// `predicate`; otherwise, `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func allSatisfy( _ predicate: (Element) throws -> Bool ) rethrows -> Bool { return try !contains { try !predicate($0) } } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the sequence contains the /// given element. /// /// This example checks to see whether a favorite actor is in an array /// storing a movie's cast. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// print(cast.contains("Marlon")) /// // Prints "true" /// print(cast.contains("James")) /// // Prints "false" /// /// - Parameter element: The element to find in the sequence. /// - Returns: `true` if the element was found in the sequence; otherwise, /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func contains(_ element: Element) -> Bool { if let result = _customContainsEquatableElement(element) { return result } else { return self.contains { $0 == element } } } } //===----------------------------------------------------------------------===// // reduce() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements /// of an entire sequence. For example, you can use this method on an array /// of numbers to find their sum or product. /// /// The `nextPartialResult` closure is called sequentially with an /// accumulating value initialized to `initialResult` and each element of /// the sequence. This example shows how to find the sum of an array of /// numbers. /// /// let numbers = [1, 2, 3, 4] /// let numberSum = numbers.reduce(0, { x, y in /// x + y /// }) /// // numberSum == 10 /// /// When `numbers.reduce(_:_:)` is called, the following steps occur: /// /// 1. The `nextPartialResult` closure is called with `initialResult`---`0` /// in this case---and the first element of `numbers`, returning the sum: /// `1`. /// 2. The closure is called again repeatedly with the previous call's return /// value and each element of the sequence. /// 3. When the sequence is exhausted, the last value returned from the /// closure is returned to the caller. /// /// If the sequence has no elements, `nextPartialResult` is never executed /// and `initialResult` is the result of the call to `reduce(_:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// `initialResult` is passed to `nextPartialResult` the first time the /// closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the sequence into a new accumulating value, to be used /// in the next call of the `nextPartialResult` closure or returned to /// the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (_ partialResult: Result, Element) throws -> Result ) rethrows -> Result { var accumulator = initialResult for element in self { accumulator = try nextPartialResult(accumulator, element) } return accumulator } /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(into:_:)` method to produce a single value from the /// elements of an entire sequence. For example, you can use this method on an /// array of integers to filter adjacent equal entries or count frequencies. /// /// This method is preferred over `reduce(_:_:)` for efficiency when the /// result is a copy-on-write type, for example an Array or a Dictionary. /// /// The `updateAccumulatingResult` closure is called sequentially with a /// mutable accumulating value initialized to `initialResult` and each element /// of the sequence. This example shows how to build a dictionary of letter /// frequencies of a string. /// /// let letters = "abracadabra" /// let letterCount = letters.reduce(into: [:]) { counts, letter in /// counts[letter, default: 0] += 1 /// } /// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1] /// /// When `letters.reduce(into:_:)` is called, the following steps occur: /// /// 1. The `updateAccumulatingResult` closure is called with the initial /// accumulating value---`[:]` in this case---and the first character of /// `letters`, modifying the accumulating value by setting `1` for the key /// `"a"`. /// 2. The closure is called again repeatedly with the updated accumulating /// value and each element of the sequence. /// 3. When the sequence is exhausted, the accumulating value is returned to /// the caller. /// /// If the sequence has no elements, `updateAccumulatingResult` is never /// executed and `initialResult` is the result of the call to /// `reduce(into:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// - updateAccumulatingResult: A closure that updates the accumulating /// value with an element of the sequence. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public func reduce<Result>( into initialResult: __owned Result, _ updateAccumulatingResult: (_ partialResult: inout Result, Element) throws -> () ) rethrows -> Result { var accumulator = initialResult for element in self { try updateAccumulatingResult(&accumulator, element) } return accumulator } } //===----------------------------------------------------------------------===// // reversed() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the elements of this sequence in reverse /// order. /// /// The sequence must be finite. /// /// - Returns: An array containing the elements of this sequence in /// reverse order. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @inlinable public __consuming func reversed() -> [Element] { // FIXME(performance): optimize to 1 pass? But Array(self) can be // optimized to a memcpy() sometimes. Those cases are usually collections, // though. var result = Array(self) let count = result.count for i in 0..<count/2 { result.swapAt(i, count - ((i + 1) as Int)) } return result } } //===----------------------------------------------------------------------===// // flatMap() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the concatenated results of calling the /// given transformation with each element of this sequence. /// /// Use this method to receive a single-level collection when your /// transformation produces a sequence or collection for each element. /// /// In this example, note the difference in the result of using `map` and /// `flatMap` with a transformation that returns an array. /// /// let numbers = [1, 2, 3, 4] /// /// let mapped = numbers.map { Array(repeating: $0, count: $0) } /// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] /// /// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) } /// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] /// /// In fact, `s.flatMap(transform)` is equivalent to /// `Array(s.map(transform).joined())`. /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns a sequence or collection. /// - Returns: The resulting flattened array. /// /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence /// and *m* is the length of the result. @inlinable public func flatMap<SegmentOfResult: Sequence>( _ transform: (Element) throws -> SegmentOfResult ) rethrows -> [SegmentOfResult.Element] { var result: [SegmentOfResult.Element] = [] for element in self { result.append(contentsOf: try transform(element)) } return result } } extension Sequence { /// Returns an array containing the non-`nil` results of calling the given /// transformation with each element of this sequence. /// /// Use this method to receive an array of non-optional values when your /// transformation produces an optional value. /// /// In this example, note the difference in the result of using `map` and /// `compactMap` with a transformation that returns an optional `Int` value. /// /// let possibleNumbers = ["1", "2", "three", "///4///", "5"] /// /// let mapped: [Int?] = possibleNumbers.map { str in Int(str) } /// // [1, 2, nil, nil, 5] /// /// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) } /// // [1, 2, 5] /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns an optional value. /// - Returns: An array of the non-`nil` results of calling `transform` /// with each element of the sequence. /// /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence /// and *m* is the length of the result. @inlinable // protocol-only public func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try _compactMap(transform) } // The implementation of compactMap accepting a closure with an optional result. // Factored out into a separate function in order to be used in multiple // overloads. @inlinable // protocol-only @inline(__always) public func _compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { var result: [ElementOfResult] = [] for element in self { if let newElement = try transform(element) { result.append(newElement) } } return result } }
apache-2.0
8649f865ce8d575b2338b2315f0ed527
38.00861
83
0.60292
4.356917
false
false
false
false
dibaicongyouwangzi/QQMusic
QQMusic/QQMusic/Classes/QQDetail/Controller/QQDetailVC.swift
1
9372
// // QQDetailVC.swift // QQMusic // // Created by 迪拜葱油王子 on 2016/11/4. // Copyright © 2016年 迪拜葱油王子. All rights reserved. // import UIKit // MARK:- 存放属性 class QQDetailVC: UIViewController { @IBOutlet weak var lrcScrollView: UIScrollView! // 歌词的视图 lazy var lrcVc: QQLrcTVC? = { return QQLrcTVC() }() // 分析界面,根据不同的更新频率,采用不同的方案赋值 /** 歌词动画背景 1 */ @IBOutlet weak var foreImageView: UIImageView! /** 背景图片 1 */ @IBOutlet weak var backImageView: UIImageView! /** 歌曲名称 1 */ @IBOutlet weak var songNameLabel: UILabel! /** 歌手名称 1 */ @IBOutlet weak var singNameLabel: UILabel! /** 总时长 1 */ @IBOutlet weak var totalTimeLabel: UILabel! /** 歌词label n */ @IBOutlet weak var lrclabel: QQLrcLabel! /** 已经播放时长 n */ @IBOutlet weak var costTimeLabel: UILabel! /** 进度条 n */ @IBOutlet weak var progressSlider: UISlider! @IBOutlet weak var playOrPauseBtn: UIButton! // 负责更新很多次的timer var timer: Timer? // 负责更新歌词的Link var updateLrcLink : CADisplayLink? } // MARK:- 业务逻辑 extension QQDetailVC { @IBAction func close() { self .dismiss(animated: true, completion: nil) } // 播放或者暂停 @IBAction func playOrPause(_ sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected{ QQMusicOperationTool.shareInstance.playCurrentMusic() resumeRotationAnimation() }else { QQMusicOperationTool.shareInstance.pauseCurrentMusic() pauseRotationAnimation() } } @IBAction func preMusic() { QQMusicOperationTool.shareInstance.preMusic() // 切换一次更新界面的操作 setupOnce() } @IBAction func nextMusic() { QQMusicOperationTool.shareInstance.nextMusic() setupOnce() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupOnce() addTimer() addLink() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) removerTimer() removeLink() } override func viewDidLoad() { super.viewDidLoad() addLrcView() setupLrcScrollView() setSlider() } // 当歌曲切换时,需要更新一次的操作 func setupOnce() -> (){ let musicMessageM = QQMusicOperationTool.shareInstance.getMusicMessageModel() guard let musicM = musicMessageM.musicM else {return} /** 背景图片 1 */ if musicM.icon != nil{ backImageView.image = UIImage(named: (musicM.icon)!) // 前进图片 foreImageView.image = UIImage(named: (musicM.icon)!) } /** 歌曲名称 1 */ songNameLabel.text = musicM.name /** 歌手名称 1 */ singNameLabel.text = musicM.singer /** 总时长 1 */ totalTimeLabel.text = QQTimeTool.getFormatTime(timeInterval: musicMessageM.totalTime) // 切换最新的歌词 let lrcMs = QQMusicDataTool.getLrcMs(lrcName: musicM.lrcname) lrcVc?.lrcMs = lrcMs addRotationAnimation() if musicMessageM.isPlaying{ resumeRotationAnimation() }else{ pauseRotationAnimation() } } // 当歌曲切换时,需要更新N次的操作 func setupTimes() -> (){ let musicMessageM = QQMusicOperationTool.shareInstance.getMusicMessageModel() /** 歌词label n */ // lrclabel.text = "" /** 已经播放时长 n */ costTimeLabel.text = QQTimeTool.getFormatTime(timeInterval: musicMessageM.costTime) /** 进度条 n */ progressSlider.value = Float(musicMessageM.costTime / musicMessageM.totalTime) playOrPauseBtn.isSelected = musicMessageM.isPlaying } func addTimer() -> (){ timer = Timer(timeInterval: 1.0, target: self, selector: #selector(QQDetailVC.setupTimes), userInfo: nil, repeats: true) RunLoop.current.add(timer!, forMode: .commonModes) } func removerTimer() -> (){ timer?.invalidate() timer = nil } func addLink() -> (){ updateLrcLink = CADisplayLink(target: self, selector: #selector(QQDetailVC.updateLrc)) updateLrcLink?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes) } func removeLink() -> (){ updateLrcLink?.invalidate() updateLrcLink = nil } // 更新歌词 func updateLrc() -> (){ let musicMessageM = QQMusicOperationTool.shareInstance.getMusicMessageModel() // 拿到歌词 // 当前时间 let time = musicMessageM.costTime // 歌词数组 let lrcMs = lrcVc?.lrcMs let rowLrcM = QQMusicDataTool.getCurrentLrcM(currentTime: time, lrcMs: lrcMs!) let lrcM = rowLrcM.lrcM // 赋值 lrclabel.text = lrcM?.lrcContent // 进度 if(lrcM != nil){ let time1 = time - lrcM!.beginTime let time2 = lrcM!.endTime - lrcM!.beginTime lrclabel.radio = CGFloat(time1 / time2) } lrcVc?.progress = lrclabel.radio // 滚动歌词 // 滚到哪一行 let row = rowLrcM.row // 赋值给lrcVC,让它来负责具体怎么滚 lrcVc?.scrollRow = row // 设置锁屏信息 if UIApplication.shared.applicationState == .background{ QQMusicOperationTool.shareInstance.setupLockMessage() } } } // MARK:- 界面操作 extension QQDetailVC { // 添加歌词视图 func addLrcView() -> (){ lrcVc?.tableView.backgroundColor = UIColor.clear lrcScrollView.addSubview((lrcVc?.tableView)!) } // 调整frame func setLrcViewFrame() -> (){ lrcVc?.tableView.frame = lrcScrollView.bounds lrcVc?.tableView.frame.origin.x = lrcScrollView.frame.size.width lrcScrollView.contentSize = CGSize(width: lrcScrollView.frame.size.width * 2, height: 0) } func setSlider() -> (){ progressSlider.setThumbImage(UIImage(named:"player_slider_playback_thumb"), for: .normal) } func setupForeImageView() -> (){ foreImageView.layer.cornerRadius = foreImageView.frame.size.width / 2 foreImageView.layer.masksToBounds = true } func setupLrcScrollView() -> (){ lrcScrollView.delegate = self lrcScrollView.isPagingEnabled = true lrcScrollView.showsHorizontalScrollIndicator = false } override var preferredStatusBarStyle: UIStatusBarStyle{ return .lightContent } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setLrcViewFrame() setupForeImageView() } } // MARK:- 做动画 extension QQDetailVC: UIScrollViewDelegate{ func scrollViewDidScroll(_ scrollView: UIScrollView) { let x = scrollView.contentOffset.x // print(x) let radio = 1 - x / scrollView.frame.size.width foreImageView.alpha = radio lrclabel.alpha = radio } // 添加旋转动画 func addRotationAnimation() -> (){ foreImageView.layer.removeAnimation(forKey: "rotation") let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = M_PI * 2 animation.duration = 30 animation.repeatCount = MAXFLOAT animation.isRemovedOnCompletion = false foreImageView.layer.add(animation, forKey: "rotation") } // 暂停旋转动画 func pauseRotationAnimation() -> (){ foreImageView.layer.pauseAnimate() } // 继续旋转动画 func resumeRotationAnimation() -> (){ foreImageView.layer.resumeAnimate() } } extension QQDetailVC { override func remoteControlReceived(with event: UIEvent?) { let type = event?.subtype switch type! { case .remoteControlPlay: print("播放") QQMusicOperationTool.shareInstance.playCurrentMusic() case .remoteControlPause: print("暂停") QQMusicOperationTool.shareInstance.pauseCurrentMusic() case .remoteControlNextTrack: print("下一首") QQMusicOperationTool.shareInstance.nextMusic() case .remoteControlPreviousTrack: print("上一首") QQMusicOperationTool.shareInstance.preMusic() default: print("nono") } setupOnce() } override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { QQMusicOperationTool.shareInstance.nextMusic() setupOnce() } }
mit
dab4c6a362d601f5b76d929253c2dea6
24.5
128
0.584608
4.451564
false
false
false
false
joncardasis/ChromaColorPicker
Tests/Extensions/UIView+DropShadowTests.swift
1
3754
// // UIView+DropShadowTests.swift // ChromaColorPickerTests // // Created by Jon Cardasis on 5/2/19. // Copyright © 2019 Jonathan Cardasis. All rights reserved. // import XCTest @testable import ChromaColorPicker class UIView_DropShadowTests: XCTestCase { var subject: UIView! override func setUp() { subject = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) } func testApplyingDropShadowUpdatesLayerProperties() { // Given let color: UIColor = .blue let opacity: Float = 0.35 let offset: CGSize = CGSize(width: 12, height: 10) let radius: CGFloat = 4.0 // When subject.applyDropShadow(color: color, opacity: opacity, offset: offset, radius: radius) // Then XCTAssertFalse(subject.layer.masksToBounds) XCTAssertEqual(subject.layer.shadowColor, color.cgColor) XCTAssertEqual(subject.layer.shadowOpacity, opacity) XCTAssertEqual(subject.layer.shadowOffset, offset) XCTAssertEqual(subject.layer.shadowRadius, radius) } func testConvenienceMethodApplyDropShadowUpdatesTheSameLayerProperties() { // Given let color: UIColor = .blue let opacity: Float = 0.35 let offset: CGSize = CGSize(width: 12, height: 10) let radius: CGFloat = 4.0 let shadowProps = ShadowProperties(color: color.cgColor, opacity: opacity, offset: offset, radius: radius) // When subject.applyDropShadow(shadowProps) // Then XCTAssertFalse(subject.layer.masksToBounds) XCTAssertEqual(subject.layer.shadowColor, color.cgColor) XCTAssertEqual(subject.layer.shadowOpacity, opacity) XCTAssertEqual(subject.layer.shadowOffset, offset) XCTAssertEqual(subject.layer.shadowRadius, radius) } func testViewShouldNotClipToBoundsWhenDropShadowApplied() { // Given, When subject.applyDropShadow(defaultShadowProperties) // Then XCTAssertFalse(subject.clipsToBounds) } func testApplyingDropShadowShouldRasterizeLayer() { // Given, When subject.applyDropShadow(defaultShadowProperties) // Then XCTAssertTrue(subject.layer.shouldRasterize) XCTAssertEqual(subject.layer.rasterizationScale, UIScreen.main.scale) } func testDropShadowPropertiesReturnsCurrentShadowProps() { // Given, When subject.applyDropShadow(defaultShadowProperties) // Then XCTAssertEqual(subject.dropShadowProperties!.color, defaultShadowProperties.color) XCTAssertEqual(subject.dropShadowProperties!.opacity, defaultShadowProperties.opacity) XCTAssertEqual(subject.dropShadowProperties!.offset, defaultShadowProperties.offset) XCTAssertEqual(subject.dropShadowProperties!.radius, defaultShadowProperties.radius) } func testDropShadowPropertiesReturnsNilWhenNoShadowColor() { // Given, When subject.applyDropShadow(defaultShadowProperties) subject.layer.shadowColor = nil // Then XCTAssertNil(subject.dropShadowProperties) } func testRemoveDropShadowRemovesVisualShadowProperties() { // Given subject.applyDropShadow(defaultShadowProperties) // When subject.removeDropShadow() // Then XCTAssertNil(subject.layer.shadowColor) XCTAssertEqual(subject.layer.shadowOpacity, 0) } } private var defaultShadowProperties: ShadowProperties { return ShadowProperties(color: UIColor.black.cgColor, opacity: 0.5, offset: CGSize(width: 2, height: 4), radius: 4) }
mit
96b39c2c0ddfcb4e6e4c04f846e8859a
32.810811
119
0.672262
5.024096
false
true
false
false
WeirdMath/TimetableSDK
Sources/JSONRepresentable.swift
1
4279
// // JSONRepresentable.swift // TimetableSDK // // Created by Sergej Jaskiewicz on 23.11.2016. // // import Foundation import SwiftyJSON public protocol JSONRepresentable { /// Creates a new entity from its JSON representation. /// /// - Parameter json: The JSON representation of the entity. /// - Throws: `TimetableError.incorrectJSONFormat` init(from json: JSON) throws } public extension JSONRepresentable { public init(from jsonData: Data) throws { let json = JSON(data: jsonData) try self.init(from: json) } } // MARK: - Standard type extensions extension Double : JSONRepresentable { public init(from json: JSON) throws { if let double = json.double { self.init(double) } else { throw TimetableError.incorrectJSON(json, whenConverting: Double.self) } } } extension Int : JSONRepresentable { public init(from json: JSON) throws { if let int = json.int { self.init(int) } else { throw TimetableError.incorrectJSON(json, whenConverting: Int.self) } } } extension String : JSONRepresentable { public init(from json: JSON) throws { if let string = json.string { self.init(string.characters) } else { throw TimetableError.incorrectJSON(json, whenConverting: String.self) } } } extension Bool : JSONRepresentable { public init(from json: JSON) throws { if let bool = json.bool { self.init(bool) } else { throw TimetableError.incorrectJSON(json, whenConverting: Bool.self) } } } // MARK: - Mapping functions internal func map<T : JSONRepresentable>(_ json: JSON) throws -> T { return try T(from: json) } internal func map<T : JSONRepresentable>(_ json: JSON) throws -> T? { if json.null != nil || !json.exists() { return nil } else { let result: T = try map(json) return result } } internal func map<T : JSONRepresentable>(_ json: JSON) throws -> [T] { if let array = json.array { return try array.map(T.init) } else { throw TimetableError.incorrectJSON(json, whenConverting: Array<T>.self) } } internal func map<T : JSONRepresentable>(_ json: JSON) throws -> [T]? { if json.null != nil || !json.exists() { return nil } else { let result: [T] = try map(json) return result } } internal func map<T : JSONRepresentable, S : JSONRepresentable>(_ json: JSON) throws -> (T, S) { do { return (try T(from: json["Item1"]), try S(from: json["Item2"])) } catch { throw TimetableError.incorrectJSON(json, whenConverting: (T, S).self) } } internal func map<T : JSONRepresentable, S : JSONRepresentable>(_ json: JSON) throws -> [(T, S)] { if let array = json.array { return try array.map(map) } else { throw TimetableError.incorrectJSON(json, whenConverting: Array<(T, S)>.self) } } internal func map<T : JSONRepresentable, S : JSONRepresentable>(_ json: JSON) throws -> [(T, S)]? { if json.null != nil || !json.exists() { return nil } else { let result: [(T, S)] = try map(json) return result } } internal func map<T, S : JSONRepresentable>(_ json: JSON, transformation: (S) -> T) throws -> T { return try transformation(S(from: json)) } internal func map<T, S : JSONRepresentable>(_ json: JSON, transformation: (S) -> T?) throws -> T? { if json.null != nil || !json.exists() { return nil } else { let result: T = try map(json, transformation: transformation) return result } } internal func map<T, S : JSONRepresentable>(_ json: JSON, transformation: (S) -> T) throws -> T? { if json.null != nil || !json.exists() { return nil } else { let result: T = try map(json, transformation: transformation) return result } } internal func map<T, S : JSONRepresentable>(_ json: JSON, transformation: (S) -> T?) throws -> T { if let result = try transformation(S(from: json)) { return result } else { throw TimetableError.incorrectJSONFormat(json, description: "Could not apply a transformation") } }
mit
72ea4dbd19224523833b1d77ec6fa4cc
26.606452
103
0.607385
3.907763
false
false
false
false
garygriswold/Bible.js
Plugins/AudioPlayer/src/ios_oldApp/AudioPlayer/AudioTOCTestament.swift
1
3249
// // AudioTOCTestament.swift // AudioPlayer // // Created by Gary Griswold on 8/8/17. // Copyright © 2017 ShortSands. All rights reserved. // //#if USE_FRAMEWORK import Utility //#endif class AudioTOCTestament { let bible: AudioTOCBible let damId: String let dbpLanguageCode: String let dbpVersionCode: String let collectionCode: String let mediaType: String var booksById: Dictionary<String, AudioTOCBook> var booksBySeq: Dictionary<Int, AudioTOCBook> init(bible: AudioTOCBible, database: Sqlite3, dbRow: [String?]) { self.bible = bible self.booksById = Dictionary<String, AudioTOCBook>() self.booksBySeq = Dictionary<Int, AudioTOCBook>() self.damId = dbRow[0]! self.collectionCode = dbRow[1]! self.mediaType = dbRow[2]! self.dbpLanguageCode = dbRow[3]! self.dbpVersionCode = dbRow[4]! let query = "SELECT bookId, bookOrder, numberOfChapters" + " FROM AudioBook" + " WHERE damId = ?" + " ORDER BY bookOrder" do { let resultSet = try database.queryV1(sql: query, values: [self.damId]) for row in resultSet { let book = AudioTOCBook(testament: self, dbRow: row) self.booksById[book.bookId] = book self.booksBySeq[book.sequence] = book } } catch let err { print("ERROR \(Sqlite3.errorDescription(error: err))") } } deinit { print("***** Deinit TOCAudioTOCBible *****") } func nextChapter(reference: AudioReference) -> AudioReference? { let ref = reference let book = ref.tocAudioBook if (ref.chapterNum < book.numberOfChapters) { let next = ref.chapterNum + 1 return AudioReference(book: ref.tocAudioBook, chapterNum: next, fileType: ref.fileType) } else { if let nextBook = self.booksBySeq[reference.sequenceNum + 1] { return AudioReference(book: nextBook, chapter: "001", fileType: ref.fileType) } } return nil } func priorChapter(reference: AudioReference) -> AudioReference? { let ref = reference let prior = ref.chapterNum - 1 if (prior > 0) { return AudioReference(book: ref.tocAudioBook, chapterNum: prior, fileType: ref.fileType) } else { if let priorBook = self.booksBySeq[reference.sequenceNum - 1] { return AudioReference(book: priorBook, chapterNum: priorBook.numberOfChapters, fileType: ref.fileType) } } return nil } func getBookList() -> String { var array = [String]() for (_, book) in self.booksBySeq { array.append(book.bookId) } return array.joined(separator: ",") } func toString() -> String { let str = "damId=" + self.damId + "\n languageCode=" + self.dbpLanguageCode + "\n versionCode=" + self.dbpVersionCode + "\n mediaType=" + self.mediaType + "\n collectionCode=" + self.collectionCode return str } }
mit
14488759b8113f4b22fd79e9f95c9fae
32.484536
100
0.576047
4.148148
false
false
false
false
appsquickly/TyphoonRestClient-Demos
TyphoonRestClientDemoSwift/TyphoonRestClientDemoSwift/ValueTransformers/TRCValueTransformerDateISO8601.swift
1
1954
//////////////////////////////////////////////////////////////////////////////// // // APPS QUICKLY // Copyright 2015 Apps Quickly Pty Ltd // All Rights Reserved. // // NOTICE: Prepared by AppsQuick.ly on behalf of Apps Quickly. This software // is proprietary information. Unauthorized use is prohibited. // //////////////////////////////////////////////////////////////////////////////// import Foundation class TRCValueTransformerDateISO8601: NSObject, TRCValueTransformer { static let sharedFormatter = NSDateFormatter() override class func initialize() { sharedFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" sharedFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") } func objectFromResponseValue(responseValue: AnyObject!, error: NSErrorPointer) -> AnyObject! { let date = TRCValueTransformerDateISO8601.sharedFormatter.dateFromString(responseValue as! String) if date == nil && error != nil { error.memory = NSError(domain: "", code: 0, userInfo: [ NSLocalizedDescriptionKey: "Can't create NSDate from string \(responseValue)"]) } return date } func requestValueFromObject(object: AnyObject!, error: NSErrorPointer) -> AnyObject! { if object.isKindOfClass(NSDate.classForCoder()) == false { if error != nil { error.memory = NSError(domain: "", code: 0, userInfo: [ NSLocalizedDescriptionKey: "input object is not NSDate"]) } return nil; } let string = TRCValueTransformerDateISO8601.sharedFormatter.stringFromDate(object as! NSDate) if !string.isEmpty && error != nil { error.memory = NSError(domain: "", code: 0, userInfo: [ NSLocalizedDescriptionKey: "Can't convert NSDate into NSString"]) } return string } }
apache-2.0
1101c9d53a98de124db1f205d1cda0ce
33.298246
147
0.575742
5.39779
false
false
false
false
Incipia/Conduction
Conduction/Classes/Conductor.swift
1
8774
// // Conductor.swift // GigSalad // // Created by Gregory Klein on 2/13/17. // Copyright © 2017 Incipia. All rights reserved. // import UIKit /* Conductor: A class that owns one or more view controllers, acts as their delegate if applicable, and encompasses the logic that's used for navigating the user through a specific 'flow' */ open class Conductor: NSObject, ConductionRouting { public weak var context: UINavigationController? public weak var alertContext: UIViewController? weak var topBeforeShowing: UIViewController? weak var previousContextDelegate: UINavigationControllerDelegate? public var willShowBlock: (() -> Void) = {} public var showBlock: (() -> Void) = {} public var willDismissBlock: (() -> Void) = {} public var dismissBlock: (() -> Void) = {} fileprivate var _isShowing: Bool = false fileprivate var _resetCompletion: (() -> Void)? fileprivate var _dismissCompletion: (() -> Void)? // Meant to be overridden open var rootViewController: UIViewController? { fatalError("\(#function) needs to be overridden") } open func conductorWillShow(in context: UINavigationController) { } open func conductorDidShow(in context: UINavigationController) { } open func conductorWillDismiss(from context: UINavigationController) { } open func conductorDidDismiss(from context: UINavigationController) { } public func show(conductor: Conductor?, animated: Bool = true) { guard let context = self.context else { return } conductor?.show(with: context, animated: animated) } public func show(with context: UINavigationController, animated: Bool = false) { guard self.context == nil else { fatalError("Conductor (\(self)) already has a context: \(String(describing: self.context))") } guard let rootViewController = rootViewController else { fatalError("Conductor (\(self)) has no root view controller") } self.context = context self.topBeforeShowing = context.topViewController previousContextDelegate = context.delegate context.delegate = self context.pushViewController(rootViewController, animated: animated) } @objc public func dismiss() { if let routeParent = routeParent { routeParent.routeChildRemoved(animated: topBeforeShowing != nil) } guard let topBeforeShowing = topBeforeShowing else { _dismissCompletion?() _dismissCompletion = nil return } _ = context?.popToViewController(topBeforeShowing, animated: true) } public func dismissWithCompletion(_ completion: @escaping (() -> Void)) { _dismissCompletion = completion dismiss() } @discardableResult @objc public func reset() -> Bool { guard let rootViewController = rootViewController else { _resetCompletion?() _resetCompletion = nil return false } _ = context?.popToViewController(rootViewController, animated: true) return true } @discardableResult @objc public func resetWithCompletion(_ completion: @escaping (() -> Void)) -> Bool { _resetCompletion = completion return reset() } fileprivate func _dismiss() { guard _isShowing else { fatalError("\(#function) called when \(self) is not showing") } _isShowing = false context?.delegate = previousContextDelegate previousContextDelegate = nil context = nil if let dismissCompletion = _dismissCompletion { dismissCompletion() _dismissCompletion = nil } dismissBlock() } // MARK: - ConductionRouting open var routingName: String { return "" } open var routeParent: ConductionRouting? open var routeChild: ConductionRouting? open var navigationContext: UINavigationController? { return context } open var modalContext: UIViewController? { return context?.topViewController } open func showInRoute(routeContext: ConductionRouting, animated: Bool) -> Bool { guard let navigationContext = routeContext.navigationContext else { return false } routeParent = routeContext show(with: navigationContext, animated: animated) return true } open func dismissFromRoute(animated: Bool) -> Bool { dismiss() return true } open func update(newRoute: ConductionRoute, completion: ((Bool) -> Void)?) { guard !self.route.forwardRouteUpdate(route: newRoute, completion: completion) else { return } completion?(false) } } open class TabConductor: Conductor { public weak var tabBarController: UITabBarController? public var tabBarContext: UINavigationController? { return tabBarController?.navigationController } public func show(in tabBarController: UITabBarController, with context: UINavigationController, animated: Bool = false) { show(with: context) var vcs: [UIViewController] = tabBarController.viewControllers ?? [] vcs.append(context) tabBarController.viewControllers = vcs self.tabBarController = tabBarController } public func show() { guard let context = context, let index = tabBarController?.viewControllers?.index(of: context) else { return } tabBarController?.selectedIndex = index } override public func dismiss() { guard let context = context, var viewControllers = tabBarController?.viewControllers else { return } guard let index = viewControllers.index(of: context) else { return } viewControllers.remove(at: index) tabBarController?.setViewControllers(viewControllers, animated: false) } } extension Conductor: UINavigationControllerDelegate { open func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { // check to see if the navigation controller is popping to it's root view controller guard let rootViewController = rootViewController else { fatalError() } let previousDelegate = previousContextDelegate if _conductorIsBeingPoppedOffContext(byShowing: viewController) { conductorWillDismiss(from: navigationController) willDismissBlock() } if !_isShowing, rootViewController == viewController { conductorWillShow(in: navigationController) willShowBlock() } previousDelegate?.navigationController?(navigationController, willShow: viewController, animated: animated) } open func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { weak var previousDelegate = previousContextDelegate defer { previousDelegate?.navigationController?(navigationController, didShow: viewController, animated: animated) } guard let rootViewController = rootViewController else { return } if !_isShowing, rootViewController == viewController { conductorDidShow(in: navigationController) _isShowing = true showBlock() } if _isShowing, rootViewController == viewController, let resetCompletion = _resetCompletion { resetCompletion() _resetCompletion = nil } if _conductorIsBeingPoppedOffContext(byShowing: viewController) { _dismiss() conductorDidDismiss(from: navigationController) } } open func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return previousContextDelegate?.navigationController?(navigationController, interactionControllerFor: animationController) } open func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return previousContextDelegate?.navigationController?(navigationController, animationControllerFor: operation, from: fromVC, to: toVC) } private func _conductorIsBeingPoppedOffContext(byShowing viewController: UIViewController) -> Bool { guard _isShowing else { return false } guard let rootViewController = rootViewController else { fatalError() } guard let rootViewControllerIndex = context?.viewControllers.index(of: rootViewController) else { return true } guard let showingViewControllerIndex = context?.viewControllers.index(of: viewController) else { return false } return showingViewControllerIndex < rootViewControllerIndex } }
mit
2b336ac685d1a5dad821f0bfac862883
38.518018
250
0.710133
5.616517
false
false
false
false
evgenyneu/Auk
Auk/AukPage.swift
1
3688
import UIKit /// The view for an individual page of the scroll view containing an image. final class AukPage: UIView { // Image view for showing a placeholder image while remote image is being downloaded. // The view is only created when a placeholder image is specified in settings. weak var placeholderImageView: UIImageView? // Image view for showing local and remote images weak var imageView: UIImageView? // Contains a URL for the remote image, if any. var remoteImage: AukRemoteImage? /** Shows an image. - parameter image: The image to be shown - parameter settings: Auk settings. */ func show(image: UIImage, settings: AukSettings) { imageView = createAndLayoutImageView(settings) imageView?.image = image } /** Shows a remote image. The image download stars if/when the page becomes visible to the user. - parameter url: The URL to the image to be displayed. - parameter settings: Auk settings. */ func show(url: String, settings: AukSettings) { if settings.placeholderImage != nil { placeholderImageView = createAndLayoutImageView(settings) } imageView = createAndLayoutImageView(settings) if let imageView = imageView { remoteImage = AukRemoteImage() remoteImage?.setup(url, imageView: imageView, placeholderImageView: placeholderImageView, settings: settings) } } /** Called when the page is currently visible to user which triggers the image download. The function is called frequently each time scroll view's content offset is changed. */ func visibleNow(_ settings: AukSettings) { remoteImage?.downloadImage(settings) } /** Called when the page is currently not visible to user which cancels the image download. The method called frequently each time scroll view's content offset is changed and the page is out of sight. */ func outOfSightNow() { remoteImage?.cancelDownload() } /// Removes image views. func removeImageViews() { placeholderImageView?.removeFromSuperview() placeholderImageView = nil imageView?.removeFromSuperview() imageView = nil } /** Prepares the page view for reuse. Clears current content from the page and stops download. */ func prepareForReuse() { removeImageViews() remoteImage?.cancelDownload() remoteImage = nil } /** Create and layout the remote image view. - parameter settings: Auk settings. */ func createAndLayoutImageView(_ settings: AukSettings) -> UIImageView { let newImageView = AukPage.createImageView(settings) addSubview(newImageView) AukPage.layoutImageView(newImageView, superview: self) return newImageView } private static func createImageView(_ settings: AukSettings) -> UIImageView { let newImageView = UIImageView() newImageView.contentMode = settings.contentMode return newImageView } /** Creates Auto Layout constrains for the image view. - parameter imageView: Image view that is used to create Auto Layout constraints. */ private static func layoutImageView(_ imageView: UIImageView, superview: UIView) { imageView.translatesAutoresizingMaskIntoConstraints = false iiAutolayoutConstraints.fillParent(imageView, parentView: superview, margin: 0, vertically: false) iiAutolayoutConstraints.fillParent(imageView, parentView: superview, margin: 0, vertically: true) } func makeAccessible(_ accessibilityLabel: String?) { isAccessibilityElement = true accessibilityTraits = UIAccessibilityTraits.image self.accessibilityLabel = accessibilityLabel } }
mit
eb8ef2ed9c08d59578e8380d7e974ab3
27.8125
198
0.716377
5.052055
false
false
false
false
jondwillis/ReactiveReSwift-Router
ReactiveReSwiftRouter/NavigationState.swift
1
1179
// // NavigationState.swift // Meet // // Created by Benjamin Encz on 11/11/15. // Copyright © 2015 DigiTales. All rights reserved. // import ReactiveReSwift public typealias RouteElementIdentifier = String public typealias Route = [RouteElementIdentifier] /// A `Hashable` and `Equatable` presentation of a route. /// Can be used to check two routes for equality. public struct RouteHash: Hashable { let routeHash: String public init(route: Route) { self.routeHash = route.joined(separator: "/") } public var hashValue: Int { return self.routeHash.hashValue } } public func == (lhs: RouteHash, rhs: RouteHash) -> Bool { return lhs.routeHash == rhs.routeHash } public struct NavigationState { public init() {} public var route: Route = [] public var routeSpecificState: [RouteHash: Any] = [:] var changeRouteAnimated: Bool = true } extension NavigationState { public func getRouteSpecificState<T>(_ route: Route) -> T? { let hash = RouteHash(route: route) return self.routeSpecificState[hash] as? T } } public protocol HasNavigationState { var navigationState: NavigationState { get set } }
mit
500acfbee7df8c2504591b2a5c31e639
23.541667
65
0.692699
4.020478
false
false
false
false
dvor/Antidote
Antidote/FriendSelectController.swift
1
6261
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit protocol FriendSelectControllerDelegate: class { func friendSelectController(_ controller: FriendSelectController, didSelectFriend friend: OCTFriend) func friendSelectControllerCancel(_ controller: FriendSelectController) } class FriendSelectController: UIViewController { weak var delegate: FriendSelectControllerDelegate? var userInfo: AnyObject? fileprivate let theme: Theme fileprivate let dataSource: FriendListDataSource fileprivate var placeholderView: UITextView! fileprivate var tableView: UITableView! init(theme: Theme, submanagerObjects: OCTSubmanagerObjects, userInfo: AnyObject? = nil) { self.theme = theme self.userInfo = userInfo let friends = submanagerObjects.friends() self.dataSource = FriendListDataSource(theme: theme, friends: friends) super.init(nibName: nil, bundle: nil) dataSource.delegate = self addNavigationButtons() edgesForExtendedLayout = UIRectEdge() } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { loadViewWithBackgroundColor(theme.colorForType(.NormalBackground)) createTableView() createPlaceholderView() installConstraints() updateViewsVisibility() } } extension FriendSelectController { func cancelButtonPressed() { delegate?.friendSelectControllerCancel(self) } } extension FriendSelectController: FriendListDataSourceDelegate { func friendListDataSourceBeginUpdates() { tableView.beginUpdates() } func friendListDataSourceEndUpdates() { self.tableView.endUpdates() updateViewsVisibility() } func friendListDataSourceInsertRowsAtIndexPaths(_ indexPaths: [IndexPath]) { tableView.insertRows(at: indexPaths, with: .automatic) } func friendListDataSourceDeleteRowsAtIndexPaths(_ indexPaths: [IndexPath]) { tableView.deleteRows(at: indexPaths, with: .automatic) } func friendListDataSourceReloadRowsAtIndexPaths(_ indexPaths: [IndexPath]) { tableView.reloadRows(at: indexPaths, with: .automatic) } func friendListDataSourceInsertSections(_ sections: IndexSet) { tableView.insertSections(sections, with: .automatic) } func friendListDataSourceDeleteSections(_ sections: IndexSet) { tableView.deleteSections(sections, with: .automatic) } func friendListDataSourceReloadSections(_ sections: IndexSet) { tableView.reloadSections(sections, with: .automatic) } func friendListDataSourceReloadTable() { tableView.reloadData() } } extension FriendSelectController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: FriendListCell.staticReuseIdentifier) as! FriendListCell let model = dataSource.modelAtIndexPath(indexPath) cell.setupWithTheme(theme, model: model) return cell } func numberOfSections(in tableView: UITableView) -> Int { return dataSource.numberOfSections() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.numberOfRowsInSection(section) } func sectionIndexTitles(for tableView: UITableView) -> [String]? { return dataSource.sectionIndexTitles() } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return dataSource.titleForHeaderInSection(section) } } extension FriendSelectController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch dataSource.objectAtIndexPath(indexPath) { case .request: // nop break case .friend(let friend): delegate?.friendSelectController(self, didSelectFriend: friend) } } } private extension FriendSelectController { func addNavigationButtons() { navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .cancel, target: self, action: #selector(FriendSelectController.cancelButtonPressed)) } func updateViewsVisibility() { var isEmpty = true for section in 0..<dataSource.numberOfSections() { if dataSource.numberOfRowsInSection(section) > 0 { isEmpty = false break } } placeholderView.isHidden = !isEmpty } func createTableView() { tableView = UITableView() tableView.estimatedRowHeight = 44.0 tableView.dataSource = self tableView.delegate = self tableView.backgroundColor = theme.colorForType(.NormalBackground) tableView.sectionIndexColor = theme.colorForType(.LinkText) // removing separators on empty lines tableView.tableFooterView = UIView() view.addSubview(tableView) tableView.register(FriendListCell.self, forCellReuseIdentifier: FriendListCell.staticReuseIdentifier) } func createPlaceholderView() { placeholderView = UITextView() placeholderView.text = String(localized: "contact_no_contacts") placeholderView.isEditable = false placeholderView.isScrollEnabled = false placeholderView.textAlignment = .center view.addSubview(placeholderView) } func installConstraints() { tableView.snp.makeConstraints { $0.edges.equalTo(view) } placeholderView.snp.makeConstraints { $0.center.equalTo(view) $0.size.equalTo(placeholderView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))) } } }
mit
40e56114bf3069db03fa7dacd0b07e22
30.781726
146
0.692381
5.47769
false
false
false
false
zzeleznick/piazza-clone
Pizzazz/Pizzazz/BoardViewController.swift
1
4078
// // BoardViewController.swift // Pizzazz // // Created by Zach Zeleznick on 5/5/16. // Copyright © 2016 zzeleznick. All rights reserved. // import UIKit class BoardViewController: ViewController { var tableView: UITableView! let cellWrapper = CellWrapper(cell: PostViewCell.self) typealias cellType = PostViewCell let sections = ["Pinned", "Favorites", "Today", "Yesterday", "This Week", "Older"] let sectionRowCount = 3 let dummyText = "I'm a post" let dummyStub = "Donald Drumf, 05/05/2016" override func addToolbar() { let toolbar = UIToolbar() toolbar.barTintColor = UIColor(white: 0.95, alpha: 1.0) let moreButton = UIButton() moreButton.setBackgroundImage(UIImage(named: "MoreIcon"), for: UIControlState()) moreButton.frame = CGRect(x: 0, y: 0, width: 30, height: 10) let composeButton = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(composeButtonPressed)) composeButton.width = 40 let item1 = UIBarButtonItem(customView: moreButton) let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) toolbar.setItems([item1, spacer, composeButton], animated: true) view.addUIElement(toolbar, frame: CGRect(x: 0, y: h-40, width: w, height: 40)) } func composeButtonPressed() { let dest = NewQuestionViewController() navigationController?.pushViewController(dest, animated: true) } func rightButtonPressed() { let dest = CourseInfoViewController() let title = navigationItem.title! let newTitle = "\(title) Course Information" dest.navigationItem.title = newTitle dest.dummyTitle = "\(title)" dest.dummySubtitle = "Description \(title)" navigationController?.pushViewController(dest, animated: true) } override func viewDidLoad() { super.viewDidLoad() let infoButton = UIButton() infoButton.setBackgroundImage(UIImage(named: "PaperIcon"), for: UIControlState()) infoButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40) infoButton.addTarget(self, action: #selector(BoardViewController.rightButtonPressed), for: .touchUpInside) let infoBar = UIBarButtonItem(customView: infoButton) navigationItem.setRightBarButton(infoBar, animated: true) tableView = UITableView(frame: CGRect(x: 0, y: 0, width: w, height: h-50), controller: self, cellWrapper: cellWrapper) view.addSubview(tableView) addToolbar() } } extension BoardViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sectionRowCount } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 32 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = HeaderViewCell() let text = sections[section] headerView.titleLabel.text = text return headerView } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellWrapper.identifier, for: indexPath) as! cellType let section = (indexPath as NSIndexPath).section let idx = sectionRowCount*section + (indexPath as NSIndexPath).item cell.titleLabel.text = "Question \(idx)" cell.bodyLabel.text = dummyText cell.detailLabel.text = dummyStub return cell } }
mit
314891e72591cdad457547622f8f7ec8
36.063636
129
0.653422
4.912048
false
false
false
false
git-hushuai/MOMO
MMHSMeterialProject/LibaryFile/SQLiteDB/SQLTable.swift
1
3854
// // SQLTable.swift // SQLiteDB-iOS // // Created by Fahim Farook on 6/11/15. // Copyright © 2015 RookSoft Pte. Ltd. All rights reserved. // import UIKit class SQLTable:NSObject { var table = "" private var data:[String:AnyObject]! required init(tableName:String) { super.init() table = tableName } func primaryKey() -> String { return "id" } func allRows<T:SQLTable>(order:String="") -> [T] { var res = [T]() self.data = values() let db = SQLiteDB.sharedInstance() var sql = "SELECT * FROM \(table)" if !order.isEmpty { sql += " ORDER BY \(order)" } let arr = db.query(sql) for row in arr { let t = T(tableName:table) for (key, _) in data { let val = row[key] t.setValue(val, forKey:key) } res.append(t) } return res } func save() -> (success:Bool, id:Int) { assert(!table.isEmpty, "You should define the table name in the sub-class") let db = SQLiteDB.sharedInstance() let key = primaryKey() self.data = values() var insert = true if let rid = data[key] { let sql = "SELECT COUNT(*) AS count FROM \(table) WHERE \(primaryKey())=\(rid)" let arr = db.query(sql) if arr.count == 1 { if let cnt = arr[0]["count"] as? Int { insert = (cnt == 0) } } } // Insert or update let (sql, params) = getSQL(insert) let rc = db.execute(sql, parameters:params) let res = (rc != 0) if !res { NSLog("Error saving record!") } return (res, Int(rc)) } // private func properties() -> [String] { // var res = [String]() // for c in Mirror(reflecting:self).children { // if let name = c.label{ // res.append(name) // } // } // return res // } private func values() -> [String:AnyObject] { var res = [String:AnyObject]() let obj = Mirror(reflecting:self) print("sqlTable info :\(obj.children.enumerate())"); for (_, attr) in obj.children.enumerate() { print("attr info :\(attr.label)"); if let name = attr.label { res[name] = getValue(attr.value as! AnyObject) } } return res } private func getValue(val:AnyObject) -> AnyObject { if val is String { return val as! String } else if val is Int { return val as! Int } else if val is Float { return val as! Float } else if val is Double { return val as! Double } else if val is Bool { return val as! Bool } else if val is NSDate { return val as! NSDate } return "nAn" } private func getSQL(forInsert:Bool = true) -> (String, [AnyObject]?) { var sql = "" var params:[AnyObject]? = nil if forInsert { // INSERT INTO tasks(task, categoryID) VALUES ('\(txtTask.text)', 1) sql = "INSERT INTO \(table)(" } else { // UPDATE tasks SET task = ? WHERE categoryID = ? sql = "UPDATE \(table) SET " } let pkey = primaryKey() var wsql = "" var rid:AnyObject? var first = true for (key, val) in data { // Primary key handling if pkey == key { if forInsert { if val is Int && (val as! Int) == -1 { // Do not add this since this is (could be?) an auto-increment value continue } } else { // Update - set up WHERE clause wsql += " WHERE " + key + " = ?" rid = val continue } } // Set up parameter array - if we get here, then there are parameters if first && params == nil { params = [AnyObject]() } if forInsert { sql += first ? key : "," + key wsql += first ? " VALUES (?" : ", ?" params!.append(val) } else { sql += first ? key + " = ?" : ", " + key + " = ?" params!.append(val) } first = false } // Finalize SQL if forInsert { sql += ")" + wsql + ")" } else if params != nil && !wsql.isEmpty { sql += wsql params!.append(rid!) } NSLog("Final SQL: \(sql) with parameters: \(params)") return (sql, params) } }
mit
268f0bdae2f39a8ece9f063768de9300
22.210843
82
0.572022
3.036249
false
false
false
false
cotkjaer/Silverback
Silverback/UILabel.swift
1
7694
// // UILabel.swift // Silverback // // Created by Christian Otkjær on 30/10/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import UIKit // MARK: - init extension UILabel { public convenience init(text: String?, color: UIColor?) { self.init(frame: CGRectZero) self.text = text if let c = color { textColor = c } sizeToFit() } } //MARK: - Set Text Animated extension UILabel { /// crossfades the existing text with the `text` parameters in `duration`seconds public func setText(text: String, duration: Double, ifDifferent: Bool = true) { if (ifDifferent && text != self.text) || !ifDifferent { UIView.transitionWithView(self, duration: duration, options: [.TransitionCrossDissolve], animations: { self.text = text }, completion: nil) } } } // MARK: - Fontname extension UILabel { public var fontName : String { get { return font.fontName } set { if fontName != newValue { if let newFont = UIFont(name: newValue, size: font.pointSize) { font = newFont } else { debugPrint("Cannot make font with name \(newValue)") } } } } } extension UILabel { public func sizeFontToFitWidth(width: CGFloat, minSize: CGFloat = 1, maxSize: CGFloat = 512) { let fontSize = font.pointSize guard minSize < maxSize - 1 else { return } if let estimatedWidth = text?.sizeWithFont(font).width { if width > estimatedWidth { if fontSize >= maxSize { font = font.fontWithSize(maxSize) } else { font = font.fontWithSize(ceil((fontSize + maxSize) / 2)) sizeFontToFitWidth(width, minSize: fontSize, maxSize: maxSize) } } else if width < estimatedWidth { if fontSize <= minSize { font = font.fontWithSize(minSize) } else { font = font.fontWithSize(floor((fontSize + minSize) / 2)) sizeFontToFitWidth(width, minSize: minSize, maxSize: fontSize) } } } } public func sizeFontToFit(sizeToFit: CGSize, minSize: CGFloat = 1, maxSize: CGFloat = 512) { let fontSize = font.pointSize guard minSize < maxSize - 1 else { return font = font.fontWithSize(minSize) } if let aText = self.attributedText { let estimatedSize = aText.boundingRectWithSize(sizeToFit, options: [ NSStringDrawingOptions.UsesLineFragmentOrigin ], context: nil).size debugPrint("estimatedSize: \(estimatedSize), sizeToFit: \(sizeToFit)") if estimatedSize.width < sizeToFit.width && estimatedSize.height < sizeToFit.height { if fontSize <= minSize { font = font.fontWithSize(minSize) } font = font.fontWithSize(floor((fontSize + maxSize) / 2)) sizeFontToFit(sizeToFit, minSize: fontSize, maxSize: maxSize) } if estimatedSize.width > sizeToFit.width || estimatedSize.height > sizeToFit.height { if fontSize >= maxSize { font = font.fontWithSize(maxSize) } font = font.fontWithSize(floor((fontSize + minSize) / 2)) sizeFontToFit(sizeToFit, minSize: minSize, maxSize: fontSize) } } } public func fontToFitSize(sizeToFit: CGSize, textToMeasure: String? = nil) -> UIFont { return (textToMeasure ?? text ?? "").fontToFitSize( sizeToFit, font: font, lineBreakMode: lineBreakMode, minSize: 4, maxSize: floor(min(sizeToFit.height, sizeToFit.width))) } } public class ClockLabel: UILabel { let timeFormatter = NSDateFormatter(timeStyle: .ShortStyle, dateStyle: .NoStyle) // MARK: - Lifecycle func setup() { scheduleUpdate() } override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } deinit { unscheduleUpdate() } // MARK: - size public override func sizeThatFits(size: CGSize) -> CGSize { return super.sizeThatFits(size) } public override func sizeToFit() { super.sizeToFit() } // MARK: - Update public func update() { foreground { self.text = self.timeFormatter.stringFromDate(NSDate()) } } private(set) var started : Bool = false { didSet { if started { scheduleUpdate() } else { unscheduleUpdate() } } } public func start() { started = true } public func stop() { started = false } // MARK: - Timers var timer: NSTimer? func scheduleUpdate() { unscheduleUpdate() update() let now = NSDate().timeIntervalSinceReferenceDate let timeUntilNextMinuteChange : Double = 60 - (now % 60) let timer = NSTimer(timeInterval: timeUntilNextMinuteChange, target: self, selector: Selector("scheduleUpdate"), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) self.timer = timer } func unscheduleUpdate() { timer?.invalidate() timer = nil } } //MARK: - Size Adjust extension UILabel { public func adjustFontSizeToFitRect(rect : CGRect) { guard text != nil else { return } frame = rect let MaxFontSize: CGFloat = 512 let MinFontSize: CGFloat = 4 var q = Int(MaxFontSize) var p = Int(MinFontSize) let constraintSize = CGSize(width: rect.width, height: CGFloat.max) while(p <= q) { let currentSize = (p + q) / 2 font = UIFont(descriptor: font.fontDescriptor(), size: CGFloat(currentSize)) let text = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:font]) let textRect = text.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, context: nil) let labelSize = textRect.size if labelSize.height < frame.height && labelSize.height >= frame.height - 10 && labelSize.width < frame.width && labelSize.width >= frame.width - 10 { break } else if labelSize.height > frame.height || labelSize.width > frame.width { q = currentSize - 1 } else { p = currentSize + 1 } } } }
mit
7527609377c13314ffae7403cef12c91
24.382838
184
0.506176
5.203654
false
false
false
false
eBardX/XestiMonitors
Sources/Core/UIKit/Accessibility/AccessibilityAnnouncementMonitor.swift
1
2561
// // AccessibilityAnnouncementMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2017-01-16. // // © 2017 J. G. Pusey (see LICENSE.md) // #if os(iOS) || os(tvOS) import Foundation import UIKit /// /// An `AccessibilityAnnouncementMonitor` instance monitors the system for /// accessibility announcements that VoiceOver has finished outputting. /// public class AccessibilityAnnouncementMonitor: BaseNotificationMonitor { /// /// Encapsulates accessibility announcements that VoiceOver has /// finished outputting. /// public enum Event { /// /// VoiceOver has finished outputting an accessibility /// announcement. /// case didFinish(Info) } /// /// Encapsulates information associated with an accessibility /// announcement that VoiceOver has finished outputting. /// public struct Info { /// /// The text used for the announcement. /// public let stringValue: String /// /// Indicates whether VoiceOver successfully outputted the /// announcement. /// public let wasSuccessful: Bool fileprivate init(_ notification: Notification) { let userInfo = notification.userInfo if let value = userInfo?[UIAccessibilityAnnouncementKeyStringValue] as? String { self.stringValue = value } else { self.stringValue = " " } if let value = (userInfo?[UIAccessibilityAnnouncementKeyWasSuccessful] as? NSNumber)?.boolValue { self.wasSuccessful = value } else { self.wasSuccessful = false } } } /// /// Initializes a new `AccessibilityAnnouncementMonitor`. /// /// - Parameters: /// - queue: The operation queue on which the handler executes. /// By default, the main operation queue is used. /// - handler: The handler to call when VoiceOver finishes /// outputting an announcement. /// public init(queue: OperationQueue = .main, handler: @escaping (Event) -> Void) { self.handler = handler super.init(queue: queue) } private let handler: (Event) -> Void override public func addNotificationObservers() { super.addNotificationObservers() observe(.UIAccessibilityAnnouncementDidFinish) { [unowned self] in self.handler(.didFinish(Info($0))) } } } #endif
mit
80b4cfd3424d97c31fc6f87913f91858
26.826087
109
0.598828
5.171717
false
false
false
false
Jigsaw-Code/outline-client
src/cordova/plugin/apple/vpn/OutlineTunnelStore.swift
1
2385
// Copyright 2018 The Outline Authors // // 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 CocoaLumberjack import CocoaLumberjackSwift // Persistence layer for a single |OutlineTunnel| object. @objcMembers class OutlineTunnelStore: NSObject { // TODO(alalama): s/connection/tunnel when we update the schema. private static let kTunnelStoreKey = "connectionStore" private static let kTunnelStatusKey = "connectionStatus" private static let kUdpSupportKey = "udpSupport" private let defaults: UserDefaults? // Constructs the store with UserDefaults as the storage. required init(appGroup: String) { defaults = UserDefaults(suiteName: appGroup) super.init() } // Loads a previously saved tunnel from the store. func load() -> OutlineTunnel? { if let encodedTunnel = defaults?.data(forKey: OutlineTunnelStore.kTunnelStoreKey) { return OutlineTunnel.decode(encodedTunnel) } return nil } // Writes |tunnel| to the store. @discardableResult func save(_ tunnel: OutlineTunnel) -> Bool { if let encodedTunnel = tunnel.encode() { defaults?.set(encodedTunnel, forKey: OutlineTunnelStore.kTunnelStoreKey) } return true } var status: OutlineTunnel.TunnelStatus { get { let status = defaults?.integer(forKey: OutlineTunnelStore.kTunnelStatusKey) ?? OutlineTunnel.TunnelStatus.disconnected.rawValue return OutlineTunnel.TunnelStatus(rawValue:status) ?? OutlineTunnel.TunnelStatus.disconnected } set(newStatus) { defaults?.set(newStatus.rawValue, forKey: OutlineTunnelStore.kTunnelStatusKey) } } var isUdpSupported: Bool { get { return defaults?.bool(forKey: OutlineTunnelStore.kUdpSupportKey) ?? false } set(udpSupport) { defaults?.set(udpSupport, forKey: OutlineTunnelStore.kUdpSupportKey) } } }
apache-2.0
4421f31b4f465b52ab8cb9fe6f3e9e14
32.125
87
0.729979
4.049236
false
false
false
false
jboullianne/EndlessTunes
Pods/SkyFloatingLabelTextField/Sources/SkyFloatingLabelTextField.swift
2
19149
// Copyright 2016-2017 Skyscanner Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License // for the specific language governing permissions and limitations under the License. import UIKit /** A beautiful and flexible textfield implementation with support for title label, error message and placeholder. */ @IBDesignable open class SkyFloatingLabelTextField: UITextField { // swiftlint:disable:this type_body_length /** A Boolean value that determines if the language displayed is LTR. Default value set automatically from the application language settings. */ open var isLTRLanguage = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight { didSet { updateTextAligment() } } fileprivate func updateTextAligment() { if isLTRLanguage { textAlignment = .left titleLabel.textAlignment = .left } else { textAlignment = .right titleLabel.textAlignment = .right } } // MARK: Animation timing /// The value of the title appearing duration dynamic open var titleFadeInDuration: TimeInterval = 0.2 /// The value of the title disappearing duration dynamic open var titleFadeOutDuration: TimeInterval = 0.3 // MARK: Colors fileprivate var cachedTextColor: UIColor? /// A UIColor value that determines the text color of the editable text @IBInspectable override dynamic open var textColor: UIColor? { set { cachedTextColor = newValue updateControl(false) } get { return cachedTextColor } } /// A UIColor value that determines text color of the placeholder label @IBInspectable dynamic open var placeholderColor: UIColor = UIColor.lightGray { didSet { updatePlaceholder() } } /// A UIColor value that determines text color of the placeholder label dynamic open var placeholderFont: UIFont? { didSet { updatePlaceholder() } } fileprivate func updatePlaceholder() { if let placeholder = placeholder, let font = placeholderFont ?? font { attributedPlaceholder = NSAttributedString( string: placeholder, attributes: [NSForegroundColorAttributeName: placeholderColor, NSFontAttributeName: font] ) } } /// A UIColor value that determines the text color of the title label when in the normal state @IBInspectable dynamic open var titleColor: UIColor = .gray { didSet { updateTitleColor() } } /// A UIColor value that determines the color of the bottom line when in the normal state @IBInspectable dynamic open var lineColor: UIColor = .lightGray { didSet { updateLineView() } } /// A UIColor value that determines the color used for the title label and line when the error message is not `nil` @IBInspectable dynamic open var errorColor: UIColor = .red { didSet { updateColors() } } /// A UIColor value that determines the text color of the title label when editing @IBInspectable dynamic open var selectedTitleColor: UIColor = .blue { didSet { updateTitleColor() } } /// A UIColor value that determines the color of the line in a selected state @IBInspectable dynamic open var selectedLineColor: UIColor = .black { didSet { updateLineView() } } // MARK: Line height /// A CGFloat value that determines the height for the bottom line when the control is in the normal state @IBInspectable dynamic open var lineHeight: CGFloat = 0.5 { didSet { updateLineView() setNeedsDisplay() } } /// A CGFloat value that determines the height for the bottom line when the control is in a selected state @IBInspectable dynamic open var selectedLineHeight: CGFloat = 1.0 { didSet { updateLineView() setNeedsDisplay() } } // MARK: View components /// The internal `UIView` to display the line below the text input. open var lineView: UIView! /// The internal `UILabel` that displays the selected, deselected title or error message based on the current state. open var titleLabel: UILabel! // MARK: Properties /** The formatter used before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`. The default implementation converts the text to uppercase. */ open var titleFormatter: ((String) -> String) = { (text: String) -> String in return text.uppercased() } /** Identifies whether the text object should hide the text being entered. */ override open var isSecureTextEntry: Bool { set { super.isSecureTextEntry = newValue fixCaretPosition() } get { return super.isSecureTextEntry } } /// A String value for the error message to display. open var errorMessage: String? { didSet { updateControl(true) } } /// The backing property for the highlighted property fileprivate var _highlighted = false /** A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation */ override open var isHighlighted: Bool { get { return _highlighted } set { _highlighted = newValue updateTitleColor() updateLineView() } } /// A Boolean value that determines whether the textfield is being edited or is selected. open var editingOrSelected: Bool { return super.isEditing || isSelected } /// A Boolean value that determines whether the receiver has an error message. open var hasErrorMessage: Bool { return errorMessage != nil && errorMessage != "" } fileprivate var _renderingInInterfaceBuilder: Bool = false /// The text content of the textfield @IBInspectable override open var text: String? { didSet { updateControl(false) } } /** The String to display when the input field is empty. The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`. */ @IBInspectable override open var placeholder: String? { didSet { setNeedsDisplay() updatePlaceholder() updateTitleLabel() } } /// The String to display when the textfield is editing and the input is not empty. @IBInspectable open var selectedTitle: String? { didSet { updateControl() } } /// The String to display when the textfield is not editing and the input is not empty. @IBInspectable open var title: String? { didSet { updateControl() } } // Determines whether the field is selected. When selected, the title floats above the textbox. open override var isSelected: Bool { didSet { updateControl(true) } } // MARK: - Initializers /** Initializes the control - parameter frame the frame of the control */ override public init(frame: CGRect) { super.init(frame: frame) init_SkyFloatingLabelTextField() } /** Intialzies the control by deserializing it - parameter coder the object to deserialize the control from */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) init_SkyFloatingLabelTextField() } fileprivate final func init_SkyFloatingLabelTextField() { borderStyle = .none createTitleLabel() createLineView() updateColors() addEditingChangedObserver() updateTextAligment() } fileprivate func addEditingChangedObserver() { self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), for: .editingChanged) } /** Invoked when the editing state of the textfield changes. Override to respond to this change. */ open func editingChanged() { updateControl(true) updateTitleLabel(true) } // MARK: create components fileprivate func createTitleLabel() { let titleLabel = UILabel() titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleLabel.font = .systemFont(ofSize: 13) titleLabel.alpha = 0.0 titleLabel.textColor = titleColor addSubview(titleLabel) self.titleLabel = titleLabel } fileprivate func createLineView() { if lineView == nil { let lineView = UIView() lineView.isUserInteractionEnabled = false self.lineView = lineView configureDefaultLineHeight() } lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] addSubview(lineView) } fileprivate func configureDefaultLineHeight() { let onePixel: CGFloat = 1.0 / UIScreen.main.scale lineHeight = 2.0 * onePixel selectedLineHeight = 2.0 * self.lineHeight } // MARK: Responder handling /** Attempt the control to become the first responder - returns: True when successfull becoming the first responder */ @discardableResult override open func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() updateControl(true) return result } /** Attempt the control to resign being the first responder - returns: True when successfull resigning being the first responder */ @discardableResult override open func resignFirstResponder() -> Bool { let result = super.resignFirstResponder() updateControl(true) return result } // MARK: - View updates fileprivate func updateControl(_ animated: Bool = false) { updateColors() updateLineView() updateTitleLabel(animated) } fileprivate func updateLineView() { if let lineView = lineView { lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected) } updateLineColor() } // MARK: - Color updates /// Update the colors for the control. Override to customize colors. open func updateColors() { updateLineColor() updateTitleColor() updateTextColor() } fileprivate func updateLineColor() { if hasErrorMessage { lineView.backgroundColor = errorColor } else { lineView.backgroundColor = editingOrSelected ? selectedLineColor : lineColor } } fileprivate func updateTitleColor() { if hasErrorMessage { titleLabel.textColor = errorColor } else { if editingOrSelected || isHighlighted { titleLabel.textColor = selectedTitleColor } else { titleLabel.textColor = titleColor } } } fileprivate func updateTextColor() { if hasErrorMessage { super.textColor = errorColor } else { super.textColor = cachedTextColor } } // MARK: - Title handling fileprivate func updateTitleLabel(_ animated: Bool = false) { var titleText: String? = nil if hasErrorMessage { titleText = titleFormatter(errorMessage!) } else { if editingOrSelected { titleText = selectedTitleOrTitlePlaceholder() if titleText == nil { titleText = titleOrPlaceholder() } } else { titleText = titleOrPlaceholder() } } titleLabel.text = titleText updateTitleVisibility(animated) } fileprivate var _titleVisible = false /* * Set this value to make the title visible */ open func setTitleVisible( _ titleVisible: Bool, animated: Bool = false, animationCompletion: ((_ completed: Bool) -> Void)? = nil ) { if _titleVisible == titleVisible { return } _titleVisible = titleVisible updateTitleColor() updateTitleVisibility(animated, completion: animationCompletion) } /** Returns whether the title is being displayed on the control. - returns: True if the title is displayed on the control, false otherwise. */ open func isTitleVisible() -> Bool { return hasText || hasErrorMessage || _titleVisible } fileprivate func updateTitleVisibility(_ animated: Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) { let alpha: CGFloat = isTitleVisible() ? 1.0 : 0.0 let frame: CGRect = titleLabelRectForBounds(bounds, editing: isTitleVisible()) let updateBlock = { () -> Void in self.titleLabel.alpha = alpha self.titleLabel.frame = frame } if animated { let animationOptions: UIViewAnimationOptions = .curveEaseOut let duration = isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in updateBlock() }, completion: completion) } else { updateBlock() completion?(true) } } // MARK: - UITextField text/placeholder positioning overrides /** Calculate the rectangle for the textfield when it is not being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func textRect(forBounds bounds: CGRect) -> CGRect { super.textRect(forBounds: bounds) let rect = CGRect( x: 0, y: titleHeight(), width: bounds.size.width, height: bounds.size.height - titleHeight() - selectedLineHeight ) return rect } /** Calculate the rectangle for the textfield when it is being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func editingRect(forBounds bounds: CGRect) -> CGRect { let rect = CGRect( x: 0, y: titleHeight(), width: bounds.size.width, height: bounds.size.height - titleHeight() - selectedLineHeight ) return rect } /** Calculate the rectangle for the placeholder - parameter bounds: The current bounds of the placeholder - returns: The rectangle that the placeholder should render in */ override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { let rect = CGRect( x: 0, y: titleHeight(), width: bounds.size.width, height: bounds.size.height - titleHeight() - selectedLineHeight ) return rect } // MARK: - Positioning Overrides /** Calculate the bounds for the title label. Override to create a custom size title field. - parameter bounds: The current bounds of the title - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the title label should render in */ open func titleLabelRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect { if editing { return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight()) } return CGRect(x: 0, y: titleHeight(), width: bounds.size.width, height: titleHeight()) } /** Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox. - parameter bounds: The current bounds of the line - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the line bar should render in */ open func lineViewRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect { let height = editing ? selectedLineHeight : lineHeight return CGRect(x: 0, y: bounds.size.height - height, width: bounds.size.width, height: height) } /** Calculate the height of the title label. -returns: the calculated height of the title label. Override to size the title with a different height */ open func titleHeight() -> CGFloat { if let titleLabel = titleLabel, let font = titleLabel.font { return font.lineHeight } return 15.0 } /** Calcualte the height of the textfield. -returns: the calculated height of the textfield. Override to size the textfield with a different height */ open func textHeight() -> CGFloat { return self.font!.lineHeight + 7.0 } // MARK: - Layout /// Invoked when the interface builder renders the control override open func prepareForInterfaceBuilder() { if #available(iOS 8.0, *) { super.prepareForInterfaceBuilder() } borderStyle = .none isSelected = true _renderingInInterfaceBuilder = true updateControl(false) invalidateIntrinsicContentSize() } /// Invoked by layoutIfNeeded automatically override open func layoutSubviews() { super.layoutSubviews() titleLabel.frame = titleLabelRectForBounds(bounds, editing: isTitleVisible() || _renderingInInterfaceBuilder) lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected || _renderingInInterfaceBuilder) } /** Calculate the content size for auto layout - returns: the content size to be used for auto layout */ override open var intrinsicContentSize: CGSize { return CGSize(width: bounds.size.width, height: titleHeight() + textHeight()) } // MARK: - Helpers fileprivate func titleOrPlaceholder() -> String? { guard let title = title ?? placeholder else { return nil } return titleFormatter(title) } fileprivate func selectedTitleOrTitlePlaceholder() -> String? { guard let title = selectedTitle ?? title ?? placeholder else { return nil } return titleFormatter(title) } } // swiftlint:disable:this file_length
gpl-3.0
012ff769f222bdc22416cdc03d1d86c7
30.495066
120
0.627761
5.421574
false
false
false
false
minikin/Algorithmics
Pods/Charts/Charts/Classes/Renderers/RadarChartRenderer.swift
5
11339
// // RadarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class RadarChartRenderer: LineRadarChartRenderer { public weak var chart: RadarChartView? public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } public override func drawData(context context: CGContext) { guard let chart = chart else { return } let radarData = chart.data if (radarData != nil) { var mostEntries = 0 for set in radarData!.dataSets { if set.entryCount > mostEntries { mostEntries = set.entryCount } } for set in radarData!.dataSets as! [IRadarChartDataSet] { if set.isVisible && set.entryCount > 0 { drawDataSet(context: context, dataSet: set, mostEntries: mostEntries) } } } } /// Draws the RadarDataSet /// /// - parameter context: /// - parameter dataSet: /// - parameter mostEntries: the entry count of the dataset with the most entries internal func drawDataSet(context context: CGContext, dataSet: IRadarChartDataSet, mostEntries: Int) { guard let chart = chart, animator = animator else { return } CGContextSaveGState(context) let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let entryCount = dataSet.entryCount let path = CGPathCreateMutable() var hasMovedToPoint = false for (var j = 0; j < entryCount; j++) { guard let e = dataSet.entryForIndex(j) else { continue } let p = ChartUtils.getPosition( center: center, dist: CGFloat(e.value - chart.chartYMin) * factor * phaseY, angle: sliceangle * CGFloat(j) * phaseX + chart.rotationAngle) if p.x.isNaN { continue } if !hasMovedToPoint { CGPathMoveToPoint(path, nil, p.x, p.y) hasMovedToPoint = true } else { CGPathAddLineToPoint(path, nil, p.x, p.y) } } // if this is the largest set, close it if dataSet.entryCount < mostEntries { // if this is not the largest set, draw a line to the center before closing CGPathAddLineToPoint(path, nil, center.x, center.y) } CGPathCloseSubpath(path) // draw filled if dataSet.isDrawFilledEnabled { if dataSet.fill != nil { drawFilledPath(context: context, path: path, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } // draw the line (only if filled is disabled or alpha is below 255) if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0 { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextSetLineWidth(context, dataSet.lineWidth) CGContextSetAlpha(context, 1.0) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextStrokePath(context) } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let chart = chart, data = chart.data, animator = animator else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let yoffset = CGFloat(5.0) for (var i = 0, count = data.dataSetCount; i < count; i++) { let dataSet = data.getDataSetByIndex(i) as! IRadarChartDataSet if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let entryCount = dataSet.entryCount for (var j = 0; j < entryCount; j++) { guard let e = dataSet.entryForIndex(j) else { continue } let p = ChartUtils.getPosition( center: center, dist: CGFloat(e.value) * factor * phaseY, angle: sliceangle * CGFloat(j) * phaseX + chart.rotationAngle) let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } ChartUtils.drawText( context: context, text: formatter.stringFromNumber(e.value)!, point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } } public override func drawExtras(context context: CGContext) { drawWeb(context: context) } private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public func drawWeb(context context: CGContext) { guard let chart = chart, data = chart.data else { return } let sliceangle = chart.sliceAngle CGContextSaveGState(context) // calculate the factor that is needed for transforming the value to // pixels let factor = chart.factor let rotationangle = chart.rotationAngle let center = chart.centerOffsets // draw the web lines that come from the center CGContextSetLineWidth(context, chart.webLineWidth) CGContextSetStrokeColorWithColor(context, chart.webColor.CGColor) CGContextSetAlpha(context, chart.webAlpha) let xIncrements = 1 + chart.skipWebLineCount for var i = 0, xValCount = data.xValCount; i < xValCount; i += xIncrements { let p = ChartUtils.getPosition( center: center, dist: CGFloat(chart.yRange) * factor, angle: sliceangle * CGFloat(i) + rotationangle) _webLineSegmentsBuffer[0].x = center.x _webLineSegmentsBuffer[0].y = center.y _webLineSegmentsBuffer[1].x = p.x _webLineSegmentsBuffer[1].y = p.y CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2) } // draw the inner-web CGContextSetLineWidth(context, chart.innerWebLineWidth) CGContextSetStrokeColorWithColor(context, chart.innerWebColor.CGColor) CGContextSetAlpha(context, chart.webAlpha) let labelCount = chart.yAxis.entryCount for (var j = 0; j < labelCount; j++) { for (var i = 0, xValCount = data.xValCount; i < xValCount; i++) { let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle) let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle) _webLineSegmentsBuffer[0].x = p1.x _webLineSegmentsBuffer[0].y = p1.y _webLineSegmentsBuffer[1].x = p2.x _webLineSegmentsBuffer[1].y = p2.y CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let chart = chart, data = chart.data as? RadarChartData, animator = animator else { return } CGContextSaveGState(context) CGContextSetLineWidth(context, data.highlightLineWidth) if (data.highlightLineDashLengths != nil) { CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle let factor = chart.factor let center = chart.centerOffsets for (var i = 0; i < indices.count; i++) { guard let set = chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as? IRadarChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) // get the index to highlight let xIndex = indices[i].xIndex let e = set.entryForXIndex(xIndex) if e?.xIndex != xIndex { continue } let j = set.entryIndex(entry: e!) let y = (e!.value - chart.chartYMin) if (y.isNaN) { continue } _highlightPointBuffer = ChartUtils.getPosition( center: center, dist: CGFloat(y) * factor * phaseY, angle: sliceangle * CGFloat(j) * phaseX + chart.rotationAngle) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
mit
0b4f990ba4f765cebbc027b94a79e052
31.492837
140
0.537437
5.632886
false
false
false
false
nakau1/Formations
Formations/Sources/Models/Image.swift
1
3866
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import UIKit enum Image: FileType { case playerFace(id: String) case playerThumb(id: String) case playerFull(id: String) case teamEmblem(id: String) case teamSmallEmblem(id: String) case teamImage(id: String) case formationTemplate(id: String) case test(id: String) case testOrigin(id: String) enum Category: String { case players case teams case formationTemplates = "formation_templates" case test } var directory: String { switch self { case let .playerFace(id), let .playerThumb(id), let .playerFull(id): return "\(Category.players.rawValue)/\(id)" case let .teamEmblem(id), let .teamSmallEmblem(id), let .teamImage(id): return "\(Category.teams.rawValue)/\(id)" case .formationTemplate: return "\(Category.formationTemplates.rawValue)" case .test, .testOrigin: return Category.test.rawValue } } var name: String { switch self { case .playerFace: return "face" case .playerThumb: return "thumb" case .playerFull: return "full" case .teamEmblem: return "emblem" case .teamSmallEmblem: return "small_emblem" case .teamImage: return "image" case let .formationTemplate(id): return id case let .test(id): return id case let .testOrigin(id): return id + "_org" } } var extensionName: String { return "png" } func process(_ image: UIImage) -> UIImage { switch self { case .playerFace: return image.adjusted(to: CGSize(400, 400), shouldExpand: true) case .playerThumb: return image.adjusted(to: CGSize(240, 240), shouldExpand: true) case .playerFull: return image.adjusted(to: CGSize(1200, 1600), shouldExpand: true) case .teamEmblem: return image.adjusted(to: CGSize(400, 400), shouldExpand: true) case .teamSmallEmblem: return image.adjusted(to: CGSize(273, 273), shouldExpand: true) case .teamImage: return image.adjusted(to: CGSize(828, 1472), shouldExpand: true) case .formationTemplate: return image case .test: return image case .testOrigin: return image } } } extension Image { func save(_ image: UIImage?) { makeDirectoryIfNeeded() if let image = image { let data = UIImagePNGRepresentation(process(image)) try? data?.write(to: URL(fileURLWithPath: path), options: [.atomic]) } else { delete() } } func load() -> UIImage? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return nil } return UIImage(data: data) } static func delete(category: Category, id: String) { let components = [ documentDirectory, resourceDirectory, category.rawValue, id, ] let path = components.reduce("") { ($0 as NSString).appendingPathComponent($1) } if FileManager.default.fileExists(atPath: path) { try! FileManager.default.removeItem(atPath: path) } } } // MARK: - UIImage Utilities extension UIImage { func save(_ image: Image) { image.save(self) } class func load(_ image: Image) -> UIImage? { return image.load() } }
apache-2.0
5a798f0c5b832ae5eead70737692a33e
30.688525
94
0.542162
4.553592
false
true
false
false
seraphjiang/JHUIKit
JHUIKit/Classes/JHProfileHeaderView.swift
1
2250
// // JHProfileHeaderView.swift // Pods // // Created by Huan Jiang on 5/6/16. // // import UIKit /// Designable Profile Header View @IBDesignable public class JHProfileHeaderView: UIView { var blurBackground: UIImageView! var avatar:JHCircleImageView! var imageLayer: CALayer! override public init(frame: CGRect) { super.init(frame:frame) } /** Init - parameter frame: frame rect - parameter radius: radius of image - returns: <#return value description#> */ public init(frame: CGRect, radius: CGFloat) { self.radius = radius super.init(frame:frame) } /** init for interface build */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// image for profile header @IBInspectable public var image: UIImage! { didSet { updateLayerProperties() } } /// radius for image @IBInspectable public var radius: CGFloat = 100 { didSet { updateLayerProperties() } } /** update layer properties */ public func updateLayerProperties() { if (blurBackground != nil) { if let i = image { self.blurBackground.image = i let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView visualEffectView.frame = blurBackground.bounds blurBackground.addSubview(visualEffectView) } } if (avatar != nil) { if let i = image { self.avatar.image = i } } } /** update layer */ public override func layoutSubviews() { if self.blurBackground == nil { self.blurBackground = UIImageView(frame: CGRectMake(0,0, self.frame.width, self.frame.height)) self.addSubview(blurBackground) } if self.avatar == nil { self.avatar = JHCircleImageView(frame: CGRectMake((self.frame.width-radius)/2, (self.frame.height-radius)/2, radius, radius)); self.addSubview(avatar); } updateLayerProperties() } }
mit
cad287eb5d2df1b84cdc8c0eea7c2456
23.193548
138
0.572
4.859611
false
false
false
false
ai260697793/weibo
新浪微博/新浪微博/UIs/Home/cell/MHOriginalView.swift
1
3798
// // MHOriginalView.swift // 新浪微博 // // Created by 莫煌 on 16/5/10. // Copyright © 2016年 MH. All rights reserved. // import UIKit import SnapKit let MHOriginalViewMargin: CGFloat = 10 class MHOriginalView: UIView { var originalViewModel: MHStatusViewModel?{ didSet { nameLabel.text = originalViewModel?.status?.user?.screen_name timeLabel.text = originalViewModel?.status?.created_at contentLabel.text = originalViewModel?.status?.text } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 加载控件 private func setupUI(){ addSubview(photoImageView) addSubview(verfityImageView) addSubview(levelImageView) addSubview(nameLabel) addSubview(timeLabel) addSubview(sourceLabel) addSubview(contentLabel) } // MARK: - 布局子控件 override func layoutSubviews() { super.layoutSubviews() /// 头像 photoImageView.snp_makeConstraints { (make) in make.left.equalTo(self.snp_left).offset(MHOriginalViewMargin) make.top.equalTo(self.snp_top).offset(MHOriginalViewMargin) make.width.height.equalTo(50) } /// 昵称 nameLabel.snp_makeConstraints { (make) in make.left.equalTo(photoImageView.snp_right).offset(MHOriginalViewMargin) make.top.equalTo(photoImageView.snp_top) } /// 等级 levelImageView.snp_makeConstraints { (make) in make.centerY.equalTo(nameLabel.snp_centerY) make.left.equalTo(nameLabel.snp_right).offset(MHOriginalViewMargin) } /// 认证 verfityImageView.snp_makeConstraints { (make) in make.centerX.equalTo(photoImageView.snp_right) make.centerY.equalTo(photoImageView.snp_bottom) } /// 时间 timeLabel.snp_makeConstraints { (make) in make.left.equalTo(photoImageView.snp_right).offset(MHOriginalViewMargin) make.bottom.equalTo(photoImageView.snp_bottom) } /// 内容 contentLabel.snp_makeConstraints { (make) in make.left.equalTo(self.snp_left) make.top.equalTo(photoImageView.snp_bottom).offset(MHOriginalViewMargin) make.right.equalTo(self.snp_right) } /// 用来自动计算行高 self.snp_makeConstraints { (make) in make.bottom.equalTo(contentLabel.snp_bottom) } } // MARK: - 懒加载控件 /// 头像 private lazy var photoImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "avatar_default_big")) return imageView }() /// 认证 private lazy var verfityImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "avatar_vip")) return imageView }() /// 等级 private lazy var levelImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "common_icon_membership")) return imageView }() /// 昵称 private lazy var nameLabel: UILabel = UILabel(size: 15, color: UIColor.lightGrayColor(), isSingleLine: true) /// 时间 private lazy var timeLabel: UILabel = UILabel(size: 13, color: UIColor.orangeColor(), isSingleLine: true) /// 来源 private lazy var sourceLabel: UILabel = UILabel(size: 13, color: UIColor.darkGrayColor(), isSingleLine: true) /// 内容 private lazy var contentLabel: UILabel = UILabel(size: 15, color: UIColor.darkGrayColor(), isSingleLine: false) }
mit
5750c40e00ca7b2d6261807267fb8f1f
28.733871
115
0.625983
4.363314
false
false
false
false
Yokong/douyu
douyu/douyu/Classes/Home/Controller/HomeController.swift
1
2729
// // HomeController.swift // douyu // // Created by Yoko on 2017/4/21. // Copyright © 2017年 Yokooll. All rights reserved. // import UIKit class HomeController: UIViewController { //MARK:- ------懒加载属性------ lazy var titleView: PageTitleView = { let titles = ["推荐", "游戏", "娱乐", "趣玩"] let v = PageTitleView(frame: CGRect(x: 0, y: 64, width: Screen_W, height: 44), titles: titles) v.delegate = self return v }() lazy var contentView: PageContentView = { let h = Screen_H - self.titleView.frame.maxY let frame = CGRect(x: 0, y: self.titleView.frame.maxY, width: Screen_W, height: h) var childVCs = [UIViewController]() childVCs.append(RecommendController()) childVCs.append(GameController()) childVCs.append(AmuseController()) childVCs.append(UIViewController()) let contentView = PageContentView(frame: frame, childVCs: childVCs, parentVC: self) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() setUp() } } //MARK:- ------基础配置------ extension HomeController { func setUp() { // 设置导航栏 navigationItem.leftBarButtonItem = UIBarButtonItem(img: #imageLiteral(resourceName: "logo"), imgH: nil, size: nil) let size = CGSize(width: 35, height: 35) let searchBar = UIBarButtonItem(img: #imageLiteral(resourceName: "btn_search"), imgH: #imageLiteral(resourceName: "btn_search_clicked"), size: size) let historyBar = UIBarButtonItem(img: #imageLiteral(resourceName: "image_my_history"), imgH: #imageLiteral(resourceName: "Image_my_history_click"), size: size) let QRCodeBar = UIBarButtonItem(img: #imageLiteral(resourceName: "Image_scan"), imgH: #imageLiteral(resourceName: "Image_scan_click"), size: size) navigationItem.rightBarButtonItems = [QRCodeBar, historyBar, searchBar] // 添加titleView automaticallyAdjustsScrollViewInsets = false view.addSubview(titleView) // 添加contentView view.addSubview(contentView) } } //MARK:- ------pageTitleView 代理------ extension HomeController: PageTitleViewDelegate { func pageTitleViewDidClick(index: Int) { contentView.setCollctionViewOffSet(index: index) } } //MARK:- ------pageContentView 代理------ extension HomeController: PageContentViewDelegate { func pageContentViewDidScroll(offSetX: CGFloat, isLeft: Bool) { titleView.setLabelSelect(offSetX: offSetX, isLeft: isLeft) } }
mit
bcbb072f5e9039f460613d49a6ee7582
26.484536
167
0.633533
4.58864
false
false
false
false
tt3tt3tt/3DTouch_test
3DTouch/DrawTouchController.swift
1
3264
// // DrawTouchController.swift // 3DTouch // // Created by SnowCheng on 16/5/15. // Copyright © 2016年 SnowCheng. All rights reserved. // import UIKit class DrawTouchController: UIViewController { let positionLable = UILabel() let forceLable = UILabel() let imageView = UIImageView() var lastPoint = CGPointZero override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.lightGrayColor() title = "drawVC" positionLable.frame = CGRect.init(x: 0, y: 50, width: 200, height: 50) forceLable.frame = CGRect.init(x: 200, y: 50, width: 200, height: 50) imageView.frame = view.bounds view.addSubview(positionLable) view.addSubview(forceLable) view.addSubview(imageView) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { lastPoint = touches.first?.locationInView(view) ?? CGPointZero } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first ?? UITouch() let currentPoint = touch.locationInView(view) ?? CGPointZero UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0) imageView.image?.drawInRect(view.bounds) let path = UIBezierPath() path.moveToPoint(lastPoint) path.addLineToPoint(currentPoint) path.lineWidth = touch.force * 5 path.lineJoinStyle = .Round path.lineCapStyle = .Round path.stroke() imageView.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() positionLable.text = "x:\(currentPoint.x), y:\(currentPoint.y)" forceLable.text = "force: \(touch.force)" lastPoint = currentPoint } override func previewActionItems() -> [UIPreviewActionItem] { let item1 = UIPreviewAction.init(title: "item1", style: .Destructive) { (_, _) in print("viewTouch__item1") let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController as? UINavigationController rootVC?.pushViewController(self, animated: true) } let item2 = UIPreviewAction.init(title: "item2", style: .Default) { (_, _) in print("viewTouch__item2") } let item3 = UIPreviewAction.init(title: "item3", style: .Selected) { (_, _) in print("viewTouch__item3") } let item4 = UIPreviewAction.init(title: "item4", style: .Selected) { (_, _) in print("viewTouch__item3") } let item5 = UIPreviewAction.init(title: "item5", style: .Selected) { (_, _) in print("viewTouch__item3") } let group1 = UIPreviewActionGroup.init(title: "group1", style: .Destructive, actions: [item1, item2]) let group2 = UIPreviewActionGroup.init(title: "group2", style: .Default, actions: [item3, item4]) let group3 = UIPreviewActionGroup.init(title: "group3", style: .Selected, actions: [item5]) return [group1, group2, group3] } }
mit
6e417ab6f8ca878f51e840361aca639e
32.96875
115
0.603189
4.567227
false
false
false
false
AlexZd/SwiftUtils
Pod/Utils/NSNumber+Helpers.swift
1
1233
// // NSNumber+Helpers.swift // // Created by Alex Zdorovets on 6/18/15. // Copyright (c) 2015 Alex Zdorovets. All rights reserved. // import Foundation extension NSNumber { /** Returns NSNumber rounded to precision */ public func roundToPrecision(precision: Int) -> NSNumber { let valueToRound = self.doubleValue let scale = pow(Double(10), Double(precision)) var tmp = valueToRound * scale tmp = Double(Int(round(tmp))) let roundedValue = tmp / scale return NSNumber(value: roundedValue) } /** Returns price representation of number, nil for device currency */ public func priceStr(currency: String?) -> String { let formatter = NumberFormatter() formatter.numberStyle = .currency if currency != nil { formatter.currencySymbol = currency! } formatter.maximumFractionDigits = 0 return formatter.string(from: self)! } public func thousandSeparated(separator: String? = nil) -> String { let nf = NumberFormatter() if separator != nil { nf.groupingSeparator = separator } nf.numberStyle = .decimal return nf.string(from: self)! } }
mit
eb342b800bde779a9b3442d9b9207fca
29.825
74
0.626115
4.600746
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/General/SecureStore.swift
1
5483
// Copyright (c) 2018 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. // // Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, // distribute, sublicense, create a derivative work, and/or sell copies of the // Software in any work that is designed, intended, or marketed for pedagogical or // instructional purposes related to programming, coding, application development, // or information technology. Permission for such use, copying, modification, // merger, publication, distribution, sublicensing, creation of derivative works, // or sale is expressly withheld. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Security public struct SecureStore { let secureStoreQueryable: SecureStoreQueryable public init(secureStoreQueryable: SecureStoreQueryable) { self.secureStoreQueryable = secureStoreQueryable } public func setValue(_ value: String, for userAccount: String) throws { guard let encodedPassword = value.data(using: .utf8) else { throw NetworkingError.other } var query = secureStoreQueryable.query query[String(kSecAttrAccount)] = userAccount var status = SecItemCopyMatching(query as CFDictionary, nil) switch status { case errSecSuccess: var attributesToUpdate: [String: Any] = [:] attributesToUpdate[String(kSecValueData)] = encodedPassword status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary) if status != errSecSuccess { throw NetworkingError.other } case errSecItemNotFound: query[String(kSecValueData)] = encodedPassword status = SecItemAdd(query as CFDictionary, nil) if status != errSecSuccess { throw NetworkingError.other } default: throw NetworkingError.other } } public func getValue(for userAccount: String) throws -> String? { var query = secureStoreQueryable.query query[String(kSecMatchLimit)] = kSecMatchLimitOne query[String(kSecReturnAttributes)] = kCFBooleanTrue query[String(kSecReturnData)] = kCFBooleanTrue query[String(kSecAttrAccount)] = userAccount var queryResult: AnyObject? let status = withUnsafeMutablePointer(to: &queryResult) { SecItemCopyMatching(query as CFDictionary, $0) } switch status { case errSecSuccess: guard let queriedItem = queryResult as? [String: Any], let passwordData = queriedItem[String(kSecValueData)] as? Data, let password = String(data: passwordData, encoding: .utf8) else { throw NetworkingError.other } return password case errSecItemNotFound: return nil default: throw NetworkingError.other } } public func removeValue(for userAccount: String) throws { var query = secureStoreQueryable.query query[String(kSecAttrAccount)] = userAccount let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw NetworkingError.other } } public func removeAllValues() throws { let query = secureStoreQueryable.query let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw NetworkingError.other } } } public protocol SecureStoreQueryable { var query: [String: Any] { get } } public struct GenericPasswordQueryable { let service: String let accessGroup: String? init(service: String, accessGroup: String? = nil) { self.service = service self.accessGroup = accessGroup } } extension GenericPasswordQueryable: SecureStoreQueryable { public var query: [String: Any] { var query: [String: Any] = [:] query[String(kSecClass)] = kSecClassGenericPassword query[String(kSecAttrService)] = service // Access group if target environment is not simulator #if !targetEnvironment(simulator) if let accessGroup = accessGroup { query[String(kSecAttrAccessGroup)] = accessGroup } #endif return query } }
mit
a16b2b777e877911bbc0b4de7db95f2e
36.554795
82
0.670254
5.287367
false
false
false
false
JiriTrecak/Laurine
Example/Laurine/Classes/Experimental/PluralCore.swift
2
11245
// // Laurine - Plural Core Plugin // // Generate swift localization file based on localizables.string in plural form // // Note: // Only for development. Will be merged to primary generator as soon as the rules are complete // // Licence: MIT // Author: Jiří Třečák http://www.jiritrecak.com @jiritrecak // class PluralCore { // Plural groups base on CLDR definition enum PluralGroup { case zero case one case two case few case many case other } enum GenderGroup { case male case female case other } fileprivate func arabicRuleForCount(_ count : UInt) -> PluralGroup { switch count { case 0: return .zero case 1: return .one case 2: return .two default: let mod100 = count % 100 if (mod100 >= 3 && mod100 <= 10) { return .few } else if (mod100 >= 11) { return .many } else { return .other } } } fileprivate func simplifiedChineseRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func traditionalChineseRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func catalanRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func croatianRuleForCount(_ count : UInt) -> PluralGroup { let mod10 = count % 10 let mod100 = count % 100 switch mod10 { case 1: switch mod100 { case 11: break default: return .one } case 2, 3, 4: switch (mod100) { case 12, 13, 14: break default: return .few } break default: break } return .many } fileprivate func czechRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one case 2, 3, 4: return .few default: return .other } } fileprivate func englishRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func frenchRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 0, 1: return .one default: return .other } } fileprivate func germanRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func danishRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func dutchRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func finnishRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func greekRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func hebrewRuleForCount(_ count : UInt) -> PluralGroup { let mod10 = count % 10 switch (count) { case 1: return .one case 2: return .two case 3...10: break default: switch (mod10) { case 0: return .many default: break } } return .other } fileprivate func hungarianRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func indonesianRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func italianRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func japaneseRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func koreanRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func latvianRuleForCount(_ count : UInt) -> PluralGroup { let mod10 = count % 10 let mod100 = count % 100 if (count == 0) { return .zero } if (count == 1) { return .one } switch (mod10) { case 1: if (mod100 != 11) { return .one } break default: break } return .many } fileprivate func malayRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func norwegianBokamlRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func norwegianNynorskRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func polishRuleForCount(_ count : UInt) -> PluralGroup { let mod10 = count % 10 let mod100 = count % 100 if (count == 1) { return .one } switch mod10 { case 2...4: switch (mod100) { case 12...14: break default: return .few } break default: break } return .many } fileprivate func portugeseRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func romanianRuleForCount(_ count : UInt) -> PluralGroup { let mod100 = count % 100 switch (count) { case 0: return .few case 1: return .one default: if (mod100 > 1 && mod100 <= 19) { return .few } break } return .other } fileprivate func russianRuleForCount(_ count : UInt) -> PluralGroup { let mod10 = count % 10 let mod100 = count % 100 switch mod100 { case 11...14: break default: switch mod10 { case 1: return .one case 2...4: return .few default: break } } return .many } fileprivate func slovakRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one case 2...4: return .few default: return .other } } fileprivate func spanishRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func swedishRuleForCount(_ count : UInt) -> PluralGroup { switch (count) { case 1: return .one default: return .other } } fileprivate func thaiRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func turkishRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func ukrainianRuleForCount(_ count : UInt) -> PluralGroup { let mod10 = count % 10 let mod100 = count % 100 switch mod100 { case 11...14: break default: switch (mod10) { case 1: return .one case 2...4: return .few default: break } } return .many } fileprivate func vietnameseRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func unknownRuleForCount(_ count : UInt) -> PluralGroup { return .other } fileprivate func ruleForLanguageCode(_ code : String) -> ((_ count : UInt) -> PluralGroup) { switch code { case "ar": return self.vietnameseRuleForCount case "ca": return self.catalanRuleForCount case "zh-Hans": return self.simplifiedChineseRuleForCount case "zh-Hant": return self.traditionalChineseRuleForCount case "cr": return croatianRuleForCount case "cs": return czechRuleForCount case "da": return danishRuleForCount case "nl": return dutchRuleForCount case "en": return englishRuleForCount case "fr": return frenchRuleForCount case "de": return germanRuleForCount case "fi": return finnishRuleForCount case "el": return greekRuleForCount case "he": return hebrewRuleForCount case "hu": return hungarianRuleForCount case "id": return indonesianRuleForCount case "it": return italianRuleForCount case "ja": return japaneseRuleForCount case "ko": return koreanRuleForCount case "lv": return latvianRuleForCount case "ms": return malayRuleForCount case "nb": return norwegianBokamlRuleForCount case "nn": return norwegianNynorskRuleForCount case "pl": return polishRuleForCount case "pt": return portugeseRuleForCount case "ro": return romanianRuleForCount case "ru": return russianRuleForCount case "es": return spanishRuleForCount case "sk": return slovakRuleForCount case "sv": return swedishRuleForCount case "th": return thaiRuleForCount case "tr": return turkishRuleForCount case "uk": return ukrainianRuleForCount case "vi": return vietnameseRuleForCount default: print("whoa whoa, unsupported language %@ bro!", code) return unknownRuleForCount } } }
mit
cd61320ada878c41f7e3f6e0111b76d2
23.812362
96
0.487633
4.991119
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/Networking/Networking.swift
1
2196
// // Networking.swift // Drrrible // // Created by Suyeol Jeon on 08/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import Moya import MoyaSugar import RxSwift typealias DrrribleNetworking = Networking<DribbbleAPI> final class Networking<Target: SugarTargetType>: MoyaSugarProvider<Target> { init(plugins: [PluginType] = []) { let session = MoyaProvider<Target>.defaultAlamofireSession() session.sessionConfiguration.timeoutIntervalForRequest = 10 super.init(session: session, plugins: plugins) } func request( _ target: Target, file: StaticString = #file, function: StaticString = #function, line: UInt = #line ) -> Single<Response> { let requestString = "\(target.method.rawValue) \(target.path)" return self.rx.request(target) .filterSuccessfulStatusCodes() .do( onSuccess: { value in let message = "SUCCESS: \(requestString) (\(value.statusCode))" log.debug(message, file: file, function: function, line: line) }, onError: { error in if let response = (error as? MoyaError)?.response { if let jsonObject = try? response.mapJSON(failsOnEmptyData: false) { let message = "FAILURE: \(requestString) (\(response.statusCode))\n\(jsonObject)" log.warning(message, file: file, function: function, line: line) } else if let rawString = String(data: response.data, encoding: .utf8) { let message = "FAILURE: \(requestString) (\(response.statusCode))\n\(rawString)" log.warning(message, file: file, function: function, line: line) } else { let message = "FAILURE: \(requestString) (\(response.statusCode))" log.warning(message, file: file, function: function, line: line) } } else { let message = "FAILURE: \(requestString)\n\(error)" log.warning(message, file: file, function: function, line: line) } }, onSubscribed: { let message = "REQUEST: \(requestString)" log.debug(message, file: file, function: function, line: line) } ) } }
mit
dd30e5bac2c29112590898e7e366975b
35.583333
95
0.620046
4.346535
false
false
false
false
slavasemeniuk/SVLoader
SVLoader/Classes/OvalLayer.swift
1
1728
// // OvalLayer.swift // Loader // // Created by Slava Semeniuk on 12/12/16. // Copyright © 2016 Slava Semeniuk. All rights reserved. // import UIKit class OvalLayer: CAShapeLayer { var centralPoint: CGPoint! var ovalPath: UIBezierPath { return UIBezierPath(ovalIn: CGRect(x: centralPoint.x, y: centralPoint.y, width: 8, height: 8)) } var expandedOvalPath: UIBezierPath { return UIBezierPath(ovalIn: CGRect(x: centralPoint.x - 2, y: centralPoint.y - 2, width: 12, height: 12)) } convenience init(center: CGPoint) { self.init() fillColor = UIColor.white.cgColor centralPoint = center opacity = 0 path = ovalPath.cgPath } func animationInA(_ seconds: CFTimeInterval, period: CFTimeInterval) { let opacityAnimation = CABasicAnimation(keyPath: "opacity") opacityAnimation.fromValue = 0 opacityAnimation.toValue = 1 opacityAnimation.isRemovedOnCompletion = false opacityAnimation.fillMode = kCAFillModeBoth add(opacityAnimation, forKey: "opacity") let animation = CABasicAnimation(keyPath: "path") animation.fromValue = ovalPath.cgPath animation.toValue = expandedOvalPath.cgPath animation.beginTime = seconds animation.duration = 0.2 animation.autoreverses = true let animationGroup = CAAnimationGroup() animationGroup.animations = [animation] animationGroup.beginTime = 0 animationGroup.duration = period animationGroup.fillMode = kCAFillModeForwards animationGroup.repeatCount = Float.infinity add(animationGroup, forKey: nil) } }
mit
3154266a75e7d150d7342a927337905e
30.4
112
0.654314
4.864789
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/ProfileUserInfoCell.swift
1
3042
// // ProfileUserInfoCell.swift // DingshanSwift // // Created by xiong qi on 15/11/18. // Copyright © 2015年 song jufeng. All rights reserved. // import Foundation class ProfileUserInfoCell:UITableViewCell { var parentdelegate:ProfileViewController? var infoView = UIView() private var userNameLabel = UILabel() private var userHeadView = UIButton() private var userHeadImg = UIImageView() override init(style astyle:UITableViewCellStyle, reuseIdentifier str:String?) { super.init(style:astyle, reuseIdentifier:str) self.backgroundColor = UIColor.whiteColor() infoView.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: 198) infoView.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.5) self.addSubview(infoView) let loginBtn = UIButton(frame: CGRect(x:0, y:20, width:100, height:50)); loginBtn.backgroundColor = UIColor.lightGrayColor() loginBtn.setTitle("login", forState: UIControlState.Normal) loginBtn.addTarget(self, action:Selector("onTapLogin:"), forControlEvents: UIControlEvents.TouchUpInside) infoView.addSubview(loginBtn) userHeadView.frame = CGRect(x: (self.bounds.size.width - 73)*0.5, y: 50, width: 73, height: 73) userHeadView.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.2) userHeadView.setImage(UIImage(named:"user_head_default"), forState: UIControlState.Normal) userHeadView.layer.cornerRadius = userHeadView.bounds.width * 0.5 userHeadView.addTarget(self, action: Selector("onTapEditInfo:"), forControlEvents: UIControlEvents.TouchUpInside) infoView.addSubview(userHeadView) userHeadImg.frame = userHeadView.bounds userHeadView.addSubview(userHeadImg) userNameLabel.frame = CGRect(x: 20, y: 128, width: self.bounds.size.width - 40, height: 16) userNameLabel.font = UIFont.systemFontOfSize(15.0) userNameLabel.textAlignment = NSTextAlignment.Center userNameLabel.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.2) infoView.addSubview(userNameLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func clearData() { } func loadCellData(data:Dictionary<String,String>) { } func refreshInfo(){ if MainConfig.sharedInstance.userLoginDone{ let info = MainConfig.sharedInstance.userInfo userNameLabel.text = info.userName userHeadImg.sd_setImageWithURL(NSURL(string: info.userHeadUrl)) } } func onTapLogin(sender:UIButton) { if self.parentdelegate != nil { self.parentdelegate?.onTapLogin() } } func onTapEditInfo(sender:UIButton) { if self.parentdelegate != nil { self.parentdelegate?.onTapEditInfo() } } }
mit
3f5e886292d1a3acb56f53818daac154
35.190476
121
0.664692
4.646789
false
false
false
false
vanshg/MacAssistant
Pods/SwiftProtobuf/Sources/SwiftProtobuf/UnknownStorage.swift
4
1628
// Sources/SwiftProtobuf/UnknownStorage.swift - Handling unknown fields // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Proto2 binary coding requires storing and recoding of unknown fields. /// This simple support class handles that requirement. A property of this type /// is compiled into every proto2 message. /// // ----------------------------------------------------------------------------- import Foundation /// Contains any unknown fields in a decoded message; that is, fields that were /// sent on the wire but were not recognized by the generated message /// implementation or were valid field numbers but with mismatching wire /// formats (for example, a field encoded as a varint when a fixed32 integer /// was expected). public struct UnknownStorage: Equatable { /// The raw protocol buffer binary-encoded bytes that represent the unknown /// fields of a decoded message. public private(set) var data = Internal.emptyData #if !swift(>=4.1) public static func ==(lhs: UnknownStorage, rhs: UnknownStorage) -> Bool { return lhs.data == rhs.data } #endif public init() {} internal mutating func append(protobufData: Data) { data.append(protobufData) } public func traverse<V: Visitor>(visitor: inout V) throws { if !data.isEmpty { try visitor.visitUnknown(bytes: data) } } }
mit
2b2ea0c2f551265cc0d757b9fb55c53b
34.391304
80
0.657862
4.59887
false
false
false
false
volendavidov/NagBar
NagBar/StatusPanel.swift
1
4836
// // StatusPanel.swift // NagBar // // Created by Volen Davidov on 28.02.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Foundation import Cocoa class StatusPanel : NSObject { // The panel height is limited to that number. If the panel needs to be bigger to // contain all monitoring items, then a scroller is added (see below). let maxPanelHeight: CGFloat = 500; let results: Array<MonitoringItem> let panelBounds: NSRect var panel: StatusNSPanel? init(results: Array<MonitoringItem>, panelBounds: NSRect) { self.results = results self.panelBounds = panelBounds } func load() { // first initialize the table, we will know the width of the panel this way let statusTable = StatusPanelTable() statusTable.initTable(results) // Get the total width of the panel by suming all columns in the table var allColumnsWidth = CGFloat(0) for column in statusTable.tableColumns { allColumnsWidth += column.width } var xCoords = (self.panelBounds.origin.x + self.panelBounds.size.width - (allColumnsWidth)) // We always want to start from the leftmost part of the display, including the dock if its position is on the left side. let visibleScreenRect = NSScreen.main?.visibleFrame if (xCoords < visibleScreenRect!.origin.x) { xCoords = visibleScreenRect!.origin.x } // The height of the panel is the number of rows * 26 (the height of a single row). // The height cannot be more than maxPanelHeight. If it is, we will add scroller and arrow several lines below. var rowHeight = 19 if #available(OSX 11.0, *) { rowHeight = 26 } var panelHeight = CGFloat(rowHeight * self.results.count); if (panelHeight > maxPanelHeight) { panelHeight = maxPanelHeight } let yCoords = self.panelBounds.origin.y - CGFloat(panelHeight); let frame = NSMakeRect(xCoords, yCoords, allColumnsWidth, panelHeight) panel = StatusNSPanel(contentRect: frame, styleMask: .borderless, backing: .buffered, defer: false) panel!.hasShadow = true panel!.makeKeyAndOrderFront(nil) let scrollView: NSScrollView if panelHeight == maxPanelHeight { let arrowRect = CGRect(x: 0, y: maxPanelHeight - 20, width: panel!.contentView!.bounds.size.width, height: 20); let drawArrow = DrawArrow(frame: arrowRect) scrollView = NSScrollView(frame: panel!.contentView!.bounds) scrollView.addSubview(drawArrow) } else { scrollView = UnscrollableScrollView(frame: panel!.contentView!.bounds) } scrollView.hasVerticalScroller = false scrollView.hasHorizontalScroller = false scrollView.documentView = statusTable panel!.contentView?.addSubview(scrollView) statusTable.reloadData() } } class UnscrollableScrollView : NSScrollView { override func scrollWheel(with theEvent: NSEvent) { } } class StatusNSPanel : NSPanel { override var canBecomeKey: Bool { return true } override var canBecomeMain: Bool { return true } } class DrawArrow : NSView { override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) let rectPath = NSBezierPath() rectPath.move(to: NSMakePoint(0, 0)) rectPath.line(to: NSMakePoint(0, 0)) rectPath.line(to: NSMakePoint(dirtyRect.size.width, 0)) rectPath.line(to: NSMakePoint(dirtyRect.size.width, dirtyRect.size.height)) rectPath.line(to: NSMakePoint(0, dirtyRect.size.width)) rectPath.line(to: NSMakePoint(0, 0)) rectPath.close() NSColor(calibratedWhite: 0.0, alpha: 0.3).setFill() rectPath.fill() let startingPoint = dirtyRect.size.width/2; let path = NSBezierPath() path.move(to: NSMakePoint(startingPoint, 0)) path.line(to: NSMakePoint(startingPoint - 75, 15)) path.line(to: NSMakePoint(startingPoint - 25, 15)) path.line(to: NSMakePoint(startingPoint - 25, 20)) path.line(to: NSMakePoint(startingPoint + 25, 20)) path.line(to: NSMakePoint(startingPoint + 25, 15)) path.line(to: NSMakePoint(startingPoint + 75, 15)) path.close() let lightColor = NSColor(calibratedWhite: 0.3, alpha: 0.9) let darkColor = NSColor(calibratedWhite: 0.1, alpha: 0.9) let fillGradient = NSGradient(starting: lightColor, ending:darkColor) fillGradient?.draw(in: path, angle: 270) } }
apache-2.0
a9b4d0d6b71879afd7c6a0cdb8f34a91
34.291971
129
0.628335
4.456221
false
false
false
false
oliverkulpakko/ATMs
ATMs/View/Controllers/ATMsViewController.swift
1
3656
// // ATMsViewController.swift // ATMs // // Created by Oliver Kulpakko on 5.12.2017. // Copyright © 2017 East Studios. All rights reserved. // import UIKit import PullUpController import MapKit protocol ATMsViewControllerDelegate: class { func didSelectATM(_ atm: ATM, in atmsViewController: ATMsViewController) } class ATMsViewController: PullUpController { // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() view.clipsToBounds = true view.layer.cornerRadius = 20 nearbyAtmCountLabel.text = "atms.loadingNearby".localized } func updateDataForLocation(_ location: CLLocation) { DispatchQueue.global(qos: .background).async { let threshold = UserDefaults.standard.float(forKey: "NearbyThreshold") self.atms = self.atms.sortedByLocation(location, nearbyThreshold: Double(threshold)) DispatchQueue.main.async { self.nearbyAtmCountLabel.text = String(format: "atms.nearby.%d".localized, self.atms.count) if !self.atms.isEmpty { self.isSorted = true } } } } @available(iOS 11.0, *) func setupTrackingButton(mapView: MKMapView) { let button = MKUserTrackingButton(mapView: mapView) userTrackingButtonContainerView.embedView(button) } // MARK: PullUpController override var pullUpControllerMiddleStickyPoints: [CGFloat] { return [topBlurView.frame.maxY + 50] } override func dismiss() { pullUpControllerMoveToVisiblePoint(pullUpControllerMiddleStickyPoints[0], animated: true, completion: nil) } // MARK: Stored Properties var atms = [ATM]() { didSet { DispatchQueue.main.async { self.tableView.reloadData() } if let location = location, !isSorted { updateDataForLocation(location) } } } weak var delegate: ATMsViewControllerDelegate? var location: CLLocation? { didSet { if let location = location, !isSorted { updateDataForLocation(location) } } } private var isSorted = false let distanceFormatter = MKDistanceFormatter() // MARK: IBOutlets @IBOutlet var backgroundBlurView: UIVisualEffectView! @IBOutlet var topBlurView: UIVisualEffectView! @IBOutlet var settingsButton: UIButton! @IBOutlet var nearbyAtmCountLabel: UILabel! @IBOutlet var userTrackingButtonContainerView: UIView! @IBOutlet var tableView: UITableView! } extension ATMsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return atms.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ATMCell", for: indexPath) as! ATMCell let atm = atms[indexPath.row] cell.addressLabel.text = atm.addressFormatted() cell.openingTimesLabel.text = atm.openingTimesFormatted() cell.modelLabel.text = atm.modelFormatted() cell.modelLabel.backgroundColor = atm.modelColor() if let location = location { let distance = atm.distanceFromLocation(location) cell.distanceLabel.text = distanceFormatter.string(fromDistance: distance) let color: UIColor switch distance { case 0...2500: color = .flatGreen case 2500...10000: color = .flatOrange default: color = .flatRed } cell.distanceLabel.backgroundColor = color } cell.distanceLabel.isHidden = (location == nil) return cell } } extension ATMsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) delegate?.didSelectATM(atms[indexPath.row], in: self) } }
mit
000087ea8def7eb74de2f9194b2fa769
23.863946
108
0.732969
3.855485
false
false
false
false
brave/browser-ios
Client/Frontend/Widgets/ChevronView.swift
2
4149
/* 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 enum ChevronDirection { case left case up case right case down } enum ChevronStyle { case angular case rounded } class ChevronView: UIView { fileprivate let Padding: CGFloat = 2.5 fileprivate var direction = ChevronDirection.right fileprivate var lineCapStyle = CGLineCap.round fileprivate var lineJoinStyle = CGLineJoin.round var lineWidth: CGFloat = 3.0 var style: ChevronStyle = .rounded { didSet { switch style { case .rounded: lineCapStyle = CGLineCap.round lineJoinStyle = CGLineJoin.round case .angular: lineCapStyle = CGLineCap.butt lineJoinStyle = CGLineJoin.miter } } } init(direction: ChevronDirection) { super.init(frame: CGRect.zero) self.direction = direction self.backgroundColor = UIColor.clear self.contentMode = UIViewContentMode.redraw } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) let strokeLength = (rect.size.height / 2) - Padding; let path: UIBezierPath switch (direction) { case .left: path = drawLeftChevronAt(CGPoint(x: rect.size.width - (strokeLength + Padding), y: strokeLength + Padding), strokeLength:strokeLength) case .up: path = drawUpChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength / 2) + Padding), strokeLength:strokeLength) case .right: path = drawRightChevronAt(CGPoint(x: rect.size.width - Padding, y: strokeLength + Padding), strokeLength:strokeLength) case .down: path = drawDownChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength * 1.5) + Padding), strokeLength:strokeLength) } tintColor.set() // The line thickness needs to be proportional to the distance from the arrow head to the tips. Making it half seems about right. path.lineCapStyle = lineCapStyle path.lineJoinStyle = lineJoinStyle path.lineWidth = lineWidth path.stroke(); } fileprivate func drawUpChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength)) } fileprivate func drawDownChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength)) } fileprivate func drawLeftChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength)) } fileprivate func drawRightChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath { return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength), head: CGPoint(x: origin.x, y: origin.y), rightTip: CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength)) } fileprivate func drawChevron(_ leftTip: CGPoint, head: CGPoint, rightTip: CGPoint) -> UIBezierPath { let path = UIBezierPath() // Left tip path.move(to: leftTip) // Arrow head path.addLine(to: head) // Right tip path.addLine(to: rightTip) return path } }
mpl-2.0
20b436eeff6dbc1305292f62711d50ab
35.078261
154
0.642564
4.456498
false
false
false
false
nastia05/TTU-iOS-Developing-Course
Lecture 8/Recipes_persistence/Recipes/RecipesTVC.swift
1
3928
// // RecipesTVC.swift // Recipes // // Created by Artemiy Sobolev on 08/02/2017. // Copyright © 2017 Artemiy Sobolev. All rights reserved. // import UIKit final class RecipeViewCell: UITableViewCell { @IBOutlet weak var preview: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var starredButton: UIButton! var recipe: Recipe! { didSet { nameLabel.text = recipe.name preview.image = recipe.image descriptionLabel.text = recipe.description updateStarButton() } } func updateStarButton() { let image = recipe.starred ? #imageLiteral(resourceName: "star") : #imageLiteral(resourceName: "star_disabled") starredButton.setImage(image, for: .normal) } @IBAction func starButtonPressed(_ sender: UIButton) { recipe.starred = !recipe.starred updateStarButton() } } final class RecipesTVC: UITableViewController { static private let recipesSID = "RecipeSID" static let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("myRecipes").appendingPathExtension("plist") var recipes: [Recipe]! override func viewDidLoad() { super.viewDidLoad() recipes = loadRecipes() ?? [] } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch segue.identifier ?? "" { case "toRecipeDetailVCSID": let recipe = (sender as! RecipeViewCell).recipe segue.destination.title = recipe?.name default: break } } //MARK: - unwind segue implementation @IBAction func unwindToRecipeList(sender: UIStoryboardSegue) { guard let sourceVC = sender.source as? AddRecipeVC else { return } if let recipe = sourceVC.recipe { recipes.append(recipe) saveRecipes() let indexPath = IndexPath(row: recipes.count-1, section: 0) tableView.insertRows(at: [indexPath] , with: .automatic) } } @IBAction func unwindBack(sender: UIStoryboardSegue) { } //MARK: - saving/loading recipes func saveRecipes() { let result = NSKeyedArchiver.archiveRootObject(recipes, toFile: RecipesTVC.fileURL.path) if !result { print("Failed to save recipes to file \(RecipesTVC.fileURL.path)") } } func loadRecipes() -> [Recipe]? { return NSKeyedUnarchiver.unarchiveObject(withFile: RecipesTVC.fileURL.path) as? [Recipe] } //MARK: - UITableViewDelegate/UITableViewDataSource implementation override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return recipes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableView.dequeueReusableCell(withIdentifier: RecipesTVC.recipesSID)! } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { (cell as! RecipeViewCell).recipe = recipes[indexPath.row] } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard editingStyle == .delete else { return } recipes.remove(at: indexPath.row) saveRecipes() tableView.deleteRows(at: [indexPath], with: .automatic) } } extension Recipe { var image: UIImage { return UIImage(named: name) ?? #imageLiteral(resourceName: "meal") } }
mit
5e7d9c5864f5214f02f4481838d31ca2
28.088889
170
0.628979
4.964602
false
false
false
false
manavgabhawala/swift
test/SILOptimizer/prespecialize.swift
1
1653
// RUN: %target-swift-frontend %s -Onone -Xllvm -sil-inline-generics=false -emit-sil | %FileCheck %s // REQUIRES: optimized_stdlib // FIXME: https://bugs.swift.org/browse/SR-2808 // XFAIL: resilient_stdlib // Check that pre-specialization works at -Onone. // This test requires the standard library to be compiled with pre-specializations! // CHECK-LABEL: sil [noinline] @_TF13prespecialize4testFTRGSaSi_4sizeSi_T_ // // function_ref specialized Collection<A where ...>.makeIterator() -> IndexingIterator<A> // CHECK: function_ref @_TTSgq5GVs14CountableRangeSi_GS_Si_s10Collections___TFesRxs10Collectionwx8IteratorzGVs16IndexingIteratorx_rS_12makeIteratorfT_GS1_x_ // // function_ref specialized IndexingIterator.next() -> A._Element? // CHECK: function_ref @_TTSgq5GVs14CountableRangeSi_GS_Si_s14_IndexableBases___TFVs16IndexingIterator4nextfT_GSqwx8_Element_ // // Look for generic specialization <Swift.Int> of Swift.Array.subscript.getter : (Swift.Int) -> A // CHECK: function_ref {{@_TTSgq5Si___TFSag9subscriptFSix|@_TTSg5Si___TFSaap9subscriptFSix}} // CHECK: return @inline(never) public func test(_ a: inout [Int], size: Int) { for i in 0..<size { for j in 0..<size { a[i] = a[j] } } } // CHECK-LABEL: sil [noinline] @_TF13prespecialize3runFT_T_ // Look for generic specialization <Swift.Int> of Swift.Array.init (repeating : A, count : Swift.Int) -> Swift.Array<A> // CHECK: function_ref @_TTSgq5Si___TFSaCfT9repeatingx5countSi_GSax_ // CHECK: return @inline(never) public func run() { let size = 10000 var p = [Int](repeating: 0, count: size) for i in 0..<size { p[i] = i } test(&p, size: size) } run()
apache-2.0
cfa0a6bff5c55a402c70c4016b7788fe
34.934783
156
0.714459
3.136622
false
true
false
false
airbnb/lottie-ios
Sources/Private/Model/Layers/TextLayerModel.swift
2
1903
// // TextLayer.swift // lottie-swift // // Created by Brandon Withrow on 1/8/19. // import Foundation /// A layer that holds text. final class TextLayerModel: LayerModel { // MARK: Lifecycle required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: TextLayerModel.CodingKeys.self) let textContainer = try container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup) text = try textContainer.decode(KeyframeGroup<TextDocument>.self, forKey: .text) animators = try textContainer.decode([TextAnimator].self, forKey: .animators) try super.init(from: decoder) } required init(dictionary: [String: Any]) throws { let containerDictionary: [String: Any] = try dictionary.value(for: CodingKeys.textGroup) let textDictionary: [String: Any] = try containerDictionary.value(for: TextCodingKeys.text) text = try KeyframeGroup<TextDocument>(dictionary: textDictionary) let animatorDictionaries: [[String: Any]] = try containerDictionary.value(for: TextCodingKeys.animators) animators = try animatorDictionaries.map { try TextAnimator(dictionary: $0) } try super.init(dictionary: dictionary) } // MARK: Internal /// The text for the layer let text: KeyframeGroup<TextDocument> /// Text animators let animators: [TextAnimator] override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) var textContainer = container.nestedContainer(keyedBy: TextCodingKeys.self, forKey: .textGroup) try textContainer.encode(text, forKey: .text) try textContainer.encode(animators, forKey: .animators) } // MARK: Private private enum CodingKeys: String, CodingKey { case textGroup = "t" } private enum TextCodingKeys: String, CodingKey { case text = "d" case animators = "a" } }
apache-2.0
519591f50305bf7eaf469899dc1d60d1
31.810345
108
0.727273
4.074946
false
false
false
false
cocoascientist/Luna
Luna/Types & Extensions/CLLocationManager+Combine.swift
1
2078
// // CLLocationManager+Combine.swift // Luna // // Created by Andrew Shepard on 8/23/19. // Copyright © 2019 Andrew Shepard. All rights reserved. // import Combine import CoreLocation class LocationManagerSubscription<SubscriberType: Subscriber>: NSObject, CLLocationManagerDelegate, Subscription where SubscriberType.Input == Result<[CLLocation], Error> { private var subscriber: SubscriberType? private let locationManager: CLLocationManager init(subscriber: SubscriberType, locationManager: CLLocationManager) { self.subscriber = subscriber self.locationManager = locationManager super.init() locationManager.delegate = self locationManager.startUpdatingLocation() } func request(_ demand: Subscribers.Demand) { // No need to handle `demand` because events are sent when they occur } func cancel() { subscriber = nil } // MARK: <CLLocationManagerDelegate> @objc func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { _ = subscriber?.receive(.failure(error)) } @objc func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { _ = subscriber?.receive(.success(locations)) } } struct LocationPublisher: Publisher { typealias Output = Result<[CLLocation], Error> typealias Failure = Never private let locationManager: CLLocationManager init(locationManager: CLLocationManager = CLLocationManager()) { self.locationManager = locationManager } func receive<S>(subscriber: S) where S : Subscriber, LocationPublisher.Failure == S.Failure, LocationPublisher.Output == S.Input { let subscription = LocationManagerSubscription(subscriber: subscriber, locationManager: locationManager) subscriber.receive(subscription: subscription) } } extension CLLocationManager { func publisher() -> LocationPublisher { return LocationPublisher(locationManager: self) } }
mit
c0c5c3a5fb5251c98282aee4d8b7b965
30.953846
172
0.70053
5.465789
false
false
false
false
drmohundro/Nimble
Nimble/Matchers/BeLessThanOrEqual.swift
1
1439
import Foundation public func beLessThanOrEqualTo<T: Comparable>(expectedValue: T?) -> MatcherFunc<T?> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be less than or equal to <\(expectedValue)>" return actualExpression.evaluate() <= expectedValue } } public func beLessThanOrEqualTo<T: NMBComparable>(expectedValue: T?) -> MatcherFunc<T?> { return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be less than or equal to <\(expectedValue)>" let actualValue = actualExpression.evaluate() return actualValue.hasValue && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedDescending } } public func <=<T: Comparable>(lhs: Expectation<T?>, rhs: T) -> Bool { lhs.to(beLessThanOrEqualTo(rhs)) return true } public func <=<T: NMBComparable>(lhs: Expectation<T?>, rhs: T) -> Bool { lhs.to(beLessThanOrEqualTo(rhs)) return true } extension NMBObjCMatcher { public class func beLessThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher { return NMBObjCMatcher { actualBlock, failureMessage, location in let block = ({ actualBlock() as NMBComparable? }) let expr = Expression(expression: block, location: location) return beLessThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage) } } }
apache-2.0
7686b415332a41e5fdb50e4691761f7f
38.972222
118
0.706741
5.084806
false
false
false
false
TTVS/NightOut
Clubber/CCInfoViewController.swift
1
1871
// // CCInfoViewController.swift // Clubber // // Created by Terra on 9/7/15. // Copyright (c) 2015 Dino Media Asia. All rights reserved. // import UIKit class CCInfoViewController: UIViewController { // swipe to go back let swipeBack = UISwipeGestureRecognizer() @IBAction func back(sender: AnyObject) { if((self.presentingViewController) != nil){ self.dismissViewControllerAnimated(true, completion: nil) NSLog("back") } } @IBOutlet var cancelButton: UIButton! @IBAction func cancelButtonPressed(sender: AnyObject) { if((self.presentingViewController) != nil){ self.dismissViewControllerAnimated(true, completion: nil) NSLog("back") } } @IBOutlet var applyButton: UIButton! @IBAction func applyButtonPressed(sender: AnyObject) { if((self.presentingViewController) != nil){ self.dismissViewControllerAnimated(true, completion: nil) NSLog("back") } } override func viewDidLoad() { super.viewDidLoad() self.applyButton.layer.cornerRadius = 3 self.cancelButton.layer.cornerRadius = 3 // swipe to go back swipeBack.direction = UISwipeGestureRecognizerDirection.Right swipeBack.addTarget(self, action: "swipeBack:") self.view.addGestureRecognizer(swipeBack) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Swipe to go Back Gesture func swipeBack(sender: UISwipeGestureRecognizer) { if((self.presentingViewController) != nil){ self.dismissViewControllerAnimated(true, completion: nil) NSLog("back") } } }
apache-2.0
9df3b59ed79066695ecc2d7352881050
25.728571
69
0.623196
5.226257
false
false
false
false
hooman/swift
stdlib/public/Concurrency/AsyncThrowingPrefixWhileSequence.swift
3
5055
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.5, *) extension AsyncSequence { /// Returns an asynchronous sequence, containing the initial, consecutive /// elements of the base sequence that satisfy the given error-throwing /// predicate. /// /// Use `prefix(while:)` to produce values while elements from the base /// sequence meet a condition you specify. The modified sequence ends when /// the predicate closure returns `false` or throws an error. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `prefix(_:)` method causes the modified /// sequence to pass through values less than `8`, but throws an /// error when it receives a value that's divisible by `5`: /// /// do { /// let stream = try Counter(howHigh: 10) /// .prefix { /// if $0 % 5 == 0 { /// throw MyError() /// } /// return $0 < 8 /// } /// for try await number in stream { /// print("\(number) ", terminator: " ") /// } /// } catch { /// print("Error: \(error)") /// } /// // Prints: 1 2 3 4 Error: MyError() /// /// - Parameter isIncluded: A error-throwing closure that takes an element of /// the asynchronous sequence as its argument and returns a Boolean value /// that indicates whether to include the element in the modified sequence. /// - Returns: An asynchronous sequence that contains, in order, the elements /// of the base sequence that satisfy the given predicate. If the predicate /// throws an error, the sequence contains only values produced prior to /// the error. @inlinable public __consuming func prefix( while predicate: @escaping (Element) async throws -> Bool ) rethrows -> AsyncThrowingPrefixWhileSequence<Self> { return AsyncThrowingPrefixWhileSequence(self, predicate: predicate) } } /// An asynchronous sequence, containing the initial, consecutive /// elements of the base sequence that satisfy the given error-throwing /// predicate. @available(SwiftStdlib 5.5, *) @frozen public struct AsyncThrowingPrefixWhileSequence<Base: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let predicate: (Base.Element) async throws -> Bool @inlinable init( _ base: Base, predicate: @escaping (Base.Element) async throws -> Bool ) { self.base = base self.predicate = predicate } } @available(SwiftStdlib 5.5, *) extension AsyncThrowingPrefixWhileSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The prefix-while sequence produces whatever type of element its base /// iterator produces. public typealias Element = Base.Element /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the prefix-while sequence. @frozen public struct Iterator: AsyncIteratorProtocol { @usableFromInline var predicateHasFailed = false @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline let predicate: (Base.Element) async throws -> Bool @inlinable init( _ baseIterator: Base.AsyncIterator, predicate: @escaping (Base.Element) async throws -> Bool ) { self.baseIterator = baseIterator self.predicate = predicate } /// Produces the next element in the prefix-while sequence. /// /// If the predicate hasn't failed yet, this method gets the next element /// from the base sequence and calls the predicate with it. If this call /// succeeds, this method passes along the element. Otherwise, it returns /// `nil`, ending the sequence. If calling the predicate closure throws an /// error, the sequence ends and `next()` rethrows the error. @inlinable public mutating func next() async throws -> Base.Element? { if !predicateHasFailed, let nextElement = try await baseIterator.next() { do { if try await predicate(nextElement) { return nextElement } else { predicateHasFailed = true } } catch { predicateHasFailed = true throw error } } return nil } } @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), predicate: predicate) } }
apache-2.0
1a14acc8bcf2194f956251172fa754ac
34.34965
80
0.638378
4.851248
false
false
false
false
jeevatkm/FrameworkBenchmarks
frameworks/Swift/kitura/Sources/KueryPostgresRaw/PostgresRaw.swift
1
8022
/* * Copyright IBM Corporation 2018 * * 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 LoggerAPI import SwiftKuery import KueryPostgres import TechEmpowerCommon let dbRows = 10000 let maxValue = 10000 // Kuery table definition for World class World: Table { let tableName = "world" let id = Column("id") let randomNumber = Column("randomnumber") } // Kuery table definition for Fortune class Fortunes: Table { let tableName = "fortune" let id = Column("id") let message = Column("message") } let world = World() let fortunes = Fortunes() // Kuery update statement for Updates var update = Update(world, set: [(world.randomNumber, RandomRow.randomValue)]) .where(world.id == RandomRow.randomId) /// Get a list of Fortunes from the database. /// /// - Parameter callback: The callback that will be invoked once the DB query /// has completed and results are available, passing an /// optional [Fortune] (on success) or AppError on /// failure. /// public func getFortunes(callback: @escaping ([Fortune]?, AppError?) -> Void) -> Void { // Get a dedicated connection object for this transaction from the pool guard let dbConn = dbConnPool.getConnection() else { return callback(nil, AppError.OtherError("Timed out waiting for a DB connection from the pool")) } // Initiate database query let query = Select(from: fortunes) dbConn.execute(query: query) { result in var resultFortunes: [Fortune]? = nil guard let rows = result.asRows, result.success else { return callback(nil, AppError.DBKueryError("Query failed: \(String(describing: result.asError))")) } do { resultFortunes = try rows.map { try Fortune.init(row: $0) } } catch { return callback(nil, AppError.DataFormatError("\(error)")) } // Invoke callback with results callback(resultFortunes, nil) } } /// Get a random row (range 1 to 10,000) from the database. /// /// - Parameter callback: The callback that will be invoked once the DB query /// has completed and results are available, passing an /// optional RandomRow (on success) or AppError on /// failure. /// public func getRandomRow_Raw(callback: @escaping (RandomRow?, AppError?) -> Void) -> Void { // Get a dedicated connection object for this transaction from the pool guard let dbConn = dbConnPool.getConnection() else { return callback(nil, AppError.OtherError("Timed out waiting for a DB connection from the pool")) } // Select random row from database range let rnd = RandomRow.randomId let query = Select(world.randomNumber, from: world) .where(world.id == rnd) // Initiate database query dbConn.execute(query: query) { result in var resultRow: RandomRow? = nil guard let resultSet = result.asResultSet, result.success else { return callback(nil, AppError.DBKueryError("Query failed: \(String(describing: result.asError))")) } for row in resultSet.rows { for value in row { guard let value = value else { return callback(nil, AppError.DBKueryError("Error: randomNumber value is nil")) } guard let randomNumber = value as? Int32 else { return callback(nil, AppError.DBKueryError("Error: could not convert \(value) to Int32")) } resultRow = RandomRow(id: rnd, randomNumber: Int(randomNumber)) } } // Invoke callback with results callback(resultRow, nil) } } /// Updates a row of World to a new value. /// /// - Parameter callback: The callback that will be invoked once the DB update /// has completed, passing an optional AppError if the /// update failed. /// public func updateRow_Raw(id: Int, callback: @escaping (AppError?) -> Void) -> Void { // Get a dedicated connection object for this transaction from the pool guard let dbConn = dbConnPool.getConnection() else { return callback(AppError.OtherError("Timed out waiting for a DB connection from the pool")) } // Generate a random number for this row let rndValue = RandomRow.randomValue let query = Update(world, set: [(world.randomNumber, rndValue)]) .where(world.id == id) // Initiate database query dbConn.execute(query: query) { result in guard result.success else { return callback(AppError.DBKueryError("Update failed: \(String(describing: result.asError))")) } // Invoke callback once done callback(nil) } } /// Get `count` random rows from the database, and pass the resulting array /// to a completion handler (or an AppError, in the event that a row could /// not be retrieved). /// /// - Parameter count: The number of rows to retrieve /// - Parameter result: The intermediate result array being built /// - Parameter completion: The closure to invoke with the result array, or error /// public func getRandomRows_Raw(count: Int, result: [RandomRow] = [], completion: @escaping ([RandomRow]?, AppError?) -> Void) { if count > 0 { // Select random row from database range getRandomRow_Raw { (resultRow, err) in if let resultRow = resultRow { var result = result result.append(resultRow) // Call recursively to get remaining rows getRandomRows_Raw(count: count-1, result: result, completion: completion) } else { if let err = err { completion(nil, err) } else { fatalError("Unexpected: result and error both nil") } } } } else { completion(result, nil) } } /// Update and retrieve `count` random rows from the database, and pass the /// resulting array to a completion handler (or an AppError, in the event /// that a row could not be retrieved or updated). /// /// - Parameter count: The number of rows to retrieve /// - Parameter result: The intermediate result array being built /// - Parameter completion: The closure to invoke with the result array, or error /// public func updateRandomRows_Raw(count: Int, result: [RandomRow] = [], completion: @escaping ([RandomRow]?, AppError?) -> Void) { if count > 0 { // Select random row from database range getRandomRow_Raw { (resultRow, err) in if let resultRow = resultRow { var result = result // Execute inner callback for updating the row updateRow_Raw(id: resultRow.id) { (err) in if let err = err { return completion(nil, err) } result.append(resultRow) // Call recursively to update remaining rows updateRandomRows_Raw(count: count-1, result: result, completion: completion) } } else { if let err = err { completion(nil, err) } else { fatalError("Unexpected: result and error both nil") } } } } else { completion(result, nil) } }
bsd-3-clause
4c36e0c11a5b5cd8097b870719008807
37.753623
129
0.616928
4.527088
false
false
false
false
k0nserv/SwiftTracer-Core
Sources/Misc/Scene.swift
1
909
// // Scene.swift // SwiftTracer // // Created by Hugo Tunius on 09/08/15. // Copyright © 2015 Hugo Tunius. All rights reserved. // public class Scene { public let objects: [Shape] public let lights: [PointLight] public let clearColor: Color public init(objects: [Shape], lights: [PointLight], clearColor: Color) { self.objects = objects self.lights = lights self.clearColor = clearColor } public func intersecting(ray: Ray) -> Intersection? { var closestHit: Intersection? for object: Shape in objects { if let hit = object.intersecting(ray: ray) { if let previousHit = closestHit , hit.t < previousHit.t { closestHit = hit } else if closestHit == nil { closestHit = hit } } } return closestHit } }
mit
cf43e947618ea9707390a3dd54764de9
24.222222
76
0.559471
4.32381
false
false
false
false
anhnc55/fantastic-swift-library
Example/Pods/paper-onboarding/Source/OnboardingContantView/Item/OnboardingContantViewItem.swift
1
4446
// // OnboardingContentViewItem.swift // AnimatedPageView // // Created by Alex K. on 21/04/16. // Copyright © 2016 Alex K. All rights reserved. // import UIKit class OnboardingContentViewItem: UIView { var bottomConstraint: NSLayoutConstraint? var centerConstraint: NSLayoutConstraint? var imageView: UIImageView? var titleLabel: UILabel? var descriptionLabel: UILabel? override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: public extension OnboardingContentViewItem { class func itemOnView(view: UIView) -> OnboardingContentViewItem { let item = Init(OnboardingContentViewItem(frame:CGRect.zero)) { $0.backgroundColor = .clearColor() $0.translatesAutoresizingMaskIntoConstraints = false } view.addSubview(item) // add constraints item >>>- { $0.attribute = .Height $0.constant = 10000 $0.relation = .LessThanOrEqual } for attribute in [NSLayoutAttribute.Leading, NSLayoutAttribute.Trailing] { (view, item) >>>- { $0.attribute = attribute } } for attribute in [NSLayoutAttribute.CenterX, NSLayoutAttribute.CenterY] { (view, item) >>>- { $0.attribute = attribute } } return item } } // MARK: create private extension OnboardingContentViewItem { func commonInit() { let titleLabel = createTitleLabel(self) let descriptionLabel = createDescriptionLabel(self) let imageView = createImage(self) // added constraints centerConstraint = (self, titleLabel, imageView) >>>- { $0.attribute = .Top $0.secondAttribute = .Bottom $0.constant = 50 } (self, descriptionLabel, titleLabel) >>>- { $0.attribute = .Top $0.secondAttribute = .Bottom $0.constant = 10 } self.titleLabel = titleLabel self.descriptionLabel = descriptionLabel self.imageView = imageView } func createTitleLabel(onView: UIView) -> UILabel { let label = Init(createLabel()) { $0.font = UIFont(name: "Nunito-Bold" , size: 36) } onView.addSubview(label) // add constraints label >>>- { $0.attribute = .Height $0.constant = 10000 $0.relation = .LessThanOrEqual } for attribute in [NSLayoutAttribute.CenterX, NSLayoutAttribute.Leading, NSLayoutAttribute.Trailing] { (onView, label) >>>- { $0.attribute = attribute } } return label } func createDescriptionLabel(onView: UIView) -> UILabel { let label = Init(createLabel()) { $0.font = UIFont(name: "OpenSans-Regular" , size: 14) $0.numberOfLines = 0 } onView.addSubview(label) // add constraints label >>>- { $0.attribute = .Height $0.constant = 10000 $0.relation = .LessThanOrEqual } for (attribute, constant) in [(NSLayoutAttribute.Leading, 30), (NSLayoutAttribute.Trailing, -30)] { (onView, label) >>>- { $0.attribute = attribute $0.constant = CGFloat(constant) } } (onView, label) >>>- { $0.attribute = .CenterX } bottomConstraint = (onView, label) >>>- { $0.attribute = .Bottom } return label } func createLabel() -> UILabel { return Init(UILabel(frame: CGRect.zero)) { $0.backgroundColor = .clearColor() $0.translatesAutoresizingMaskIntoConstraints = false $0.textAlignment = .Center $0.textColor = .whiteColor() } } func createImage(onView: UIView) -> UIImageView { let imageView = Init(UIImageView(frame: CGRect.zero)) { $0.contentMode = .ScaleAspectFit $0.translatesAutoresizingMaskIntoConstraints = false } onView.addSubview(imageView) // add constratints for attribute in [NSLayoutAttribute.Width, NSLayoutAttribute.Height] { imageView >>>- { $0.attribute = attribute $0.constant = 188 } } for attribute in [NSLayoutAttribute.CenterX, NSLayoutAttribute.Top] { (onView, imageView) >>>- { $0.attribute = attribute } } return imageView } }
mit
1cd30316c1adf251161406062adff8a6
25
105
0.596625
4.531091
false
false
false
false
jngd/advanced-ios10-training
T9E01/T9E01/AppDelegate.swift
1
2312
/** * Copyright (c) 2016 Juan Garcia * * 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 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { print(userActivity.contentAttributeSet?.title) //nil print(userActivity.isEligibleForSearch) let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController : UINavigationController = mainStoryboardIpad.instantiateViewController(withIdentifier: "MainViewController") as! UINavigationController self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = initialViewController self.window?.makeKeyAndVisible() // let viewController = self.window?.rootViewController!.storyboard?.instantiateViewControllerWithIdentifier("RecipeViewController") as! RecipeViewController // // viewController.recipeImageURL = celda["imagen"] as? String // viewController.recipeNameText = celda["nombre"] as? String // viewController.recipeDescriptionText = celda["descripcion"] as? String // initialViewController.pushViewController(viewController, animated: true) return true } }
apache-2.0
61f9b560a7d107e2de355e459f2af95f
44.333333
164
0.78763
4.708758
false
false
false
false
hyperoslo/Orchestra
Example/OrchestraDemo/OrchestraDemo/Sources/Controllers/ProjectDetailController.swift
1
2788
import UIKit import Cartography import Imaginary import Hue class ProjectDetailController: UIViewController { let project: Project lazy var scrollView: UIScrollView = { let scrollView = UIScrollView(frame: CGRectZero) scrollView.alwaysBounceVertical = true return scrollView }() lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .ScaleAspectFit return imageView }() lazy var infoLabel: UILabel = { let label = UILabel() label.textAlignment = .Center label.textColor = UIColor.hex("999") label.font = UIFont.systemFontOfSize(18) label.numberOfLines = 0 return label }() lazy var button: UIButton = { [unowned self] in let button = UIButton(type: .System) button.backgroundColor = UIColor.hex("F57D2D") button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.titleLabel?.font = UIFont.systemFontOfSize(18) button.setTitle(NSLocalizedString("View on GitHub", comment: "").uppercaseString, forState: .Normal) button.addTarget(self, action: "buttonDidPress", forControlEvents: .TouchUpInside) return button }() // MARK: - Initializers required init(project: Project) { self.project = project super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() title = project.name view.backgroundColor = UIColor.whiteColor() view.addSubview(scrollView) [imageView, infoLabel, button].forEach { scrollView.addSubview($0) } imageView.setImage(project.imageURL) infoLabel.text = project.info configureConstrains() } // MARK: - Configuration func configureConstrains() { infoLabel.sizeToFit() constrain(scrollView) { scrollView in scrollView.edges == scrollView.superview!.edges } constrain(imageView, infoLabel, button) { imageView, infoLabel, button in let superview = imageView.superview! imageView.top == superview.top + 15 imageView.centerX == superview.centerX imageView.width == 300 imageView.height == 150 infoLabel.top == imageView.bottom + 30 infoLabel.left == imageView.left infoLabel.right == imageView.right button.top == infoLabel.bottom + 40 button.centerX == superview.centerX button.width == 200 button.height == 50 } view.layoutIfNeeded() scrollView.contentSize = CGSize( width: view.frame.width, height: button.frame.maxY + 20) } // MARK: - Actions func buttonDidPress() { UIApplication.sharedApplication().openURL(project.githubURL) } }
mit
d6e62a1cc7277ea8e6db7f8cf0f4f0e2
23.034483
86
0.680775
4.654424
false
false
false
false
SmallPlanetSwift/Saturn
Source/TypeExtensions/UIView+String.swift
1
1455
// // UIView+String.swift // Saturn // // Created by Quinn McHenry on 11/16/15. // Copyright © 2015 Small Planet. All rights reserved. // extension UIViewContentMode: StringLiteralConvertible { public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public typealias UnicodeScalarLiteralType = Character public init(stringLiteral value: String) { switch value.lowercaseString { case "scaletofill": self = ScaleToFill case "scaleaspectfit": self = ScaleAspectFit case "scaleaspectfill": self = ScaleAspectFill case "redraw": self = Redraw case "center": self = Center case "top": self = Top case "bottom": self = Bottom case "left": self = Left case "right": self = Right case "topleft": self = TopLeft case "topright": self = TopRight case "bottomleft": self = BottomLeft case "bottomright": self = BottomRight default: self = Center } } public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(stringLiteral: "\(value)") } }
mit
e7f9c8101bb8e99864749369fe0190a5
25.925926
91
0.577717
5.249097
false
false
false
false
abdullah-chhatra/iLayout
Example/Example/ViewController.swift
1
3855
// // ViewController.swift // Example // // Created by Abdulmunaf Chhatra on 5/25/15. // Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved. // import UIKit import iLayout class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let CELLID = "Cellid" let options = [ "Pin to egde/margin of Superview", "Set dimentions", "Relative dimensions", "Placement and Alignment", "Fill superview", "Vertical Lineaer Layout", "Horizontal Lineaer Layout", "Auto adjust Vertical Scroll View", "Auto adjust Horizontal Scroll View"] @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: CELLID) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CELLID, for: indexPath) cell.textLabel?.text = options[(indexPath as NSIndexPath).row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath as NSIndexPath).row { case 0: let vc = ExampleViewController(view: PinSuverviewView(), titleText: options[indexPath.row]) navigationController?.pushViewController(vc, animated: true) break case 1: let vc = ExampleViewController(view: SetDimensionsView(), titleText: options[indexPath.row]) navigationController?.pushViewController(vc, animated: true) break case 2: let vc = ExampleViewController(view: RelativeDimensionView(), titleText: options[indexPath.row]) navigationController?.pushViewController(vc, animated: true) break case 3: let vc = ExampleViewController(view: PlacementView(), titleText: options[indexPath.row]) navigationController?.pushViewController(vc, animated: true) break case 4: let vc = ExampleViewController(view: FillSuperviewView(), titleText: options[indexPath.row]) navigationController?.pushViewController(vc, animated: true) break case 5: let vc = storyboard?.instantiateViewController(withIdentifier: "LayoutViewController") as! LayoutViewController vc.layoutProvider = VerticalLayoutProvider() navigationController?.pushViewController(vc, animated: true) break case 6: let vc = storyboard?.instantiateViewController(withIdentifier: "LayoutViewController") as! LayoutViewController vc.layoutProvider = HorizontalLayoutProvider() navigationController?.pushViewController(vc, animated: true) break case 7: let vc = storyboard?.instantiateViewController(withIdentifier: "LayoutViewController") as! LayoutViewController vc.layoutProvider = AutoScrollVerticalLayoutProvider() navigationController?.pushViewController(vc, animated: true) break case 8: let vc = storyboard?.instantiateViewController(withIdentifier: "LayoutViewController") as! LayoutViewController vc.layoutProvider = AutoScrollHorizontalLayoutProvider() navigationController?.pushViewController(vc, animated: true) break default: break } } }
mit
6cb0770556cb302abff352b9d818e35c
37.168317
123
0.63476
5.77961
false
false
false
false
snepo/ios-networking
ios-garment-manager/GarmentManager/GarmentManager/ActiveGarment.swift
1
2572
// // ActiveGarment.swift // nadix // // Created by james on 30/3/17. // Copyright © 2017 Snepo. All rights reserved. // import Foundation import FocusMotion protocol ActiveGarmentDelegate { func activeGarment(_ activeGarment:ActiveGarment, didChangeType type:GarmentType) } struct AccelerometerReading { var x: Int16 var y: Int16 var z: Int16 } enum PantsSection : Int{ case waist = 0 case upperLeft = 1 case upperRight = 2 case lowerLeft = 3 case lowerRight = 4 static let allSections = [waist, upperLeft, upperRight, lowerLeft, lowerRight] } enum TopSection : Int { case middle = 0 case left = 1 case right = 2 static let allSections = [middle, left, right] } enum GarmentTypeMaxIndex : Int { case top = 2 case pants = 4 } class ActiveGarment { var delegate : ActiveGarmentDelegate? var startDate:Date var fmDeviceOutput: FMDeviceOutput var garment : Garment? var garmentType : GarmentType { if let g = garment, let resolvedType = GarmentType(rawValue:g.type) { return resolvedType } return .unknown } var sensors: [Int8:AccelerometerReading] = [:] var (maxActiveIndex, maxIndexUpdate) : (Int8?, Date?) var isPlayingSong = false init(_ garment:Garment) { self.garment = garment garment.type = GarmentType.unknown.rawValue startDate = Date() //reset when garment type discovered fmDeviceOutput = FMDeviceOutput.init(numAccel: 5, numGyro: 0, numMag: 0) } func updateGarmentType() -> GarmentType { var garmentType:GarmentType = .unknown //if just lost sensor count if maxIndexUpdate != nil, // had a max update Date().timeIntervalSince(maxIndexUpdate!) > 2.0 { //was over 2s ago //reset max flags (maxActiveIndex, maxIndexUpdate) = (nil, nil) garmentType = .unknown } else if maxActiveIndex == Int8(GarmentTypeMaxIndex.pants.rawValue) { garmentType = .pants } //print("currentType: \(garment?.type), detectedType: \(garmentType.rawValue)") //check if changed if let g = garment, g.type != garmentType.rawValue { if garmentType != .unknown { //clear old sensor data fmDeviceOutput.clear() startDate = Date() } garment?.type = garmentType.rawValue delegate?.activeGarment(self, didChangeType: garmentType) } return garmentType } }
mit
91957a3cba93d49a9ea04b37e8ad81d0
26.645161
87
0.625049
3.925191
false
false
false
false
Mattmlm/codepathgithubrepofinder
GithubDemo/GithubRepo.swift
1
3223
// // GithubRepo.swift // GithubDemo // // Created by Nhan Nguyen on 5/12/15. // Copyright (c) 2015 codepath. All rights reserved. // import Foundation import AFNetworking private let reposUrl = "https://api.github.com/search/repositories" private let clientId: String? = nil private let clientSecret: String? = nil class GithubRepo: CustomStringConvertible { var name: String? var ownerHandle: String? var ownerAvatarURL: String? var stars: Int? var forks: Int? var repoDescription: String? init(jsonResult: NSDictionary) { if let name = jsonResult["name"] as? String { self.name = name } if let stars = jsonResult["stargazers_count"] as? Int? { self.stars = stars } if let forks = jsonResult["forks_count"] as? Int? { self.forks = forks } if let owner = jsonResult["owner"] as? NSDictionary { if let ownerHandle = owner["login"] as? String { self.ownerHandle = ownerHandle } if let ownerAvatarURL = owner["avatar_url"] as? String { self.ownerAvatarURL = ownerAvatarURL } } if let repoDescription = jsonResult["description"] as? String { self.repoDescription = repoDescription } } class func fetchRepos(settings: GithubRepoSearchSettings, successCallback: ([GithubRepo]) -> Void, error: ((NSError?) -> Void)?) { let manager = AFHTTPRequestOperationManager() let params = queryParamsWithSettings(settings); manager.GET(reposUrl, parameters: params, success: { (operation ,responseObject) -> Void in if let results = responseObject["items"] as? NSArray { var repos: [GithubRepo] = [] for result in results as! [NSDictionary] { repos.append(GithubRepo(jsonResult: result)) } successCallback(repos) } }, failure: { (operation, requestError) -> Void in if let errorCallback = error { errorCallback(requestError) } }) } private class func queryParamsWithSettings(settings: GithubRepoSearchSettings) -> [String: String] { var params: [String:String] = [:]; if let clientId = clientId { params["client_id"] = clientId; } if let clientSecret = clientSecret { params["client_secret"] = clientSecret; } var q = ""; if let searchString = settings.searchString { q = q + searchString; } q = q + " stars:>\(settings.minStars)"; params["q"] = q; params["sort"] = "stars"; params["order"] = "desc"; return params; } var description: String { return "[Name: \(self.name!)]" + "\n\t[Stars: \(self.stars!)]" + "\n\t[Forks: \(self.forks!)]" + "\n\t[Owner: \(self.ownerHandle!)]" + "\n\t[Avatar: \(self.ownerAvatarURL!)]" + "\n\t[Description: \(self.repoDescription!)]" } }
mit
5b5164e7506cc7bd580293625659926c
30.300971
134
0.546075
4.624103
false
false
false
false
evgenyneu/JsonSwiftson
JsonSwiftsonTests/optionalArrayWithClosure.swift
1
1470
// // Map an optional array with a closure using `optional: true` parameter. // If the value is null the mapping is considered successful. // // Examples // ------- // // [ { "planet": "Saturn" }, { "planet": "Moon" } ] // null // import UIKit import XCTest import JsonSwiftson class optionalArrayWithClosureTests: XCTestCase { func testOptionalArrayWithClosure() { let p = JsonSwiftson(json: "[ { \"planet\": \"Saturn\" }, { \"planet\": \"Moon\" } ]") let result: [String]? = p.mapArrayOfObjects(optional: true) { m in m["planet"].map() ?? "✋" } XCTAssert(p.ok) XCTAssertEqual(["Saturn", "Moon"], result!) } func testOptionalArrayWithClosure_null() { let p = JsonSwiftson(json: "null") let result: [String]? = p.mapArrayOfObjects(optional: true) { m in m["planet"].map() ?? "✋" } XCTAssert(p.ok) XCTAssert(result == nil) } // ----- errors ----- func testError_optionalArrayWithClosure_wrongType() { let p = JsonSwiftson(json: "234") let result: [String]? = p.mapArrayOfObjects(optional: true) { m in m["planet"].map() ?? "✋" } XCTAssertFalse(p.ok) XCTAssert(result == nil) } func testError_optionalArrayWithClosure_incorrectJson() { let p = JsonSwiftson(json: "{ incorrect") let result: [String]? = p.mapArrayOfObjects(optional: true) { m in m["planet"].map() ?? "✋" } XCTAssertFalse(p.ok) XCTAssert(result == nil) } }
mit
7518d15d34e339e6c11db0a87e2d210f
22.222222
90
0.605335
3.636816
false
true
false
false
y-hryk/ViewPager
Classes/MenuView.swift
1
21261
// // MenuView.swift // ViewPagerDemo // // Created by yamaguchi on 2016/08/31. // Copyright © 2016年 h.yamaguchi. All rights reserved. // import UIKit public protocol MenuViewDelegate: class { func menuViewDidTapMeunItem(index: Int, direction: UIPageViewControllerNavigationDirection) func menuViewWillBeginDragging(scrollView: UIScrollView) func menuViewDidEndDragging(scrollView: UIScrollView) } open class MenuView: UIView { open weak var delegate: MenuViewDelegate? fileprivate var option = ViewPagerOption() fileprivate var indicatorView: UIView! fileprivate let factor: CGFloat = 4.0 fileprivate var currentIndex: Int = 0 fileprivate var currentOffsetX: CGFloat = 0.0 fileprivate var currentIndicatorPointX: CGFloat = 0.0 fileprivate var contentWidth: CGFloat = 0.0 fileprivate var collectionView : UICollectionView! fileprivate var titles = [String]() fileprivate var indicatorPositionY: CGFloat { if self.option.indicatorType == .line { return self.frame.height - 1.5 } else { return 5 } } fileprivate var indicatorHeight: CGFloat { if self.option.indicatorType == .line { return 1.5 } else { return self.option.menuItemHeight - (5 * 2) } } override init(frame: CGRect) { super.init(frame: frame) self.frame = frame self.setupViews() } init(titles: [String], option: ViewPagerOption) { super.init(frame: CGRect.zero) self.titles = titles self.option = option self.setupViews() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Private fileprivate func setupViews() { self.backgroundColor = self.option.backgroundColor self.indicatorView = UIView() self.indicatorView.frame = CGRect(x: (self.frame.width / 2), y: self.indicatorPositionY, width: 0, height: self.indicatorHeight) self.indicatorView.backgroundColor = self.option.menuItemIndicatorColor self.indicatorView.layer.cornerRadius = self.option.indicatorRadius self.addSubview(self.indicatorView) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) self.collectionView.backgroundColor = UIColor.clear self.collectionView.register(MenuCell.self, forCellWithReuseIdentifier: "MenuCell") self.collectionView.showsHorizontalScrollIndicator = false self.collectionView.alwaysBounceHorizontal = true self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.scrollsToTop = false self.collectionView.isUserInteractionEnabled = true self.addSubview(self.collectionView) let shadowView = UIView() shadowView.backgroundColor = UIColor.lightGray self.addSubview(shadowView) self.collectionView.translatesAutoresizingMaskIntoConstraints = false self.addConstraints([ NSLayoutConstraint(item: self.collectionView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier:1.0, constant: 0), NSLayoutConstraint(item: self.collectionView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: self.collectionView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: self.collectionView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0) ]) shadowView.translatesAutoresizingMaskIntoConstraints = false self.addConstraints([ NSLayoutConstraint(item: shadowView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: shadowView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: shadowView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.5), NSLayoutConstraint(item: shadowView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 0.5) ]) if self.option.pagerType == .segmeted { self.collectionView.bounces = false } } fileprivate func colorToRGBA(color: UIColor) -> ((red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)) { var red: CGFloat = 1.0, green: CGFloat = 1.0, blue: CGFloat = 1.0, alpha: CGFloat = 1.0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return (red: red, green: green, blue: blue, alpha) } fileprivate func changeMenuItemFontColor(ratio: CGFloat, currentIndex: Int, nextIndex: Int ) { let color = self.colorToRGBA(color: self.option.menuItemFontColor) let selectedColor = self.colorToRGBA(color: self.option.menuItemSelectedFontColor) let ratioAbs = fabs(ratio) let currentColor = UIColor(red: color.red * ratioAbs + selectedColor.red * (1.0 - ratioAbs), green: color.green * ratioAbs + selectedColor.green * (1.0 - ratioAbs), blue: color.blue * ratioAbs + selectedColor.blue * (1.0 - ratioAbs), alpha: color.alpha * ratioAbs + selectedColor.alpha * (1.0 - ratioAbs)) let nextColor = UIColor(red: color.red * (1.0 - ratioAbs) + selectedColor.red * ratioAbs, green: color.green * (1.0 - ratioAbs) + selectedColor.green * ratioAbs, blue: color.blue * (1.0 - ratioAbs) + selectedColor.blue * ratioAbs, alpha: color.alpha * (1.0 - ratioAbs) + selectedColor.alpha * ratioAbs) // Current itemFont let currentIndexPath = IndexPath(item: self.option.pagerType.isInfinity() ? currentIndex + self.titles.count : currentIndex, section: 0) if let currentCell = self.collectionView.cellForItem(at: currentIndexPath) as? MenuCell { currentCell.label.textColor = currentColor if ratioAbs < 0.5 { currentCell.label.font = self.option.menuItemSelectedFont } else { currentCell.label.font = self.option.menuItemFont } } // Next ItemFont var nextIndexPath = IndexPath(item: self.option.pagerType.isInfinity() ? nextIndex + self.titles.count : nextIndex, section: 0) if self.option.pagerType.isInfinity() { if currentIndex == self.titles.count - 1 && nextIndex == 0 { nextIndexPath = IndexPath(item: self.titles.count * 2, section: 0) } if nextIndex == self.titles.count - 1 && currentIndex == 0 { nextIndexPath = IndexPath(item: self.titles.count - 1, section: 0) } } if let nextCell = self.collectionView.cellForItem(at: nextIndexPath) as? MenuCell { nextCell.label.textColor = nextColor if ratioAbs > 0.5 { nextCell.label.font = self.option.menuItemSelectedFont } else { nextCell.label.font = self.option.menuItemFont } } } fileprivate func moveMenuItem(indexPath: IndexPath, animated: Bool) { if self.option.pagerType.isInfinity() { // infinity self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: animated) let itemWidth = MenuCell.cellWidth(self.titles[indexPath.row % self.titles.count], option: self.option) if animated { UIView.animate(withDuration: 0.35) { self.indicatorView.frame = CGRect(x: (self.frame.width / 2) - (itemWidth / 2), y: self.indicatorPositionY, width: itemWidth, height: self.indicatorHeight) } } else { self.indicatorView.frame = CGRect(x: (self.frame.width / 2) - (itemWidth / 2), y: self.indicatorPositionY, width: itemWidth, height: self.indicatorHeight) } } else { let scrollWidth = self.collectionView.contentSize.width - self.collectionView.frame.size.width let ratio = CGFloat(self.currentIndex) / CGFloat(self.titles.count - 1) var margin: CGFloat = 0.0 if self.option.pagerType != .segmeted { margin = self.option.menuItemMargin } // indicator var indicatorPointX: CGFloat = 0.0 for (idx, _) in self.titles.enumerated() { if idx <= self.currentIndex && idx != 0 { let itemWidth = MenuCell.cellWidth(self.titles[idx - 1], option: self.option) indicatorPointX = CGFloat(indicatorPointX) + CGFloat(itemWidth) + margin } } indicatorPointX = CGFloat(indicatorPointX) - (scrollWidth * ratio) + margin self.currentIndicatorPointX = CGFloat(indicatorPointX) let itemWidth = MenuCell.cellWidth(self.titles[indexPath.row % self.titles.count], option: self.option) if animated { UIView.animate(withDuration: 0.35) { if self.collectionView.contentSize.width > self.collectionView.frame.size.width { self.collectionView.contentOffset.x = (scrollWidth * ratio) } self.indicatorView.frame = CGRect(x: self.currentIndicatorPointX , y: self.indicatorPositionY, width: itemWidth, height: self.indicatorHeight) } } else { if self.collectionView.contentSize.width > self.collectionView.frame.size.width { self.collectionView.contentOffset.x = (scrollWidth * ratio) } self.indicatorView.frame = CGRect(x: self.currentIndicatorPointX , y: self.indicatorPositionY, width: itemWidth, height: self.indicatorHeight) } } self.currentOffsetX = self.collectionView.contentOffset.x if !animated { self.collectionView.visibleCells.forEach { (cell) in if let cell = cell as? MenuCell { if self.currentIndex % self.titles.count == cell.label.tag % self.titles.count { cell.label.textColor = self.option.menuItemSelectedFontColor cell.label.font = self.option.menuItemSelectedFont cell.indicator.isHidden = false } else { cell.label.textColor = self.option.menuItemFontColor cell.label.font = self.option.menuItemFont cell.indicator.isHidden = true } } } self.indicatorView.isHidden = true } } fileprivate func scrollToMenuItemAtIndexUserTap(indexPath: IndexPath, animated: Bool) { self.updateCollectionViewUserInteractionEnabled(userInteractionEnabled: false) let currentIndex = indexPath.row % self.titles.count if self.currentIndex % self.titles.count != currentIndex { self.indicatorView.isHidden = false self.collectionView.visibleCells.forEach { (cell) in if let cell = cell as? MenuCell { cell.indicator.isHidden = true } } } var direction: UIPageViewControllerNavigationDirection = .forward if ((self.option.pagerType.isInfinity() && indexPath.row < self.titles.count)) || (indexPath.row < self.currentIndex) { direction = .reverse } self.currentIndex = self.option.pagerType.isInfinity() ? currentIndex + self.titles.count : currentIndex self.moveMenuItem(indexPath: indexPath, animated: true) self.delegate?.menuViewDidTapMeunItem(index: currentIndex, direction: direction) } // MARK: Public open func reloadItems() { self.collectionView.reloadData() self.currentIndicatorPointX = 0 self.currentOffsetX = 0 } open func scrollToMenuItemAtIndex(index: Int) { self.currentIndex = self.option.pagerType.isInfinity() ? index + self.titles.count : index let indexPath = IndexPath(item: self.currentIndex, section: 0) self.moveMenuItem(indexPath: indexPath, animated: false) } open func updateMenuItemOffset(currentIndex: Int, nextIndex: Int, offsetX: CGFloat) { self.indicatorView.isHidden = false self.collectionView.visibleCells.forEach { (cell) in if let cell = cell as? MenuCell { cell.indicator.isHidden = true } } if self.currentOffsetX == 0 { self.currentOffsetX = self.collectionView.contentOffset.x } if self.currentIndicatorPointX <= 0 { self.currentIndicatorPointX = 0 } // scroll ratio let ratio = offsetX / self.frame.width if self.option.pagerType.isInfinity() { // infinity let currentItemWidth = MenuCell.cellWidth(self.titles[currentIndex], option: self.option) let nextItemWidth = MenuCell.cellWidth(self.titles[nextIndex], option: self.option) let diffItemWidth = fabs(ratio) * (nextItemWidth - currentItemWidth) let indicatorWidth = currentItemWidth + diffItemWidth self.indicatorView.frame = CGRect(x: (self.frame.width / 2) - (indicatorWidth / 2), y: self.indicatorPositionY, width: indicatorWidth, height: self.indicatorHeight) let itemOffetX = (currentItemWidth / 2.0) + (nextItemWidth / 2.0) let scrollOffsetX = ratio * itemOffetX var margin: CGFloat = 0.0 if self.option.pagerType != .segmeted { margin = self.option.menuItemMargin } self.collectionView.contentOffset.x = self.currentOffsetX + scrollOffsetX + (margin * ratio) } else { if nextIndex >= 0 && nextIndex < self.titles.count { let currentItemWidth = MenuCell.cellWidth(self.titles[currentIndex], option: self.option) let nextItemWidth = MenuCell.cellWidth(self.titles[nextIndex], option: self.option) let diffItemWidth = fabs(ratio) * (nextItemWidth - currentItemWidth) let indicatorWidth = currentItemWidth + diffItemWidth let scrollWidth = self.collectionView.contentSize.width - self.collectionView.frame.size.width var currentScrollWidth = scrollWidth / CGFloat(self.titles.count - 1) // check to scroll collectionView if self.collectionView.contentSize.width > self.collectionView.frame.size.width { self.collectionView.contentOffset.x = (currentScrollWidth * ratio) + self.currentOffsetX; if currentIndex == 0 { self.collectionView.contentOffset.x -= self.currentOffsetX } } else { currentScrollWidth = 0 } let itemWidth = ratio < 0 ? nextItemWidth : currentItemWidth var margin: CGFloat = 0.0 if self.option.pagerType != .segmeted { margin = self.option.menuItemMargin } let indicatorPointX = (itemWidth * ratio) + (margin * ratio) - (currentScrollWidth * ratio) + self.currentIndicatorPointX self.indicatorView.frame = CGRect(x: indicatorPointX , y: self.indicatorPositionY, width: indicatorWidth, height: self.indicatorHeight) } } // menu item animation self.changeMenuItemFontColor(ratio: ratio, currentIndex: currentIndex, nextIndex: nextIndex) } open func updateCollectionViewUserInteractionEnabled(userInteractionEnabled: Bool) { self.collectionView.isUserInteractionEnabled = userInteractionEnabled } } // MARK: UICollectionViewDataSource extension MenuView : UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if self.option.pagerType.isInfinity() { return self.titles.count * Int(self.factor) } return self.titles.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MenuCell", for: indexPath) as! MenuCell cell.setRowData(datas: self.titles, indexPath: indexPath, currentIndex: self.currentIndex, option: self.option) return cell } } // MARK: UICollectionViewDelegate extension MenuView: UICollectionViewDelegate { public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.delegate?.menuViewDidEndDragging(scrollView: scrollView) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { if self.option.pagerType == .segmeted { return 0.0 } return self.option.menuItemMargin } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { if self.option.pagerType == .segmeted { return UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0) } return UIEdgeInsets(top: 0.0, left: self.option.menuItemMargin, bottom: 0.0, right: self.option.menuItemMargin) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let index = (indexPath as NSIndexPath).row % self.titles.count if self.option.pagerType == .segmeted { self.option.menuItemWidth = self.frame.size.width / CGFloat(self.titles.count) } let width = MenuCell.cellWidth(self.titles[index], option: self.option) return CGSize(width: width, height: self.frame.height) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { if self.option.pagerType == .segmeted { return 0.0 } return self.option.menuItemMargin } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.scrollToMenuItemAtIndexUserTap(indexPath: indexPath, animated: true) } } // MARK: UIScrollViewDelegate extension MenuView: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { // print("\(scrollView.contentOffset.x)") if self.option.pagerType.isInfinity() { if self.contentWidth == 0.0 { self.contentWidth = floor(scrollView.contentSize.width / self.factor) } if (scrollView.contentOffset.x <= 0.0) || (scrollView.contentOffset.x > self.contentWidth * 2.0) { scrollView.contentOffset.x = self.contentWidth } } } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.indicatorView.isHidden = true self.collectionView.reloadData() self.delegate?.menuViewWillBeginDragging(scrollView: scrollView) } }
mit
dd5120761f74458c1e53b01c58695c8e
43.195426
187
0.6097
5.139749
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/MercadoPago.swift
1
17121
// // MercadoPago.swift // MercadoPagoSDK // // Created by Matias Gualino on 28/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class MercadoPago : NSObject, UIAlertViewDelegate { public class var PUBLIC_KEY : String { return "public_key" } public class var PRIVATE_KEY : String { return "private_key" } public class var ERROR_KEY_CODE : Int { return -1 } public class var ERROR_API_CODE : Int { return -2 } public class var ERROR_UNKNOWN_CODE : Int { return -3 } public class var ERROR_NOT_INSTALLMENTS_FOUND : Int { return -4 } public class var ERROR_PAYMENT : Int { return -4 } let BIN_LENGTH : Int = 6 let MP_API_BASE_URL : String = "https://api.mercadopago.com" public var privateKey : String? public var publicKey : String? public var paymentMethodId : String? public var paymentTypeId : String? public init (publicKey: String) { self.publicKey = publicKey } static var temporalNav : UINavigationController? public init (keyType: String?, key: String?) { if keyType != nil && key != nil { if keyType != MercadoPago.PUBLIC_KEY && keyType != MercadoPago.PRIVATE_KEY { fatalError("keyType must be 'public_key' or 'private_key'.") } else { if keyType == MercadoPago.PUBLIC_KEY { self.publicKey = key } else if keyType == MercadoPago.PUBLIC_KEY { self.privateKey = key } } } else { fatalError("keyType and key cannot be nil.") } } public class func startCustomerCardsViewController(cards: [Card], callback: (selectedCard: Card?) -> Void) -> CustomerCardsViewController { return CustomerCardsViewController(cards: cards, callback: callback) } public class func startNewCardViewController(keyType: String, key: String, paymentMethod: PaymentMethod, requireSecurityCode: Bool, callback: (cardToken: CardToken) -> Void) -> NewCardViewController { return NewCardViewController(keyType: keyType, key: key, paymentMethod: paymentMethod, requireSecurityCode: requireSecurityCode, callback: callback) } public class func startPaymentMethodsViewController(merchantPublicKey: String, supportedPaymentTypes: [String], callback:(paymentMethod: PaymentMethod) -> Void) -> PaymentMethodsViewController { return PaymentMethodsViewController(merchantPublicKey: merchantPublicKey, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public class func startIssuersViewController(merchantPublicKey: String, paymentMethod: PaymentMethod, callback: (issuer: Issuer) -> Void) -> IssuersViewController { return IssuersViewController(merchantPublicKey: merchantPublicKey, paymentMethod: paymentMethod, callback: callback) } public class func startInstallmentsViewController(payerCosts: [PayerCost], amount: Double, callback: (payerCost: PayerCost?) -> Void) -> InstallmentsViewController { return InstallmentsViewController(payerCosts: payerCosts, amount: amount, callback: callback) } public class func startCongratsViewController(payment: Payment, paymentMethod: PaymentMethod) -> CongratsViewController { return CongratsViewController(payment: payment, paymentMethod: paymentMethod) } public class func startPromosViewController(merchantPublicKey: String) -> PromoViewController { return PromoViewController(publicKey: merchantPublicKey) } public class func startVaultViewController(merchantPublicKey: String, merchantBaseUrl: String?, merchantGetCustomerUri: String?, merchantAccessToken: String?, amount: Double, supportedPaymentTypes: [String], callback: (paymentMethod: PaymentMethod, tokenId: String?, issuerId: NSNumber?, installments: Int) -> Void) -> VaultViewController { return VaultViewController(merchantPublicKey: merchantPublicKey, merchantBaseUrl: merchantBaseUrl, merchantGetCustomerUri: merchantGetCustomerUri, merchantAccessToken: merchantAccessToken, amount: amount, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public func createNewCardToken(cardToken : CardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { cardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, cardToken: cardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func createToken(savedCardToken : SavedCardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { savedCardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, savedCardToken: savedCardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPaymentMethods(success: (paymentMethods: [PaymentMethod]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getPaymentMethods(public_key: self.publicKey!, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { let paymentMethods = jsonResult as? NSArray var pms : [PaymentMethod] = [PaymentMethod]() if paymentMethods != nil { for i in 0..<paymentMethods!.count { if let pmDic = paymentMethods![i] as? NSDictionary { pms.append(PaymentMethod.fromJSON(pmDic)) } } } success(paymentMethods: pms) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIdentificationTypes(success: (identificationTypes: [IdentificationType]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : IdentificationService = IdentificationService(baseURL: MP_API_BASE_URL) service.getIdentificationTypes(public_key: self.publicKey, privateKey: self.privateKey, success: {(jsonResult: AnyObject?) -> Void in if let error = jsonResult as? NSDictionary { if (error["status"]! as? Int) == 404 { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_API_CODE, userInfo: error as [NSObject : AnyObject])) } } } else { let identificationTypesResult = jsonResult as? NSArray? var identificationTypes : [IdentificationType] = [IdentificationType]() if identificationTypesResult != nil { for var i = 0; i < identificationTypesResult!!.count; i++ { if let identificationTypeDic = identificationTypesResult!![i] as? NSDictionary { identificationTypes.append(IdentificationType.fromJSON(identificationTypeDic)) } } } success(identificationTypes: identificationTypes) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getInstallments(bin: String, amount: Double, issuerId: NSNumber?, paymentTypeId: String, success: (installments: [Installment]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getInstallments(public_key: self.publicKey!, bin: bin, amount: amount, issuer_id: issuerId, payment_type_id: paymentTypeId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { let paymentMethods = jsonResult as? NSArray var installments : [Installment] = [Installment]() if paymentMethods != nil && paymentMethods?.count > 0 { if let dic = paymentMethods![0] as? NSDictionary { installments.append(Installment.fromJSON(dic)) } success(installments: installments) } else { let error : NSError = NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_NOT_INSTALLMENTS_FOUND, userInfo: ["message": "NOT_INSTALLMENTS_FOUND".localized + "\(amount)"]) failure?(error: error) } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIssuers(paymentMethodId : String, success: (issuers: [Issuer]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getIssuers(public_key: self.publicKey!, payment_method_id: paymentMethodId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { let issuersArray = jsonResult as? NSArray var issuers : [Issuer] = [Issuer]() if issuersArray != nil { for i in 0..<issuersArray!.count { if let issuerDic = issuersArray![i] as? NSDictionary { issuers.append(Issuer.fromJSON(issuerDic)) } } } success(issuers: issuers) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPromos(success: (promos: [Promo]?) -> Void, failure: ((error: NSError) -> Void)?) { // TODO: Está hecho para MLA fijo porque va a cambiar la URL para que dependa de una API y una public key let service : PromosService = PromosService(baseURL: MP_API_BASE_URL) service.getPromos(public_key: self.publicKey!, success: { (jsonResult) -> Void in let promosArray = jsonResult as? NSArray? var promos : [Promo] = [Promo]() if promosArray != nil { for var i = 0; i < promosArray!!.count; i++ { if let promoDic = promosArray!![i] as? NSDictionary { promos.append(Promo.fromJSON(promoDic)) } } } success(promos: promos) }, failure: failure) } public class func isCardPaymentType(paymentTypeId: String) -> Bool { if paymentTypeId == "credit_card" || paymentTypeId == "debit_card" || paymentTypeId == "prepaid_card" { return true } return false } public class func getBundle() -> NSBundle? { let privatePath : NSString? = NSBundle.mainBundle().privateFrameworksPath if privatePath != nil { let path = privatePath!.stringByAppendingPathComponent("MercadoPagoSDK.framework") return NSBundle(path: path) } return nil } public class func getImage(name: String) -> UIImage? { let bundle = getBundle() if (UIDevice.currentDevice().systemVersion as NSString).compare("8.0", options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending { var nameArr = name.characters.split {$0 == "."}.map(String.init) let imageExtension : String = nameArr[1] let filePath = bundle?.pathForResource(name, ofType: imageExtension) if filePath != nil { return UIImage(contentsOfFile: filePath!) } else { return nil } } if #available(iOS 8.0, *) { return UIImage(named:name, inBundle: bundle, compatibleWithTraitCollection:nil) } else { } return nil } public class func screenBoundsFixedToPortraitOrientation() -> CGRect { let screenSize : CGRect = UIScreen.mainScreen().bounds if NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1 && UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) { return CGRectMake(0.0, 0.0, screenSize.height, screenSize.width) } return screenSize } public class func showAlertViewWithError(error: NSError?, nav: UINavigationController?) { let msgDefault = "An error occurred while processing your request. Please try again." var msg : String? = msgDefault if error != nil { msg = error!.userInfo["message"] as? String } MercadoPago.temporalNav = nav let alert = UIAlertView() alert.title = "MercadoPago Error" alert.delegate = self alert.message = "Error = \(msg != nil ? msg! : msgDefault)" alert.addButtonWithTitle("OK") alert.show() } public func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == 0 { MercadoPago.temporalNav?.popViewControllerAnimated(true) } } }
mit
5a398400f42ab4721fd2832eb45b2417
45.272973
344
0.595678
5.039741
false
false
false
false
kaltura/playkit-ios
Classes/Player/AVAsset/AssetHandler.swift
1
3642
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation import AVFoundation @objc public protocol AssetHandler { init() func build(from mediaSource: PKMediaSource, readyCallback: @escaping (Error?, AVURLAsset?) -> Void) } extension AssetHandler { static func getPreferredMediaSource(from mediaEntry: PKMediaEntry) -> (PKMediaSource, AssetHandler.Type)? { guard let sources = mediaEntry.sources else { PKLog.error("no media sources in mediaEntry!") return nil } let defaultHandler = DefaultAssetHandler.self // Preference: Local, HLS, FPS*, MP4, WVM*, MP3, MOV if let source = sources.first(where: {$0 is LocalMediaSource}) { if source.mediaFormat == .wvm { return (source, DRMSupport.widevineClassicHandler!) } else { return (source, defaultHandler) } } if DRMSupport.fairplay { if let source = sources.first(where: {$0.mediaFormat == .hls}) { return (source, defaultHandler) } } else { if let source = sources.first(where: {$0.mediaFormat == .hls && ($0.drmData == nil || $0.drmData!.isEmpty) }) { return (source, defaultHandler) } } if let source = sources.first(where: {$0.mediaFormat == .mp4}) { return (source, defaultHandler) } if DRMSupport.widevineClassic, let source = sources.first(where: {$0.mediaFormat == .wvm}) { return (source, DRMSupport.widevineClassicHandler!) } if let source = sources.first(where: {$0.mediaFormat == .mp3}) { return (source, defaultHandler) } PKLog.error("no playable media sources!") return nil } } protocol RefreshableAssetHandler: AssetHandler { func shouldRefreshAsset(mediaSource: PKMediaSource, refreshCallback: @escaping (Bool) -> Void) func refreshAsset(mediaSource: PKMediaSource) } enum AssetError : Error { case noFpsCertificate case noLicenseUri case invalidDrmScheme case invalidContentUrl(URL?) case noPlayableSources } class DRMSupport { // FairPlay is not available in simulators and before iOS8 static let fairplay: Bool = { if !Platform.isSimulator, #available(iOS 8, *) { return true } else { return false } }() // FairPlay is not available in simulators and is only downloadable in iOS10 and up. static let fairplayOffline: Bool = { if !Platform.isSimulator, #available(iOS 10, *) { return true } else { return false } }() // Widevine is optional (and not available in simulators) static let widevineClassic = widevineClassicHandler != nil // Preload the Widevine Classic Handler, if available static let widevineClassicHandler: AssetHandler.Type? = { if Platform.isSimulator { return nil } return NSClassFromString("PlayKit.WidevineClassicAssetHandler") as? AssetHandler.Type }() }
agpl-3.0
3fc79c6408bec5f6eeead9e85160b1f1
31.810811
123
0.574684
4.621827
false
false
false
false
mozilla-mobile/firefox-ios
Extensions/ShareTo/UXConstants.swift
2
1624
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit struct UX { static let doneDialogAnimationDuration: TimeInterval = 0.2 static let durationToShowDoneDialog: TimeInterval = UX.doneDialogAnimationDuration + 0.8 static let alphaForFullscreenOverlay: CGFloat = 0.3 static let dialogCornerRadius: CGFloat = 8 static let topViewHeight = 364 static let topViewHeightForSearchMode = 160 static let topViewWidth = 345 static let viewHeightForDoneState = 170 static let pageInfoRowHeight = 64 static let actionRowHeight = 44 static let actionRowSpacingBetweenIconAndTitle: CGFloat = 16 static let actionRowIconSize = 24 static let rowInset: CGFloat = 16 static let pageInfoRowLeftInset = UX.rowInset + 6 static let pageInfoLineSpacing: CGFloat = 2 static let doneLabelFont = UIFont.boldSystemFont(ofSize: 17) static let baseFont = UIFont.systemFont(ofSize: 15) static let navBarLandscapeShrinkage = 10 // iOS automatically shrinks nav bar in compact landscape static let numberOfActionRows = 5 // One more row than this for the page info row. // Small iPhone screens in landscape can only fit 4 rows without resizing the screen. We can fit one more row // by shrinking rows, so this shrinkage code is here if needed. static let enableResizeRowsForSmallScreens = UX.numberOfActionRows > 4 static let perRowShrinkageForLandscape = UX.enableResizeRowsForSmallScreens ? 8 : 0 }
mpl-2.0
cea44bb84ff8c41c4813d07e5970d854
48.212121
113
0.756158
4.523677
false
false
false
false
Praesentia/MedKit-Swift
Source/MeasurementController.swift
1
2611
/* ----------------------------------------------------------------------------- This source file is part of MedKit. Copyright 2017-2018 Jon Griffeth 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 MedKitAssignedNumbers /** Measurement Controller */ public class MeasurementController: ResourceController, ResourceObserver { public typealias Measurement = MeasurementProtocolV1.Measurement // MARK: - Properties public weak var delegate : MeasurementControllerDelegate? public private(set) var measurement : Measurement? // MARK: - Private private typealias MeasurementProtocol = MeasurementProtocolV1 private typealias Notification = MeasurementProtocolV1.Notification // MARK: - Initialiers /** Initialize instance. */ override public init(for resource: Resource) { super.init(for: resource) } // MARK: - ResourceController override public func start() { resource.addObserver(self) { error in self.delegate?.measurementControllerDidStart(self) } } override public func stop() { resource.removeObserver(self) { error in self.delegate?.measurementController(self, didStopForReason: error) } } // MARK: - ResourceObserver /** Resource did notify. - Parameters: - resource: - notification: */ public func resource(_ resource: Resource, didNotify notification: AnyCodable) { do { let container = try notification.decoder.container(keyedBy: Notification.CodingKeys.self) let type = try container.decode(Notification.NotificationType.self, forKey: .type) switch type { case .didUpdate : measurement = try container.decode(Notification.DidUpdate.Args.self, forKey: .args) delegate?.measurementControllerDidUpdate(self) } } catch { } } } // End of File
apache-2.0
4ec3cea72c3188f06dcdc2cbfec98b35
25.917526
101
0.628112
5.201195
false
false
false
false
1457792186/JWSwift
熊猫TV2/XMTV/Classes/Entertainment/ViewModel/OutdoorLivingVM.swift
2
497
// // OutdoorLivingVM.swift // XMTV // // Created by Mac on 2017/1/11. // Copyright © 2017年 Mac. All rights reserved. // import UIKit class OutdoorLivingVM: BaseVM { func requestData(finishedCallback : @escaping () -> ()) { loadAnchorGroupData(isLiveData: true, URLString: "http://api.m.panda.tv/ajax_get_live_list_by_cate?cate=hwzb&pageno=1&pagenum=20&order=person_num&status=2&__version=1.1.7.1305&__plat=ios&__channel=appstore", finishedCallback: finishedCallback) } }
apache-2.0
612ae9395e079b7425e9e0d1fbbf4d5c
31.933333
251
0.700405
3.012195
false
false
false
false
sora0077/iTunesMusic
Demo/Utils/Utils+Reactive.swift
1
3625
// // Utils+Reactive.swift // iTunesMusic // // Created by 林達也 on 2016/08/21. // Copyright © 2016年 jp.sora0077. All rights reserved. // import Foundation import iTunesMusic import RxSwift import RxCocoa func prefetchArtworkURLs<P: Playlist>(size: Int) -> AnyObserver<P> where P: Swift.Collection, P.Iterator.Element == Track { return AnyObserver { on in if case .next(let playlist) = on { let urls = playlist.flatMap { $0.artworkURL(size: size) } DispatchQueue.global(qos: .background).async { prefetchImages(with: urls) } } } } extension ObservableType { func flatMap<T>(_ transform: @escaping (E) -> T?) -> Observable<T> { func notNil(_ val: Any?) -> Bool { return val != nil } return map(transform).filter({ $0 != nil }).map({ $0! }) } } extension Reactive where Base: UIScrollView { func reachedBottom(offsetRatio: CGFloat = 0) -> Observable<Bool> { return contentOffset .map { [weak base=base] contentOffset in guard let scrollView = base else { return false } let visibleHeight = scrollView.frame.height - scrollView.contentInset.top - scrollView.contentInset.bottom let y = contentOffset.y + scrollView.contentInset.top let threshold = max(0.0, scrollView.contentSize.height - visibleHeight - visibleHeight * offsetRatio) return y > threshold } .throttle(0.1, scheduler: MainScheduler.instance) .distinctUntilChanged() } } extension UITableView { private struct UITableViewKey { static var isMoving: UInt8 = 0 } var isMoving: Bool { set { objc_setAssociatedObject(self, &UITableViewKey.isMoving, newValue, .OBJC_ASSOCIATION_ASSIGN) } get { return objc_getAssociatedObject(self, &UITableViewKey.isMoving) as? Bool ?? false } } func performUpdates(deletions: [IndexPath], insertions: [IndexPath], modifications: [IndexPath]) { beginUpdates() if isMoving && deletions.count == insertions.count && modifications.isEmpty { isMoving = false reloadSections(IndexSet(0..<numberOfSections), with: .automatic) } else { if !deletions.isEmpty { deleteRows(at: deletions, with: .automatic) } if !insertions.isEmpty { insertRows(at: insertions, with: .top) } if !modifications.isEmpty { reloadRows(at: modifications, with: .automatic) } } endUpdates() } } extension Reactive where Base: UITableView { func itemUpdates(_ configure: ((_ index: Int) -> (row: Int, section: Int))? = nil) -> AnyObserver<CollectionChange> { return UIBindingObserver(UIElement: base) { tableView, changes in switch changes { case .initial: tableView.reloadData() case let .update(deletions: deletions, insertions: insertions, modifications: modifications): func indexPath(_ i: Int) -> IndexPath { let (row, section) = configure?(i) ?? (i, 0) return IndexPath(row: row, section: section) } tableView.performUpdates( deletions: deletions.map(indexPath), insertions: insertions.map(indexPath), modifications: modifications.map(indexPath) ) } }.asObserver() } }
mit
527e0be25dfe55323a613ebcb537a8c8
33.769231
123
0.583794
4.814913
false
false
false
false
brentdax/swift
test/DebugInfo/typealias.swift
1
1138
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s func markUsed<T>(_ t: T) {} class DWARF { // CHECK-DAG: ![[BASE:.*]] = !DICompositeType({{.*}}identifier: "$ss6UInt32VD" // CHECK-DAG: ![[DIEOFFSET:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s9typealias5DWARFC9DIEOffsetaD",{{.*}} line: [[@LINE+1]], baseType: ![[BASE]]) typealias DIEOffset = UInt32 // CHECK-DAG: ![[VOID:.*]] = !DICompositeType({{.*}}identifier: "$sytD" // CHECK-DAG: ![[PRIVATETYPE:.*]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s9typealias5DWARFC11PrivateType{{.+}}aD",{{.*}} line: [[@LINE+1]], baseType: ![[VOID]]) fileprivate typealias PrivateType = () fileprivate static func usePrivateType() -> PrivateType { return () } } func main () { // CHECK-DAG: !DILocalVariable(name: "a",{{.*}} type: ![[DIEOFFSET]] let a : DWARF.DIEOffset = 123 markUsed(a) // CHECK-DAG: !DILocalVariable(name: "b",{{.*}} type: ![[DIEOFFSET]] let b = DWARF.DIEOffset(456) as DWARF.DIEOffset markUsed(b) // CHECK-DAG: !DILocalVariable(name: "c",{{.*}} type: ![[PRIVATETYPE]] let c = DWARF.usePrivateType() markUsed(c); } main();
apache-2.0
b23fa96b89a2947b74f0fdd68019a3fd
39.642857
169
0.625659
3.356932
false
false
false
false
src256/libswift
libswift/Classes/SwitchCell.swift
1
1384
// // SwitchCell.swift // // // Created by sora on 2016/11/15. // // import UIKit public protocol SwitchCellDelegate : AnyObject { func switchCellChanged(sender: UISwitch) } // UISwitchを内蔵したテーブルセル public class SwitchCell: UITableViewCell { var valueSwitch: UISwitch! weak var delegate: SwitchCellDelegate? override public func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCell.SelectionStyle.none self.valueSwitch = UISwitch() valueSwitch.autoresizingMask = [ .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] valueSwitch.addTarget(self, action: #selector(valueChanged(sender:)), for: .touchUpInside) self.accessoryView = valueSwitch } override public func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } public func configure(title: String, value: Bool) { self.textLabel!.text = title self.valueSwitch.isOn = value } public func setValueFieldDelegate(_ delegate : SwitchCellDelegate) { self.delegate = delegate } @objc public func valueChanged(sender: UISwitch) { if let delegate = delegate { delegate.switchCellChanged(sender: valueSwitch) } } }
mit
cbd6cc76ea5392cfa1317362825fe7b0
26.24
98
0.671806
4.812721
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationsViewController.swift
1
72637
import Foundation import CoreData import CocoaLumberjack import WordPressShared import WordPressAuthenticator import Gridicons /// The purpose of this class is to render the collection of Notifications, associated to the main /// WordPress.com account. /// /// Plus, we provide a simple mechanism to render the details for a specific Notification, /// given its remote identifier. /// class NotificationsViewController: UITableViewController, UIViewControllerRestoration { @objc static let selectedNotificationRestorationIdentifier = "NotificationsSelectedNotificationKey" @objc static let selectedSegmentIndexRestorationIdentifier = "NotificationsSelectedSegmentIndexKey" // MARK: - Properties let formatter = FormattableContentFormatter() /// TableHeader /// @IBOutlet var tableHeaderView: UIView! /// Filtering Tab Bar /// @IBOutlet weak var filterTabBar: FilterTabBar! /// The unified list requires an extra 10pt space on top of the list, but returns to the original padding /// while scrolled and stickied. This should be removed once the unified list is fully rolled out. /// See: https://git.io/JBQlU /// @IBOutlet private weak var filterTabBarBottomConstraint: NSLayoutConstraint! /// Inline Prompt Header View /// @IBOutlet var inlinePromptView: AppFeedbackPromptView! /// TableView Handler: Our commander in chief! /// fileprivate var tableViewHandler: WPTableViewHandler! /// NoResults View /// private let noResultsViewController = NoResultsViewController.controller() /// All of the data will be fetched during the FetchedResultsController init. Prevent overfetching /// fileprivate var lastReloadDate = Date() /// Indicates whether the view is required to reload results on viewWillAppear, or not /// fileprivate var needsReloadResults = false /// Cached values used for returning the estimated row heights of autosizing cells. /// fileprivate let estimatedRowHeightsCache = NSCache<AnyObject, AnyObject>() /// Notifications that must be deleted display an "Undo" button, which simply cancels the deletion task. /// fileprivate var notificationDeletionRequests: [NSManagedObjectID: NotificationDeletionRequest] = [:] /// Notifications being deleted are proactively filtered from the list. /// fileprivate var notificationIdsBeingDeleted = Set<NSManagedObjectID>() /// Notifications that were unread when the list was loaded. /// fileprivate var unreadNotificationIds = Set<NSManagedObjectID>() /// Used to store (and restore) the currently selected filter segment. /// fileprivate var restorableSelectedSegmentIndex: Int = 0 /// Used to keep track of the currently selected notification, /// to restore it between table view reloads and state restoration. /// fileprivate var selectedNotification: Notification? = nil /// JetpackLoginVC being presented. /// internal var jetpackLoginViewController: JetpackLoginViewController? = nil /// Timestamp of the most recent note before updates /// Used to count notifications to show the second notifications prompt /// private var timestampBeforeUpdatesForSecondAlert: String? /// Activity Indicator to be shown when refreshing a Jetpack site status. /// let activityIndicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView(style: .medium) indicator.hidesWhenStopped = true return indicator }() /// Notification Settings button lazy var notificationSettingsButton: UIBarButtonItem = { let button = UIBarButtonItem(image: .gridicon(.cog), style: .plain, target: self, action: #selector(showNotificationSettings)) button.accessibilityLabel = NSLocalizedString("Notification Settings", comment: "Link to Notification Settings section") return button }() /// Convenience property that stores feature flag value for unified list. /// This should be removed once the feature is fully rolled out. private var usesUnifiedList: Bool = FeatureFlag.unifiedCommentsAndNotificationsList.enabled { didSet { // Since this view controller is the root view controller for notifications tab, we need to check whether // the value has changed in `viewWillAppear`. If so, reload the table view to use the correct design. if usesUnifiedList != oldValue { reloadTableViewPreservingSelection() updateFilterBarConstraints() } } } // MARK: - View Lifecycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) restorationClass = NotificationsViewController.self startListeningToAccountNotifications() startListeningToTimeChangeNotifications() } override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupTableView() setupTableFooterView() setupTableHandler() setupRefreshControl() setupNoResultsView() setupFilterBar() tableView.tableHeaderView = tableHeaderView setupConstraints() reloadTableViewPreservingSelection() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupInlinePrompt() // Manually deselect the selected row. if splitViewControllerIsHorizontallyCompact { // This is required due to a bug in iOS7 / iOS8 tableView.deselectSelectedRowWithAnimation(true) selectedNotification = nil } // While we're onscreen, please, update rows with animations tableViewHandler.updateRowAnimation = .fade // Tracking WPAnalytics.track(WPAnalyticsStat.openedNotificationsList) // Notifications startListeningToNotifications() resetApplicationBadge() updateLastSeenTime() // Refresh the UI reloadResultsControllerIfNeeded() if !splitViewControllerIsHorizontallyCompact { reloadTableViewPreservingSelection() } if !AccountHelper.isDotcomAvailable() { promptForJetpackCredentials() } else { jetpackLoginViewController?.view.removeFromSuperview() jetpackLoginViewController?.removeFromParent() } // Refresh feature flag value for unified list. // This should be removed when the feature is fully rolled out. usesUnifiedList = FeatureFlag.unifiedCommentsAndNotificationsList.enabled showNoResultsViewIfNeeded() selectFirstNotificationIfAppropriate() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) syncNewNotifications() markSelectedNotificationAsRead() registerUserActivity() markWelcomeNotificationAsSeenIfNeeded() if userDefaults.notificationsTabAccessCount < Constants.inlineTabAccessCount { userDefaults.notificationsTabAccessCount += 1 } if shouldShowPrimeForPush { setupNotificationPrompt() } else if AppRatingUtility.shared.shouldPromptForAppReview(section: InlinePrompt.section) { setupAppRatings() self.showInlinePrompt() } showNotificationPrimerAlertIfNeeded() showSecondNotificationsAlertIfNeeded() if AppConfiguration.showsWhatIsNew { WPTabBarController.sharedInstance()?.presentWhatIsNew(on: self) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopListeningToNotifications() dismissNoNetworkAlert() // If we're not onscreen, don't use row animations. Otherwise the fade animation might get animated incrementally tableViewHandler.updateRowAnimation = .none } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.layoutHeaderView() } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) DispatchQueue.main.async { self.showNoResultsViewIfNeeded() } if splitViewControllerIsHorizontallyCompact { tableView.deselectSelectedRowWithAnimation(true) } else { if let selectedNotification = selectedNotification { selectRow(for: selectedNotification, animated: true, scrollPosition: .middle) } else { selectFirstNotificationIfAppropriate() } } tableView.tableHeaderView = tableHeaderView } // MARK: - State Restoration static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { return WPTabBarController.sharedInstance().notificationsViewController } override func encodeRestorableState(with coder: NSCoder) { if let uriRepresentation = selectedNotification?.objectID.uriRepresentation() { coder.encode(uriRepresentation, forKey: type(of: self).selectedNotificationRestorationIdentifier) } // If the filter's 'Unread', we won't save it because the notification // that's selected won't be unread any more once we come back to it. let index: Filter = (filter != .unread) ? filter : .none coder.encode(index.rawValue, forKey: type(of: self).selectedSegmentIndexRestorationIdentifier) super.encodeRestorableState(with: coder) } override func decodeRestorableState(with coder: NSCoder) { decodeSelectedSegmentIndex(with: coder) decodeSelectedNotification(with: coder) reloadResultsController() super.decodeRestorableState(with: coder) } fileprivate func decodeSelectedNotification(with coder: NSCoder) { if let uriRepresentation = coder.decodeObject(forKey: type(of: self).selectedNotificationRestorationIdentifier) as? URL { let context = ContextManager.sharedInstance().mainContext if let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: uriRepresentation), let object = try? context.existingObject(with: objectID), let notification = object as? Notification { selectedNotification = notification } } } fileprivate func decodeSelectedSegmentIndex(with coder: NSCoder) { restorableSelectedSegmentIndex = coder.decodeInteger(forKey: type(of: self).selectedSegmentIndexRestorationIdentifier) if let filterTabBar = filterTabBar, filterTabBar.selectedIndex != restorableSelectedSegmentIndex { filterTabBar.setSelectedIndex(restorableSelectedSegmentIndex, animated: false) } } override func applicationFinishedRestoringState() { super.applicationFinishedRestoringState() guard let navigationControllers = navigationController?.children else { return } for case let detailVC as NotificationDetailsViewController in navigationControllers { if detailVC.onDeletionRequestCallback == nil, let note = detailVC.note { configureDetailsViewController(detailVC, withNote: note) } } } // MARK: - UITableView Methods override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sectionInfo = tableViewHandler.resultsController.sections?[section] else { return nil } if usesUnifiedList, let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ListTableHeaderView.defaultReuseID) as? ListTableHeaderView { headerView.title = Notification.descriptionForSectionIdentifier(sectionInfo.name) return headerView } let headerView = NoteTableHeaderView.makeFromNib() headerView.title = Notification.descriptionForSectionIdentifier(sectionInfo.name) headerView.separatorColor = tableView.separatorColor return headerView } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Make sure no SectionFooter is rendered return CGFloat.leastNormalMagnitude } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { // Make sure no SectionFooter is rendered return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = usesUnifiedList ? ListTableViewCell.defaultReuseID : NoteTableViewCell.reuseIdentifier() let expectedType = usesUnifiedList ? ListTableViewCell.self : NoteTableViewCell.self let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) guard type(of: cell) == expectedType else { DDLogError("Error getting Notification table cell.") return .init() } configureCell(cell, at: indexPath) return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { estimatedRowHeightsCache.setObject(cell.frame.height as AnyObject, forKey: indexPath as AnyObject) } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { if let height = estimatedRowHeightsCache.object(forKey: indexPath as AnyObject) as? CGFloat { return height } return Settings.estimatedRowHeight } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Failsafe: Make sure that the Notification (still) exists guard let note = tableViewHandler.resultsController.managedObject(atUnsafe: indexPath) as? Notification else { tableView.deselectSelectedRowWithAnimation(true) return } // Push the Details: Unless the note has a pending deletion! guard deletionRequestForNoteWithID(note.objectID) == nil else { return } selectedNotification = note showDetails(for: note) } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .none } override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // skip when the notification is marked for deletion. guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification, deletionRequestForNoteWithID(note.objectID) == nil else { return nil } let isRead = note.read let title = isRead ? NSLocalizedString("Mark Unread", comment: "Marks a notification as unread") : NSLocalizedString("Mark Read", comment: "Marks a notification as unread") let action = UIContextualAction(style: .normal, title: title, handler: { (action, view, completionHandler) in if isRead { self.markAsUnread(note: note) } else { self.markAsRead(note: note) } completionHandler(true) }) action.backgroundColor = .neutral(.shade50) return UISwipeActionsConfiguration(actions: [action]) } override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // skip when the notification is marked for deletion. guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification, let block: FormattableCommentContent = note.contentGroup(ofKind: .comment)?.blockOfKind(.comment), deletionRequestForNoteWithID(note.objectID) == nil else { return nil } var actions: [UIContextualAction] = [] // Trash comment if let trashAction = block.action(id: TrashCommentAction.actionIdentifier()), let command = trashAction.command, let title = command.actionTitle { let action = UIContextualAction(style: .normal, title: title, handler: { (_, _, completionHandler) in let actionContext = ActionContext(block: block, completion: { [weak self] (request, success) in guard let request = request else { return } self?.showUndeleteForNoteWithID(note.objectID, request: request) }) trashAction.execute(context: actionContext) completionHandler(true) }) action.backgroundColor = command.actionColor actions.append(action) } // Approve comment guard let approveEnabled = block.action(id: ApproveCommentAction.actionIdentifier())?.enabled, approveEnabled == true else { return nil } let approveAction = block.action(id: ApproveCommentAction.actionIdentifier()) if let title = approveAction?.command?.actionTitle { let action = UIContextualAction(style: .normal, title: title, handler: { (_, _, completionHandler) in let actionContext = ActionContext(block: block) approveAction?.execute(context: actionContext) completionHandler(true) }) action.backgroundColor = approveAction?.command?.actionColor actions.append(action) } let configuration = UISwipeActionsConfiguration(actions: actions) configuration.performsFirstActionWithFullSwipe = false return configuration } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let note = sender as? Notification else { return } guard let detailsViewController = segue.destination as? NotificationDetailsViewController else { return } configureDetailsViewController(detailsViewController, withNote: note) } fileprivate func configureDetailsViewController(_ detailsViewController: NotificationDetailsViewController, withNote note: Notification) { detailsViewController.navigationItem.largeTitleDisplayMode = .never detailsViewController.dataSource = self detailsViewController.note = note detailsViewController.onDeletionRequestCallback = { request in self.showUndeleteForNoteWithID(note.objectID, request: request) } detailsViewController.onSelectedNoteChange = { note in self.selectRow(for: note) } } } // MARK: - User Interface Initialization // private extension NotificationsViewController { func setupNavigationBar() { navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .always // Don't show 'Notifications' in the next-view back button // we are using a space character because we need a non-empty string to ensure a smooth // transition back, with large titles enabled. navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) navigationItem.title = NSLocalizedString("Notifications", comment: "Notifications View Controller title") } func updateNavigationItems() { navigationItem.rightBarButtonItem = shouldDisplaySettingsButton ? notificationSettingsButton : nil } @objc func closeNotificationSettings() { dismiss(animated: true, completion: nil) } func setupConstraints() { // Inline prompt is initially hidden! inlinePromptView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tableHeaderView.topAnchor.constraint(equalTo: tableView.topAnchor), tableHeaderView.safeLeadingAnchor.constraint(equalTo: tableView.safeLeadingAnchor), tableHeaderView.safeTrailingAnchor.constraint(equalTo: tableView.safeTrailingAnchor) ]) } func setupTableView() { // Since this view controller is a root view controller for the notifications tab, both `NoteTableViewCell` and the new List components // need to be registered to handle feature flag changes. When the feature is fully rolled out, let's remove NoteTableViewCell. // Register unified list components. tableView.register(ListTableHeaderView.defaultNib, forHeaderFooterViewReuseIdentifier: ListTableHeaderView.defaultReuseID) tableView.register(ListTableViewCell.defaultNib, forCellReuseIdentifier: ListTableViewCell.defaultReuseID) // Register the cells let nib = UINib(nibName: NoteTableViewCell.classNameWithoutNamespaces(), bundle: Bundle.main) tableView.register(nib, forCellReuseIdentifier: NoteTableViewCell.reuseIdentifier()) // UITableView tableView.accessibilityIdentifier = "Notifications Table" tableView.cellLayoutMarginsFollowReadableWidth = false tableView.estimatedSectionHeaderHeight = UITableView.automaticDimension WPStyleGuide.configureAutomaticHeightRows(for: tableView) WPStyleGuide.configureColors(view: view, tableView: tableView) } func setupTableFooterView() { // Fix: Hide the cellSeparators, when the table is empty tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: 1)) } func setupTableHandler() { let handler = WPTableViewHandler(tableView: tableView) handler.cacheRowHeights = false handler.delegate = self tableViewHandler = handler } func setupInlinePrompt() { precondition(inlinePromptView != nil) inlinePromptView.alpha = WPAlphaZero inlinePromptView.isHidden = true } func setupRefreshControl() { let control = UIRefreshControl() control.addTarget(self, action: #selector(refresh), for: .valueChanged) refreshControl = control } func setupNoResultsView() { noResultsViewController.delegate = self } func setupFilterBar() { WPStyleGuide.configureFilterTabBar(filterTabBar) filterTabBar.superview?.backgroundColor = .filterBarBackground filterTabBar.items = Filter.allFilters filterTabBar.addTarget(self, action: #selector(selectedFilterDidChange(_:)), for: .valueChanged) updateFilterBarConstraints() } /// If notifications are displayed with the new unified list, add an extra space below the filter tab bar. /// Once unified list is fully rolled out, this should be applied in Notifications.storyboard instead. /// See: https://git.io/JBQlU func updateFilterBarConstraints() { filterTabBarBottomConstraint.constant = usesUnifiedList ? Constants.filterTabBarBottomSpace : 0 // With the 10pt bottom padding addition, ensure that the extra padding has the same background color // as the table header cell. NOTE: Move this line to `setupFilterBar` once the feature flag is removed. filterTabBar.superview?.backgroundColor = usesUnifiedList ? .systemBackground : .filterBarBackground } } // MARK: - Notifications // private extension NotificationsViewController { func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) nc.addObserver(self, selector: #selector(notificationsWereUpdated), name: NSNotification.Name(rawValue: NotificationSyncMediatorDidUpdateNotifications), object: nil) nc.addObserver(self, selector: #selector(dynamicTypeDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil) } func startListeningToAccountNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(defaultAccountDidChange), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil) } func startListeningToTimeChangeNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(significantTimeChange), name: UIApplication.significantTimeChangeNotification, object: nil) } func stopListeningToNotifications() { let nc = NotificationCenter.default nc.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) nc.removeObserver(self, name: NSNotification.Name(rawValue: NotificationSyncMediatorDidUpdateNotifications), object: nil) } @objc func applicationDidBecomeActive(_ note: Foundation.Notification) { // Let's reset the badge, whenever the app comes back to FG, and this view was upfront! guard isViewLoaded == true && view.window != nil else { return } resetApplicationBadge() updateLastSeenTime() reloadResultsControllerIfNeeded() } @objc func defaultAccountDidChange(_ note: Foundation.Notification) { needsReloadResults = true resetNotifications() resetLastSeenTime() resetApplicationBadge() syncNewNotifications() } @objc func notificationsWereUpdated(_ note: Foundation.Notification) { // If we're onscreen, don't leave the badge updated behind guard UIApplication.shared.applicationState == .active else { return } resetApplicationBadge() updateLastSeenTime() } @objc func significantTimeChange(_ note: Foundation.Notification) { needsReloadResults = true if UIApplication.shared.applicationState == .active && isViewLoaded == true && view.window != nil { reloadResultsControllerIfNeeded() } } @objc func dynamicTypeDidChange() { tableViewHandler.resultsController.fetchedObjects?.forEach { ($0 as? Notification)?.resetCachedAttributes() } } } // MARK: - Public Methods // extension NotificationsViewController { /// Pushes the Details for a given notificationID, immediately, if the notification is already available. /// Otherwise, will attempt to Sync the Notification. If this cannot be achieved before the timeout defined /// by `Syncing.pushMaxWait` kicks in, we'll just do nothing (in order not to disrupt the UX!). /// /// - Parameter notificationID: The ID of the Notification that should be rendered onscreen. /// @objc func showDetailsForNotificationWithID(_ noteId: String) { if let note = loadNotification(with: noteId) { showDetails(for: note) return } syncNotification(with: noteId, timeout: Syncing.pushMaxWait) { note in self.showDetails(for: note) } } /// Pushes the details for a given Notification Instance. /// private func showDetails(for note: Notification) { DDLogInfo("Pushing Notification Details for: [\(note.notificationId)]") // Before trying to show the details of a notification, we need to make sure the view is loaded. // // Ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/12669#issuecomment-561579415 // Ref: https://sentry.io/organizations/a8c/issues/1329631657/ // loadViewIfNeeded() /// Note: markAsRead should be the *first* thing we do. This triggers a context save, and may have many side effects that /// could affect the OP's that go below!!!. /// /// YES figuring that out took me +90 minutes of debugger time!!! /// markAsRead(note: note) trackWillPushDetails(for: note) ensureNotificationsListIsOnscreen() ensureNoteIsNotBeingFiltered(note) selectRow(for: note, animated: false, scrollPosition: .top) // Display Details // if let postID = note.metaPostID, let siteID = note.metaSiteID, note.kind == .matcher || note.kind == .newPost { let readerViewController = ReaderDetailViewController.controllerWithPostID(postID, siteID: siteID) readerViewController.navigationItem.largeTitleDisplayMode = .never showDetailViewController(readerViewController, sender: nil) return } // This dispatch avoids a bug that was occurring occasionally where navigation (nav bar and tab bar) // would be missing entirely when launching the app from the background and presenting a notification. // The issue seems tied to performing a `pop` in `prepareToShowDetails` and presenting // the new detail view controller at the same time. More info: https://github.com/wordpress-mobile/WordPress-iOS/issues/6976 // // Plus: Avoid pushing multiple DetailsViewController's, upon quick & repeated touch events. // view.isUserInteractionEnabled = false DispatchQueue.main.async { self.performSegue(withIdentifier: NotificationDetailsViewController.classNameWithoutNamespaces(), sender: note) self.view.isUserInteractionEnabled = true } } /// Tracks: Details Event! /// private func trackWillPushDetails(for note: Notification) { // Ensure we don't track if the app has been launched by a push notification in the background if UIApplication.shared.applicationState != .background { let properties = [Stats.noteTypeKey: note.type ?? Stats.noteTypeUnknown] WPAnalytics.track(.openedNotificationDetails, withProperties: properties) } } /// Failsafe: Make sure the Notifications List is onscreen! /// private func ensureNotificationsListIsOnscreen() { guard navigationController?.visibleViewController != self else { return } _ = navigationController?.popViewController(animated: false) } /// This method will make sure the Notification that's about to be displayed is not currently being filtered. /// private func ensureNoteIsNotBeingFiltered(_ note: Notification) { guard filter != .none else { return } let noteIndexPath = tableView.indexPathsForVisibleRows?.first { indexPath in return note == tableViewHandler.resultsController.object(at: indexPath) as? Notification } guard noteIndexPath == nil else { return } filter = .none } /// Will display an Undelete button on top of a given notification. /// On timeout, the destructive action (received via parameter) will be exeuted, and the notification /// will (supposedly) get deleted. /// /// - Parameters: /// - noteObjectID: The Core Data ObjectID associated to a given notification. /// - request: A DeletionRequest Struct /// private func showUndeleteForNoteWithID(_ noteObjectID: NSManagedObjectID, request: NotificationDeletionRequest) { // Mark this note as Pending Deletion and Reload notificationDeletionRequests[noteObjectID] = request reloadRowForNotificationWithID(noteObjectID) // Dispatch the Action block perform(#selector(deleteNoteWithID), with: noteObjectID, afterDelay: Syncing.undoTimeout) } /// Presents the Notifications Settings screen. /// @objc func showNotificationSettings() { let controller = NotificationSettingsViewController() controller.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(closeNotificationSettings)) let navigationController = UINavigationController(rootViewController: controller) navigationController.modalPresentationStyle = .formSheet navigationController.modalTransitionStyle = .coverVertical present(navigationController, animated: true, completion: nil) } } // MARK: - Notifications Deletion Mechanism // private extension NotificationsViewController { @objc func deleteNoteWithID(_ noteObjectID: NSManagedObjectID) { // Was the Deletion Canceled? guard let request = deletionRequestForNoteWithID(noteObjectID) else { return } // Hide the Notification notificationIdsBeingDeleted.insert(noteObjectID) reloadResultsController() // Hit the Deletion Action request.action { success in self.notificationDeletionRequests.removeValue(forKey: noteObjectID) self.notificationIdsBeingDeleted.remove(noteObjectID) // Error: let's unhide the row if success == false { self.reloadResultsController() } } } func cancelDeletionRequestForNoteWithID(_ noteObjectID: NSManagedObjectID) { notificationDeletionRequests.removeValue(forKey: noteObjectID) reloadRowForNotificationWithID(noteObjectID) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(deleteNoteWithID), object: noteObjectID) } func deletionRequestForNoteWithID(_ noteObjectID: NSManagedObjectID) -> NotificationDeletionRequest? { return notificationDeletionRequests[noteObjectID] } } // MARK: - Marking as Read // private extension NotificationsViewController { func markSelectedNotificationAsRead() { guard let note = selectedNotification else { return } markAsRead(note: note) } func markAsRead(note: Notification) { guard !note.read else { return } NotificationSyncMediator()?.markAsRead(note) } func markAsUnread(note: Notification) { guard note.read else { return } NotificationSyncMediator()?.markAsUnread(note) } func markWelcomeNotificationAsSeenIfNeeded() { let welcomeNotificationSeenKey = userDefaults.welcomeNotificationSeenKey if !userDefaults.bool(forKey: welcomeNotificationSeenKey) { userDefaults.set(true, forKey: welcomeNotificationSeenKey) resetApplicationBadge() } } } // MARK: - Unread notifications caching // private extension NotificationsViewController { /// Updates the cached list of unread notifications, and optionally reloads the results controller. /// func refreshUnreadNotifications(reloadingResultsController: Bool = true) { guard let notes = tableViewHandler.resultsController.fetchedObjects as? [Notification] else { return } let previous = unreadNotificationIds // This is additive because we don't want to remove anything // from the list unless we explicitly call // clearUnreadNotifications() notes.lazy.filter({ !$0.read }).forEach { note in unreadNotificationIds.insert(note.objectID) } if previous != unreadNotificationIds && reloadingResultsController { reloadResultsController() } } /// Empties the cached list of unread notifications. /// func clearUnreadNotifications() { let shouldReload = !unreadNotificationIds.isEmpty unreadNotificationIds.removeAll() if shouldReload { reloadResultsController() } } } // MARK: - WPTableViewHandler Helpers // private extension NotificationsViewController { func reloadResultsControllerIfNeeded() { // NSFetchedResultsController groups notifications based on a transient property ("sectionIdentifier"). // Simply calling reloadData doesn't make the FRC recalculate the sections. // For that reason, let's force a reload, only when 1 day has elapsed, and sections would have changed. // let daysElapsed = Calendar.current.daysElapsedSinceDate(lastReloadDate) guard daysElapsed != 0 || needsReloadResults else { return } reloadResultsController() } func reloadResultsController() { // Update the Predicate: We can't replace the previous fetchRequest, since it's readonly! let fetchRequest = tableViewHandler.resultsController.fetchRequest fetchRequest.predicate = predicateForFetchRequest() /// Refetch + Reload _ = try? tableViewHandler.resultsController.performFetch() reloadTableViewPreservingSelection() // Empty State? showNoResultsViewIfNeeded() // Don't overwork! lastReloadDate = Date() needsReloadResults = false } func reloadRowForNotificationWithID(_ noteObjectID: NSManagedObjectID) { do { let note = try mainContext.existingObject(with: noteObjectID) if let indexPath = tableViewHandler.resultsController.indexPath(forObject: note) { tableView.reloadRows(at: [indexPath], with: .fade) } } catch { DDLogError("Error refreshing Notification Row \(error)") } } func selectRow(for notification: Notification, animated: Bool = true, scrollPosition: UITableView.ScrollPosition = .none) { selectedNotification = notification if let indexPath = tableViewHandler.resultsController.indexPath(forObject: notification), indexPath != tableView.indexPathForSelectedRow { DDLogInfo("\(self) \(#function) Selecting row at \(indexPath) for Notification: \(notification.notificationId) (\(notification.type ?? "Unknown type")) - \(notification.title ?? "No title")") tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition) } } func reloadTableViewPreservingSelection() { tableView.reloadData() // Show the current selection if our split view isn't collapsed if !splitViewControllerIsHorizontallyCompact, let notification = selectedNotification { selectRow(for: notification, animated: false, scrollPosition: .none) } } } // MARK: - UIRefreshControl Methods // extension NotificationsViewController { @objc func refresh() { guard let mediator = NotificationSyncMediator() else { refreshControl?.endRefreshing() return } let start = Date() mediator.sync { [weak self] (error, _) in let delta = max(Syncing.minimumPullToRefreshDelay + start.timeIntervalSinceNow, 0) let delay = DispatchTime.now() + Double(Int64(delta * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delay) { self?.refreshControl?.endRefreshing() self?.clearUnreadNotifications() if let _ = error { self?.handleConnectionError() } } } } } extension NotificationsViewController: NetworkAwareUI { func contentIsEmpty() -> Bool { return tableViewHandler.resultsController.isEmpty() } func noConnectionMessage() -> String { return NSLocalizedString("No internet connection. Some content may be unavailable while offline.", comment: "Error message shown when the user is browsing Notifications without an internet connection.") } } extension NotificationsViewController: NetworkStatusDelegate { func networkStatusDidChange(active: Bool) { reloadResultsControllerIfNeeded() } } // MARK: - FilterTabBar Methods // extension NotificationsViewController { @objc func selectedFilterDidChange(_ filterBar: FilterTabBar) { selectedNotification = nil let properties = [Stats.selectedFilter: filter.analyticsTitle] WPAnalytics.track(.notificationsTappedSegmentedControl, withProperties: properties) updateUnreadNotificationsForFilterTabChange() reloadResultsController() selectFirstNotificationIfAppropriate() } @objc func selectFirstNotificationIfAppropriate() { guard !splitViewControllerIsHorizontallyCompact && selectedNotification == nil else { return } // If we don't currently have a selected notification and there is a notification in the list, then select it. if let firstNotification = tableViewHandler.resultsController.fetchedObjects?.first as? Notification, let indexPath = tableViewHandler.resultsController.indexPath(forObject: firstNotification) { selectRow(for: firstNotification, animated: false, scrollPosition: .none) self.tableView(tableView, didSelectRowAt: indexPath) return } // If we're not showing the Jetpack prompt or the fullscreen No Results View, // then clear any detail view controller that may be present. // (i.e. don't add an empty detail VC if the primary is full width) if let splitViewController = splitViewController as? WPSplitViewController, splitViewController.wpPrimaryColumnWidth != WPSplitViewControllerPrimaryColumnWidth.full { let controller = UIViewController() controller.navigationItem.largeTitleDisplayMode = .never showDetailViewController(controller, sender: nil) } } @objc func updateUnreadNotificationsForFilterTabChange() { if filter == .unread { refreshUnreadNotifications(reloadingResultsController: false) } else { clearUnreadNotifications() } } } // MARK: - WPTableViewHandlerDelegate Methods // extension NotificationsViewController: WPTableViewHandlerDelegate { func managedObjectContext() -> NSManagedObjectContext { return ContextManager.sharedInstance().mainContext } func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> { let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName()) request.sortDescriptors = [NSSortDescriptor(key: Filter.sortKey, ascending: false)] request.predicate = predicateForFetchRequest() return request } @objc func predicateForFetchRequest() -> NSPredicate { let deletedIdsPredicate = NSPredicate(format: "NOT (SELF IN %@)", Array(notificationIdsBeingDeleted)) let selectedFilterPredicate = predicateForSelectedFilters() return NSCompoundPredicate(andPredicateWithSubpredicates: [deletedIdsPredicate, selectedFilterPredicate]) } @objc func predicateForSelectedFilters() -> NSPredicate { guard let condition = filter.condition else { return NSPredicate(value: true) } var subpredicates: [NSPredicate] = [NSPredicate(format: condition)] if filter == .unread { subpredicates.append(NSPredicate(format: "SELF IN %@", Array(unreadNotificationIds))) } return NSCompoundPredicate(orPredicateWithSubpredicates: subpredicates) } func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) { // iOS 8 has a nice bug in which, randomly, the last cell per section was getting an extra separator. // For that reason, we draw our own separators. // guard let note = tableViewHandler.resultsController.object(at: indexPath) as? Notification else { return } let deletionRequest = deletionRequestForNoteWithID(note.objectID) let isLastRow = tableViewHandler.resultsController.isLastIndexPathInSection(indexPath) // configure unified list cell if the feature flag is enabled. if usesUnifiedList, let cell = cell as? ListTableViewCell { cell.configureWithNotification(note) // handle undo overlays cell.configureUndeleteOverlay(with: deletionRequest?.kind.legendText) { [weak self] in self?.cancelDeletionRequestForNoteWithID(note.objectID) } // additional configurations cell.showsBottomSeparator = !isLastRow cell.accessibilityHint = Self.accessibilityHint(for: note) return } // otherwise, configure using the (soon-to-be) legacy NoteTableViewCell. guard let cell = cell as? NoteTableViewCell else { return } cell.attributedSubject = note.renderSubject() cell.attributedSnippet = note.renderSnippet() cell.read = note.read cell.noticon = note.noticon cell.unapproved = note.isUnapprovedComment cell.showsBottomSeparator = !isLastRow cell.undeleteOverlayText = deletionRequest?.kind.legendText cell.onUndelete = { [weak self] in self?.cancelDeletionRequestForNoteWithID(note.objectID) } cell.accessibilityHint = Self.accessibilityHint(for: note) cell.downloadIconWithURL(note.iconURL) } func sectionNameKeyPath() -> String { return "sectionIdentifier" } @objc func entityName() -> String { return Notification.classNameWithoutNamespaces() } private var shouldCountNotificationsForSecondAlert: Bool { userDefaults.notificationPrimerInlineWasAcknowledged && userDefaults.secondNotificationsAlertCount != Constants.secondNotificationsAlertDisabled } func tableViewWillChangeContent(_ tableView: UITableView) { guard shouldCountNotificationsForSecondAlert, let notification = tableViewHandler.resultsController.fetchedObjects?.first as? Notification, let timestamp = notification.timestamp else { timestampBeforeUpdatesForSecondAlert = nil return } timestampBeforeUpdatesForSecondAlert = timestamp } func tableViewDidChangeContent(_ tableView: UITableView) { // Due to an UIKit bug, we need to draw our own separators (Issue #2845). Let's update the separator status // after a DB OP. This loop has been measured in the order of milliseconds (iPad Mini) // for indexPath in tableView.indexPathsForVisibleRows ?? [] { let cell = tableView.cellForRow(at: indexPath) // Apply the same handling for ListTableViewCell. // this should be removed when it's confirmed that default table separators no longer trigger issues // resolved in #2845, and the unified list feature is fully rolled out. if usesUnifiedList, let listCell = cell as? ListTableViewCell { let isLastRow = tableViewHandler.resultsController.isLastIndexPathInSection(indexPath) listCell.showsBottomSeparator = !isLastRow continue } if let noteCell = cell as? NoteTableViewCell { let isLastRow = tableViewHandler.resultsController.isLastIndexPathInSection(indexPath) noteCell.showsBottomSeparator = !isLastRow } } refreshUnreadNotifications() // Update NoResults View showNoResultsViewIfNeeded() if let selectedNotification = selectedNotification { selectRow(for: selectedNotification, animated: false, scrollPosition: .none) } else { selectFirstNotificationIfAppropriate() } // count new notifications for second alert guard shouldCountNotificationsForSecondAlert else { return } userDefaults.secondNotificationsAlertCount += newNotificationsForSecondAlert if isViewOnScreen() { showSecondNotificationsAlertIfNeeded() } } // counts the new notifications for the second alert private var newNotificationsForSecondAlert: Int { guard let previousTimestamp = timestampBeforeUpdatesForSecondAlert, let notifications = tableViewHandler.resultsController.fetchedObjects as? [Notification] else { return 0 } for notification in notifications.enumerated() { if let timestamp = notification.element.timestamp, timestamp <= previousTimestamp { return notification.offset } } return 0 } private static func accessibilityHint(for note: Notification) -> String? { switch note.kind { case .comment: return NSLocalizedString("Shows details and moderation actions.", comment: "Accessibility hint for a comment notification.") case .commentLike, .like: return NSLocalizedString("Shows all likes.", comment: "Accessibility hint for a post or comment “like” notification.") case .follow: return NSLocalizedString("Shows all followers", comment: "Accessibility hint for a follow notification.") case .matcher, .newPost: return NSLocalizedString("Shows the post", comment: "Accessibility hint for a match/mention on a post notification.") default: return nil } } } // MARK: - Filter Helpers // private extension NotificationsViewController { func showFiltersSegmentedControlIfApplicable() { guard filterTabBar.isHidden == true && shouldDisplayFilters == true else { return } UIView.animate(withDuration: WPAnimationDurationDefault, animations: { self.filterTabBar.isHidden = false }) } func hideFiltersSegmentedControlIfApplicable() { if filterTabBar.isHidden == false && shouldDisplayFilters == false { self.filterTabBar.isHidden = true } } var shouldDisplayFilters: Bool { // Filters should only be hidden whenever there are no Notifications in the bucket (contrary to the FRC's // results, which are filtered by the active predicate!). // return mainContext.countObjects(ofType: Notification.self) > 0 && !shouldDisplayJetpackPrompt } } // MARK: - NoResults Helpers // private extension NotificationsViewController { func showNoResultsViewIfNeeded() { noResultsViewController.removeFromView() updateSplitViewAppearanceForNoResultsView() updateNavigationItems() // Hide the filter header if we're showing the Jetpack prompt hideFiltersSegmentedControlIfApplicable() // Show Filters if needed guard shouldDisplayNoResultsView == true else { showFiltersSegmentedControlIfApplicable() return } guard connectionAvailable() else { showNoConnectionView() return } // Refresh its properties: The user may have signed into WordPress.com noResultsViewController.configure(title: noResultsTitleText, buttonTitle: noResultsButtonText, subtitle: noResultsMessageText, image: "wp-illustration-notifications") addNoResultsToView() } func showNoConnectionView() { noResultsViewController.configure(title: noConnectionTitleText, subtitle: noConnectionMessage()) addNoResultsToView() } func addNoResultsToView() { addChild(noResultsViewController) tableView.insertSubview(noResultsViewController.view, belowSubview: tableHeaderView) noResultsViewController.view.frame = tableView.frame setupNoResultsViewConstraints() noResultsViewController.didMove(toParent: self) } func setupNoResultsViewConstraints() { guard let nrv = noResultsViewController.view else { return } tableHeaderView.translatesAutoresizingMaskIntoConstraints = false nrv.translatesAutoresizingMaskIntoConstraints = false nrv.setContentHuggingPriority(.defaultLow, for: .horizontal) NSLayoutConstraint.activate([ nrv.widthAnchor.constraint(equalTo: view.widthAnchor), nrv.centerXAnchor.constraint(equalTo: view.centerXAnchor), nrv.topAnchor.constraint(equalTo: tableHeaderView.bottomAnchor), nrv.bottomAnchor.constraint(equalTo: view.safeBottomAnchor) ]) } func updateSplitViewAppearanceForNoResultsView() { guard let splitViewController = splitViewController as? WPSplitViewController else { return } let columnWidth: WPSplitViewControllerPrimaryColumnWidth = (shouldDisplayFullscreenNoResultsView || shouldDisplayJetpackPrompt) ? .full : .default if splitViewController.wpPrimaryColumnWidth != columnWidth { splitViewController.wpPrimaryColumnWidth = columnWidth } if columnWidth == .default { splitViewController.dimDetailViewController(shouldDimDetailViewController, withAlpha: WPAlphaZero) } } var noConnectionTitleText: String { return NSLocalizedString("Unable to Sync", comment: "Title of error prompt shown when a sync the user initiated fails.") } var noResultsTitleText: String { return filter.noResultsTitle } var noResultsMessageText: String? { guard AppConfiguration.showsReader else { return nil } return filter.noResultsMessage } var noResultsButtonText: String? { guard AppConfiguration.showsReader else { return nil } return filter.noResultsButtonTitle } var shouldDisplayJetpackPrompt: Bool { return AccountHelper.isDotcomAvailable() == false } var shouldDisplaySettingsButton: Bool { return AccountHelper.isDotcomAvailable() } var shouldDisplayNoResultsView: Bool { return tableViewHandler.resultsController.fetchedObjects?.count == 0 && !shouldDisplayJetpackPrompt } var shouldDisplayFullscreenNoResultsView: Bool { return shouldDisplayNoResultsView && filter == .none } var shouldDimDetailViewController: Bool { return shouldDisplayNoResultsView && filter != .none } } // MARK: - NoResultsViewControllerDelegate extension NotificationsViewController: NoResultsViewControllerDelegate { func actionButtonPressed() { let properties = [Stats.sourceKey: Stats.sourceValue] switch filter { case .none, .comment, .follow, .like: WPAnalytics.track(.notificationsTappedViewReader, withProperties: properties) WPTabBarController.sharedInstance().showReaderTab() case .unread: WPAnalytics.track(.notificationsTappedNewPost, withProperties: properties) WPTabBarController.sharedInstance().showPostTab() } } } // MARK: - Inline Prompt Helpers // internal extension NotificationsViewController { func showInlinePrompt() { guard inlinePromptView.alpha != WPAlphaFull, userDefaults.notificationPrimerAlertWasDisplayed, userDefaults.notificationsTabAccessCount >= Constants.inlineTabAccessCount else { return } UIView.animate(withDuration: WPAnimationDurationDefault, delay: 0, options: .curveEaseIn, animations: { self.inlinePromptView.isHidden = false }) UIView.animate(withDuration: WPAnimationDurationDefault * 0.5, delay: WPAnimationDurationDefault * 0.75, options: .curveEaseIn, animations: { self.inlinePromptView.alpha = WPAlphaFull }) WPAnalytics.track(.appReviewsSawPrompt) } func hideInlinePrompt(delay: TimeInterval) { UIView.animate(withDuration: WPAnimationDurationDefault * 0.75, delay: delay, animations: { self.inlinePromptView.alpha = WPAlphaZero }) UIView.animate(withDuration: WPAnimationDurationDefault, delay: delay + WPAnimationDurationDefault * 0.5, animations: { self.inlinePromptView.isHidden = true }) } } // MARK: - Sync'ing Helpers // private extension NotificationsViewController { func syncNewNotifications() { guard connectionAvailable() else { return } let mediator = NotificationSyncMediator() mediator?.sync() } func syncNotification(with noteId: String, timeout: TimeInterval, success: @escaping (_ note: Notification) -> Void) { let mediator = NotificationSyncMediator() let startDate = Date() DDLogInfo("Sync'ing Notification [\(noteId)]") mediator?.syncNote(with: noteId) { error, note in guard abs(startDate.timeIntervalSinceNow) <= timeout else { DDLogError("Error: Timeout while trying to load Notification [\(noteId)]") return } guard let note = note else { DDLogError("Error: Couldn't load Notification [\(noteId)]") return } DDLogInfo("Notification Sync'ed in \(startDate.timeIntervalSinceNow) seconds") success(note) } } func updateLastSeenTime() { guard let note = tableViewHandler.resultsController.fetchedObjects?.first as? Notification else { return } guard let timestamp = note.timestamp, timestamp != lastSeenTime else { return } let mediator = NotificationSyncMediator() mediator?.updateLastSeen(timestamp) { error in guard error == nil else { return } self.lastSeenTime = timestamp } } func loadNotification(with noteId: String) -> Notification? { let predicate = NSPredicate(format: "(notificationId == %@)", noteId) return mainContext.firstObject(ofType: Notification.self, matching: predicate) } func loadNotification(near note: Notification, withIndexDelta delta: Int) -> Notification? { guard let notifications = tableViewHandler?.resultsController.fetchedObjects as? [Notification] else { return nil } guard let noteIndex = notifications.firstIndex(of: note) else { return nil } let targetIndex = noteIndex + delta guard targetIndex >= 0 && targetIndex < notifications.count else { return nil } func notMatcher(_ note: Notification) -> Bool { return note.kind != .matcher } if delta > 0 { return notifications .suffix(from: targetIndex) .first(where: notMatcher) } else { return notifications .prefix(through: targetIndex) .reversed() .first(where: notMatcher) } } func resetNotifications() { do { selectedNotification = nil mainContext.deleteAllObjects(ofType: Notification.self) try mainContext.save() tableView.reloadData() } catch { DDLogError("Error while trying to nuke Notifications Collection: [\(error)]") } } func resetLastSeenTime() { lastSeenTime = nil } func resetApplicationBadge() { // These notifications are cleared, so we just need to take Zendesk unread notifications // into account when setting the app icon count. UIApplication.shared.applicationIconBadgeNumber = ZendeskUtils.unreadNotificationsCount } } // MARK: - WPSplitViewControllerDetailProvider // extension NotificationsViewController: WPSplitViewControllerDetailProvider { func initialDetailViewControllerForSplitView(_ splitView: WPSplitViewController) -> UIViewController? { // The first notification view will be populated by `selectFirstNotificationIfAppropriate` // on viewWillAppear, so we'll just return an empty view here. let controller = UIViewController() controller.view.backgroundColor = .basicBackground return controller } private func fetchFirstNotification() -> Notification? { let context = managedObjectContext() let fetchRequest = self.fetchRequest() fetchRequest.fetchLimit = 1 if let results = try? context.fetch(fetchRequest) as? [Notification] { return results.first } return nil } } // MARK: - Details Navigation Datasource // extension NotificationsViewController: NotificationsNavigationDataSource { @objc func notification(succeeding note: Notification) -> Notification? { return loadNotification(near: note, withIndexDelta: -1) } @objc func notification(preceding note: Notification) -> Notification? { return loadNotification(near: note, withIndexDelta: +1) } } // MARK: - SearchableActivity Conformance // extension NotificationsViewController: SearchableActivityConvertable { var activityType: String { return WPActivityType.notifications.rawValue } var activityTitle: String { return NSLocalizedString("Notifications", comment: "Title of the 'Notifications' tab - used for spotlight indexing on iOS.") } var activityKeywords: Set<String>? { let keyWordString = NSLocalizedString("wordpress, notifications, alerts, updates", comment: "This is a comma separated list of keywords used for spotlight indexing of the 'Notifications' tab.") let keywordArray = keyWordString.arrayOfTags() guard !keywordArray.isEmpty else { return nil } return Set(keywordArray) } } // MARK: - Private Properties // private extension NotificationsViewController { var mainContext: NSManagedObjectContext { return ContextManager.sharedInstance().mainContext } var actionsService: NotificationActionsService { return NotificationActionsService(managedObjectContext: mainContext) } var userDefaults: UserDefaults { return UserDefaults.standard } var lastSeenTime: String? { get { return userDefaults.string(forKey: Settings.lastSeenTime) } set { userDefaults.setValue(newValue, forKey: Settings.lastSeenTime) } } var filter: Filter { get { let selectedIndex = filterTabBar?.selectedIndex ?? Filter.none.rawValue return Filter(rawValue: selectedIndex) ?? .none } set { filterTabBar?.setSelectedIndex(newValue.rawValue) reloadResultsController() } } enum Filter: Int, FilterTabBarItem { case none = 0 case unread = 1 case comment = 2 case follow = 3 case like = 4 var condition: String? { switch self { case .none: return nil case .unread: return "read = NO" case .comment: return "type = '\(NotificationKind.comment.rawValue)'" case .follow: return "type = '\(NotificationKind.follow.rawValue)'" case .like: return "type = '\(NotificationKind.like.rawValue)' OR type = '\(NotificationKind.commentLike.rawValue)'" } } var title: String { switch self { case .none: return NSLocalizedString("All", comment: "Displays all of the Notifications, unfiltered") case .unread: return NSLocalizedString("Unread", comment: "Filters Unread Notifications") case .comment: return NSLocalizedString("Comments", comment: "Filters Comments Notifications") case .follow: return NSLocalizedString("Follows", comment: "Filters Follows Notifications") case .like: return NSLocalizedString("Likes", comment: "Filters Likes Notifications") } } var analyticsTitle: String { switch self { case .none: return "All" case .unread: return "Unread" case .comment: return "Comments" case .follow: return "Follows" case .like: return "Likes" } } var noResultsTitle: String { switch self { case .none: return NSLocalizedString("No notifications yet", comment: "Displayed in the Notifications Tab as a title, when there are no notifications") case .unread: return NSLocalizedString("You're all up to date!", comment: "Displayed in the Notifications Tab as a title, when the Unread Filter shows no unread notifications as a title") case .comment: return NSLocalizedString("No comments yet", comment: "Displayed in the Notifications Tab as a title, when the Comments Filter shows no notifications") case .follow: return NSLocalizedString("No followers yet", comment: "Displayed in the Notifications Tab as a title, when the Follow Filter shows no notifications") case .like: return NSLocalizedString("No likes yet", comment: "Displayed in the Notifications Tab as a title, when the Likes Filter shows no notifications") } } var noResultsMessage: String { switch self { case .none: return NSLocalizedString("Get active! Comment on posts from blogs you follow.", comment: "Displayed in the Notifications Tab as a message, when there are no notifications") case .unread: return NSLocalizedString("Reignite the conversation: write a new post.", comment: "Displayed in the Notifications Tab as a message, when the Unread Filter shows no notifications") case .comment: return NSLocalizedString("Join a conversation: comment on posts from blogs you follow.", comment: "Displayed in the Notifications Tab as a message, when the Comments Filter shows no notifications") case .follow, .like: return NSLocalizedString("Get noticed: comment on posts you've read.", comment: "Displayed in the Notifications Tab as a message, when the Follow Filter shows no notifications") } } var noResultsButtonTitle: String { switch self { case .none, .comment, .follow, .like: return NSLocalizedString("Go to Reader", comment: "Displayed in the Notifications Tab as a button title, when there are no notifications") case .unread: return NSLocalizedString("Create a Post", comment: "Displayed in the Notifications Tab as a button title, when the Unread Filter shows no notifications") } } static let sortKey = "timestamp" static let allFilters = [Filter.none, .unread, .comment, .follow, .like] } enum Settings { static let estimatedRowHeight = CGFloat(70) static let lastSeenTime = "notifications_last_seen_time" } enum Stats { static let networkStatusKey = "network_status" static let noteTypeKey = "notification_type" static let noteTypeUnknown = "unknown" static let sourceKey = "source" static let sourceValue = "notifications" static let selectedFilter = "selected_filter" } enum Syncing { static let minimumPullToRefreshDelay = TimeInterval(1.5) static let pushMaxWait = TimeInterval(1.5) static let syncTimeout = TimeInterval(10) static let undoTimeout = TimeInterval(4) } enum InlinePrompt { static let section = "notifications" } } // MARK: - Push Notifications Permission Alert extension NotificationsViewController: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { guard let fancyAlertController = presented as? FancyAlertViewController else { return nil } return FancyAlertPresentationController(presentedViewController: fancyAlertController, presenting: presenting) } private func showNotificationPrimerAlertIfNeeded() { guard !userDefaults.notificationPrimerAlertWasDisplayed else { return } DispatchQueue.main.asyncAfter(deadline: .now() + Constants.displayAlertDelay) { self.showNotificationPrimerAlert() } } private func notificationAlertApproveAction(_ controller: FancyAlertViewController) { InteractiveNotificationsManager.shared.requestAuthorization { _ in DispatchQueue.main.async { controller.dismiss(animated: true) } } } private func showNotificationPrimerAlert() { let alertController = FancyAlertViewController.makeNotificationPrimerAlertController(approveAction: notificationAlertApproveAction(_:)) showNotificationAlert(alertController) } private func showSecondNotificationAlert() { let alertController = FancyAlertViewController.makeNotificationSecondAlertController(approveAction: notificationAlertApproveAction(_:)) showNotificationAlert(alertController) } private func showNotificationAlert(_ alertController: FancyAlertViewController) { let mainContext = ContextManager.shared.mainContext let accountService = AccountService(managedObjectContext: mainContext) guard accountService.defaultWordPressComAccount() != nil else { return } PushNotificationsManager.shared.loadAuthorizationStatus { [weak self] (enabled) in guard enabled == .notDetermined else { return } UserDefaults.standard.notificationPrimerAlertWasDisplayed = true let alert = alertController alert.modalPresentationStyle = .custom alert.transitioningDelegate = self self?.tabBarController?.present(alert, animated: true) } } private func showSecondNotificationsAlertIfNeeded() { guard userDefaults.secondNotificationsAlertCount >= Constants.secondNotificationsAlertThreshold else { return } showSecondNotificationAlert() userDefaults.secondNotificationsAlertCount = Constants.secondNotificationsAlertDisabled } private enum Constants { static let inlineTabAccessCount = 6 static let displayAlertDelay = 0.2 // number of notifications after which the second alert will show up static let secondNotificationsAlertThreshold = 10 static let secondNotificationsAlertDisabled = -1 /// the amount of bottom padding added to the filter tab bar. To be used with unified list. static let filterTabBarBottomSpace: CGFloat = 10.0 } } // MARK: - Scrolling // extension NotificationsViewController: WPScrollableViewController { // Used to scroll view to top when tapping on tab bar item when VC is already visible. func scrollViewToTop() { tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true) } }
gpl-2.0
4c8cf0897e20670894df4320dbdb8064
37.470869
203
0.66825
5.919077
false
false
false
false
dokun1/jordan-meme-ios
JordanHeadMeme/JordanHeadMeme/InfoViewController.swift
1
2551
// // InfoViewController.swift // JordanHeadMeme // // Created by David Okun on 2/16/16. // Copyright © 2016 David Okun, LLC. All rights reserved. // import UIKit import Foundation import Crashlytics class InfoViewController: UIViewController { @IBOutlet weak var versionLabel: UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let version = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String { if let build = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String { let debug = UIApplication.sharedApplication().isDebugMode ? "DEBUG" : "" versionLabel.text = "© David Okun, 2016, v\(version)-\(build)\(debug)" } } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Analytics.logCustomEventWithName("Info View Shown", customAttributes:nil) } @IBAction func githubIconTapped() { Analytics.logCustomEventWithName("Social Link Tapped", customAttributes:["Site Loaded":"Github"]) let url = NSURL.init(string: "https://www.github.com/dokun1/jordan-meme-ios") UIApplication.sharedApplication().openURL(url!) } @IBAction func twitterIconTapped() { Analytics.logCustomEventWithName("Social Link Tapped", customAttributes:["Site Loaded":"Twitter"]) let url = NSURL.init(string: "https://www.twitter.com/dokun24") UIApplication.sharedApplication().openURL(url!) } @IBAction func instagramIconTapped() { Analytics.logCustomEventWithName("Social Link Tapped", customAttributes:["Site Loaded":"Instagram"]) let url = NSURL.init(string: "https://www.instagram.com/dokun1") UIApplication.sharedApplication().openURL(url!) } @IBAction func internetIconTapped() { Analytics.logCustomEventWithName("Social Link Tapped", customAttributes:["Site Loaded":"Website"]) let url = NSURL.init(string: "http://okun.io") UIApplication.sharedApplication().openURL(url!) } @IBAction func reviewButtonTapped() { Analytics.logCustomEventWithName("Social Link Tapped", customAttributes:["Site Loaded":"Review"]) let url = NSURL.init(string: "itms-apps://itunes.apple.com/app/id1084796562") UIApplication.sharedApplication().openURL(url!) } @IBAction func goBackButtonTapped() { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
e66c8a3cefd7ac02a97e424ac94f3118
38.828125
108
0.675951
4.755597
false
false
false
false
think-dev/MadridBUS
MadridBUS/Source/Data/BusNodeBasicInfo.swift
1
510
import Foundation import ObjectMapper final class BusNodeBasicInfo: Mappable { var id: Int = 0 var name: String = "" var lines: [String] = [] var wifi: Bool = false var latitude: Double = 0.0 var longitude: Double = 0.0 required init?(map: Map) {} func mapping(map: Map) { id <- map["node"] name <- map["name"] lines <- map["lines"] wifi <- map["Wifi"] latitude <- map["latitude"] longitude <- map["longitude"] } }
mit
6dfaa8efa4a6997b47aa0c55f2e6abfc
22.181818
40
0.545098
3.953488
false
false
false
false
thatseeyou/SpriteKitExamples.playground
Pages/SKSpriteNode.xcplaygroundpage/Contents.swift
1
1223
/*: ### SKView 크기에 맞는 SKScene을 추가한다. - SKSpriteNode를 이용해서 사각형을 만든다. */ import UIKit import SpriteKit class GameScene: SKScene { var contentCreated = false override func didMove(to view: SKView) { if self.contentCreated != true { let sprite = SKSpriteNode(color: #colorLiteral(red: 0.4931360483169556, green: 0, blue: 0.1765155345201492, alpha: 1), size: CGSize(width: 100, height: 100)) sprite.position = CGPoint(x: 100, y: 100) addChild(sprite) self.contentCreated = true } } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // add SKView do { let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480)) skView.showsFPS = true //skView.showsNodeCount = true skView.ignoresSiblingOrder = true let scene = GameScene(size: CGSize(width: 320, height: 480)) scene.scaleMode = .aspectFit skView.presentScene(scene) self.view.addSubview(skView) } } } PlaygroundHelper.showViewController(ViewController())
isc
728b56da129726727fdae55b4a4aee54
25.795455
169
0.609839
4.079585
false
false
false
false
powerytg/Accented
Accented/UI/Common/Components/Stream/SingleHeader/SingleHeaderStreamViewModel.swift
1
3789
// // SingleHeaderStreamViewModel.swift // Accented // // Created by Tiangong You on 8/25/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class SingleHeaderStreamViewModel: StreamViewModel, PhotoRendererDelegate { var cardRendererReuseIdentifier : String { return "renderer" } let streamHeaderReuseIdentifier = "streamHeader" // Section index for the headers private let headerSection = 0 var headerHeight : CGFloat { fatalError("Subclass must specify a header height") } required init(stream : StreamModel, collectionView : UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) { super.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: flowLayoutDelegate) } override var photoStartSection : Int { return 1 } override func registerCellTypes() { collectionView.register(DefaultStreamPhotoCell.self, forCellWithReuseIdentifier: cardRendererReuseIdentifier) let streamHeaderNib = UINib(nibName: "DefaultSingleStreamHeaderCell", bundle: nil) collectionView.register(streamHeaderNib, forCellWithReuseIdentifier: streamHeaderReuseIdentifier) } override func createLayoutTemplateGenerator(_ maxWidth: CGFloat) -> StreamTemplateGenerator { return PhotoGroupTemplateGenarator(maxWidth: maxWidth) } override func createCollectionViewLayout() { layout = SingleHeaderStreamLayout(headerHeight: headerHeight) layout.footerReferenceSize = CGSize(width: 50, height: 50) } func streamHeader(_ indexPath : IndexPath) -> UICollectionViewCell { fatalError("Subclass must specify a stream header") } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if !collection.loaded { let loadingCell = collectionView.dequeueReusableCell(withReuseIdentifier: initialLoadingRendererReuseIdentifier, for: indexPath) return loadingCell } else if indexPath.section == headerSection { if indexPath.item == 0 { return streamHeader(indexPath) } else { fatalError("There is no header cells beyond index 0") } } else { let group = photoGroups[(indexPath as NSIndexPath).section - photoStartSection] let photo = group[(indexPath as NSIndexPath).item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cardRendererReuseIdentifier, for: indexPath) as! StreamPhotoCellBaseCollectionViewCell cell.photo = photo cell.renderer.delegate = self cell.setNeedsLayout() return cell } } override func numberOfSections(in collectionView: UICollectionView) -> Int { if !stream.loaded { return photoStartSection + 1 } else { return photoGroups.count + photoStartSection } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == headerSection { return 2 } else { if !stream.loaded { return 1 } else { return photoGroups[section - photoStartSection].count } } } // MARK: - PhotoRendererDelegate func photoRendererDidReceiveTap(_ renderer: PhotoRenderer) { let navContext = DetailNavigationContext(selectedPhoto: renderer.photo!, sourceImageView: renderer.imageView) NavigationService.sharedInstance.navigateToDetailPage(navContext) } }
mit
4fc2801b80af84175f4ae5320d511d73
36.137255
165
0.670011
5.713424
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/PledgeExpandableRewardsHeaderViewModel.swift
1
6369
import KsApi import Prelude import ReactiveSwift import UIKit public enum PledgeExpandableRewardsHeaderItem { case header(PledgeExpandableHeaderRewardCellData) case reward(PledgeExpandableHeaderRewardCellData) public var data: PledgeExpandableHeaderRewardCellData { switch self { case let .header(data): return data case let .reward(data): return data } } public var isHeader: Bool { switch self { case .header: return true case .reward: return false } } public var isReward: Bool { switch self { case .header: return false case .reward: return true } } } public struct PledgeExpandableRewardsHeaderViewData { public let rewards: [Reward] public let selectedQuantities: SelectedRewardQuantities public let projectCountry: Project.Country public let omitCurrencyCode: Bool } public protocol PledgeExpandableRewardsHeaderViewModelInputs { func configure(with data: PledgeExpandableRewardsHeaderViewData) func expandButtonTapped() func viewDidLoad() } public protocol PledgeExpandableRewardsHeaderViewModelOutputs { var loadRewardsIntoDataSource: Signal<[PledgeExpandableRewardsHeaderItem], Never> { get } var expandRewards: Signal<Bool, Never> { get } } public protocol PledgeExpandableRewardsHeaderViewModelType { var inputs: PledgeExpandableRewardsHeaderViewModelInputs { get } var outputs: PledgeExpandableRewardsHeaderViewModelOutputs { get } } public final class PledgeExpandableRewardsHeaderViewModel: PledgeExpandableRewardsHeaderViewModelType, PledgeExpandableRewardsHeaderViewModelInputs, PledgeExpandableRewardsHeaderViewModelOutputs { public init() { let data = Signal.combineLatest( self.configureWithRewardsProperty.signal.skipNil(), self.viewDidLoadProperty.signal ) .map(first) let rewards = data.map(\.rewards) let selectedQuantities = data.map(\.selectedQuantities) let latestRewardDeliveryDate = rewards.map { rewards in rewards .compactMap { $0.estimatedDeliveryOn } .reduce(0) { accum, value in max(accum, value) } } self.expandRewards = self.expandButtonTappedProperty.signal .scan(false) { current, _ in !current } let estimatedDeliveryString = latestRewardDeliveryDate.map { date -> String? in guard date > 0 else { return nil } let dateString = Format.date( secondsInUTC: date, template: DateFormatter.monthYear, timeZone: UTCTimeZone ) return Strings.backing_info_estimated_delivery_date(delivery_date: dateString) } .skipNil() let total: Signal<Double, Never> = Signal.combineLatest( rewards, selectedQuantities ) .map { rewards, selectedQuantities in rewards.reduce(0.0) { total, reward in let totalForReward = reward.minimum .multiplyingCurrency(Double(selectedQuantities[reward.id] ?? 0)) return total.addingCurrency(totalForReward) } } self.loadRewardsIntoDataSource = Signal.zip( data, selectedQuantities, estimatedDeliveryString, total ) .map(items) } private let configureWithRewardsProperty = MutableProperty<PledgeExpandableRewardsHeaderViewData?>(nil) public func configure(with data: PledgeExpandableRewardsHeaderViewData) { self.configureWithRewardsProperty.value = data } private let expandButtonTappedProperty = MutableProperty(()) public func expandButtonTapped() { self.expandButtonTappedProperty.value = () } private let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } public let loadRewardsIntoDataSource: Signal<[PledgeExpandableRewardsHeaderItem], Never> public let expandRewards: Signal<Bool, Never> public var inputs: PledgeExpandableRewardsHeaderViewModelInputs { return self } public var outputs: PledgeExpandableRewardsHeaderViewModelOutputs { return self } } // MARK: - Functions private func items( with data: PledgeExpandableRewardsHeaderViewData, selectedQuantities: SelectedRewardQuantities, estimatedDeliveryString: String, total: Double ) -> [PledgeExpandableRewardsHeaderItem] { guard let totalAmountAttributedText = attributedHeaderCurrency( with: data.projectCountry, amount: total, omitUSCurrencyCode: data.omitCurrencyCode ) else { return [] } let headerItem = PledgeExpandableRewardsHeaderItem.header(( text: estimatedDeliveryString, amount: totalAmountAttributedText )) let rewardItems = data.rewards.compactMap { reward -> PledgeExpandableRewardsHeaderItem? in guard let title = reward.title else { return nil } let quantity = selectedQuantities[reward.id] ?? 0 let itemString = quantity > 1 ? "\(Format.wholeNumber(quantity)) x \(title)" : title let amountAttributedText = attributedRewardCurrency( with: data.projectCountry, amount: reward.minimum, omitUSCurrencyCode: data.omitCurrencyCode ) return PledgeExpandableRewardsHeaderItem.reward(( text: itemString, amount: amountAttributedText )) } return [headerItem] + rewardItems } private func attributedHeaderCurrency( with projectCountry: Project.Country, amount: Double, omitUSCurrencyCode: Bool ) -> NSAttributedString? { let defaultAttributes = checkoutCurrencyDefaultAttributes() .withAllValuesFrom([.foregroundColor: UIColor.ksr_support_400]) let superscriptAttributes = checkoutCurrencySuperscriptAttributes() guard let attributedCurrency = Format.attributedCurrency( amount, country: projectCountry, omitCurrencyCode: omitUSCurrencyCode, defaultAttributes: defaultAttributes, superscriptAttributes: superscriptAttributes, maximumFractionDigits: 0, minimumFractionDigits: 0 ) else { return nil } return attributedCurrency } private func attributedRewardCurrency( with projectCountry: Project.Country, amount: Double, omitUSCurrencyCode: Bool ) -> NSAttributedString { let currencyString = Format.currency( amount, country: projectCountry, omitCurrencyCode: omitUSCurrencyCode, maximumFractionDigits: 0, minimumFractionDigits: 0 ) return NSAttributedString( string: currencyString, attributes: [ .foregroundColor: UIColor.ksr_support_400, .font: UIFont.ksr_subhead().bolded ] ) }
apache-2.0
7fcffe57e1d28645d048208288a4143e
29.042453
105
0.746114
4.929567
false
false
false
false
uasys/swift
test/SILGen/objc_dictionary_bridging.swift
4
6806
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen -enable-sil-ownership %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo @objc class Foo : NSObject { // Bridging dictionary parameters // CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (NSDictionary, Foo) -> () func bridge_Dictionary_param(_ dict: Dictionary<Foo, Foo>) { // CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ // CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary // CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type // CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}F // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] : $() } // CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo' // Bridging dictionary results // CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary func bridge_Dictionary_result() -> Dictionary<Foo, Foo> { // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: [[DICT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF // CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]] // CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]] // CHECK: destroy_value [[DICT]] // CHECK: return [[NSDICT]] : $NSDictionary } // CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo' var property: Dictionary<Foo, Foo> = [:] // Property getter // CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[GETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvg : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: [[DICT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF // CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]] // CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]] // CHECK: destroy_value [[DICT]] // CHECK: return [[NSDICT]] : $NSDictionary // CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvgTo' // Property setter // CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvsTo : $@convention(objc_method) (NSDictionary, Foo) -> () // CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ // CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary // CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type // CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGvs : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] : $() // CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary // CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vsTo : $@convention(objc_method) (NSDictionary, Foo) -> () @objc var nonVerbatimProperty: Dictionary<String, Int> = [:] } func ==(x: Foo, y: Foo) -> Bool { }
apache-2.0
fdaafca0a3017d281461eb8d99e427d4
72.075269
208
0.641995
3.387836
false
false
false
false
jsooriah/Armchair
Source/Armchair.swift
2
73872
// Armchair.swift // // Copyright (c) 2014 Armchair (http://github.com/UrbanApps/Armchair) // // 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 StoreKit import SystemConfiguration #if os(iOS) import UIKit #elseif os(OSX) import AppKit #else // Not yet supported #endif // MARK: - // MARK: PUBLIC Interface // MARK: - // MARK: Properties /* * Get/Set your Apple generated software id. * This is the only required setup value. * This call needs to be first. No default. */ public var appID: String = "" public func appID(appID: String) { Armchair.appID = appID Manager.defaultManager.appID = appID } /* * Get/Set the App Name to use in the prompt * Default value is your localized display name from the info.plist */ public func appName() -> String { return Manager.defaultManager.appName } public func appName(appName: String) { Manager.defaultManager.appName = appName } /* * Get/Set the title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func reviewTitle() -> String { return Manager.defaultManager.reviewTitle } public func reviewTitle(reviewTitle: String) { Manager.defaultManager.reviewTitle = reviewTitle } /* * Get/Set the message to use on the review prompt. * Default value is a localized * "If you enjoy using <appName>, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" */ public func reviewMessage() -> String { return Manager.defaultManager.reviewMessage } public func reviewMessage(reviewMessage: String) { Manager.defaultManager.reviewMessage = reviewMessage } /* * Get/Set the cancel button title to use on the review prompt. * Default value is a localized "No, Thanks" */ public func cancelButtonTitle() -> String { return Manager.defaultManager.cancelButtonTitle } public func cancelButtonTitle(cancelButtonTitle: String) { Manager.defaultManager.cancelButtonTitle = cancelButtonTitle } /* * Get/Set the rate button title to use on the review prompt. * Default value is a localized "Rate <appName>" */ public func rateButtonTitle() -> String { return Manager.defaultManager.rateButtonTitle } public func rateButtonTitle(rateButtonTitle: String) { Manager.defaultManager.rateButtonTitle = rateButtonTitle } /* * Get/Set the remind me later button title to use on the review prompt. * It is optional, so you can set it to nil to hide the remind button from displaying * Default value is a localized "Remind me later" */ public func remindButtonTitle() -> String? { return Manager.defaultManager.remindButtonTitle } public func remindButtonTitle(remindButtonTitle: String?) { Manager.defaultManager.remindButtonTitle = remindButtonTitle } /* * Get/Set the NSUserDefault keys that store the usage data for Armchair * Default values are in the form of "<appID>_Armchair<Setting>" */ public func keyForArmchairKeyType(keyType: ArmchairKey) -> String { return Manager.defaultManager.keyForArmchairKeyType(keyType) } public func setKey(key: NSString, armchairKeyType: ArmchairKey) { Manager.defaultManager.setKey(key, armchairKeyType: armchairKeyType) } /* * Get/Set the prefix to the NSUserDefault keys that store the usage data for Armchair * Default value is the App ID, and it is prepended to the keys for key type, above * This prevents different apps using a shared Key/Value store from overwriting each other. */ public func keyPrefix() -> String { return Manager.defaultManager.keyPrefix } public func keyPrefix(keyPrefix: String) { Manager.defaultManager.keyPrefix = keyPrefix } /* * Get/Set the object that stores the usage data for Armchair * it is optional but if you pass nil, Armchair can not run. * Default value is NSUserDefaults.standardUserDefaults() */ public func userDefaultsObject() -> ArmchairDefaultsObject? { return Manager.defaultManager.userDefaultsObject } public func userDefaultsObject(userDefaultsObject: ArmchairDefaultsObject?) { Manager.defaultManager.userDefaultsObject = userDefaultsObject } /* * Users will need to have the same version of your app installed for this many * days before they will be prompted to rate it. * Default => 30 */ public func daysUntilPrompt() -> UInt { return Manager.defaultManager.daysUntilPrompt } public func daysUntilPrompt(daysUntilPrompt: UInt) { Manager.defaultManager.daysUntilPrompt = daysUntilPrompt } /* * An example of a 'use' would be if the user launched the app. Bringing the app * into the foreground (on devices that support it) would also be considered * a 'use'. * * Users need to 'use' the same version of the app this many times before * before they will be prompted to rate it. * Default => 20 */ public func usesUntilPrompt() -> UInt { return Manager.defaultManager.usesUntilPrompt } public func usesUntilPrompt(usesUntilPrompt: UInt) { Manager.defaultManager.usesUntilPrompt = usesUntilPrompt } /* * A significant event can be anything you want to be in your app. In a * telephone app, a significant event might be placing or receiving a call. * In a game, it might be beating a level or a boss. This is just another * layer of filtering that can be used to make sure that only the most * loyal of your users are being prompted to rate you on the app store. * If you leave this at a value of 0 (default), then this won't be a criterion * used for rating. * * To tell Armchair that the user has performed * a significant event, call the method Armchair.userDidSignificantEvent() * Default => 0 */ public func significantEventsUntilPrompt() -> UInt { return Manager.defaultManager.significantEventsUntilPrompt } public func significantEventsUntilPrompt(significantEventsUntilPrompt: UInt) { Manager.defaultManager.significantEventsUntilPrompt = significantEventsUntilPrompt } /* * Once the rating alert is presented to the user, they might select * 'Remind me later'. This value specifies how many days Armchair * will wait before reminding them. A value of 0 disables reminders and * removes the 'Remind me later' button. * Default => 1 */ public func daysBeforeReminding() -> UInt { return Manager.defaultManager.daysBeforeReminding } public func daysBeforeReminding(daysBeforeReminding: UInt) { Manager.defaultManager.daysBeforeReminding = daysBeforeReminding } /* * By default, Armchair tracks all new bundle versions. * When it detects a new version, it resets the values saved for usage, * significant events, popup shown, user action etc... * By setting this to false, Armchair will ONLY track the version it * was initialized with. If this setting is set to true, Armchair * will reset after each new version detection. * Default => true */ public func tracksNewVersions() -> Bool { return Manager.defaultManager.tracksNewVersions } public func tracksNewVersions(tracksNewVersions: Bool) { Manager.defaultManager.tracksNewVersions = tracksNewVersions } /* * If the user has rated the app once before, and you don't want it to show on * a new version, set this to false. This is useful if you release small bugfix * versions and don't want to pester your users with popups for every minor * version. For example, you might set this to false for every minor build, then * when you push a major version upgrade, leave it as true to ask for a rating again. * Default => true */ public func shouldPromptIfRated() -> Bool { return Manager.defaultManager.shouldPromptIfRated } public func shouldPromptIfRated(shouldPromptIfRated: Bool) { Manager.defaultManager.shouldPromptIfRated = shouldPromptIfRated } /* * If set to true, the main bundle will always be used to load localized strings. * Set this to true if you have provided your own custom localizations in * ArmchairLocalizable.strings in your main bundle * Default => false. */ public func useMainAppBundleForLocalizations() -> Bool { return Manager.defaultManager.useMainAppBundleForLocalizations } public func useMainAppBundleForLocalizations(useMainAppBundleForLocalizations: Bool) { Manager.defaultManager.useMainAppBundleForLocalizations = useMainAppBundleForLocalizations } /* * If you are an Apple Affiliate, enter your code here. * If none is set, the author's code will be used as it is better to be set as something * rather than nothing. If you want to thank me for making Armchair, feel free * to leave this value at it's default. */ public func affiliateCode() -> String { return Manager.defaultManager.affiliateCode } public func affiliateCode(affiliateCode: String) { Manager.defaultManager.affiliateCode = affiliateCode } /* * If you are an Apple Affiliate, enter your campaign code here. * Default => "Armchair-<appID>" */ public func affiliateCampaignCode() -> String { return Manager.defaultManager.affiliateCampaignCode } public func affiliateCampaignCode(affiliateCampaignCode: String) { Manager.defaultManager.affiliateCampaignCode = affiliateCampaignCode } /* * 'true' will show the Armchair alert everytime. Useful for testing * how your message looks and making sure the link to your app's review page works. * Calling this method in a production build (DEBUG preprocessor macro is not defined) * has no effect. In app store builds, you don't have to worry about accidentally * leaving debugEnabled to true * Default => false */ public func debugEnabled() -> Bool { return Manager.defaultManager.debugEnabled } public func debugEnabled(debugEnabled: Bool) { #if Debug Manager.defaultManager.debugEnabled = debugEnabled #else println("[Armchair] Debug is disabled on release builds.") println("[Armchair] If you really want to enable debug mode,") println("[Armchair] add \"-DDebug\" to your Swift Compiler - Custom Flags") println("[Armchair] section in the target's build settings for release") #endif } /* * * */ public func resetDefaults() { Manager.defaultManager.debugEnabled = false Manager.defaultManager.appName = Manager.defaultManager.defaultAppName() Manager.defaultManager.reviewTitle = Manager.defaultManager.defaultReviewTitle() Manager.defaultManager.reviewMessage = Manager.defaultManager.defaultReviewMessage() Manager.defaultManager.cancelButtonTitle = Manager.defaultManager.defaultCancelButtonTitle() Manager.defaultManager.rateButtonTitle = Manager.defaultManager.defaultRateButtonTitle() Manager.defaultManager.remindButtonTitle = Manager.defaultManager.defaultRemindButtonTitle() Manager.defaultManager.daysUntilPrompt = 30 Manager.defaultManager.daysBeforeReminding = 1 Manager.defaultManager.shouldPromptIfRated = true Manager.defaultManager.significantEventsUntilPrompt = 20 Manager.defaultManager.tracksNewVersions = true Manager.defaultManager.useMainAppBundleForLocalizations = false Manager.defaultManager.affiliateCode = Manager.defaultManager.defaultAffiliateCode() Manager.defaultManager.affiliateCampaignCode = Manager.defaultManager.defaultAffiliateCampaignCode() Manager.defaultManager.didDeclineToRateClosure = nil Manager.defaultManager.didDisplayAlertClosure = nil Manager.defaultManager.didOptToRateClosure = nil Manager.defaultManager.didOptToRemindLaterClosure = nil #if os(iOS) Manager.defaultManager.usesAnimation = true Manager.defaultManager.usesAlertController = false Manager.defaultManager.opensInStoreKit = Manager.defaultManager.defaultOpensInStoreKit() Manager.defaultManager.willPresentModalViewClosure = nil Manager.defaultManager.didDismissModalViewClosure = nil #endif Manager.defaultManager.armchairKeyFirstUseDate = Manager.defaultManager.defaultArmchairKeyFirstUseDate() Manager.defaultManager.armchairKeyUseCount = Manager.defaultManager.defaultArmchairKeyUseCount() Manager.defaultManager.armchairKeySignificantEventCount = Manager.defaultManager.defaultArmchairKeySignificantEventCount() Manager.defaultManager.armchairKeyCurrentVersion = Manager.defaultManager.defaultArmchairKeyCurrentVersion() Manager.defaultManager.armchairKeyRatedCurrentVersion = Manager.defaultManager.defaultArmchairKeyRatedCurrentVersion() Manager.defaultManager.armchairKeyDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyReminderRequestDate = Manager.defaultManager.defaultArmchairKeyReminderRequestDate() Manager.defaultManager.armchairKeyPreviousVersion = Manager.defaultManager.defaultArmchairKeyPreviousVersion() Manager.defaultManager.armchairKeyPreviousVersionRated = Manager.defaultManager.defaultArmchairKeyPreviousVersionRated() Manager.defaultManager.armchairKeyPreviousVersionDeclinedToRate = Manager.defaultManager.defaultArmchairKeyDeclinedToRate() Manager.defaultManager.armchairKeyRatedAnyVersion = Manager.defaultManager.defaultArmchairKeyRatedAnyVersion() Manager.defaultManager.armchairKeyAppiraterMigrationCompleted = Manager.defaultManager.defaultArmchairKeyAppiraterMigrationCompleted() Manager.defaultManager.armchairKeyUAAppReviewManagerMigrationCompleted = Manager.defaultManager.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() Manager.defaultManager.keyPrefix = Manager.defaultManager.defaultKeyPrefix() } #if os(iOS) /* * Set whether or not Armchair uses animation when pushing modal StoreKit * view controllers for the app. * Default => true */ public func usesAnimation() -> Bool { return Manager.defaultManager.usesAnimation } public func usesAnimation(usesAnimation: Bool) { Manager.defaultManager.usesAnimation = usesAnimation } /* * Set whether or not Armchair uses a UIAlertController when presenting on iOS 8 * We prefer not to use it so that the Rate button can be on the bottom and the cancel button on the top, * Something not possible as of iOS 8.0 * Default => false */ public func usesAlertController() -> Bool { return Manager.defaultManager.usesAlertController } public func usesAlertController(usesAlertController: Bool) { Manager.defaultManager.usesAlertController = usesAlertController } /* * If set to true, Armchair will open App Store link inside the app using * SKStoreProductViewController. * - itunes affiliate codes DO NOT work on iOS 7 inside StoreKit, * - itunes affiliate codes DO work on iOS 8 inside StoreKit, * Default => false on iOS 7, true on iOS 8+ */ public func opensInStoreKit() -> Bool { return Manager.defaultManager.opensInStoreKit } public func opensInStoreKit(opensInStoreKit: Bool) { Manager.defaultManager.opensInStoreKit = opensInStoreKit } #endif // MARK: Events /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * If the user has performed enough significant events and used the app enough, * you can suppress the rating alert by passing false for canPromptForRating. The * rating alert will simply be postponed until it is called again with true for * canPromptForRating. */ public func userDidSignificantEvent(canPromptForRating: Bool) { Manager.defaultManager.userDidSignificantEvent(canPromptForRating) } /* * Tells Armchair that the user performed a significant event. * A significant event is whatever you want it to be. If you're app is used * to make VoIP calls, then you might want to call this method whenever the * user places a call. If it's a game, you might want to call this whenever * the user beats a level boss. * * This is similar to the userDidSignificantEvent method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func userDidSignificantEvent(shouldPrompt: ArmchairShouldPromptClosure) { Manager.defaultManager.userDidSignificantEvent(shouldPrompt) } // MARK: Prompts /* * Tells Armchair to show the prompt (a rating alert). The prompt * will be showed if there is an internet connection available, the user hasn't * declined to rate, hasn't rated current version and you are tracking new versions. * * You could call to show the prompt regardless of Armchair settings, * for instance, in the case of some special event in your app. */ public func showPrompt() { Manager.defaultManager.showPrompt() } /* * Tells Armchair to show the review prompt alert if all restrictions have been met. * The prompt will be shown if all restrictions are met, there is an internet connection available, * the user hasn't declined to rate, hasn't rated current version, and you are tracking new versions. * * You could call to show the prompt, for instance, in the case of some special event in your app, * like a user login. */ public func showPromptIfNecessary() { Manager.defaultManager.showPrompt(ifNecessary: true) } /* * Tells Armchair to show the review prompt alert. * * This is similar to the showPromptIfNecessary method, but allows the passing of a * ArmchairShouldPromptClosure that will be executed before prompting. * The closure passes all the keys and values that Armchair uses to * determine if it the prompt conditions have been met, and it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * The closure is run synchronous and on the main queue, so be sure to handle it appropriately. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func showPrompt(shouldPrompt: ArmchairShouldPromptClosure) { Manager.defaultManager.showPrompt(shouldPrompt) } // MARK: Misc /* * This is the review URL string, generated by substituting the appID, affiliate code * and affilitate campaign code into the template URL. */ public func reviewURLString() -> String { return Manager.defaultManager.reviewURLString() } /* * Tells Armchair to open the App Store page where the user can specify a * rating for the app. Also records the fact that this has happened, so the * user won't be prompted again to rate the app. * * The only case where you should call this directly is if your app has an * explicit "Rate this app" command somewhere. In all other cases, don't worry * about calling this -- instead, just call the other functions listed above, * and let Armchair handle the bookkeeping of deciding when to ask the user * whether to rate the app. */ public func rateApp() { Manager.defaultManager.rateApp() } #if os(iOS) /* * Tells Armchair to immediately close any open rating modals * for instance, a StoreKit rating View Controller. */ public func closeModalPanel() { Manager.defaultManager.closeModalPanel() } #endif // MARK: Closures /* * Armchair uses closures instead of delegate methods for callbacks. * Default is nil for all of them. */ public typealias ArmchairClosure = () -> () public typealias ArmchairAnimateClosure = (Bool) -> () public typealias ArmchairShouldPromptClosure = (ArmchairTrackingInfo) -> Bool public typealias ArmchairShouldIncrementClosure = () -> Bool public func onDidDisplayAlert(didDisplayAlertClosure: ArmchairClosure?) { Manager.defaultManager.didDisplayAlertClosure = didDisplayAlertClosure } public func onDidDeclineToRate(didDeclineToRateClosure: ArmchairClosure?) { Manager.defaultManager.didDeclineToRateClosure = didDeclineToRateClosure } public func onDidOptToRate(didOptToRateClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRateClosure = didOptToRateClosure } public func onDidOptToRemindLater(didOptToRemindLaterClosure: ArmchairClosure?) { Manager.defaultManager.didOptToRemindLaterClosure = didOptToRemindLaterClosure } #if os(iOS) public func onWillPresentModalView(willPresentModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.willPresentModalViewClosure = willPresentModalViewClosure } public func onDidDismissModalView(didDismissModalViewClosure: ArmchairAnimateClosure?) { Manager.defaultManager.didDismissModalViewClosure = didDismissModalViewClosure } #endif /* * The setShouldPromptClosure is called just after all the rating coditions * have been met and Armchair has decided it should display a prompt, * but just before the prompt actually displays. * * The closure passes all the keys and values that Armchair used to * determine that the prompt conditions had been met, but it is up to you * to use this info and return a Bool on whether or not the prompt should be shown. * Return true to proceed and show the prompt, return false to kill the pending presentation. */ public func shouldPromptClosure(shouldPromptClosure: ArmchairShouldPromptClosure?) { Manager.defaultManager.shouldPromptClosure = shouldPromptClosure } /* * The setShouldIncrementUseClosure, if valid, is called before incrementing the use count. * Returning false allows you to ignore a use. This may be usefull in cases such as Facebook login * where the app is backgrounded momentarily and the resultant enter foreground event should * not be considered another use. */ public func shouldIncrementUseCountClosure(shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure?) { Manager.defaultManager.shouldIncrementUseCountClosure = shouldIncrementUseCountClosure } // MARK: - // MARK: Armchair Defaults Protocol @objc public protocol ArmchairDefaultsObject { func objectForKey(defaultName: String) -> AnyObject? func setObject(value: AnyObject?, forKey defaultName: String) func removeObjectForKey(defaultName: String) func stringForKey(defaultName: String) -> String? func integerForKey(defaultName: String) -> Int func doubleForKey(defaultName: String) -> Double func boolForKey(defaultName: String) -> Bool func setInteger(value: Int, forKey defaultName: String) func setDouble(value: Double, forKey defaultName: String) func setBool(value: Bool, forKey defaultName: String) func synchronize() -> Bool } public class StandardUserDefaults: ArmchairDefaultsObject { let defaults = NSUserDefaults.standardUserDefaults() @objc public func objectForKey(defaultName: String) -> AnyObject? { return defaults.objectForKey(defaultName) } @objc public func setObject(value: AnyObject?, forKey defaultName: String) { defaults.setObject(value, forKey: defaultName) } @objc public func removeObjectForKey(defaultName: String) { defaults.removeObjectForKey(defaultName) } @objc public func stringForKey(defaultName: String) -> String? { return defaults.stringForKey(defaultName) } @objc public func integerForKey(defaultName: String) -> Int { return defaults.integerForKey(defaultName) } @objc public func doubleForKey(defaultName: String) -> Double { return defaults.doubleForKey(defaultName) } @objc public func boolForKey(defaultName: String) -> Bool { return defaults.boolForKey(defaultName) } @objc public func setInteger(value: Int, forKey defaultName: String) { defaults.setInteger(value, forKey: defaultName) } @objc public func setDouble(value: Double, forKey defaultName: String) { defaults.setDouble(value, forKey: defaultName) } @objc public func setBool(value: Bool, forKey defaultName: String) { defaults.setBool(value, forKey: defaultName) } @objc public func synchronize() -> Bool { return defaults.synchronize() } } public enum ArmchairKey: String, CustomStringConvertible { case FirstUseDate = "First Use Date" case UseCount = "Use Count" case SignificantEventCount = "Significant Event Count" case CurrentVersion = "Current Version" case RatedCurrentVersion = "Rated Current Version" case DeclinedToRate = "Declined To Rate" case ReminderRequestDate = "Reminder Request Date" case PreviousVersion = "Previous Version" case PreviousVersionRated = "Previous Version Rated" case PreviousVersionDeclinedToRate = "Previous Version Declined To Rate" case RatedAnyVersion = "Rated Any Version" case AppiraterMigrationCompleted = "Appirater Migration Completed" case UAAppReviewManagerMigrationCompleted = "UAAppReviewManager Migration Completed" static let allValues = [FirstUseDate, UseCount, SignificantEventCount, CurrentVersion, RatedCurrentVersion, DeclinedToRate, ReminderRequestDate, PreviousVersion, PreviousVersionRated, PreviousVersionDeclinedToRate, RatedAnyVersion, AppiraterMigrationCompleted, UAAppReviewManagerMigrationCompleted] public var description : String { get { return self.rawValue } } } public class ArmchairTrackingInfo: CustomStringConvertible { public let info: Dictionary<ArmchairKey, AnyObject> init(info: Dictionary<ArmchairKey, AnyObject>) { self.info = info } public var description: String { get { var description = "ArmchairTrackingInfo\r" for (key, val) in info { description += " - \(key): \(val)\r" } return description } } } public struct AppiraterKey { static var FirstUseDate = "kAppiraterFirstUseDate" static var UseCount = "kAppiraterUseCount" static var SignificantEventCount = "kAppiraterSignificantEventCount" static var CurrentVersion = "kAppiraterCurrentVersion" static var RatedCurrentVersion = "kAppiraterRatedCurrentVersion" static var RatedAnyVersion = "kAppiraterRatedAnyVersion" static var DeclinedToRate = "kAppiraterDeclinedToRate" static var ReminderRequestDate = "kAppiraterReminderRequestDate" } // MARK: - // MARK: PRIVATE Interface #if os(iOS) public class ArmchairManager : NSObject, UIAlertViewDelegate, SKStoreProductViewControllerDelegate { } #elseif os(OSX) public class ArmchairManager : NSObject, NSAlertDelegate { } #else // Untested, and currently unsupported #endif public class Manager : ArmchairManager { #if os(iOS) private var operatingSystemVersion = NSString(string: UIDevice.currentDevice().systemVersion).doubleValue #elseif os(OSX) private var operatingSystemVersion = Double(NSProcessInfo.processInfo().operatingSystemVersion.majorVersion) #else #endif // MARK: - // MARK: Review Alert & Properties #if os(iOS) private var ratingAlert: UIAlertView? = nil private let reviewURLTemplate = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&id=APP_ID&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE" #elseif os(OSX) private var ratingAlert: NSAlert? = nil private let reviewURLTemplate = "macappstore://itunes.apple.com/us/app/idAPP_ID?ls=1&mt=12&at=AFFILIATE_CODE&ct=AFFILIATE_CAMPAIGN_CODE" #else #endif private lazy var appName: String = self.defaultAppName() private func defaultAppName() -> String { let mainBundle = NSBundle.mainBundle() let displayName = mainBundle.objectForInfoDictionaryKey("CFBundleDisplayName") as? String let bundleNameKey = kCFBundleNameKey as String let name = mainBundle.objectForInfoDictionaryKey(bundleNameKey) as? String return displayName ?? name ?? "This App" } private lazy var reviewTitle: String = self.defaultReviewTitle() private func defaultReviewTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedStringForKey(template, value:"", table: "ArmchairLocalizable") } return template.stringByReplacingOccurrencesOfString("%@", withString: "\(self.appName)", options: NSStringCompareOptions(rawValue: 0), range: nil) } private lazy var reviewMessage: String = self.defaultReviewMessage() private func defaultReviewMessage() -> String { var template = "If you enjoy using %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedStringForKey(template, value:"", table: "ArmchairLocalizable") } return template.stringByReplacingOccurrencesOfString("%@", withString: "\(self.appName)", options: NSStringCompareOptions(rawValue: 0), range: nil) } private lazy var cancelButtonTitle: String = self.defaultCancelButtonTitle() private func defaultCancelButtonTitle() -> String { var title = "No, Thanks" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedStringForKey(title, value:"", table: "ArmchairLocalizable") } return title } private lazy var rateButtonTitle: String = self.defaultRateButtonTitle() private func defaultRateButtonTitle() -> String { var template = "Rate %@" // Check for a localized version of the default title if let bundle = self.bundle() { template = bundle.localizedStringForKey(template, value:"", table: "ArmchairLocalizable") } return template.stringByReplacingOccurrencesOfString("%@", withString: "\(self.appName)", options: NSStringCompareOptions(rawValue: 0), range: nil) } private lazy var remindButtonTitle: String? = self.defaultRemindButtonTitle() private func defaultRemindButtonTitle() -> String? { //if reminders are disabled, return a nil title to supress the button if self.daysBeforeReminding == 0 { return nil } var title = "Remind me later" // Check for a localized version of the default title if let bundle = self.bundle() { title = bundle.localizedStringForKey(title, value:"", table: "ArmchairLocalizable") } return title } // Tracking Logic / Configuration private var appID: String = "" { didSet { keyPrefix = defaultKeyPrefix() if affiliateCampaignCode == defaultAffiliateCampaignCode() { affiliateCampaignCode = affiliateCampaignCode + "-\(appID)" } } } // MARK: Properties with sensible defaults private var daysUntilPrompt: UInt = 30 private var usesUntilPrompt: UInt = 20 private var significantEventsUntilPrompt: UInt = 0 private var daysBeforeReminding: UInt = 1 private var tracksNewVersions: Bool = true private var shouldPromptIfRated: Bool = true private var useMainAppBundleForLocalizations: Bool = false private var debugEnabled: Bool = false { didSet { if self.debugEnabled { debugLog("Debug enabled for app: \(appID)") } } } // If you aren't going to set an affiliate code yourself, please leave this as is. // It is my affiliate code. It is better that somebody's code is used rather than nobody's. private var affiliateCode: String = "11l7j9" private var affiliateCampaignCode: String = "Armchair" #if os(iOS) private var usesAnimation: Bool = true private var usesAlertController: Bool = false private lazy var opensInStoreKit: Bool = self.defaultOpensInStoreKit() private func defaultOpensInStoreKit() -> Bool { return operatingSystemVersion >= 8 } #endif // MARK: Tracking Keys with sensible defaults private lazy var armchairKeyFirstUseDate: String = self.defaultArmchairKeyFirstUseDate() private lazy var armchairKeyUseCount: String = self.defaultArmchairKeyUseCount() private lazy var armchairKeySignificantEventCount: String = self.defaultArmchairKeySignificantEventCount() private lazy var armchairKeyCurrentVersion: String = self.defaultArmchairKeyCurrentVersion() private lazy var armchairKeyRatedCurrentVersion: String = self.defaultArmchairKeyRatedCurrentVersion() private lazy var armchairKeyDeclinedToRate: String = self.defaultArmchairKeyDeclinedToRate() private lazy var armchairKeyReminderRequestDate: String = self.defaultArmchairKeyReminderRequestDate() private lazy var armchairKeyPreviousVersion: String = self.defaultArmchairKeyPreviousVersion() private lazy var armchairKeyPreviousVersionRated: String = self.defaultArmchairKeyPreviousVersionRated() private lazy var armchairKeyPreviousVersionDeclinedToRate: String = self.defaultArmchairKeyPreviousVersionDeclinedToRate() private lazy var armchairKeyRatedAnyVersion: String = self.defaultArmchairKeyRatedAnyVersion() private lazy var armchairKeyAppiraterMigrationCompleted: String = self.defaultArmchairKeyAppiraterMigrationCompleted() private lazy var armchairKeyUAAppReviewManagerMigrationCompleted: String = self.defaultArmchairKeyUAAppReviewManagerMigrationCompleted() private func defaultArmchairKeyFirstUseDate() -> String { return "ArmchairFirstUseDate" } private func defaultArmchairKeyUseCount() -> String { return "ArmchairUseCount" } private func defaultArmchairKeySignificantEventCount() -> String { return "ArmchairSignificantEventCount" } private func defaultArmchairKeyCurrentVersion() -> String { return "ArmchairKeyCurrentVersion" } private func defaultArmchairKeyRatedCurrentVersion() -> String { return "ArmchairRatedCurrentVersion" } private func defaultArmchairKeyDeclinedToRate() -> String { return "ArmchairKeyDeclinedToRate" } private func defaultArmchairKeyReminderRequestDate() -> String { return "ArmchairReminderRequestDate" } private func defaultArmchairKeyPreviousVersion() -> String { return "ArmchairPreviousVersion" } private func defaultArmchairKeyPreviousVersionRated() -> String { return "ArmchairPreviousVersionRated" } private func defaultArmchairKeyPreviousVersionDeclinedToRate() -> String { return "ArmchairPreviousVersionDeclinedToRate" } private func defaultArmchairKeyRatedAnyVersion() -> String { return "ArmchairKeyRatedAnyVersion" } private func defaultArmchairKeyAppiraterMigrationCompleted() -> String { return "ArmchairAppiraterMigrationCompleted" } private func defaultArmchairKeyUAAppReviewManagerMigrationCompleted() -> String { return "ArmchairUAAppReviewManagerMigrationCompleted" } private lazy var keyPrefix: String = self.defaultKeyPrefix() private func defaultKeyPrefix() -> String { if !self.appID.isEmpty { return self.appID + "_" } else { return "_" } } private var userDefaultsObject:ArmchairDefaultsObject? = StandardUserDefaults() // MARK: Optional Closures var didDisplayAlertClosure: ArmchairClosure? var didDeclineToRateClosure: ArmchairClosure? var didOptToRateClosure: ArmchairClosure? var didOptToRemindLaterClosure: ArmchairClosure? #if os(iOS) var willPresentModalViewClosure: ArmchairAnimateClosure? var didDismissModalViewClosure: ArmchairAnimateClosure? #endif var shouldPromptClosure: ArmchairShouldPromptClosure? var shouldIncrementUseCountClosure: ArmchairShouldIncrementClosure? // MARK: State Vars private var modalPanelOpen: Bool = false #if os(iOS) private lazy var currentStatusBarStyle: UIStatusBarStyle = { return UIApplication.sharedApplication().statusBarStyle }() #endif // MARK: - // MARK: PRIVATE Methods private func userDidSignificantEvent(canPromptForRating: Bool) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { self.incrementSignificantEventAndRate(canPromptForRating) } } private func userDidSignificantEvent(shouldPrompt: ArmchairShouldPromptClosure) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { self.incrementSignificantEventAndRate(shouldPrompt) } } // MARK: - // MARK: PRIVATE Rating Helpers private func incrementAndRate(canPromptForRating: Bool) { migrateKeysIfNecessary() incrementUseCount() showPrompt(ifNecessary: canPromptForRating) } private func incrementAndRate(shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementUseCount() showPrompt(shouldPrompt) } private func incrementSignificantEventAndRate(canPromptForRating: Bool) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(ifNecessary: canPromptForRating) } private func incrementSignificantEventAndRate(shouldPrompt: ArmchairShouldPromptClosure) { migrateKeysIfNecessary() incrementSignificantEventCount() showPrompt(shouldPrompt) } private func incrementUseCount() { var shouldIncrement = true if let closure = shouldIncrementUseCountClosure { shouldIncrement = closure() } if shouldIncrement { _incrementCountForKeyType(ArmchairKey.UseCount) } } private func incrementSignificantEventCount() { _incrementCountForKeyType(ArmchairKey.SignificantEventCount) } private func _incrementCountForKeyType(incrementKeyType: ArmchairKey) { let incrementKey = keyForArmchairKeyType(incrementKeyType) let bundleVersionKey = kCFBundleVersionKey as String // App's version. Not settable as the other ivars because that would be crazy. let currentVersion = NSBundle.mainBundle().objectForInfoDictionaryKey(bundleVersionKey) as? String if currentVersion == nil { assertionFailure("Could not read kCFBundleVersionKey from InfoDictionary") return } // Get the version number that we've been tracking thus far let currentVersionKey = keyForArmchairKeyType(ArmchairKey.CurrentVersion) var trackingVersion: String? = userDefaultsObject?.stringForKey(currentVersionKey) // New install, or changed keys if trackingVersion == nil { trackingVersion = currentVersion userDefaultsObject?.setObject(currentVersion, forKey: currentVersionKey) } debugLog("Tracking version: \(trackingVersion!)") if trackingVersion == currentVersion { // Check if the first use date has been set. if not, set it. let firstUseDateKey = keyForArmchairKeyType(ArmchairKey.FirstUseDate) var timeInterval: Double? = userDefaultsObject?.doubleForKey(firstUseDateKey) if 0 == timeInterval { timeInterval = NSDate().timeIntervalSince1970 userDefaultsObject?.setObject(NSNumber(double: timeInterval!), forKey: firstUseDateKey) } // Increment the key's count var incrementKeyCount = userDefaultsObject?.integerForKey(incrementKey) userDefaultsObject?.setInteger(++incrementKeyCount!, forKey:incrementKey) debugLog("Incremented \(incrementKeyType): \(incrementKeyCount!)") } else if tracksNewVersions { // it's a new version of the app, so restart tracking userDefaultsObject?.setObject(trackingVersion, forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersion)) userDefaultsObject?.setObject(userDefaultsObject?.objectForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionRated)) userDefaultsObject?.setObject(userDefaultsObject?.objectForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)), forKey: keyForArmchairKeyType(ArmchairKey.PreviousVersionDeclinedToRate)) userDefaultsObject?.setObject(currentVersion, forKey: currentVersionKey) userDefaultsObject?.setObject(NSNumber(double: NSDate().timeIntervalSince1970), forKey: keyForArmchairKeyType(ArmchairKey.FirstUseDate)) userDefaultsObject?.setObject(NSNumber(integer: 1), forKey: keyForArmchairKeyType(ArmchairKey.UseCount)) userDefaultsObject?.setObject(NSNumber(integer: 0), forKey: keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) userDefaultsObject?.setObject(NSNumber(bool: false), forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setObject(NSNumber(bool: false), forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) userDefaultsObject?.setObject(NSNumber(double: 0), forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) debugLog("Reset Tracking Version to: \(trackingVersion!)") } userDefaultsObject?.synchronize() } private func showPrompt(ifNecessary canPromptForRating: Bool) { if canPromptForRating && connectedToNetwork() && ratingConditionsHaveBeenMet() { var shouldPrompt: Bool = true if let closure = shouldPromptClosure { if NSThread.isMainThread() { shouldPrompt = closure(trackingInfo()) } else { dispatch_sync(dispatch_get_main_queue()) { shouldPrompt = closure(self.trackingInfo()) } } } if shouldPrompt { dispatch_async(dispatch_get_main_queue()) { self.showRatingAlert() } } } } private func showPrompt(shouldPrompt: ArmchairShouldPromptClosure) { var shouldPromptVal = false if NSThread.isMainThread() { shouldPromptVal = shouldPrompt(trackingInfo()) } else { dispatch_sync(dispatch_get_main_queue()) { shouldPromptVal = shouldPrompt(self.trackingInfo()) } } if (shouldPromptVal) { dispatch_async(dispatch_get_main_queue()) { self.showRatingAlert() } } } private func showPrompt() { if !appID.isEmpty && connectedToNetwork() && !userHasDeclinedToRate() && !userHasRatedCurrentVersion() { showRatingAlert() } } private func ratingConditionsHaveBeenMet() -> Bool { if debugEnabled { return true } if appID.isEmpty { return false } // check if the app has been used long enough let timeIntervalOfFirstLaunch = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.FirstUseDate)) if let timeInterval = timeIntervalOfFirstLaunch { let dateOfFirstLaunch = NSDate(timeIntervalSince1970: timeInterval) let timeSinceFirstLaunch = NSDate().timeIntervalSinceDate(dateOfFirstLaunch) let timeUntilRate: NSTimeInterval = 60 * 60 * 24 * Double(daysUntilPrompt) if timeSinceFirstLaunch < timeUntilRate { return false } } else { return false } // check if the app has been used enough times let useCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.UseCount)) if let count = useCount { if UInt(count) <= usesUntilPrompt { return false } } else { return false } // check if the user has done enough significant events let significantEventCount = userDefaultsObject?.integerForKey(keyForArmchairKeyType(ArmchairKey.SignificantEventCount)) if let count = significantEventCount { if UInt(count) < significantEventsUntilPrompt { return false } } else { return false } // Check if the user previously has declined to rate this version of the app if userHasDeclinedToRate() { return false } // Check if the user has already rated the app? if userHasRatedCurrentVersion() { return false } // If the user wanted to be reminded later, has enough time passed? let timeIntervalOfReminder = userDefaultsObject?.doubleForKey(keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) if let timeInterval = timeIntervalOfReminder { let reminderRequestDate = NSDate(timeIntervalSince1970: timeInterval) let timeSinceReminderRequest = NSDate().timeIntervalSinceDate(reminderRequestDate) let timeUntilReminder: NSTimeInterval = 60 * 60 * 24 * Double(daysBeforeReminding) if timeSinceReminderRequest < timeUntilReminder { return false } } else { return false } // if we have a global set to not show if the end-user has already rated once, and the developer has not opted out of displaying on minor updates let ratedAnyVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) if let ratedAlready = ratedAnyVersion { if (!shouldPromptIfRated && ratedAlready) { return false } } return true } private func userHasDeclinedToRate() -> Bool { if let declined = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) { return declined } else { return false } } private func userHasRatedCurrentVersion() -> Bool { if let ratedCurrentVersion = userDefaultsObject?.boolForKey(keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) { return ratedCurrentVersion } else { return false } } private func showsRemindButton() -> Bool { return (remindButtonTitle != nil) } private func showRatingAlert() { #if os(iOS) if operatingSystemVersion >= 8 && usesAlertController { /* iOS 8 uses new UIAlertController API*/ let alertView : UIAlertController = UIAlertController(title: reviewTitle, message: reviewMessage, preferredStyle: UIAlertControllerStyle.Alert) alertView.addAction(UIAlertAction(title: cancelButtonTitle, style:UIAlertActionStyle.Cancel, handler: { (alert: UIAlertAction!) in self.dontRate() })) if (showsRemindButton()) { alertView.addAction(UIAlertAction(title: remindButtonTitle!, style:UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) in self.remindMeLater() })) } alertView.addAction(UIAlertAction(title: rateButtonTitle, style:UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) in self._rateApp() })) // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.sharedApplication().keyWindow?.rootViewController { if let topController = topMostViewController(presentingController) { topController.presentViewController(alertView, animated: usesAnimation) { print("presentViewController() completed") } } } } else { /* Otherwise we use UIAlertView still */ var alertView: UIAlertView if (showsRemindButton()) { alertView = UIAlertView(title: reviewTitle, message: reviewMessage, delegate: self, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: remindButtonTitle!, rateButtonTitle) } else { alertView = UIAlertView(title: reviewTitle, message: reviewMessage, delegate: self, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: rateButtonTitle) } // If we have a remind button, show it first. Otherwise show the rate button // If we have a remind button, show the rate button next. Otherwise stop adding buttons. alertView.cancelButtonIndex = -1 ratingAlert = alertView alertView.show() if let closure = didDisplayAlertClosure { closure() } } #elseif os(OSX) let alert: NSAlert = NSAlert() alert.messageText = reviewTitle alert.informativeText = reviewMessage alert.addButtonWithTitle(rateButtonTitle) if showsRemindButton() { alert.addButtonWithTitle(remindButtonTitle!) } alert.addButtonWithTitle(cancelButtonTitle) ratingAlert = alert if let window = NSApplication.sharedApplication().keyWindow { alert.beginSheetModalForWindow(window) { (response: NSModalResponse) in self.handleNSAlertReturnCode(response) } } else { let returnCode = alert.runModal() handleNSAlertReturnCode(returnCode) } if let closure = self.didDisplayAlertClosure { closure() } #else #endif } // MARK: - // MARK: PRIVATE Alert View / StoreKit Delegate Methods #if os(iOS) public func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { // cancelButtonIndex is set to -1 to show the cancel button up top, but a tap on it ends up here with index 0 if (alertView.cancelButtonIndex == buttonIndex || 0 == buttonIndex) { // they don't want to rate it dontRate() } else if (showsRemindButton() && 1 == buttonIndex) { // remind them later remindMeLater() } else { // they want to rate it _rateApp() } } //Delegate call from the StoreKit view. public func productViewControllerDidFinish(viewController: SKStoreProductViewController!) { closeModalPanel() } //Close the in-app rating (StoreKit) view and restore the previous status bar style. private func closeModalPanel() { if modalPanelOpen { UIApplication.sharedApplication().setStatusBarStyle(currentStatusBarStyle, animated:usesAnimation) let usedAnimation = usesAnimation modalPanelOpen = false // get the top most controller (= the StoreKit Controller) and dismiss it if let presentingController = UIApplication.sharedApplication().keyWindow?.rootViewController { if let topController = topMostViewController(presentingController) { topController.dismissViewControllerAnimated(usesAnimation) { if let closure = self.didDismissModalViewClosure { closure(usedAnimation) } } currentStatusBarStyle = UIStatusBarStyle.Default } } } } #elseif os(OSX) private func handleNSAlertReturnCode(returnCode: NSInteger) { switch (returnCode) { case NSAlertFirstButtonReturn: // they want to rate it _rateApp() case NSAlertSecondButtonReturn: // remind them later or cancel if showsRemindButton() { remindMeLater() } else { dontRate() } case NSAlertThirdButtonReturn: // they don't want to rate it dontRate() default: return } } #else #endif private func dontRate() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.DeclinedToRate)) userDefaultsObject?.synchronize() if let closure = didDeclineToRateClosure { closure() } } private func remindMeLater() { userDefaultsObject?.setDouble(NSDate().timeIntervalSince1970, forKey: keyForArmchairKeyType(ArmchairKey.ReminderRequestDate)) userDefaultsObject?.synchronize() if let closure = didOptToRemindLaterClosure { closure() } } private func _rateApp() { rateApp() if let closure = didOptToRateClosure { closure() } } private func rateApp() { userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion)) userDefaultsObject?.setBool(true, forKey: keyForArmchairKeyType(ArmchairKey.RatedAnyVersion)) userDefaultsObject?.synchronize() #if os(iOS) // Use the in-app StoreKit view if set, available (iOS 7+) and imported. This works in the simulator. if opensInStoreKit { let storeViewController = SKStoreProductViewController() var productParameters: [String:AnyObject]! = [SKStoreProductParameterITunesItemIdentifier : appID] if (operatingSystemVersion >= 8) { productParameters[SKStoreProductParameterAffiliateToken] = affiliateCode productParameters[SKStoreProductParameterCampaignToken] = affiliateCampaignCode } storeViewController.loadProductWithParameters(productParameters, completionBlock: nil) storeViewController.delegate = self if let closure = willPresentModalViewClosure { closure(usesAnimation) } if let rootController = getRootViewController() { rootController.presentViewController(storeViewController, animated: usesAnimation) { self.modalPanelOpen = true //Temporarily use a status bar to match the StoreKit view. self.currentStatusBarStyle = UIApplication.sharedApplication().statusBarStyle UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: self.usesAnimation) } } //Use the standard openUrl method } else { if let url = NSURL(string: reviewURLString()) { UIApplication.sharedApplication().openURL(url) } } if UIDevice.currentDevice().model.rangeOfString("Simulator") != nil { debugLog("iTunes App Store is not supported on the iOS simulator.") debugLog(" - We would have went to \(reviewURLString()).") debugLog(" - Try running on a test-device") let fakeURL = reviewURLString().stringByReplacingOccurrencesOfString("itms-apps", withString:"http") debugLog(" - Or try copy/pasting \(fakeURL) into a browser on your computer.") } #elseif os(OSX) if let url = NSURL(string: reviewURLString()) { let opened = NSWorkspace.sharedWorkspace().openURL(url) if !opened { debugLog("Failed to open \(url)") } } #else #endif } private func reviewURLString() -> String { let template = reviewURLTemplate var reviewURL = template.stringByReplacingOccurrencesOfString("APP_ID", withString: "\(appID)") reviewURL = reviewURL.stringByReplacingOccurrencesOfString("AFFILIATE_CODE", withString: "\(affiliateCode)") reviewURL = reviewURL.stringByReplacingOccurrencesOfString("AFFILIATE_CAMPAIGN_CODE", withString: "\(affiliateCampaignCode)") return reviewURL } // Mark: - // Mark: PRIVATE Key Helpers private func trackingInfo() -> ArmchairTrackingInfo { var trackingInfo: Dictionary<ArmchairKey, AnyObject> = [:] for keyType in ArmchairKey.allValues { let obj: AnyObject? = userDefaultsObject?.objectForKey(keyForArmchairKeyType(keyType)) if let val = obj as? NSObject { trackingInfo[keyType] = val } else { trackingInfo[keyType] = NSNull() } } return ArmchairTrackingInfo(info: trackingInfo) } private func keyForArmchairKeyType(keyType: ArmchairKey) -> String { switch (keyType) { case .FirstUseDate: return keyPrefix + armchairKeyFirstUseDate case .UseCount: return keyPrefix + armchairKeyUseCount case .SignificantEventCount: return keyPrefix + armchairKeySignificantEventCount case .CurrentVersion: return keyPrefix + armchairKeyCurrentVersion case .RatedCurrentVersion: return keyPrefix + armchairKeyRatedCurrentVersion case .DeclinedToRate: return keyPrefix + armchairKeyDeclinedToRate case .ReminderRequestDate: return keyPrefix + armchairKeyReminderRequestDate case .PreviousVersion: return keyPrefix + armchairKeyPreviousVersion case .PreviousVersionRated: return keyPrefix + armchairKeyPreviousVersionRated case .PreviousVersionDeclinedToRate: return keyPrefix + armchairKeyPreviousVersionDeclinedToRate case .RatedAnyVersion: return keyPrefix + armchairKeyRatedAnyVersion case .AppiraterMigrationCompleted: return keyPrefix + armchairKeyAppiraterMigrationCompleted case .UAAppReviewManagerMigrationCompleted: return keyPrefix + armchairKeyUAAppReviewManagerMigrationCompleted } } private func setKey(key: NSString, armchairKeyType: ArmchairKey) { switch armchairKeyType { case .FirstUseDate: armchairKeyFirstUseDate = key as String case .UseCount: armchairKeyUseCount = key as String case .SignificantEventCount: armchairKeySignificantEventCount = key as String case .CurrentVersion: armchairKeyCurrentVersion = key as String case .RatedCurrentVersion: armchairKeyRatedCurrentVersion = key as String case .DeclinedToRate: armchairKeyDeclinedToRate = key as String case .ReminderRequestDate: armchairKeyReminderRequestDate = key as String case .PreviousVersion: armchairKeyPreviousVersion = key as String case .PreviousVersionRated: armchairKeyPreviousVersionRated = key as String case .PreviousVersionDeclinedToRate: armchairKeyPreviousVersionDeclinedToRate = key as String case .RatedAnyVersion: armchairKeyRatedAnyVersion = key as String case .AppiraterMigrationCompleted: armchairKeyAppiraterMigrationCompleted = key as String case .UAAppReviewManagerMigrationCompleted: armchairKeyUAAppReviewManagerMigrationCompleted = key as String } } private func armchairKeyForAppiraterKey(appiraterKey: String) -> String { switch appiraterKey { case AppiraterKey.FirstUseDate: return keyForArmchairKeyType(ArmchairKey.FirstUseDate) case AppiraterKey.UseCount: return keyForArmchairKeyType(ArmchairKey.UseCount) case AppiraterKey.SignificantEventCount: return keyForArmchairKeyType(ArmchairKey.SignificantEventCount) case AppiraterKey.CurrentVersion: return keyForArmchairKeyType(ArmchairKey.CurrentVersion) case AppiraterKey.RatedCurrentVersion: return keyForArmchairKeyType(ArmchairKey.RatedCurrentVersion) case AppiraterKey.DeclinedToRate: return keyForArmchairKeyType(ArmchairKey.DeclinedToRate) case AppiraterKey.ReminderRequestDate: return keyForArmchairKeyType(ArmchairKey.ReminderRequestDate) case AppiraterKey.RatedAnyVersion: return keyForArmchairKeyType(ArmchairKey.RatedAnyVersion) default: return "" } } private func migrateAppiraterKeysIfNecessary() { let appiraterAlreadyCompletedKey: NSString = keyForArmchairKeyType(.AppiraterMigrationCompleted) let appiraterMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appiraterAlreadyCompletedKey as String) if let completed = appiraterMigrationAlreadyCompleted { if completed { return } } let oldKeys: [String] = [AppiraterKey.FirstUseDate, AppiraterKey.UseCount, AppiraterKey.SignificantEventCount, AppiraterKey.CurrentVersion, AppiraterKey.RatedCurrentVersion, AppiraterKey.RatedAnyVersion, AppiraterKey.DeclinedToRate, AppiraterKey.ReminderRequestDate] for oldKey in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { let newKey = armchairKeyForAppiraterKey(oldKey) userDefaultsObject?.setObject(val, forKey: newKey) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(bool: true), forKey: appiraterAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } // This only supports the default UAAppReviewManager keys. If you customized them, you will have to manually migrate your values over. private func migrateUAAppReviewManagerKeysIfNecessary() { let appReviewManagerAlreadyCompletedKey: NSString = keyForArmchairKeyType(.UAAppReviewManagerMigrationCompleted) let appReviewManagerMigrationAlreadyCompleted = userDefaultsObject?.boolForKey(appReviewManagerAlreadyCompletedKey as String) if let completed = appReviewManagerMigrationAlreadyCompleted { if completed { return } } // By default, UAAppReviewManager keys are in the format <appID>_UAAppReviewManagerKey<keyType> let oldKeys: [String:ArmchairKey] = ["\(appID)_UAAppReviewManagerKeyFirstUseDate" : ArmchairKey.FirstUseDate, "\(appID)_UAAppReviewManagerKeyUseCount" : ArmchairKey.UseCount, "\(appID)_UAAppReviewManagerKeySignificantEventCount" : ArmchairKey.SignificantEventCount, "\(appID)_UAAppReviewManagerKeyCurrentVersion" : ArmchairKey.CurrentVersion, "\(appID)_UAAppReviewManagerKeyRatedCurrentVersion" : ArmchairKey.RatedCurrentVersion, "\(appID)_UAAppReviewManagerKeyDeclinedToRate" : ArmchairKey.DeclinedToRate, "\(appID)_UAAppReviewManagerKeyReminderRequestDate" : ArmchairKey.ReminderRequestDate, "\(appID)_UAAppReviewManagerKeyPreviousVersion" : ArmchairKey.PreviousVersion, "\(appID)_UAAppReviewManagerKeyPreviousVersionRated" : ArmchairKey.PreviousVersionRated, "\(appID)_UAAppReviewManagerKeyPreviousVersionDeclinedToRate" : ArmchairKey.PreviousVersionDeclinedToRate, "\(appID)_UAAppReviewManagerKeyRatedAnyVersion" : ArmchairKey.RatedAnyVersion] for (oldKey, newKeyType) in oldKeys { let oldValue: NSObject? = userDefaultsObject?.objectForKey(oldKey) as? NSObject if let val = oldValue { userDefaultsObject?.setObject(val, forKey: keyForArmchairKeyType(newKeyType)) userDefaultsObject?.removeObjectForKey(oldKey) } } userDefaultsObject?.setObject(NSNumber(bool: true), forKey: appReviewManagerAlreadyCompletedKey as String) userDefaultsObject?.synchronize() } private func migrateKeysIfNecessary() { migrateAppiraterKeysIfNecessary() migrateUAAppReviewManagerKeysIfNecessary() } // MARK: - // MARK: Internet Connectivity private func connectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return false } var flags : SCNetworkReachabilityFlags = [] if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.Reachable) let needsConnection = flags.contains(.ConnectionRequired) return (isReachable && !needsConnection) } // MARK: - // MARK: PRIVATE Misc Helpers private func bundle() -> NSBundle? { var bundle: NSBundle? = nil if useMainAppBundleForLocalizations { bundle = NSBundle.mainBundle() } else { let armchairBundleURL: NSURL? = NSBundle.mainBundle().URLForResource("Armchair", withExtension: "bundle") if let url = armchairBundleURL { bundle = NSBundle(URL: url) } else { bundle = NSBundle.mainBundle() } } return bundle } #if os(iOS) private func topMostViewController(controller: UIViewController?) -> UIViewController? { var isPresenting: Bool = false var topController: UIViewController? = controller repeat { // this path is called only on iOS 6+, so -presentedViewController is fine here. if let controller = topController { if let presented = controller.presentedViewController { isPresenting = true topController = presented } else { isPresenting = false } } } while isPresenting return topController } private func getRootViewController() -> UIViewController? { if var window = UIApplication.sharedApplication().keyWindow { if window.windowLevel != UIWindowLevelNormal { let windows: NSArray = UIApplication.sharedApplication().windows for candidateWindow in windows { if let candidateWindow = candidateWindow as? UIWindow { if candidateWindow.windowLevel == UIWindowLevelNormal { window = candidateWindow break } } } } for subView in window.subviews { if let responder = subView.nextResponder() { if responder.isKindOfClass(UIViewController) { return topMostViewController(responder as? UIViewController) } } } } return nil } #endif private func hideRatingAlert() { if let alert = ratingAlert { debugLog("Hiding Alert") #if os(iOS) if alert.visible { alert.dismissWithClickedButtonIndex(alert.cancelButtonIndex, animated: false) } #elseif os(OSX) if let window = NSApplication.sharedApplication().keyWindow { NSApp.endSheet(window) } #else #endif ratingAlert = nil } } private func defaultAffiliateCode() -> String { return "11l7j9" } private func defaultAffiliateCampaignCode() -> String { return "Armchair" } // MARK: - // MARK: Notification Handlers public func appWillResignActive(notification: NSNotification) { debugLog("appWillResignActive:") hideRatingAlert() } public func applicationDidFinishLaunching(notification: NSNotification) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { self.debugLog("applicationDidFinishLaunching:") self.migrateKeysIfNecessary() self.incrementUseCount() } } public func applicationWillEnterForeground(notification: NSNotification) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { self.debugLog("applicationWillEnterForeground:") self.migrateKeysIfNecessary() self.incrementUseCount() } } // MARK: - // MARK: Singleton public class var defaultManager: Manager { assert(Armchair.appID != "", "Armchair.appID(appID: String) has to be the first Armchair call made.") struct Singleton { static let instance: Manager = Manager(appID: Armchair.appID) } return Singleton.instance } init(appID: String) { super.init() setupNotifications() } // MARK: Singleton Instance Setup private func setupNotifications() { #if os(iOS) NSNotificationCenter.defaultCenter().addObserver(self, selector: "appWillResignActive:", name: UIApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidFinishLaunching:", name: UIApplicationDidFinishLaunchingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil) #elseif os(OSX) NSNotificationCenter.defaultCenter().addObserver(self, selector: "appWillResignActive:", name: NSApplicationWillResignActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidFinishLaunching:", name: NSApplicationDidFinishLaunchingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterForeground:", name: NSApplicationWillBecomeActiveNotification, object: nil) #else #endif } // MARK: - // MARK: Printable override public var debugDescription: String { get { return "Armchair: appID=\(Armchair.appID)" } } // MARK: - // MARK: Debug let lockQueue = dispatch_queue_create("com.armchair.lockqueue", nil) private func debugLog(log: String) { if debugEnabled { dispatch_sync(lockQueue, { print("[Armchair] \(log)") }) } } }
mit
243925662b959ce04dd30a667a022aa0
41.824348
302
0.68287
5.082703
false
false
false
false
ostholz/ercode
ERCode/GalleryController.swift
1
5964
// // GalleryController.swift // ERCode // // Created by Dong Wang on 03.11.14. // Copyright (c) 2014 i2dm. All rights reserved. // import Foundation class GalleryController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { /* TODO: die Hintergrundbilder wurden (sollen) in ~/Documents/wallpapers/ gespeichert. die Thumbnaibilder wurde in ~/Documents/thumbs/ gespeichert. */ @IBOutlet weak var allWallpapers: UICollectionView! var imageslider = NSMutableArray() // var swipeLeftRecognizer : UISwipeGestureRecognizer? // var swipeRightRecognizer : UISwipeGestureRecognizer? // var tapRecognizer : UITapGestureRecognizer? override func viewWillAppear(animated: Bool) { // self.navigationController?.navigationBarHidden = true self.navigationController?.navigationBar.topItem?.title = "WALLPAPER" self.navigationController?.navigationBar.topItem? allWallpapers.reloadData() } override func viewDidLoad() { // Defined as Global Variable in StatusChecker.swift savedWallpaper = NSUserDefaults.standardUserDefaults().objectForKey("wallpapers") as? NSMutableArray if savedWallpaper == nil { savedWallpaper = NSMutableArray() } if (savedWallpaper?.count == 0) { savedWallpaper?.addObject(NSDictionary(objects: ["addNewWallpaper", "add_wp_cell.png"], forKeys: [kKeyWallpapername, kKeyThumbname])) } // right bar button let rightBarButton = UIBarButtonItem(image: UIImage(named: "add_wp_icon.png"), style: UIBarButtonItemStyle.Plain, target: self, action: "createNewWallpaper:") self.navigationItem.rightBarButtonItem = rightBarButton for p in 0...2 { let swipeLeftRecognizer = UISwipeGestureRecognizer(target: self, action: "didSwipeLeft:") let swipeRightRecognizer = UISwipeGestureRecognizer(target: self, action: "didSwipeRight:") let tapRecognizer = UITapGestureRecognizer(target: self, action: "tapBackToMain:") let imageView = UIImageView(frame: CGRectZero) imageView.userInteractionEnabled = true imageView.addGestureRecognizer(swipeLeftRecognizer) imageView.addGestureRecognizer(swipeRightRecognizer) imageView.addGestureRecognizer(tapRecognizer) imageslider.addObject(imageView) } } deinit{ // TODO: Save Wallpaper list NSUserDefaults.standardUserDefaults().setObject(savedWallpaper, forKey: "wallpapers") NSUserDefaults.standardUserDefaults().synchronize() } func setCollectionView() { let filemanager = NSFileManager.defaultManager() let documentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String // let contents = filemanager.contentsAtPath(documentPath) as [String] // for filename in contents { // if (filename.hasPrefix("wallpaper")) { // // } // } } func didSwipeLeft(recognizer: UISwipeGestureRecognizer) { println("swipe left") } func didSwipeRight(recognizer: UISwipeGestureRecognizer) { println("swipe right") } func tapBackToMain(recognizer: UITapGestureRecognizer) { let currentIV = imageslider[1] as UIImageView let thisWidth = self.view.bounds.width let thisHeight = self.view.bounds.height let maskview = self.view.viewWithTag(199) maskview?.removeFromSuperview() UIView.animateWithDuration(0.4, animations: { currentIV.frame = CGRectMake(thisWidth / 2, thisHeight / 2, 0, 0) }, completion: { [unowned self] (Bool) -> Void in currentIV.removeFromSuperview() } ) } func makeSlider(index: Int) { let maskview = UIView(frame: self.view.bounds) maskview.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8) maskview.tag = 199 self.view.addSubview(maskview) if index == 0 { } let namedict = savedWallpaper?[index] as NSDictionary let currentIV = imageslider[1] as UIImageView currentIV.image = StatusChecker.getWallpaper(namedict[kKeyWallpapername] as NSString) let thisWidth = self.view.bounds.width let thisHeight = self.view.bounds.height currentIV.frame = CGRectMake(thisWidth / 2, thisWidth / 2, 0, 0) self.view.addSubview(currentIV) UIView.animateWithDuration(0.4, animations: { currentIV.frame = CGRectMake(0, 0, thisWidth, thisHeight) }) } // MARK: - custom Methods @IBAction func createNewWallpaper(sender: AnyObject) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let wallpaperVC = storyboard.instantiateViewControllerWithIdentifier("Wallpaper") as UIViewController self.navigationController?.pushViewController(wallpaperVC, animated: true) } // MARK: - UICollectionView DataSource and Delegate Methods func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("WallpaperCell", forIndexPath: indexPath) as UICollectionViewCell var imageview: UIImageView = cell.contentView.viewWithTag(101) as UIImageView // tag: 101 let namedict: NSDictionary = savedWallpaper?[indexPath.row] as NSDictionary let wpname: NSString = namedict[kKeyThumbname] as NSString if wpname == "add_wp_cell.png" { imageview.image = UIImage(named: "add_wp_cell.png") } else { imageview.image = StatusChecker.getWallpaper(wpname) } // cell.layer.borderColor = UIColor.grayColor().CGColor // cell.layer.borderWidth = 1.0 return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if indexPath.row == (savedWallpaper!.count - 1) { createNewWallpaper(self) } else { makeSlider(indexPath.row) } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return savedWallpaper!.count } }
apache-2.0
3109440ff4c6d90dbcd67db343717ef7
31.950276
157
0.729544
4.612529
false
false
false
false
MiezelKat/AWSense
AWSenseConnect/AWSenseConnectWatch/SensingDataBuffer.swift
1
2958
// // SensingDataBuffer.swift // AWSenseConnect // // Created by Katrin Hansel on 05/03/2017. // Copyright © 2017 Katrin Haensel. All rights reserved. // import Foundation import AWSenseShared internal class SensingDataBuffer{ private let bufferLimit = 1024 private let bufferLimitHR = 10 // MARK: - properties var sensingSession : SensingSession var sensingBuffers : [AWSSensorType : [AWSSensorData]] var sensingBufferBatchNo : [AWSSensorType : Int] var sensingBufferEvent : SensingBufferEvent = SensingBufferEvent() // MARK: - init init(withSession session : SensingSession){ sensingSession = session sensingBuffers = [AWSSensorType : [AWSSensorData]]() sensingBufferBatchNo = [AWSSensorType : Int]() for s : AWSSensorType in sensingSession.sensorConfig.enabledSensors{ sensingBuffers[s] = [AWSSensorData]() sensingBufferBatchNo[s] = 1 } } // MARK: - methods func append(sensingData data: AWSSensorData, forType type: AWSSensorType){ let count = sensingBuffers[type]!.count sensingBuffers[type]!.append(data) if(type != .heart_rate && count > bufferLimit){ if(type == .device_motion){ print("devide motion") } sensingBufferEvent.raiseEvent(withType: .bufferLimitReached, forSensor: type) }else if (type == .heart_rate && count > bufferLimitHR){ sensingBufferEvent.raiseEvent(withType: .bufferLimitReached, forSensor: type) } } func prepareDataToSend(forType type: AWSSensorType) -> (Int, [AWSSensorData]){ let batchNo = sensingBufferBatchNo[type]! let data = sensingBuffers[type]! // reset the buffer sensingBuffers[type]!.removeAll(keepingCapacity: true) return (batchNo, data) } public func subscribe(handler: SensingBufferEventHandler){ sensingBufferEvent.add(handler: handler) } public func unsubscribe(handler: SensingBufferEventHandler){ sensingBufferEvent.remove(handler: handler) } } class SensingBufferEvent{ private var eventHandlers = [SensingBufferEventHandler]() public func raiseEvent(withType type: SensingBufferEventType, forSensor stype : AWSSensorType) { for handler in self.eventHandlers { handler.handle(withType: type, forSensor: stype) } } public func add(handler: SensingBufferEventHandler){ eventHandlers.append(handler) } public func remove(handler: SensingBufferEventHandler){ eventHandlers = eventHandlers.filter { $0 !== handler } } } protocol SensingBufferEventHandler : class { func handle(withType type: SensingBufferEventType, forSensor stype: AWSSensorType) } enum SensingBufferEventType{ case bufferLimitReached }
mit
c5053f0653119d618d467609124148f3
28.277228
100
0.655394
4.38724
false
false
false
false
justeat/JustPeek
JustPeek/Classes/PeekViewController.swift
1
3435
// // PeekViewController.swift // JustPeek // // Copyright 2016 Just Eat Holdings Ltd. // import UIKit internal class PeekViewController: UIViewController { fileprivate let peekContext: PeekContext fileprivate let contentView: UIView fileprivate let peekView: PeekView internal init?(peekContext: PeekContext) { self.peekContext = peekContext guard let contentViewController = peekContext.destinationViewController else { return nil } // NOTE: it seems UIVisualEffectView has a blur radius too high for what we want to achieve... moreover // it's not safe to animate it's alpha component peekView = PeekView(frame: peekContext.initalPreviewFrame(), contentView: contentViewController.view) contentView = UIApplication.shared.keyWindow!.blurredSnapshotView //UIScreen.mainScreen().blurredSnapshotView super.init(nibName: nil, bundle: nil) peekView.frame = convertedInitialFrame() } override func viewDidLoad() { super.viewDidLoad() view.addSubview(contentView) contentView.addSubview(peekView) } internal required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) must not be used") } internal func peek(_ completion: ((Bool) -> Void)? = nil) { animatePeekView(true, completion: completion) } internal func pop(_ completion: ((Bool) -> Void)?) { animatePeekView(false, completion: completion) } fileprivate func convertedInitialFrame() -> CGRect { return self.view.convert(peekContext.initalPreviewFrame(), from: peekContext.sourceView) } fileprivate func animatePeekView(_ forBeingPresented: Bool, completion: ((Bool) -> Void)?) { let destinationFrame = forBeingPresented ? peekContext.finalPreviewFrame() : convertedInitialFrame() contentView.alpha = forBeingPresented ? 0.0 : 1.0 let contentViewAnimation = { [weak self] in if let strongSelf = self { strongSelf.contentView.alpha = 1.0 - strongSelf.contentView.alpha } } peekView.animateToFrame(destinationFrame, alongsideAnimation: contentViewAnimation, completion: completion) } } private extension UIScreen { var blurredSnapshotView: UIView { get { let view = UIScreen.main.snapshotView(afterScreenUpdates: false) return view.blurredSnapshotView } } } private extension UIView { var blurredSnapshotView: UIView { get { let view = UIImageView(frame: bounds) if let image = snapshot { let radius = CGFloat(20.0) // just because with this value the result looks good view.image = image.applyBlur(withRadius: radius, tintColor: nil, saturationDeltaFactor: 1.0, maskImage: nil) } return view } } var snapshot: UIImage? { get { UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) if let context = UIGraphicsGetCurrentContext() { layer.render(in: context) } else { drawHierarchy(in: bounds, afterScreenUpdates: false) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } }
apache-2.0
8cf32b4b24d3f17ecc3239195bef45ca
33.35
124
0.640757
5.149925
false
false
false
false
Harry-L/5-3-1
ios-charts-master/Charts/Classes/Data/Implementations/Standard/LineChartDataSet.swift
3
4879
// // LineChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet { private func initialize() { // default color circleColors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) } public required init() { super.init() initialize() } public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) initialize() } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors private var _cubicIntensity = CGFloat(0.2) /// Intensity for cubic lines (min = 0.05, max = 1) /// /// **default**: 0.2 public var cubicIntensity: CGFloat { get { return _cubicIntensity } set { _cubicIntensity = newValue if (_cubicIntensity > 1.0) { _cubicIntensity = 1.0 } if (_cubicIntensity < 0.05) { _cubicIntensity = 0.05 } } } /// If true, cubic lines are drawn instead of linear public var drawCubicEnabled = false /// - returns: true if drawing cubic lines is enabled, false if not. public var isDrawCubicEnabled: Bool { return drawCubicEnabled } /// The radius of the drawn circles. public var circleRadius = CGFloat(8.0) public var circleColors = [UIColor]() /// - returns: the color at the given index of the DataSet's circle-color array. /// Performs a IndexOutOfBounds check by modulus. public func getCircleColor(var index: Int) -> UIColor? { let size = circleColors.count index = index % size if (index >= size) { return nil } return circleColors[index] } /// Sets the one and ONLY color that should be used for this DataSet. /// Internally, this recreates the colors array and adds the specified color. public func setCircleColor(color: UIColor) { circleColors.removeAll(keepCapacity: false) circleColors.append(color) } /// Resets the circle-colors array and creates a new one public func resetCircleColors(index: Int) { circleColors.removeAll(keepCapacity: false) } /// If true, drawing circles is enabled public var drawCirclesEnabled = true /// - returns: true if drawing circles for this DataSet is enabled, false if not public var isDrawCirclesEnabled: Bool { return drawCirclesEnabled } /// The color of the inner circle (the circle-hole). public var circleHoleColor = UIColor.whiteColor() /// True if drawing circles for this DataSet is enabled, false if not public var drawCircleHoleEnabled = true /// - returns: true if drawing the circle-holes is enabled, false if not. public var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled } /// This is how much (in pixels) into the dash pattern are we starting from. public var lineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] public var lineDashLengths: [CGFloat]? /// formatter for customizing the position of the fill-line private var _fillFormatter: ChartFillFormatter = BarLineChartFillFormatter() /// Sets a custom FillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic. public var fillFormatter: ChartFillFormatter? { get { return _fillFormatter } set { if newValue == nil { _fillFormatter = BarLineChartFillFormatter() } else { _fillFormatter = newValue! } } } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! LineChartDataSet copy.circleColors = circleColors copy.circleRadius = circleRadius copy.cubicIntensity = cubicIntensity copy.lineDashPhase = lineDashPhase copy.lineDashLengths = lineDashLengths copy.drawCirclesEnabled = drawCirclesEnabled copy.drawCubicEnabled = drawCubicEnabled return copy } }
mit
5284332386667cb41b4a77a208846668
28.569697
154
0.605862
4.92331
false
false
false
false
JustLoveBen/iOS_FixUncertain
reg/reg/test.playground/Contents.swift
1
429
//: Playground - noun: a place where people can play import UIKit var regex = "((((\\+)|(00))?[- ]?\\d{1,9})[- ]?)?[0-9 \\-]{5,26}" var str = "00 86 18301022300" var str1 = "00 86 21 12345678" var str2 = "+86 183-0102-2300" var str3 = "0318 4351269" var str4 = "+86 132 9999 9999" var predicate = NSPredicate(format: "SELF MATCHES %@", regex) if predicate.evaluateWithObject(str4) { print("OK") } else { print("NO") }
mit
90b56310e6fc33a4c554d342a24b0bb0
24.235294
65
0.613054
2.86
false
false
false
false