repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Search/Query/Query.swift
1
1160
// // Query.swift // // // Created by Vladislav Fitc on 17.02.2020. // import Foundation public struct Query: Equatable, SearchParameters { internal var searchParametersStorage: SearchParametersStorage /// Custom parameters public var customParameters: [String: JSON]? public init(_ query: String? = nil) { searchParametersStorage = .init() self.searchParametersStorage.query = query } static let empty = Query() } extension Query: Codable { public init(from decoder: Decoder) throws { self.searchParametersStorage = try .init(from: decoder) customParameters = try CustomParametersCoder.decode(from: decoder, excludingKeys: SearchParametersStorage.CodingKeys.self) } public func encode(to encoder: Encoder) throws { try searchParametersStorage.encode(to: encoder) if let customParameters = customParameters { try CustomParametersCoder.encode(customParameters, to: encoder) } } } extension Query: SearchParametersStorageContainer { } extension Query: Builder {} extension Query: ExpressibleByStringInterpolation { public init(stringLiteral value: String) { self.init(value) } }
mit
72af648ad95567ae27a6d054d4ed92b5
20.481481
126
0.735345
4.344569
false
false
false
false
easytargetmixel/micopi_ios
micopi/Engine/Foliage/FoliageNode.swift
1
3213
class FoliageNode { var positionVector: Vector2 let maxJitter: Double let pushForce: Double let radius: Double let neighbourGravity: Double let preferredNeighbourDistance: Double let maxPushDistance: Double let pushForceRatio = 0.01 let radiusRatio = 1.0 / 256.0 let neighbourGravityRatio = 1.0 / 1.4 let preferredNeighbourDistanceRatio = 0.5 var next: FoliageNode? var randomNumberGenerator: RandomNumberGenerator = RandomNumberGenerator() var jitter: Double { get { return randomNumberGenerator.d( greater: -maxJitter, smaller: maxJitter ) } } init(positionVector: Vector2, maxJitter: Double, worldSize: Double) { self.positionVector = positionVector self.maxJitter = maxJitter pushForce = worldSize * pushForceRatio radius = worldSize * radiusRatio neighbourGravity = -radius * neighbourGravityRatio preferredNeighbourDistance = worldSize * preferredNeighbourDistanceRatio maxPushDistance = worldSize } func update(invertMovement: Bool = false) { positionVector = positionVector + Vector2(x: jitter, y: jitter) updateAcceleration(invertMovement: invertMovement) } func updateAcceleration(invertMovement: Bool = false) { var otherNode = next! var force = 0.0 var angle = 0.0 // self.addAccelerationToAttractor(); var accelerationVector = Vector2.zero repeat { let distance = positionVector.dist(to: otherNode.positionVector) if (distance > maxPushDistance) { guard let nextNode = otherNode.next else { break } otherNode = nextNode continue } let vectorToOtherNode = otherNode.positionVector - positionVector angle = positionVector.angle(with: otherNode.positionVector) + (angle * 0.05) force *= 0.05 if (otherNode === next) { if (distance > self.preferredNeighbourDistance) { // force = mPreferredNeighbourDistanceHalf; force += (distance / self.pushForce); } else { force -= self.neighbourGravity; } } else { if (distance < self.radius) { force -= self.radius; } else { force -= (self.pushForce / distance); } } if invertMovement { force *= -1 } accelerationVector = accelerationVector + (vectorToOtherNode.normalized() * force) guard let nextNode = otherNode.next else { break } otherNode = nextNode } while (otherNode !== self) positionVector = positionVector + accelerationVector } }
gpl-3.0
58bfa8fe8ededb48a6dcd774a527b49b
31.13
80
0.53159
5.284539
false
false
false
false
scottsievert/swix
swix_ios_app/swix_ios_app/swix/tests/speed.swift
4
1807
// // speed.swift // swix // // Created by Scott Sievert on 8/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation // should be run while optimized! class swixSpeedTests { init(){ time(pe1, name:"Project Euler 1") time(pe10, name:"Project Euler 10") time(pe73, name:"Project Euler 73") time(pi_approx, name:"Pi approximation") time(soft_thresholding, name:"Soft thresholding") } } func time(f:()->(), name:String="function"){ let start = NSDate() f() print(NSString(format:"\(name) time (s): %.4f", -1 * start.timeIntervalSinceNow)) } func pe1(){ let N = 1e6 let x = arange(N) // seeing where that modulo is 0 var i = argwhere((abs(x%3) < 1e-9) || (abs(x%5) < 1e-9)) // println(sum(x[i])) // prints 233168.0, the correct answer } func pe10(){ // find all primes var N = 2e6.int var primes = arange(Double(N)) var top = (sqrt(N.double)).int for i in 2 ..< top{ var max:Int = (N/i) var j = arange(2, max: max.double) * i.double primes[j] *= 0.0 } // sum(primes) is the correct answer } func pe73(){ var N = 1e3 var i = arange(N)+1 var (n, d) = meshgrid(i, y: i) var f = (n / d).flat f = unique(f) var j = (f > 1/3) && (f < 1/2) // println(f[argwhere(j)].n) } func soft_thresholding(){ let N = 1e2.int var j = linspace(-1, max: 1, num:N) var (x, y) = meshgrid(j, y: j) var z = pow(x, power: 2) + pow(y, power: 2) var i = abs(z) < 0.5 z[argwhere(i)] *= 0 z[argwhere(1-i)] -= 0.5 } func pi_approx(){ let N = 1e6 var k = arange(N) var pi_approx = 1 / (2*k + 1) pi_approx[2*k[0..<(N/2).int]+1] *= -1 // println(4 * pi_approx) // prints 3.14059265383979 }
mit
29e811e536559097dce981479c6ce4f9
22.480519
85
0.542889
2.797214
false
false
false
false
zetasq/Aiakos
Aiakos/AiaConverter.swift
1
8642
// // AiaConverter.swift // Aiakos // // Created by Zhu Shengqi on 12/6/15. // Copyright © 2015 DSoftware. All rights reserved. // import Foundation public enum AiaJSONConversionError: ErrorType { case InvalidJSONArrayStructure case InvalidJSONDictionaryStructure case ModelSerializationFailure } internal var cachedPropertyKeyMapping: [String: [String: String]] = [:] public class AiaConverter: AiaJSONConverter {} public protocol AiaJSONConverter: AiaJSONSerializer, AiaJSONDeserializer {} extension AiaConverter { static func propertyMappingForModel(model: AiaModel) -> [String: String] { var propertyMapping: [String: String] if let cachedMapping = cachedPropertyKeyMapping["\(model.dynamicType)"] { propertyMapping = cachedMapping } else { if let customPropertyMappingObj = model as? AiaJSONCustomPropertyMapping { propertyMapping = customPropertyMappingObj.dynamicType.customPropertyMapping } else { propertyMapping = [:] let mirror = Mirror(reflecting: model) for child in mirror.children { if let propertyName = child.label { propertyMapping[propertyName] = propertyName } } } cachedPropertyKeyMapping["\(model.dynamicType)"] = propertyMapping } return propertyMapping } } // MARK: - AiaJSONSerializer public protocol AiaJSONSerializer { static func jsonArrayFromModelArray(modelArray: [AiaModel]) throws -> [AnyObject] static func jsonArrayDataFromModelArray(modelArray: [AiaModel]) throws -> NSData static func jsonDictionaryFromModelDictionary(modelDictionary: [String: AiaModel]) throws -> [String: AnyObject] static func jsonDictionaryDataFromModelDictionary(modelDictionary: [String: AiaModel]) throws -> NSData static func jsonDictionaryFromModel(model: AiaModel) throws -> [String: AnyObject] static func jsonDictionaryDataFromModel(model: AiaModel) throws -> NSData } public extension AiaJSONSerializer { static func jsonArrayFromModelArray(modelArray: [AiaModel]) throws -> [AnyObject] { var jsonArray: [AnyObject] = [] for model in modelArray { let jsonDictionary = try jsonDictionaryFromModel(model) jsonArray.append(jsonDictionary) } return jsonArray } static func jsonArrayDataFromModelArray(modelArray: [AiaModel]) throws -> NSData { let jsonArray = try jsonArrayFromModelArray(modelArray) let jsonArrayData = try NSJSONSerialization.dataWithJSONObject(jsonArray, options: []) return jsonArrayData } static func jsonDictionaryFromModelDictionary(modelDictionary: [String: AiaModel]) throws -> [String: AnyObject] { var jsonDictionary: [String: AnyObject] = [:] for (key, model) in modelDictionary { jsonDictionary[key] = try jsonDictionaryFromModel(model) } return jsonDictionary } static func jsonDictionaryDataFromModelDictionary(modelDictionary: [String: AiaModel]) throws -> NSData { let jsonDictionary = try jsonDictionaryFromModelDictionary(modelDictionary) let jsonDictionaryData = try NSJSONSerialization.dataWithJSONObject(jsonDictionary, options: []) return jsonDictionaryData } static func jsonDictionaryFromModel(model: AiaModel) throws -> [String: AnyObject] { var jsonDictionary: [String: AnyObject] = [:] let propertyMapping = AiaConverter.propertyMappingForModel(model) for (propertyName, mappedJSONKey) in propertyMapping { if let jsonObject = model.jsonObjectForPropertyName(propertyName) { jsonDictionary[mappedJSONKey] = jsonObject } } return jsonDictionary } static func jsonDictionaryDataFromModel(model: AiaModel) throws -> NSData { let jsonDictionary = try jsonDictionaryFromModel(model) let jsonDictionaryData = try NSJSONSerialization.dataWithJSONObject(jsonDictionary, options: []) return jsonDictionaryData } } // MARK: - AiaJSONDeserializer public protocol AiaJSONDeserializer { static func modelArrayOfType(modelType: AiaModel.Type, fromJSONArray jsonArray: [AnyObject]) throws -> [AiaModel] static func modelArrayOfType(modelType: AiaModel.Type, fromJSONArrayData jsonData: NSData) throws -> [AiaModel] static func modelDictionaryOfType(modelType: AiaModel.Type, fromJSONDictionary jsonDictionary: [String: AnyObject]) throws -> [String: AiaModel] static func modelDictionaryOfType(modelType: AiaModel.Type, fromJSONDictionaryData jsonData: NSData) throws -> [String: AiaModel] static func modelOfType(modelType: AiaModel.Type, fromJSONDictionary jsonDictionary: [String: AnyObject]) throws -> AiaModel static func modelOfType(modelType: AiaModel.Type, fromJSONDictionaryData jsonData: NSData) throws -> AiaModel } public extension AiaJSONDeserializer { static func modelArrayOfType(modelType: AiaModel.Type, fromJSONArray jsonArray: [AnyObject]) throws -> [AiaModel] { var models: [AiaModel] = [] for jsonObject in jsonArray { if let jsonDictionary = jsonObject as? [String: AnyObject] { let model = try modelOfType(modelType, fromJSONDictionary: jsonDictionary) models.append(model) } else { throw AiaJSONConversionError.InvalidJSONDictionaryStructure } } return models } static func modelArrayOfType(modelType: AiaModel.Type, fromJSONArrayData jsonData: NSData) throws -> [AiaModel] { if let jsonArray = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [AnyObject] { let models = try modelArrayOfType(modelType, fromJSONArray: jsonArray) return models } else { throw AiaJSONConversionError.InvalidJSONArrayStructure } } static func modelDictionaryOfType(modelType: AiaModel.Type, fromJSONDictionary jsonDictionary: [String: AnyObject]) throws -> [String: AiaModel] { var modelDic: [String: AiaModel] = [:] for (key, value) in jsonDictionary { if let valueDictionary = value as? [String: AnyObject] { let model = try modelOfType(modelType, fromJSONDictionary: valueDictionary) modelDic[key] = model } else { throw AiaJSONConversionError.InvalidJSONDictionaryStructure } } return modelDic } static func modelDictionaryOfType(modelType: AiaModel.Type, fromJSONDictionaryData jsonData: NSData) throws -> [String: AiaModel] { if let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String: AnyObject] { let modelDic = try modelDictionaryOfType(modelType, fromJSONDictionary: jsonDictionary) return modelDic } else { throw AiaJSONConversionError.InvalidJSONDictionaryStructure } } static func modelOfType(modelType: AiaModel.Type, fromJSONDictionary jsonDictionary: [String: AnyObject]) throws -> AiaModel { let model: AiaModel if let customDeserializable = modelType as? AiaJSONCustomDeserializable.Type { model = customDeserializable.customTypeForJSONDeserializationFromJSONDictionary(jsonDictionary).init() } else { model = modelType.init() } let propertyMapping = AiaConverter.propertyMappingForModel(model) for (propertyName, mappedJSONKey) in propertyMapping { if let value = jsonDictionary[mappedJSONKey] { model.setValue(value, forPropertyName: propertyName) } } return model } static func modelOfType(modelType: AiaModel.Type, fromJSONDictionaryData jsonData: NSData) throws -> AiaModel { if let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String: AnyObject] { let model = try modelOfType(modelType, fromJSONDictionary: jsonDictionary) return model } else { throw AiaJSONConversionError.InvalidJSONDictionaryStructure } } }
mit
fef6ae91ca942b0b0d06e2f10ed7e18c
36.899123
150
0.665548
5.221148
false
false
false
false
TCA-Team/iOS
TUM Campus App/DataSources/MenuDataSource.swift
1
2653
// // MenuDataSource.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit class MenuDataSource: NSObject, UICollectionViewDataSource { let cellType: AnyClass = MenuCollectionViewCell.self var isEmpty: Bool { return data.isEmpty } let flowLayoutDelegate: UICollectionViewDelegateFlowLayout = ListFlowLayoutDelegate() var data: [CafeteriaMenu] = [] let cellReuseID = "MenuCardCell" let cardReuseID = "MenuCard" init(data: [CafeteriaMenu]) { self.data = data super.init() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseID, for: indexPath) as! MenuCollectionViewCell let dish = data[indexPath.row] cell.dishLabel.text = dish.details.nameWithEmojiWithoutAnnotations cell.dishDetailLabel.text = "" for description in dish.details.annotationDescriptions { if dish.details.annotationDescriptions.last != description { cell.dishDetailLabel.text!.append("\(description), ") } else { cell.dishDetailLabel.text!.append(description) } } switch dish.price { case let .service(student, employee, guest)?: let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale(identifier: "de_DE") cell.priceLabel.text = formatter.string(for: student) case .selfService?: cell.priceLabel.text = "n/a" case .none: cell.priceLabel.text = "n/a" } cell.priceLabel.textColor = .gray return cell } }
gpl-3.0
57391f57b7f0d9514204e1513cb3267c
34.851351
130
0.658877
4.75448
false
false
false
false
eBardX/XestiMonitors
Sources/Core/UIKit/Other/KeyboardMonitor.swift
1
7616
// // KeyboardMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2016-11-23. // // © 2016 J. G. Pusey (see LICENSE.md) // #if os(iOS) import Foundation import UIKit /// /// A `KeyboardMonitor` instance monitors the keyboard for changes to its /// visibility or to its frame. /// public class KeyboardMonitor: BaseNotificationMonitor { /// /// Encapsulates changes to the visibility of the keyboard and to the /// frame of the keyboard. /// public enum Event { /// /// The frame of the keyboard has changed. /// case didChangeFrame(Info) /// /// The keyboard has been dismissed. /// case didHide(Info) /// /// The keyboard has been displayed. /// case didShow(Info) /// /// The frame of the keyboard is about to change. /// case willChangeFrame(Info) /// /// The keyboard is about to be dismissed. /// case willHide(Info) /// /// The keyboard is about to be displayed. /// case willShow(Info) } /// /// Encapsulates information associated with a keyboard monitor event. /// public struct Info { /// /// Defines how the keyboard will be animated onto or off the /// screen. /// public let animationCurve: UIViewAnimationCurve /// /// The duration of the animation onto or off the screen in /// seconds. /// public let animationDuration: TimeInterval /// /// The start frame of the keyboard in screen coordinates. These /// coordinates do not take into account any rotation factors /// applied to the window’s contents as a result of interface /// orientation changes. Thus, you may need to convert the /// rectangle to window coordinates or to view coordinates before /// using it. /// public let frameBegin: CGRect /// /// The end frame of the keyboard in screen coordinates. These /// coordinates do not take into account any rotation factors /// applied to the window’s contents as a result of interface /// orientation changes. Thus, you may need to convert the /// rectangle to window coordinates or to view coordinates before /// using it. /// public let frameEnd: CGRect /// /// Whether the keyboard belongs to the current app. With /// multitasking on iPad, all visible apps are notified when the /// keyboard appears and disappears. `true` for the app that caused /// the keyboard to appear and `false` for any other apps. /// public let isLocal: Bool fileprivate init(_ notification: Notification) { let userInfo = notification.userInfo if let rawValue = (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue, let value = UIViewAnimationCurve(rawValue: rawValue) { self.animationCurve = value } else { self.animationCurve = .easeInOut } if let value = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue { self.animationDuration = value } else { self.animationDuration = 0.0 } if let value = (userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { self.frameBegin = value } else { self.frameBegin = .zero } if let value = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.frameEnd = value } else { self.frameEnd = .zero } if let value = (userInfo?[UIKeyboardIsLocalUserInfoKey] as? NSNumber)?.boolValue { self.isLocal = value } else { self.isLocal = true } } } /// /// Specifies which events to monitor. /// public struct Options: OptionSet { /// /// Monitor `didChangeFrame` events. /// public static let didChangeFrame = Options(rawValue: 1 << 0) /// /// Monitor `didHide` events. /// public static let didHide = Options(rawValue: 1 << 1) /// /// Monitor `didShow` events. /// public static let didShow = Options(rawValue: 1 << 2) /// /// Monitor `willChangeFrame` events. /// public static let willChangeFrame = Options(rawValue: 1 << 3) /// /// Monitor `willHide` events. /// public static let willHide = Options(rawValue: 1 << 4) /// /// Monitor `willShow` events. /// public static let willShow = Options(rawValue: 1 << 5) /// /// Monitor all events. /// public static let all: Options = [.didChangeFrame, .didHide, .didShow, .willChangeFrame, .willHide, .willShow] /// :nodoc: public init(rawValue: UInt) { self.rawValue = rawValue } /// :nodoc: public let rawValue: UInt } /// /// Initializes a new `KeyboardMonitor`. /// /// - Parameters: /// - options: The options that specify which events to monitor. /// By default, all events are monitored. /// - queue: The operation queue on which the handler executes. /// By default, the main operation queue is used. /// - handler: The handler to call when the visibility of the /// keyboard or the frame of the keyboard changes or is /// about to change. /// public init(options: Options = .all, queue: OperationQueue = .main, handler: @escaping (Event) -> Void) { self.handler = handler self.options = options super.init(queue: queue) } private let handler: (Event) -> Void private let options: Options override public func addNotificationObservers() { super.addNotificationObservers() if options.contains(.didChangeFrame) { observe(.UIKeyboardDidChangeFrame) { [unowned self] in self.handler(.didChangeFrame(Info($0))) } } if options.contains(.didHide) { observe(.UIKeyboardDidHide) { [unowned self] in self.handler(.didHide(Info($0))) } } if options.contains(.didShow) { observe(.UIKeyboardDidShow) { [unowned self] in self.handler(.didShow(Info($0))) } } if options.contains(.willChangeFrame) { observe(.UIKeyboardWillChangeFrame) { [unowned self] in self.handler(.willChangeFrame(Info($0))) } } if options.contains(.willHide) { observe(.UIKeyboardWillHide) { [unowned self] in self.handler(.willHide(Info($0))) } } if options.contains(.willShow) { observe(.UIKeyboardWillShow) { [unowned self] in self.handler(.willShow(Info($0))) } } } } #endif
mit
d13cbd6550cbb23848f80eacfac57dad
28.964567
106
0.532256
5.292768
false
false
false
false
gitkong/FLTableViewComponent
FLTableComponent/FLTableBaseComponent.swift
2
8765
// // FLTableBaseComponent.swift // FLComponentDemo // // Created by gitKong on 2017/5/11. // Copyright © 2017年 gitKong. All rights reserved. // import UIKit let FLTableViewCellDefaultHeight : CGFloat = 44 class FLTableBaseComponent: FLBaseComponent, FLTableComponentConfiguration { private(set) var tableView : UITableView? private(set) var componentIdentifier : String = "" private(set) var isCustomIdentifier = false init(tableView : UITableView){ super.init() self.tableView = tableView self.register() isCustomIdentifier = false // self.componentIdentifier = "\(NSStringFromClass(type(of: self))).Component.\(section!))" } convenience init(tableView : UITableView, identifier : String){ self.init(tableView: tableView) isCustomIdentifier = true self.componentIdentifier = identifier } final override var section: Int? { didSet { if !isCustomIdentifier { self.componentIdentifier = "\(NSStringFromClass(type(of: self))).Component.\(section!))" } } } final override func reloadSelfComponent() { tableView?.reloadSections(IndexSet.init(integer: section!), with: UITableViewRowAnimation.none) } } // MARK : base configuration extension FLTableBaseComponent { override func register() { tableView?.registerClass(UITableViewCell.self, withReuseIdentifier: cellIdentifier) tableView?.registerClass(FLTableViewHeaderFooterView.self, withReuseIdentifier: headerIdentifier) tableView?.registerClass(FLTableViewHeaderFooterView.self, withReuseIdentifier: footerIdentifier) } var tableViewCellStyle: UITableViewCellStyle { return .default } func numberOfRows() -> NSInteger { return 0 } func cellForRow(at row: Int) -> UITableViewCell { var cell = tableView?.dequeueReusableCell(withIdentifier: cellIdentifier) if cell == nil { cell = UITableViewCell.init(style: tableViewCellStyle, reuseIdentifier: cellIdentifier) self.additionalOperationForReuseCell(cell) } return cell! } func additionalOperationForReuseCell(_ cell : UITableViewCell?) { // something to reuse } } // MARK : header or footer customizaion extension FLTableBaseComponent { /// you can override this method to perform additional operation, such as add lable or button into headerView to resue, but if you had registed the class of FLTableViewHeaderFooterView for headerView, this method will be invalid, so if you want it to be valiable, do not call super when you override register() method /// /// - Parameter headerView: headerView for ready to reuse func additionalOperationForReuseHeaderView(_ headerView : FLTableViewHeaderFooterView?) { // do something , such as add lable or button into headerView or footerView to resue } /// you can override this method to perform additional operation, such as add lable or button into footerView to resue, but if you had registed the class of FLTableViewHeaderFooterView for footerView, this method will be invalid, so if you want it to be valiable, do not call super when you override register() method /// /// - Parameter footerView: footerView for ready to reuse func additionalOperationForReuseFooterView(_ footerView : FLTableViewHeaderFooterView?) { } /// when you override this method, you should call super to get headerView if you just regist the class of FLTableViewHeaderFooterView; if you override the method of register() to regist the subclass of FLTableViewHeaderFooterView, you can not call super to get headerView, and you should call init(reuseIdentifier: String?, section: Int) and addClickDelegete(for headerFooterView : FLTableViewHeaderFooterView?) if this headerView have to accurate tapping event /// /// - Parameter section: current section /// - Returns: FLTableViewHeaderFooterView func headerView() -> FLTableViewHeaderFooterView? { var headerView = tableView?.dequeueReusableHeaderFooterView(withReuseIdentifier: self.headerIdentifier) // MARK : if subclass override headerView(at section: Int) method , also override register() and do nothing in it, so headerView will be nil, then create the new one to reuse it if (headerView == nil) { // MARK : if you want header or footer view have accurate event handling capabilities, you should initialize with init(reuseIdentifier: String?, section: Int) headerView = FLTableViewHeaderFooterView.init(reuseIdentifier: self.headerIdentifier,section: section!) additionalOperationForReuseHeaderView(headerView) } if let headerTitle = self.titleForHeader() { headerView?.titleLabel.attributedText = headerTitle } headerView?.section = section return headerView } /// when you override this method, you should call super to get footerView if you just regist the class of FLTableViewHeaderFooterView; if you override the method of register() to regist the subclass of FLTableViewHeaderFooterView, you can not call super to get headerView, and you should call init(reuseIdentifier: String?, section: Int) and addClickDelegete(for headerFooterView : FLTableViewHeaderFooterView?) if this footerView have to accurate tapping event /// /// - Returns: FLTableViewHeaderFooterView func footerView() -> FLTableViewHeaderFooterView? { var footerView = tableView?.dequeueReusableHeaderFooterView(withReuseIdentifier: footerIdentifier) if (footerView == nil) { // MARK : if you want header or footer view have accurate event handling capabilities, you should initialize with init(reuseIdentifier: String?, section: Int) footerView = FLTableViewHeaderFooterView.init(reuseIdentifier: self.footerIdentifier,section: section!) additionalOperationForReuseFooterView(footerView) } if let footerTitle = self.titleForFooter() { footerView?.titleLabel.attributedText = footerTitle } footerView?.section = section return footerView } func titleForHeader() -> NSMutableAttributedString? { return nil } func titleForFooter() -> NSMutableAttributedString? { return nil } } // MARK : highlight control extension FLTableBaseComponent { func tableView(shouldHighlight cell: UITableViewCell?, at row: Int) -> Bool { return true; } func tableView(didHighlight cell: UITableViewCell?, at row: Int) { // do something } func tableView(didUnHighlight cell: UITableViewCell?, at row: Int) { // do something } } // MARK : height customization extension FLTableBaseComponent { func heightForRow(at row: Int) -> CGFloat { return FLTableViewCellDefaultHeight } func heightForHeader() -> CGFloat { if let headerTitle = self.titleForHeader() { return suitableTitleHeight(forString: headerTitle) } return CGFloat.leastNormalMagnitude } func heightForFooter() -> CGFloat { if let footerTitle = self.titleForFooter() { return suitableTitleHeight(forString: footerTitle) } return CGFloat.leastNormalMagnitude } private func suitableTitleHeight(forString string : NSMutableAttributedString) -> CGFloat{ let option = NSStringDrawingOptions.usesLineFragmentOrigin let rect = string.boundingRect(with: CGSize.init(width: UIScreen.main.bounds.width - 2 * FLHeaderFooterTitleLeftPadding, height: CGFloat.greatestFiniteMagnitude), options: option, context: nil) // footer or header height must higher than the real rect for footer or header title,otherwise, footer or header title will offset return rect.height + FLHeaderFooterTitleTopPadding * 2 } } // MARK : Display customization extension FLTableBaseComponent { func tableView(willDisplayCell cell: UITableViewCell, at row: Int){ // do nothing } func tableView(didEndDisplayCell cell: UITableViewCell, at row: Int){ } func tableView(willDisplayHeaderView view: FLTableViewHeaderFooterView){ } func tableView(willDisplayFooterView view: FLTableViewHeaderFooterView){ } func tableView(didEndDisplayHeaderView view: FLTableViewHeaderFooterView){ } func tableView(didEndDisplayFooterView view: FLTableViewHeaderFooterView){ } }
mit
ca216aed78dbffd973dd9030186bfdc2
37.942222
467
0.697329
5.452396
false
false
false
false
diversario/ios-showcase-app
ios-app-showcase/FirstRunVC.swift
1
3072
// // FirstRunVC.swift // ios-app-showcase // // Created by Ilya Shaisultanov on 1/26/16. // Copyright © 2016 Ilya Shaisultanov. All rights reserved. // import UIKit class FirstRunVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageButton: UIImageView! @IBOutlet weak var textField: UITextField! let ipc = UIImagePickerController() var tap: UITapGestureRecognizer! var imagePicked = false override func viewDidLoad() { super.viewDidLoad() if let username = NSUserDefaults.standardUserDefaults().valueForKey("username") { performSegueWithIdentifier("toFeedVC", sender: nil) return } ipc.delegate = self tap = UITapGestureRecognizer(target: self, action: "onImageTapped:") imageButton.addGestureRecognizer(tap) } override func awakeFromNib() { super.awakeFromNib() } func onImageTapped(sender: AnyObject) { presentViewController(ipc, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let img = info["UIImagePickerControllerOriginalImage"] as? UIImage imagePicked = true imageButton.image = img imageButton.layer.cornerRadius = imageButton.frame.size.width / 2 imageButton.contentMode = .ScaleAspectFill imageButton.clipsToBounds = true imageButton.alpha = 1 ipc.dismissViewControllerAnimated(true, completion: nil) } @IBAction func onContinue(sender: UIButton) { if let username = textField.text where username != "" { if imagePicked { DataService.ds.uploadImage(imageButton.image!, { err, url in DataService.ds.REF_USER_CURRENT.childByAppendingPath("profileImageUrl").setValue(url) }) } DataService.ds.REF_USER_CURRENT.childByAppendingPath("username").setValue(username) NSUserDefaults.standardUserDefaults().setValue(username, forKey: "username") NSUserDefaults.standardUserDefaults().synchronize() performSegueWithIdentifier("toFeedVC", sender: nil) } else { let originalBorder = self.textField.layer.borderWidth let originalColor = self.textField.layer.borderColor let b = CABasicAnimation(keyPath: "borderWidth") b.fromValue = originalBorder b.toValue = originalBorder + 0.5 let c = CABasicAnimation(keyPath: "borderColor") c.fromValue = originalColor c.toValue = UIColor.redColor().CGColor let gr = CAAnimationGroup() gr.duration = 0.5 gr.animations = [b, c] self.textField.layer.addAnimation(gr, forKey: "borderWidth and borderColor") } } }
mit
d536f8823861859905c921ceed48ccb2
34.298851
123
0.627483
5.533333
false
false
false
false
ubi-naist/SenStick
SenStickSDK/SenStickSDK/SenStickDeviceManager.swift
1
9700
// // SenStickDeviceManager.swift // SenStickSDK // // Created by AkihiroUehara on 2016/03/15. // Copyright © 2016年 AkihiroUehara. All rights reserved. // import Foundation import CoreBluetooth // SenStickDeviceManagerクラスは、BLEデバイスの発見と、デバイスリストの管理を行うクラスです。シングルトンです。 // // シングルトン // このクラスはシングルトンです。sharedInstanceプロパティを通じてのみ、このクラスのインスタンスにアクセスできます。 // このクラスがシングルトンになっているのは、BLE接続管理は、アプリケーションで1つのCBCentralManagerクラスのインスタンスでまとめられるべきだからです。 // シングルトンにするために、init()メソッドはプライベートになっています。 // // デバイスの発見 // デバイスを発見するにはスキャンをします。scan()メソッドでスキャンが開始されます。1秒ごとに引数で渡したブロックが呼び出されます。 // スキャンを中止するにはcancelScan()メソッドを呼び出します。 // スキャンの状況は、isScanningプロパティで取得できます。 // // デバイスのリスト管理 // デバイスが発見されるたびに、devicesプロパティが更新されます。devicesプロパティの更新はKVO(Key Value Observation)で取得できます。 // open class SenStickDeviceManager : NSObject, CBCentralManagerDelegate { let queue: DispatchQueue var manager: CBCentralManager? var scanTimer: DispatchSourceTimer? var scanCallback:((_ remaining: TimeInterval) -> Void)? // Properties, KVO dynamic open fileprivate(set) var devices:[SenStickDevice] = [] // iOS10で、列挙型 CBCentralManagerStateがCBManagerStateに変更された。 // 型名だけの変更で要素は変更がないので、Intの値としては、そのまま同じコードでiOS10以降も動く。 // しかし強い型を使うSwiftでは、iOSのバージョンの差を吸収しなくてはならない。 // 1つは、列挙型を引き継いで、バージョンごとにプロパティを提供する方法。 // コメントアウトしたのがそのコード。これはアプリケーション側で、iOSのバージョンごとにプロパティを書き分けなくてはならない。手間だろう。 // 綺麗ではないが、Int型をそのまま表に出すことにする。 /* // iOS10でCBCentralManagerStateは廃止されてCBManagerStateが代替。型が異なるのでプロパティをそれぞれに分けている。 var _state : Int = 0 @available(iOS 10.0, *) dynamic open fileprivate(set) var state: CBManagerState { get { return CBManagerState(rawValue: _state) ?? .unknown } set(newState) { _state = newState.rawValue } } // iOS9まではCBCentralManagerStateを使う。 @available(iOS, introduced: 5.0, deprecated: 10.0, message: "Use state instead") dynamic open fileprivate(set) var centralState: CBCentralManagerState { get { return CBCentralManagerState(rawValue: _state) ?? .unknown } set(newState) { _state = newState.rawValue } } */ dynamic open fileprivate(set) var state: Int = 0 dynamic open fileprivate(set) var isScanning: Bool = false // Initializer, Singleton design pattern. open static let sharedInstance: SenStickDeviceManager = SenStickDeviceManager() fileprivate override init() { queue = DispatchQueue(label: "senstick.ble-queue") // serial queue super.init() manager = CBCentralManager.init(delegate: self, queue: queue) } // MARK: Public methods // 1秒毎にコールバックします。0になれば終了です。 open func scan(_ duration:TimeInterval = 5.0, callback:((_ remaining: TimeInterval) -> Void)?) { // デバイスリストをクリアする DispatchQueue.main.async(execute: { self.devices = [] }) // スキャン中、もしくはBTの電源がオフであれば、直ちに終了。 if manager!.isScanning || manager!.state != .poweredOn { callback?(0) return } // スキャン時間は1秒以上、30秒以下に制約 let scanDuration = max(1, min(30, duration)) scanCallback = callback // 接続済のペリフェラルを取得する for peripheral in (manager!.retrieveConnectedPeripherals(withServices: [SenStickUUIDs.advertisingServiceUUID])) { addPeripheral(peripheral, name:nil) } // スキャンを開始する。 manager!.scanForPeripherals(withServices: [SenStickUUIDs.advertisingServiceUUID], options: nil) isScanning = true var remaining = scanDuration scanTimer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: DispatchQueue.main) scanTimer?.scheduleRepeating(deadline: DispatchTime.now(), interval: 1.0) // 1秒ごとのタイマー scanTimer?.setEventHandler { // 時間を-1秒。 remaining = max(0, remaining - 1) if remaining <= 0 { self.cancelScan() } // 継続ならばシグナリング self.scanCallback?(remaining) } scanTimer!.resume() } open func scan(_ duration:TimeInterval = 5.0) { scan(duration, callback: nil) } open func cancelScan() { guard manager!.isScanning else { return } scanTimer!.cancel() self.scanCallback?(0) self.scanCallback = nil self.manager!.stopScan() self.isScanning = false } // CentralManagerにデリゲートを設定して初期状態に戻します。 // ファームウェア更新などで、CentralManagerを別に渡して利用した後、復帰するために使います。 open func reset() { // デバイスリストをクリアする DispatchQueue.main.async(execute: { self.devices = [] }) manager?.delegate = self } // MARK: Private methods func addPeripheral(_ peripheral: CBPeripheral, name: String?) { //すでに配列にあるかどうか探す, なければ追加。KVOを活かすため、配列それ自体を代入する if !devices.contains(where: { element -> Bool in element.peripheral == peripheral }) { var devs = Array<SenStickDevice>(self.devices) devs.append(SenStickDevice(manager: self.manager!, peripheral: peripheral, name: name)) DispatchQueue.main.async(execute: { self.devices = devs }) } } // MARK: CBCentralManagerDelegate open func centralManagerDidUpdateState(_ central: CBCentralManager) { // BLEの処理は独立したキューで走っているので、KVOを活かすためにメインキューで代入する DispatchQueue.main.async(execute: { // iOS9以前とiOS10以降で、stateの列挙型の型名は異なるが、Intの値と要素はまったく同じ。 // iOSのバージョンごとにプロパティを分けた場合は、コメントアウトのコードでバージョンに合わせて適合させられるが、使う側からすればややこしいだけか。 /* if #available(iOS 10.0, *) { self.state = central.state } else { // iOS10以前 self.centralState = CBCentralManagerState(rawValue:central.state.rawValue) ?? .unknown } */ self.state = central.state.rawValue }) switch central.state { case .poweredOn: break case .poweredOff: DispatchQueue.main.async(execute: { self.devices = [] }) case .unauthorized: DispatchQueue.main.async(execute: { self.devices = [] }) case .unknown: DispatchQueue.main.async(execute: { self.devices = [] }) case .unsupported: DispatchQueue.main.async(execute: { self.devices = [] }) break default: break } } open func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { DispatchQueue.main.async(execute: { self.addPeripheral(peripheral, name: advertisementData[CBAdvertisementDataLocalNameKey] as? String ) }) } open func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { for device in devices.filter({element -> Bool in element.peripheral == peripheral}) { DispatchQueue.main.async(execute: { device.onConnected() }) } } open func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { for device in devices.filter({element -> Bool in element.peripheral == peripheral}) { DispatchQueue.main.async(execute: { device.onDisConnected() }) } } }
mit
199b268e28a3cd01eb04b903583f304e
31.544304
151
0.619085
3.674607
false
false
false
false
skedgo/tripkit-ios
Tests/TripKitTests/searching/TKPeliasTitleTest.swift
1
1997
// // TKPeliasTitleTest.swift // TripKitTests // // Created by Adrian Schönig on 18.07.18. // Copyright © 2018 SkedGo Pty Ltd. All rights reserved. // import XCTest @testable import TripKit class TKPeliasTitleTest: XCTestCase { func testAussieSubtitles() throws { let decoder = JSONDecoder() let data = try self.dataFromJSON(named: "pelias-au") let collection = try decoder.decode(TKGeoJSON.self, from: data) let coordinates = collection.toNamedCoordinates() let subtitles = coordinates.compactMap { $0.subtitle } XCTAssertFalse(subtitles.contains("10 Spring Street, Australia"), "Results has subtitle with just country in it.") XCTAssertNotEqual(subtitles.count, 0, "No subtitles!") XCTAssertEqual(Set(subtitles).count, coordinates.count, "Some subtitles repeat") } func testGermanSubtitles() throws { let decoder = JSONDecoder() let data = try self.dataFromJSON(named: "pelias-de") let collection = try decoder.decode(TKGeoJSON.self, from: data) let coordinates = collection.toNamedCoordinates() let subtitles = coordinates.compactMap { $0.subtitle } XCTAssertFalse(subtitles.contains("Kasperackerweg 31, Nürnberg, Germany"), "Result has subtitle without postcode.") XCTAssertNotEqual(subtitles.count, 0, "No subtitles!") XCTAssertEqual(Set(subtitles).count, 1, "Expecting one common subtitle, the city, as titles cover street names already.") } func testMericanSubtitles() throws { let decoder = JSONDecoder() let data = try self.dataFromJSON(named: "pelias-us") let collection = try decoder.decode(TKGeoJSON.self, from: data) let coordinates = collection.toNamedCoordinates() let subtitles = coordinates.compactMap { $0.subtitle } XCTAssertNotEqual(subtitles.count, 0, "No subtitles!") XCTAssertEqual(Set(subtitles).count, 3, "Expecting one common subtitle, different variations of the city, as titles cover street names already.") } }
apache-2.0
a6636700e0ff0549f688b0eba914b017
37.346154
149
0.719157
4.242553
false
true
false
false
justindarc/firefox-ios
Client/Frontend/Library/RemoteTabsPanel.swift
1
26924
/* 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 Account import Shared import SnapKit import Storage import Sync import XCGLogger private let log = Logger.browserLogger private struct RemoteTabsPanelUX { static let HeaderHeight = SiteTableViewControllerUX.RowHeight // Not HeaderHeight! static let RowHeight = SiteTableViewControllerUX.RowHeight static let EmptyStateInstructionsWidth = 170 static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 // UX TODO I set this to 8 so that it all fits on landscape static let EmptyStateSignInButtonColor = UIColor.Photon.Blue40 static let EmptyStateSignInButtonCornerRadius: CGFloat = 4 static let EmptyStateSignInButtonHeight = 44 static let EmptyStateSignInButtonWidth = 200 // Backup and active strings added in Bug 1205294. static let EmptyStateInstructionsSyncTabsPasswordsBookmarksString = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.") static let EmptyStateInstructionsSyncTabsPasswordsString = NSLocalizedString("Sync your tabs, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.") static let EmptyStateInstructionsGetTabsBookmarksPasswordsString = NSLocalizedString("Get your open tabs, bookmarks, and passwords from your other devices.", comment: "A re-worded offer about Sync, displayed when the Sync home panel is empty, that emphasizes one-way data transfer, not syncing.") static let HistoryTableViewHeaderChevronInset: CGFloat = 10 static let HistoryTableViewHeaderChevronSize: CGFloat = 20 static let HistoryTableViewHeaderChevronLineWidth: CGFloat = 3.0 } private let RemoteClientIdentifier = "RemoteClient" private let RemoteTabIdentifier = "RemoteTab" class RemoteTabsPanel: UIViewController, LibraryPanel { weak var libraryPanelDelegate: LibraryPanelDelegate? fileprivate lazy var tableViewController = RemoteTabsTableViewController() fileprivate lazy var historyBackButton: HistoryBackButton = { let button = HistoryBackButton() button.addTarget(self, action: #selector(historyBackButtonWasTapped), for: .touchUpInside) return button }() let profile: Profile init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: .FirefoxAccountChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: .ProfileDidFinishSyncing, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableViewController.profile = profile tableViewController.remoteTabsPanel = self view.backgroundColor = UIColor.theme.tableView.rowBackground tableViewController.tableView.backgroundColor = .clear addChild(tableViewController) self.view.addSubview(tableViewController.view) self.view.addSubview(historyBackButton) historyBackButton.snp.makeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(50) make.bottom.equalTo(tableViewController.view.snp.top) } tableViewController.view.snp.makeConstraints { make in make.top.equalTo(historyBackButton.snp.bottom) make.left.right.bottom.equalTo(self.view) } tableViewController.didMove(toParent: self) } @objc func notificationReceived(_ notification: Notification) { switch notification.name { case .FirefoxAccountChanged, .ProfileDidFinishSyncing: DispatchQueue.main.async { self.tableViewController.refreshTabs() } break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } @objc fileprivate func historyBackButtonWasTapped(_ gestureRecognizer: UITapGestureRecognizer) { _ = self.navigationController?.popViewController(animated: true) } } enum RemoteTabsError { case notLoggedIn case noClients case noTabs case failedToSync func localizedString() -> String { switch self { case .notLoggedIn: return "" // This does not have a localized string because we have a whole specific screen for it. case .noClients: return Strings.EmptySyncedTabsPanelNullStateDescription case .noTabs: return NSLocalizedString("You don’t have any tabs open in Firefox on your other devices.", comment: "Error message in the remote tabs panel") case .failedToSync: return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel") } } } protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate { } class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource { weak var libraryPanel: LibraryPanel? fileprivate var clientAndTabs: [ClientAndTabs] init(libraryPanel: LibraryPanel, clientAndTabs: [ClientAndTabs]) { self.libraryPanel = libraryPanel self.clientAndTabs = clientAndTabs } func numberOfSections(in tableView: UITableView) -> Int { return self.clientAndTabs.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.clientAndTabs[section].tabs.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return RemoteTabsPanelUX.HeaderHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let clientTabs = self.clientAndTabs[section] let client = clientTabs.client let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: RemoteClientIdentifier) as! TwoLineHeaderFooterView view.frame = CGRect(width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight) view.textLabel?.text = client.name view.contentView.backgroundColor = UIColor.theme.tableView.headerBackground /* * A note on timestamps. * We have access to two timestamps here: the timestamp of the remote client record, * and the set of timestamps of the client's tabs. * Neither is "last synced". The client record timestamp changes whenever the remote * client uploads its record (i.e., infrequently), but also whenever another device * sends a command to that client -- which can be much later than when that client * last synced. * The client's tabs haven't necessarily changed, but it can still have synced. * Ideally, we should save and use the modified time of the tabs record itself. * This will be the real time that the other client uploaded tabs. */ let timestamp = clientTabs.approximateLastSyncTime() let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.") view.detailTextLabel?.text = String(format: label, Date.fromTimestamp(timestamp).toRelativeTimeString()) let image: UIImage? if client.type == "desktop" { image = UIImage.templateImageNamed("deviceTypeDesktop") image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list") } else { image = UIImage.templateImageNamed("deviceTypeMobile") image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list") } view.imageView.tintColor = UIColor.theme.tableView.rowText view.imageView.image = image view.imageView.contentMode = .center view.mergeAccessibilityLabels() return view } fileprivate func tabAtIndexPath(_ indexPath: IndexPath) -> RemoteTab { return clientAndTabs[indexPath.section].tabs[indexPath.item] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RemoteTabIdentifier, for: indexPath) as! TwoLineTableViewCell let tab = tabAtIndexPath(indexPath) cell.setLines(tab.title, detailText: tab.URL.absoluteString) // TODO: Bug 1144765 - Populate image with cached favicons. return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let tab = tabAtIndexPath(indexPath) if let libraryPanel = self.libraryPanel { // It's not a bookmark, so let's call it Typed (which means History, too). libraryPanel.libraryPanelDelegate?.libraryPanel(didSelectURL: tab.URL, visitType: VisitType.typed) } } } // MARK: - class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource { weak var libraryPanel: LibraryPanel? var error: RemoteTabsError var notLoggedCell: UITableViewCell? init(libraryPanel: LibraryPanel, error: RemoteTabsError) { self.libraryPanel = libraryPanel self.error = error self.notLoggedCell = nil } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let cell = self.notLoggedCell { cell.updateConstraints() } return tableView.bounds.height } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Making the footer height as small as possible because it will disable button tappability if too high. return 1 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch error { case .notLoggedIn: let cell = RemoteTabsNotLoggedInCell(libraryPanel: libraryPanel) self.notLoggedCell = cell return cell default: let cell = RemoteTabsErrorCell(error: self.error) self.notLoggedCell = nil return cell } } } fileprivate let emptySyncImageName = "emptySync" // MARK: - class RemoteTabsErrorCell: UITableViewCell { static let Identifier = "RemoteTabsErrorCell" let titleLabel = UILabel() let emptyStateImageView = UIImageView() let instructionsLabel = UILabel() init(error: RemoteTabsError) { super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier) selectionStyle = .none separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) let containerView = UIView() contentView.addSubview(containerView) emptyStateImageView.image = UIImage.templateImageNamed(emptySyncImageName) containerView.addSubview(emptyStateImageView) emptyStateImageView.snp.makeConstraints { (make) -> Void in make.top.equalTo(containerView) make.centerX.equalTo(containerView) } titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = .center containerView.addSubview(titleLabel) instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = error.localizedString() instructionsLabel.textAlignment = .center instructionsLabel.numberOfLines = 0 containerView.addSubview(instructionsLabel) titleLabel.snp.makeConstraints { make in make.top.equalTo(emptyStateImageView.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(emptyStateImageView) } instructionsLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems / 2) make.centerX.equalTo(containerView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } containerView.snp.makeConstraints { make in // Let the container wrap around the content make.top.equalTo(emptyStateImageView.snp.top) make.left.bottom.right.equalTo(instructionsLabel) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(contentView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(contentView.snp.centerY).offset(LibraryPanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).offset(20).priority(1000) } containerView.backgroundColor = .clear applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { emptyStateImageView.tintColor = UIColor.theme.tableView.rowText titleLabel.textColor = UIColor.theme.tableView.headerTextDark instructionsLabel.textColor = UIColor.theme.tableView.headerTextDark backgroundColor = UIColor.theme.homePanel.panelBackground } } // MARK: - class RemoteTabsNotLoggedInCell: UITableViewCell { static let Identifier = "RemoteTabsNotLoggedInCell" var libraryPanel: LibraryPanel? let instructionsLabel = UILabel() let signInButton = UIButton() let titleLabel = UILabel() let emptyStateImageView = UIImageView() init(libraryPanel: LibraryPanel?) { super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier) selectionStyle = .none self.libraryPanel = libraryPanel let createAnAccountButton = UIButton(type: .system) emptyStateImageView.image = UIImage.templateImageNamed(emptySyncImageName) contentView.addSubview(emptyStateImageView) titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = .center contentView.addSubview(titleLabel) instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = Strings.EmptySyncedTabsPanelNotSignedInStateDescription instructionsLabel.textAlignment = .center instructionsLabel.numberOfLines = 0 contentView.addSubview(instructionsLabel) signInButton.setTitle(Strings.FxASignInToSync, for: []) signInButton.titleLabel?.textColor = .white signInButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .subheadline) signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius signInButton.clipsToBounds = true signInButton.addTarget(self, action: #selector(signIn), for: .touchUpInside) contentView.addSubview(signInButton) createAnAccountButton.setTitle(NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j"), for: []) createAnAccountButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .caption1) createAnAccountButton.addTarget(self, action: #selector(createAnAccount), for: .touchUpInside) contentView.addSubview(createAnAccountButton) emptyStateImageView.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(instructionsLabel) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(contentView).offset(LibraryPanelUX.EmptyTabContentOffset + 30).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).priority(1000) } titleLabel.snp.makeConstraints { make in make.top.equalTo(emptyStateImageView.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(emptyStateImageView) } createAnAccountButton.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(signInButton) make.top.equalTo(signInButton.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) } applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { emptyStateImageView.tintColor = UIColor.theme.tableView.rowText titleLabel.textColor = UIColor.theme.tableView.headerTextDark instructionsLabel.textColor = UIColor.theme.tableView.headerTextDark signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor signInButton.setTitleColor(UIColor.theme.tableView.headerTextDark, for: []) backgroundColor = UIColor.theme.homePanel.panelBackground } @objc fileprivate func signIn() { if let libraryPanel = self.libraryPanel { libraryPanel.libraryPanelDelegate?.libraryPanelDidRequestToSignIn() } } @objc fileprivate func createAnAccount() { if let libraryPanel = self.libraryPanel { libraryPanel.libraryPanelDelegate?.libraryPanelDidRequestToCreateAccount() } } override func updateConstraints() { if UIApplication.shared.statusBarOrientation.isLandscape && !(DeviceInfo.deviceModel().range(of: "iPad") != nil) { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.left.lessThanOrEqualTo(contentView.snp.left).offset(80).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.right.lessThanOrEqualTo(contentView.snp.centerX).offset(-30).priority(1000) } signInButton.snp.remakeConstraints { make in make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) make.centerY.equalTo(emptyStateImageView).offset(2*RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.right.greaterThanOrEqualTo(contentView.snp.right).offset(-70).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.left.greaterThanOrEqualTo(contentView.snp.centerX).offset(10).priority(1000) } } else { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(contentView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } signInButton.snp.remakeConstraints { make in make.centerX.equalTo(contentView) make.top.equalTo(instructionsLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) } } super.updateConstraints() } } fileprivate class RemoteTabsTableViewController: UITableViewController { weak var remoteTabsPanel: RemoteTabsPanel? var profile: Profile! var tableViewDelegate: RemoteTabsPanelDataSource? { didSet { tableView.dataSource = tableViewDelegate tableView.delegate = tableViewDelegate } } fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.register(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier) tableView.register(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier) tableView.rowHeight = RemoteTabsPanelUX.RowHeight tableView.separatorInset = .zero tableView.tableFooterView = UIView() // prevent extra empty rows at end tableView.delegate = nil tableView.dataSource = nil } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Add a refresh control if the user is logged in and the control was not added before. If the user is not // logged in, remove any existing control. if profile.hasSyncableAccount() && refreshControl == nil { addRefreshControl() } else if !profile.hasSyncableAccount() && refreshControl != nil { removeRefreshControl() } onRefreshPulled() } // MARK: - Refreshing TableView func addRefreshControl() { let control = UIRefreshControl() control.addTarget(self, action: #selector(onRefreshPulled), for: .valueChanged) refreshControl = control tableView.refreshControl = control } func removeRefreshControl() { tableView.refreshControl = nil refreshControl = nil } @objc func onRefreshPulled() { refreshControl?.beginRefreshing() refreshTabs(updateCache: true) } func endRefreshing() { // Always end refreshing, even if we failed! refreshControl?.endRefreshing() // Remove the refresh control if the user has logged out in the meantime if !profile.hasSyncableAccount() { removeRefreshControl() } } func updateDelegateClientAndTabData(_ clientAndTabs: [ClientAndTabs]) { guard let remoteTabsPanel = remoteTabsPanel else { return } if clientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(libraryPanel: remoteTabsPanel, error: .noClients) } else { let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 } if nonEmptyClientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(libraryPanel: remoteTabsPanel, error: .noTabs) } else { self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(libraryPanel: remoteTabsPanel, clientAndTabs: nonEmptyClientAndTabs) } } } fileprivate func refreshTabs(updateCache: Bool = false) { guard let remoteTabsPanel = remoteTabsPanel else { return } assert(Thread.isMainThread) // Short circuit if the user is not logged in guard profile.hasSyncableAccount() else { self.endRefreshing() self.tableViewDelegate = RemoteTabsPanelErrorDataSource(libraryPanel: remoteTabsPanel, error: .notLoggedIn) return } // Get cached tabs. self.profile.getCachedClientsAndTabs().uponQueue(.main) { result in guard let clientAndTabs = result.successValue else { self.endRefreshing() self.tableViewDelegate = RemoteTabsPanelErrorDataSource(libraryPanel: remoteTabsPanel, error: .failedToSync) return } // Update UI with cached data. self.updateDelegateClientAndTabData(clientAndTabs) if updateCache { // Fetch updated tabs. self.profile.getClientsAndTabs().uponQueue(.main) { result in if let clientAndTabs = result.successValue { // Update UI with updated tabs. self.updateDelegateClientAndTabData(clientAndTabs) } self.endRefreshing() } } else { self.endRefreshing() } } } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } } extension RemoteTabsTableViewController: LibraryPanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let tab = (tableViewDelegate as? RemoteTabsPanelClientAndTabsDataSource)?.tabAtIndexPath(indexPath) else { return nil } return Site(url: String(describing: tab.URL), title: tab.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { return getDefaultContextMenuActions(for: site, libraryPanelDelegate: remoteTabsPanel?.libraryPanelDelegate) } } extension RemoteTabsPanel: Themeable { func applyTheme() { historyBackButton.applyTheme() tableViewController.tableView.reloadData() tableViewController.refreshTabs() } }
mpl-2.0
08cafd15a88be6d133a88e08cdcd4eaa
41.463722
300
0.696716
5.335315
false
false
false
false
silt-lang/silt
Sources/Mantle/Infer.swift
1
3668
/// Infer.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Lithosphere import Moho extension TypeChecker where PhaseState == CheckPhaseState { // Type inference for Type Theory terms. // // Inference is easy since we've already scope checked terms: just look into // the context. func infer(_ t: Term<TT>, in ctx: Context) -> Type<TT> { switch t { case .type: return .type case let .pi(domain, codomain): self.checkTT(domain, hasType: TT.type, in: ctx) self.checkTT(codomain, hasType: TT.type, in: [(wildcardName, domain)]) return TT.type case let .apply(head, elims): var type = self.infer(head, in: ctx) var head = TT.apply(head, []) for el in elims { switch el { case let .apply(arg): guard case let .pi(dom, cod) = type else { fatalError() } self.checkTT(arg, hasType: dom, in: ctx) type = self.forceInstantiate(cod, [arg]) head = self.eliminate(head, [.apply(arg)]) case let .project(proj): print(proj) fatalError() } } return type case let .equal(type, lhs, rhs): self.checkTT(type, hasType: TT.type, in: ctx) self.checkTT(lhs, hasType: type, in: ctx) self.checkTT(rhs, hasType: type, in: ctx) return TT.type default: fatalError() } } } extension TypeChecker where PhaseState == CheckPhaseState { func inferInvertibility(_ cs: [Clause]) -> Instantiability.Invertibility { var seenHeads = Set<Instantiability.Invertibility.TermHead>() seenHeads.reserveCapacity(cs.count) var injectiveClauses = [Clause]() injectiveClauses.reserveCapacity(cs.count) for clause in cs { guard let clauseBody = clause.body else { return .notInvertible(cs) } switch clauseBody { case let .apply(.definition(name), _): switch self.getOpenedDefinition(name.key).1 { case .constant(_, .data(_)), .constant(_, .record(_, _)), .constant(_, .postulate), .projection(_, _, _): guard seenHeads.insert(.definition(name.key)).inserted else { return .notInvertible(cs) } injectiveClauses.append(clause) case .constant(_, .function(_)), .dataConstructor(_, _, _): return .notInvertible(cs) case .module(_): fatalError() } case .apply(_, _): return .notInvertible(cs) case let .constructor(name, _): guard seenHeads.insert(.definition(name.key)).inserted else { return .notInvertible(cs) } injectiveClauses.append(clause) case .pi(_, _): guard seenHeads.insert(.pi).inserted else { return .notInvertible(cs) } injectiveClauses.append(clause) case .lambda(_), .refl, .type, .equal(_, _, _): return .notInvertible(cs) } } return .invertible(injectiveClauses) } } extension TypeChecker { func infer(_ h: Head<TT>, in ctx: Context) -> Type<TT> { switch h { case let .variable(v): return Environment(ctx).lookupVariable(v, self.eliminate)! case let .definition(name): let contextDef = self.signature.lookupDefinition(name.key)! let openedDef = self.openContextualDefinition(contextDef, name.args) return self.getTypeOfOpenedDefinition(openedDef) case let .meta(mv): return self.signature.lookupMetaType(mv)! } } }
mit
90ecc2292de8a54a3e53d39a17a9a038
30.62069
78
0.597056
3.931404
false
false
false
false
shahmishal/swift
stdlib/public/core/BridgeObjectiveC.swift
1
24574
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A Swift Array or Dictionary of types conforming to /// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or /// NSDictionary, respectively. The elements of the resulting NSArray /// or NSDictionary will be the result of calling `_bridgeToObjectiveC` /// on each element of the source container. public protocol _ObjectiveCBridgeable { associatedtype _ObjectiveCType: AnyObject /// Convert `self` to Objective-C. func _bridgeToObjectiveC() -> _ObjectiveCType /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from `NSArray` to `Array<Element>`, we can defer /// the checking for the individual elements of the array. /// /// - parameter result: The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) /// Try to bridge from an Objective-C object of the bridged class /// type to a value of the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// - parameter result: The location where the result is written. /// /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant /// information is provided for the convenience of the runtime's `dynamic_cast` /// implementation, so that it need not look into the optional representation /// to determine success. @discardableResult static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) -> Bool /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for unconditional bridging when /// interoperating with Objective-C code, either in the body of an /// Objective-C thunk or when calling Objective-C code, and may /// defer complete checking until later. For example, when bridging /// from `NSArray` to `Array<Element>`, we can defer the checking /// for the individual elements of the array. /// /// \param source The Objective-C object from which we are /// bridging. This optional value will only be `nil` in cases where /// an Objective-C method has returned a `nil` despite being marked /// as `_Nonnull`/`nonnull`. In most such cases, bridging will /// generally force the value immediately. However, this gives /// bridging the flexibility to substitute a default value to cope /// with historical decisions, e.g., an existing Objective-C method /// that returns `nil` to for "empty result" rather than (say) an /// empty array. In such cases, when `nil` does occur, the /// implementation of `Swift.Array`'s conformance to /// `_ObjectiveCBridgeable` will produce an empty array rather than /// dynamically failing. @_effects(readonly) static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self } #if _runtime(_ObjC) //===--- Bridging for metatypes -------------------------------------------===// /// A stand-in for a value of metatype type. /// /// The language and runtime do not yet support protocol conformances for /// structural types like metatypes. However, we can use a struct that contains /// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table /// will be ABI-compatible with one that directly provided conformance to the /// metatype type itself. public struct _BridgeableMetatype: _ObjectiveCBridgeable { internal var value: AnyObject.Type internal init(value: AnyObject.Type) { self.value = value } public typealias _ObjectiveCType = AnyObject public func _bridgeToObjectiveC() -> AnyObject { return value } public static func _forceBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) { result = _BridgeableMetatype(value: source as! AnyObject.Type) } public static func _conditionallyBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) -> Bool { if let type = source as? AnyObject.Type { result = _BridgeableMetatype(value: type) return true } result = nil return false } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?) -> _BridgeableMetatype { var result: _BridgeableMetatype? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } //===--- Bridging facilities written in Objective-C -----------------------===// // Functions that must discover and possibly use an arbitrary type's // conformance to a given protocol. See ../runtime/Casting.cpp for // implementations. //===----------------------------------------------------------------------===// /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC @inlinable public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { if _fastPath(_isClassOrObjCExistential(T.self)) { return unsafeBitCast(x, to: AnyObject.self) } return _bridgeAnythingNonVerbatimToObjectiveC(x) } @_silgen_name("") public // @testable func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject /// Convert a purportedly-nonnull `id` value from Objective-C into an Any. /// /// Since Objective-C APIs sometimes get their nullability annotations wrong, /// this includes a failsafe against nil `AnyObject`s, wrapping them up as /// a nil `AnyObject?`-inside-an-`Any`. /// // COMPILER_INTRINSIC public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any { if let nonnullObject = possiblyNullObject { return nonnullObject // AnyObject-in-Any } return possiblyNullObject as Any } /// Convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, trap; /// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`; /// - otherwise, trap. @inlinable public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as! T } var result: T? _bridgeNonVerbatimFromObjectiveC(x, T.self, &result) return result! } /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, the result is empty; /// + otherwise, returns the result of /// `T._conditionallyBridgeFromObjectiveC(x)`; /// - otherwise, the result is empty. @inlinable public func _conditionallyBridgeFromObjectiveC<T>( _ x: AnyObject, _: T.Type ) -> T? { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as? T } var result: T? _ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result) return result } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } @_silgen_name("") @usableFromInline internal func _bridgeNonVerbatimFromObjectiveC<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) /// Helper stub to upcast to Any and store the result to an inout Any? /// on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny") internal func _bridgeNonVerbatimFromObjectiveCToAny( _ x: AnyObject, _ result: inout Any? ) { result = x as Any } /// Helper stub to upcast to Optional on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimBoxedValue") internal func _bridgeNonVerbatimBoxedValue<NativeType>( _ x: UnsafePointer<NativeType>, _ result: inout NativeType? ) { result = x.pointee } /// Runtime optional to conditionally perform a bridge from an object to a value /// type. /// /// - parameter result: Will be set to the resulting value if bridging succeeds, and /// unchanged otherwise. /// /// - Returns: `true` to indicate success, `false` to indicate failure. @_silgen_name("") public func _bridgeNonVerbatimFromObjectiveCConditional<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) -> Bool /// Determines if values of a given type can be converted to an Objective-C /// representation. /// /// - If `T` is a class type, returns `true`; /// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`. public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool { if _fastPath(_isClassOrObjCExistential(T.self)) { return true } return _isBridgedNonVerbatimToObjectiveC(T.self) } @_silgen_name("") public func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool /// A type that's bridged "verbatim" does not conform to /// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an /// `AnyObject`. When this function returns true, the storage of an /// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`. @inlinable // FIXME(sil-serialize-all) public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool { return _isClassOrObjCExistential(T.self) } /// Retrieve the Objective-C type to which the given type is bridged. @inlinable // FIXME(sil-serialize-all) public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? { if _fastPath(_isClassOrObjCExistential(T.self)) { return T.self } return _getBridgedNonVerbatimObjectiveCType(T.self) } @_silgen_name("") public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type? // -- Pointer argument bridging /// A mutable pointer-to-ObjC-pointer argument. /// /// This type has implicit conversions to allow passing any of the following /// to a C or ObjC API: /// /// - `nil`, which gets passed as a null pointer, /// - an inout argument of the referenced type, which gets passed as a pointer /// to a writeback temporary with autoreleasing ownership semantics, /// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is. /// /// Passing pointers to mutable arrays of ObjC class pointers is not /// directly supported. Unlike `UnsafeMutablePointer<Pointee>`, /// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that /// does not own a reference count to the referenced /// value. UnsafeMutablePointer's operations, by contrast, assume that /// the referenced storage owns values loaded from or stored to it. /// /// This type does not carry an owner pointer unlike the other C*Pointer types /// because it only needs to reference the results of inout conversions, which /// already have writeback-scoped lifetime. @frozen public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */> : _Pointer { public let _rawValue: Builtin.RawPointer @_transparent public // COMPILER_INTRINSIC init(_ _rawValue: Builtin.RawPointer) { self._rawValue = _rawValue } /// Access the `Pointee` instance referenced by `self`. /// /// - Precondition: the pointee has been initialized with an instance of type /// `Pointee`. @inlinable public var pointee: Pointee { /// Retrieve the value the pointer points to. @_transparent get { // We can do a strong load normally. return UnsafePointer(self).pointee } /// Set the value the pointer points to, copying over the previous value. /// /// AutoreleasingUnsafeMutablePointers are assumed to reference a /// value with __autoreleasing ownership semantics, like 'NSFoo**' /// in ARC. This autoreleases the argument before trivially /// storing it to the referenced memory. @_transparent nonmutating set { // Autorelease the object reference. typealias OptionalAnyObject = AnyObject? let newAnyObject = unsafeBitCast(newValue, to: OptionalAnyObject.self) Builtin.retain(newAnyObject) Builtin.autorelease(newAnyObject) // Trivially assign it as an OpaquePointer; the pointer references an // autoreleasing slot, so retains/releases of the original value are // unneeded. typealias OptionalUnmanaged = Unmanaged<AnyObject>? UnsafeMutablePointer<Pointee>(_rawValue).withMemoryRebound( to: OptionalUnmanaged.self, capacity: 1) { if let newAnyObject = newAnyObject { $0.pointee = Unmanaged.passUnretained(newAnyObject) } else { $0.pointee = nil } } } } /// Access the `i`th element of the raw array pointed to by /// `self`. /// /// - Precondition: `self != nil`. @inlinable // unsafe-performance public subscript(i: Int) -> Pointee { @_transparent get { // We can do a strong load normally. return (UnsafePointer<Pointee>(self) + i).pointee } } /// Explicit construction from an UnsafeMutablePointer. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init<U>(_ from: UnsafeMutablePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from an UnsafeMutablePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init?<U>(_ from: UnsafeMutablePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Explicit construction from a UnsafePointer. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init<U>(_ from: UnsafePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from a UnsafePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init?<U>(_ from: UnsafePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension UnsafeMutableRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } extension UnsafeRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } internal struct _CocoaFastEnumerationStackBuf { // Clang uses 16 pointers. So do we. internal var _item0: UnsafeRawPointer? internal var _item1: UnsafeRawPointer? internal var _item2: UnsafeRawPointer? internal var _item3: UnsafeRawPointer? internal var _item4: UnsafeRawPointer? internal var _item5: UnsafeRawPointer? internal var _item6: UnsafeRawPointer? internal var _item7: UnsafeRawPointer? internal var _item8: UnsafeRawPointer? internal var _item9: UnsafeRawPointer? internal var _item10: UnsafeRawPointer? internal var _item11: UnsafeRawPointer? internal var _item12: UnsafeRawPointer? internal var _item13: UnsafeRawPointer? internal var _item14: UnsafeRawPointer? internal var _item15: UnsafeRawPointer? @_transparent internal var count: Int { return 16 } internal init() { _item0 = nil _item1 = _item0 _item2 = _item0 _item3 = _item0 _item4 = _item0 _item5 = _item0 _item6 = _item0 _item7 = _item0 _item8 = _item0 _item9 = _item0 _item10 = _item0 _item11 = _item0 _item12 = _item0 _item13 = _item0 _item14 = _item0 _item15 = _item0 _internalInvariant(MemoryLayout.size(ofValue: self) >= MemoryLayout<Optional<UnsafeRawPointer>>.size * count) } } /// Get the ObjC type encoding for a type as a pointer to a C string. /// /// This is used by the Foundation overlays. The compiler will error if the /// passed-in type is generic or not representable in Objective-C @_transparent public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> { // This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is // only supported by the compiler for concrete types that are representable // in ObjC. return UnsafePointer(Builtin.getObjCTypeEncoding(type)) } #endif //===--- Bridging without the ObjC runtime --------------------------------===// #if !_runtime(_ObjC) /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } public // SPI(Foundation) protocol _NSSwiftValue: class { init(_ value: Any) var value: Any { get } static var null: AnyObject { get } } @usableFromInline internal class __SwiftValue { @usableFromInline let value: Any @usableFromInline init(_ value: Any) { self.value = value } @usableFromInline static let null = __SwiftValue(Optional<Any>.none as Any) } // Internal stdlib SPI @_silgen_name("swift_unboxFromSwiftValueWithType") public func swift_unboxFromSwiftValueWithType<T>( _ source: inout AnyObject, _ result: UnsafeMutablePointer<T> ) -> Bool { if source === _nullPlaceholder { if let unpacked = Optional<Any>.none as? T { result.initialize(to: unpacked) return true } } if let box = source as? __SwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } else if let box = source as? _NSSwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } return false } // Internal stdlib SPI @_silgen_name("swift_swiftValueConformsTo") public func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool { if let foundationType = _foundationSwiftValueType { return foundationType is T.Type } else { return __SwiftValue.self is T.Type } } @_silgen_name("_swift_extractDynamicValue") public func _extractDynamicValue<T>(_ value: T) -> AnyObject? @_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible") public func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject? internal protocol _Unwrappable { func _unwrap() -> Any? } extension Optional: _Unwrappable { internal func _unwrap() -> Any? { return self } } private let _foundationSwiftValueType = _typeByName("Foundation.__SwiftValue") as? _NSSwiftValue.Type @usableFromInline internal var _nullPlaceholder: AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.null } else { return __SwiftValue.null } } @usableFromInline func _makeSwiftValue(_ value: Any) -> AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.init(value) } else { return __SwiftValue(value) } } /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { var done = false var result: AnyObject! let source: Any = x if let dynamicSource = _extractDynamicValue(x) { result = dynamicSource as AnyObject done = true } if !done, let wrapper = source as? _Unwrappable { if let value = wrapper._unwrap() { result = value as AnyObject } else { result = _nullPlaceholder } done = true } if !done { if type(of: source) as? AnyClass != nil { result = unsafeBitCast(x, to: AnyObject.self) } else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) { result = object } else { result = _makeSwiftValue(source) } } return result } #endif // !_runtime(_ObjC)
apache-2.0
82b1fd2cf4fe9e958ea2a4aec439e9ad
31.334211
101
0.685806
4.27597
false
false
false
false
jopamer/swift
test/stdlib/TestJSONEncoder.swift
1
67944
// 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 // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Swift import Foundation // MARK: - Test Suite #if FOUNDATION_XCTEST import XCTest class TestJSONEncoderSuper : XCTestCase { } #else import StdlibUnittest class TestJSONEncoderSuper { } #endif class TestJSONEncoder : TestJSONEncoderSuper { // MARK: - Encoding Top-Level Empty Types func testEncodingTopLevelEmptyStruct() { let empty = EmptyStruct() _testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary) } func testEncodingTopLevelEmptyClass() { let empty = EmptyClass() _testRoundTrip(of: empty, expectedJSON: _jsonEmptyDictionary) } // MARK: - Encoding Top-Level Single-Value Types func testEncodingTopLevelSingleValueEnum() { _testEncodeFailure(of: Switch.off) _testEncodeFailure(of: Switch.on) _testRoundTrip(of: TopLevelWrapper(Switch.off)) _testRoundTrip(of: TopLevelWrapper(Switch.on)) } func testEncodingTopLevelSingleValueStruct() { _testEncodeFailure(of: Timestamp(3141592653)) _testRoundTrip(of: TopLevelWrapper(Timestamp(3141592653))) } func testEncodingTopLevelSingleValueClass() { _testEncodeFailure(of: Counter()) _testRoundTrip(of: TopLevelWrapper(Counter())) } // MARK: - Encoding Top-Level Structured Types func testEncodingTopLevelStructuredStruct() { // Address is a struct type with multiple fields. let address = Address.testValue _testRoundTrip(of: address) } func testEncodingTopLevelStructuredClass() { // Person is a class with multiple fields. let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"appleseed@apple.com\"}".data(using: .utf8)! let person = Person.testValue _testRoundTrip(of: person, expectedJSON: expectedJSON) } func testEncodingTopLevelStructuredSingleStruct() { // Numbers is a struct which encodes as an array through a single value container. let numbers = Numbers.testValue _testRoundTrip(of: numbers) } func testEncodingTopLevelStructuredSingleClass() { // Mapping is a class which encodes as a dictionary through a single value container. let mapping = Mapping.testValue _testRoundTrip(of: mapping) } func testEncodingTopLevelDeepStructuredType() { // Company is a type with fields which are Codable themselves. let company = Company.testValue _testRoundTrip(of: company) } func testEncodingClassWhichSharesEncoderWithSuper() { // Employee is a type which shares its encoder & decoder with its superclass, Person. let employee = Employee.testValue _testRoundTrip(of: employee) } func testEncodingTopLevelNullableType() { // EnhancedBool is a type which encodes either as a Bool or as nil. _testEncodeFailure(of: EnhancedBool.true) _testEncodeFailure(of: EnhancedBool.false) _testEncodeFailure(of: EnhancedBool.fileNotFound) _testRoundTrip(of: TopLevelWrapper(EnhancedBool.true), expectedJSON: "{\"value\":true}".data(using: .utf8)!) _testRoundTrip(of: TopLevelWrapper(EnhancedBool.false), expectedJSON: "{\"value\":false}".data(using: .utf8)!) _testRoundTrip(of: TopLevelWrapper(EnhancedBool.fileNotFound), expectedJSON: "{\"value\":null}".data(using: .utf8)!) } // MARK: - Output Formatting Tests func testEncodingOutputFormattingDefault() { let expectedJSON = "{\"name\":\"Johnny Appleseed\",\"email\":\"appleseed@apple.com\"}".data(using: .utf8)! let person = Person.testValue _testRoundTrip(of: person, expectedJSON: expectedJSON) } func testEncodingOutputFormattingPrettyPrinted() { let expectedJSON = "{\n \"name\" : \"Johnny Appleseed\",\n \"email\" : \"appleseed@apple.com\"\n}".data(using: .utf8)! let person = Person.testValue _testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted]) } func testEncodingOutputFormattingSortedKeys() { if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) { let expectedJSON = "{\"email\":\"appleseed@apple.com\",\"name\":\"Johnny Appleseed\"}".data(using: .utf8)! let person = Person.testValue _testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys]) } } func testEncodingOutputFormattingPrettyPrintedSortedKeys() { if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) { let expectedJSON = "{\n \"email\" : \"appleseed@apple.com\",\n \"name\" : \"Johnny Appleseed\"\n}".data(using: .utf8)! let person = Person.testValue _testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys]) } } // MARK: - Date Strategy Tests func testEncodingDate() { // We can't encode a top-level Date, so it'll be wrapped in a dictionary. _testRoundTrip(of: TopLevelWrapper(Date())) // Optional dates should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(Date())) } func testEncodingDateSecondsSince1970() { // Cannot encode an arbitrary number of seconds since we've lost precision since 1970. let seconds = 1000.0 let expectedJSON = "{\"value\":1000}".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in a dictionary. _testRoundTrip(of: TopLevelWrapper(Date(timeIntervalSince1970: seconds)), expectedJSON: expectedJSON, dateEncodingStrategy: .secondsSince1970, dateDecodingStrategy: .secondsSince1970) // Optional dates should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(Date(timeIntervalSince1970: seconds)), expectedJSON: expectedJSON, dateEncodingStrategy: .secondsSince1970, dateDecodingStrategy: .secondsSince1970) } func testEncodingDateMillisecondsSince1970() { // Cannot encode an arbitrary number of seconds since we've lost precision since 1970. let seconds = 1000.0 let expectedJSON = "{\"value\":1000000}".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in a dictionary. _testRoundTrip(of: TopLevelWrapper(Date(timeIntervalSince1970: seconds)), expectedJSON: expectedJSON, dateEncodingStrategy: .millisecondsSince1970, dateDecodingStrategy: .millisecondsSince1970) // Optional dates should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(Date(timeIntervalSince1970: seconds)), expectedJSON: expectedJSON, dateEncodingStrategy: .millisecondsSince1970, dateDecodingStrategy: .millisecondsSince1970) } func testEncodingDateISO8601() { if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime let timestamp = Date(timeIntervalSince1970: 1000) let expectedJSON = "{\"value\":\"\(formatter.string(from: timestamp))\"}".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in a dictionary. _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .iso8601, dateDecodingStrategy: .iso8601) // Optional dates should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .iso8601, dateDecodingStrategy: .iso8601) } } func testEncodingDateFormatted() { let formatter = DateFormatter() formatter.dateStyle = .full formatter.timeStyle = .full let timestamp = Date(timeIntervalSince1970: 1000) let expectedJSON = "{\"value\":\"\(formatter.string(from: timestamp))\"}".data(using: .utf8)! // We can't encode a top-level Date, so it'll be wrapped in a dictionary. _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .formatted(formatter), dateDecodingStrategy: .formatted(formatter)) // Optional dates should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .formatted(formatter), dateDecodingStrategy: .formatted(formatter)) } func testEncodingDateCustom() { let timestamp = Date() // We'll encode a number instead of a date. let encode = { (_ data: Date, _ encoder: Encoder) throws -> Void in var container = encoder.singleValueContainer() try container.encode(42) } let decode = { (_: Decoder) throws -> Date in return timestamp } // We can't encode a top-level Date, so it'll be wrapped in a dictionary. let expectedJSON = "{\"value\":42}".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .custom(encode), dateDecodingStrategy: .custom(decode)) // Optional dates should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .custom(encode), dateDecodingStrategy: .custom(decode)) } func testEncodingDateCustomEmpty() { let timestamp = Date() // Encoding nothing should encode an empty keyed container ({}). let encode = { (_: Date, _: Encoder) throws -> Void in } let decode = { (_: Decoder) throws -> Date in return timestamp } // We can't encode a top-level Date, so it'll be wrapped in a dictionary. let expectedJSON = "{\"value\":{}}".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .custom(encode), dateDecodingStrategy: .custom(decode)) // Optional dates should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(timestamp), expectedJSON: expectedJSON, dateEncodingStrategy: .custom(encode), dateDecodingStrategy: .custom(decode)) } // MARK: - Data Strategy Tests func testEncodingData() { let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF]) // We can't encode a top-level Data, so it'll be wrapped in a dictionary. let expectedJSON = "{\"value\":[222,173,190,239]}".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(data), expectedJSON: expectedJSON, dataEncodingStrategy: .deferredToData, dataDecodingStrategy: .deferredToData) // Optional data should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(data), expectedJSON: expectedJSON, dataEncodingStrategy: .deferredToData, dataDecodingStrategy: .deferredToData) } func testEncodingDataBase64() { let data = Data(bytes: [0xDE, 0xAD, 0xBE, 0xEF]) // We can't encode a top-level Data, so it'll be wrapped in a dictionary. let expectedJSON = "{\"value\":\"3q2+7w==\"}".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(data), expectedJSON: expectedJSON) // Optional data should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(data), expectedJSON: expectedJSON) } func testEncodingDataCustom() { // We'll encode a number instead of data. let encode = { (_ data: Data, _ encoder: Encoder) throws -> Void in var container = encoder.singleValueContainer() try container.encode(42) } let decode = { (_: Decoder) throws -> Data in return Data() } // We can't encode a top-level Data, so it'll be wrapped in a dictionary. let expectedJSON = "{\"value\":42}".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(Data()), expectedJSON: expectedJSON, dataEncodingStrategy: .custom(encode), dataDecodingStrategy: .custom(decode)) // Optional data should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(Data()), expectedJSON: expectedJSON, dataEncodingStrategy: .custom(encode), dataDecodingStrategy: .custom(decode)) } func testEncodingDataCustomEmpty() { // Encoding nothing should encode an empty keyed container ({}). let encode = { (_: Data, _: Encoder) throws -> Void in } let decode = { (_: Decoder) throws -> Data in return Data() } // We can't encode a top-level Data, so it'll be wrapped in a dictionary. let expectedJSON = "{\"value\":{}}".data(using: .utf8)! _testRoundTrip(of: TopLevelWrapper(Data()), expectedJSON: expectedJSON, dataEncodingStrategy: .custom(encode), dataDecodingStrategy: .custom(decode)) // Optional Data should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(Data()), expectedJSON: expectedJSON, dataEncodingStrategy: .custom(encode), dataDecodingStrategy: .custom(decode)) } // MARK: - Non-Conforming Floating Point Strategy Tests func testEncodingNonConformingFloats() { _testEncodeFailure(of: TopLevelWrapper(Float.infinity)) _testEncodeFailure(of: TopLevelWrapper(-Float.infinity)) _testEncodeFailure(of: TopLevelWrapper(Float.nan)) _testEncodeFailure(of: TopLevelWrapper(Double.infinity)) _testEncodeFailure(of: TopLevelWrapper(-Double.infinity)) _testEncodeFailure(of: TopLevelWrapper(Double.nan)) // Optional Floats/Doubles should encode the same way. _testEncodeFailure(of: OptionalTopLevelWrapper(Float.infinity)) _testEncodeFailure(of: OptionalTopLevelWrapper(-Float.infinity)) _testEncodeFailure(of: OptionalTopLevelWrapper(Float.nan)) _testEncodeFailure(of: OptionalTopLevelWrapper(Double.infinity)) _testEncodeFailure(of: OptionalTopLevelWrapper(-Double.infinity)) _testEncodeFailure(of: OptionalTopLevelWrapper(Double.nan)) } func testEncodingNonConformingFloatStrings() { let encodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .convertToString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN") let decodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "INF", negativeInfinity: "-INF", nan: "NaN") _testRoundTrip(of: TopLevelWrapper(Float.infinity), expectedJSON: "{\"value\":\"INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: TopLevelWrapper(-Float.infinity), expectedJSON: "{\"value\":\"-INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) // Since Float.nan != Float.nan, we have to use a placeholder that'll encode NaN but actually round-trip. _testRoundTrip(of: TopLevelWrapper(FloatNaNPlaceholder()), expectedJSON: "{\"value\":\"NaN\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: TopLevelWrapper(Double.infinity), expectedJSON: "{\"value\":\"INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: TopLevelWrapper(-Double.infinity), expectedJSON: "{\"value\":\"-INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) // Since Double.nan != Double.nan, we have to use a placeholder that'll encode NaN but actually round-trip. _testRoundTrip(of: TopLevelWrapper(DoubleNaNPlaceholder()), expectedJSON: "{\"value\":\"NaN\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) // Optional Floats and Doubles should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(Float.infinity), expectedJSON: "{\"value\":\"INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: OptionalTopLevelWrapper(-Float.infinity), expectedJSON: "{\"value\":\"-INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: OptionalTopLevelWrapper(Double.infinity), expectedJSON: "{\"value\":\"INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) _testRoundTrip(of: OptionalTopLevelWrapper(-Double.infinity), expectedJSON: "{\"value\":\"-INF\"}".data(using: .utf8)!, nonConformingFloatEncodingStrategy: encodingStrategy, nonConformingFloatDecodingStrategy: decodingStrategy) } // MARK: - Key Strategy Tests private struct EncodeMe : Encodable { var keyName: String func encode(to coder: Encoder) throws { var c = coder.container(keyedBy: _TestKey.self) try c.encode("test", forKey: _TestKey(stringValue: keyName)!) } } func testEncodingKeyStrategySnake() { let toSnakeCaseTests = [ ("simpleOneTwo", "simple_one_two"), ("myURL", "my_url"), ("singleCharacterAtEndX", "single_character_at_end_x"), ("thisIsAnXMLProperty", "this_is_an_xml_property"), ("single", "single"), // no underscore ("", ""), // don't die on empty string ("a", "a"), // single character ("aA", "a_a"), // two characters ("version4Thing", "version4_thing"), // numerics ("partCAPS", "part_caps"), // only insert underscore before first all caps ("partCAPSLowerAGAIN", "part_caps_lower_again"), // switch back and forth caps. ("manyWordsInThisThing", "many_words_in_this_thing"), // simple lowercase + underscore + more ("asdfĆqer", "asdf_ćqer"), ("already_snake_case", "already_snake_case"), ("dataPoint22", "data_point22"), ("dataPoint22Word", "data_point22_word"), ("_oneTwoThree", "_one_two_three"), ("oneTwoThree_", "one_two_three_"), ("__oneTwoThree", "__one_two_three"), ("oneTwoThree__", "one_two_three__"), ("_oneTwoThree_", "_one_two_three_"), ("__oneTwoThree", "__one_two_three"), ("__oneTwoThree__", "__one_two_three__"), ("_test", "_test"), ("_test_", "_test_"), ("__test", "__test"), ("test__", "test__"), ("m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ", "m͉̟̹y̦̳_g͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖_u͇̝̠r͙̻̥͓̣l̥̖͎͓̪̫ͅ_r̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ"), // because Itai wanted to test this ("🐧🐟", "🐧🐟") // fishy emoji example? ] for test in toSnakeCaseTests { let expected = "{\"\(test.1)\":\"test\"}" let encoded = EncodeMe(keyName: test.0) let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase let resultData = try! encoder.encode(encoded) let resultString = String(bytes: resultData, encoding: .utf8) expectEqual(expected, resultString) } } func testEncodingKeyStrategyCustom() { let expected = "{\"QQQhello\":\"test\"}" let encoded = EncodeMe(keyName: "hello") let encoder = JSONEncoder() let customKeyConversion = { (_ path : [CodingKey]) -> CodingKey in let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)! return key } encoder.keyEncodingStrategy = .custom(customKeyConversion) let resultData = try! encoder.encode(encoded) let resultString = String(bytes: resultData, encoding: .utf8) expectEqual(expected, resultString) } private struct EncodeNested : Encodable { let nestedValue: EncodeMe } private struct EncodeNestedNested : Encodable { let outerValue: EncodeNested } func testEncodingKeyStrategyPath() { // Make sure a more complex path shows up the way we want // Make sure the path reflects keys in the Swift, not the resulting ones in the JSON let expected = "{\"QQQouterValue\":{\"QQQnestedValue\":{\"QQQhelloWorld\":\"test\"}}}" let encoded = EncodeNestedNested(outerValue: EncodeNested(nestedValue: EncodeMe(keyName: "helloWorld"))) let encoder = JSONEncoder() var callCount = 0 let customKeyConversion = { (_ path : [CodingKey]) -> CodingKey in // This should be called three times: // 1. to convert 'outerValue' to something // 2. to convert 'nestedValue' to something // 3. to convert 'helloWorld' to something callCount = callCount + 1 if path.count == 0 { expectUnreachable("The path should always have at least one entry") } else if path.count == 1 { expectEqual(["outerValue"], path.map { $0.stringValue }) } else if path.count == 2 { expectEqual(["outerValue", "nestedValue"], path.map { $0.stringValue }) } else if path.count == 3 { expectEqual(["outerValue", "nestedValue", "helloWorld"], path.map { $0.stringValue }) } else { expectUnreachable("The path mysteriously had more entries") } let key = _TestKey(stringValue: "QQQ" + path.last!.stringValue)! return key } encoder.keyEncodingStrategy = .custom(customKeyConversion) let resultData = try! encoder.encode(encoded) let resultString = String(bytes: resultData, encoding: .utf8) expectEqual(expected, resultString) expectEqual(3, callCount) } private struct DecodeMe : Decodable { let found: Bool init(from coder: Decoder) throws { let c = try coder.container(keyedBy: _TestKey.self) // Get the key that we expect to be passed in (camel case) let camelCaseKey = try c.decode(String.self, forKey: _TestKey(stringValue: "camelCaseKey")!) // Use the camel case key to decode from the JSON. The decoder should convert it to snake case to find it. found = try c.decode(Bool.self, forKey: _TestKey(stringValue: camelCaseKey)!) } } func testDecodingKeyStrategyCamel() { let fromSnakeCaseTests = [ ("", ""), // don't die on empty string ("a", "a"), // single character ("ALLCAPS", "ALLCAPS"), // If no underscores, we leave the word as-is ("ALL_CAPS", "allCaps"), // Conversion from screaming snake case ("single", "single"), // do not capitalize anything with no underscore ("snake_case", "snakeCase"), // capitalize a character ("one_two_three", "oneTwoThree"), // more than one word ("one_2_three", "one2Three"), // numerics ("one2_three", "one2Three"), // numerics, part 2 ("snake_Ćase", "snakeĆase"), // do not further modify a capitalized diacritic ("snake_ćase", "snakeĆase"), // capitalize a diacritic ("alreadyCamelCase", "alreadyCamelCase"), // do not modify already camel case ("__this_and_that", "__thisAndThat"), ("_this_and_that", "_thisAndThat"), ("this__and__that", "thisAndThat"), ("this_and_that__", "thisAndThat__"), ("this_aNd_that", "thisAndThat"), ("_one_two_three", "_oneTwoThree"), ("one_two_three_", "oneTwoThree_"), ("__one_two_three", "__oneTwoThree"), ("one_two_three__", "oneTwoThree__"), ("_one_two_three_", "_oneTwoThree_"), ("__one_two_three", "__oneTwoThree"), ("__one_two_three__", "__oneTwoThree__"), ("_test", "_test"), ("_test_", "_test_"), ("__test", "__test"), ("test__", "test__"), ("_", "_"), ("__", "__"), ("___", "___"), ("m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ", "m͉̟̹y̦̳G͍͚͎̳r̤͉̤͕ͅea̲͕t͇̥̼͖U͇̝̠R͙̻̥͓̣L̥̖͎͓̪̫ͅR̩͖̩eq͈͓u̞e̱s̙t̤̺ͅ"), // because Itai wanted to test this ("🐧_🐟", "🐧🐟") // fishy emoji example? ] for test in fromSnakeCaseTests { // This JSON contains the camel case key that the test object should decode with, then it uses the snake case key (test.0) as the actual key for the boolean value. let input = "{\"camelCaseKey\":\"\(test.1)\",\"\(test.0)\":true}".data(using: .utf8)! let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let result = try! decoder.decode(DecodeMe.self, from: input) expectTrue(result.found) } } private struct DecodeMe2 : Decodable { var hello: String } func testDecodingKeyStrategyCustom() { let input = "{\"----hello\":\"test\"}".data(using: .utf8)! let decoder = JSONDecoder() let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in // This converter removes the first 4 characters from the start of all string keys, if it has more than 4 characters let string = path.last!.stringValue guard string.count > 4 else { return path.last! } let newString = String(string.dropFirst(4)) return _TestKey(stringValue: newString)! } decoder.keyDecodingStrategy = .custom(customKeyConversion) let result = try! decoder.decode(DecodeMe2.self, from: input) expectEqual("test", result.hello) } private struct DecodeMe3 : Codable { var thisIsCamelCase : String } func testEncodingKeyStrategySnakeGenerated() { // Test that this works with a struct that has automatically generated keys let input = "{\"this_is_camel_case\":\"test\"}".data(using: .utf8)! let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let result = try! decoder.decode(DecodeMe3.self, from: input) expectEqual("test", result.thisIsCamelCase) } func testDecodingKeyStrategyCamelGenerated() { let encoded = DecodeMe3(thisIsCamelCase: "test") let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase let resultData = try! encoder.encode(encoded) let resultString = String(bytes: resultData, encoding: .utf8) expectEqual("{\"this_is_camel_case\":\"test\"}", resultString) } func testKeyStrategySnakeGeneratedAndCustom() { // Test that this works with a struct that has automatically generated keys struct DecodeMe4 : Codable { var thisIsCamelCase : String var thisIsCamelCaseToo : String private enum CodingKeys : String, CodingKey { case thisIsCamelCase = "fooBar" case thisIsCamelCaseToo } } // Decoding let input = "{\"foo_bar\":\"test\",\"this_is_camel_case_too\":\"test2\"}".data(using: .utf8)! let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let decodingResult = try! decoder.decode(DecodeMe4.self, from: input) expectEqual("test", decodingResult.thisIsCamelCase) expectEqual("test2", decodingResult.thisIsCamelCaseToo) // Encoding let encoded = DecodeMe4(thisIsCamelCase: "test", thisIsCamelCaseToo: "test2") let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase let encodingResultData = try! encoder.encode(encoded) let encodingResultString = String(bytes: encodingResultData, encoding: .utf8) expectEqual("{\"foo_bar\":\"test\",\"this_is_camel_case_too\":\"test2\"}", encodingResultString) } func testKeyStrategyDuplicateKeys() { // This test is mostly to make sure we don't assert on duplicate keys struct DecodeMe5 : Codable { var oneTwo : String var numberOfKeys : Int enum CodingKeys : String, CodingKey { case oneTwo case oneTwoThree } init() { oneTwo = "test" numberOfKeys = 0 } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) oneTwo = try container.decode(String.self, forKey: .oneTwo) numberOfKeys = container.allKeys.count } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(oneTwo, forKey: .oneTwo) try container.encode("test2", forKey: .oneTwoThree) } } let customKeyConversion = { (_ path: [CodingKey]) -> CodingKey in // All keys are the same! return _TestKey(stringValue: "oneTwo")! } // Decoding // This input has a dictionary with two keys, but only one will end up in the container let input = "{\"unused key 1\":\"test1\",\"unused key 2\":\"test2\"}".data(using: .utf8)! let decoder = JSONDecoder() decoder.keyDecodingStrategy = .custom(customKeyConversion) let decodingResult = try! decoder.decode(DecodeMe5.self, from: input) // There will be only one result for oneTwo (the second one in the json) expectEqual(1, decodingResult.numberOfKeys) // Encoding let encoded = DecodeMe5() let encoder = JSONEncoder() encoder.keyEncodingStrategy = .custom(customKeyConversion) let decodingResultData = try! encoder.encode(encoded) let decodingResultString = String(bytes: decodingResultData, encoding: .utf8) // There will be only one value in the result (the second one encoded) expectEqual("{\"oneTwo\":\"test2\"}", decodingResultString) } // MARK: - Encoder Features func testNestedContainerCodingPaths() { let encoder = JSONEncoder() do { let _ = try encoder.encode(NestedContainersTestType()) } catch let error as NSError { expectUnreachable("Caught error during encoding nested container types: \(error)") } } func testSuperEncoderCodingPaths() { let encoder = JSONEncoder() do { let _ = try encoder.encode(NestedContainersTestType(testSuperEncoder: true)) } catch let error as NSError { expectUnreachable("Caught error during encoding nested container types: \(error)") } } func testInterceptDecimal() { let expectedJSON = "{\"value\":10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000}".data(using: .utf8)! // Want to make sure we write out a JSON number, not the keyed encoding here. // 1e127 is too big to fit natively in a Double, too, so want to make sure it's encoded as a Decimal. let decimal = Decimal(sign: .plus, exponent: 127, significand: Decimal(1)) _testRoundTrip(of: TopLevelWrapper(decimal), expectedJSON: expectedJSON) // Optional Decimals should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(decimal), expectedJSON: expectedJSON) } func testInterceptURL() { // Want to make sure JSONEncoder writes out single-value URLs, not the keyed encoding. let expectedJSON = "{\"value\":\"http:\\/\\/swift.org\"}".data(using: .utf8)! let url = URL(string: "http://swift.org")! _testRoundTrip(of: TopLevelWrapper(url), expectedJSON: expectedJSON) // Optional URLs should encode the same way. _testRoundTrip(of: OptionalTopLevelWrapper(url), expectedJSON: expectedJSON) } // MARK: - Type coercion func testTypeCoercion() { _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int8].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int16].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int32].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int64].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt8].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt16].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt32].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt64].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [Float].self) _testRoundTripTypeCoercionFailure(of: [false, true], as: [Double].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int8], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int16], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int32], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int64], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt8], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt16], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt32], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt64], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Float], as: [Bool].self) _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Double], as: [Bool].self) } func testDecodingConcreteTypeParameter() { let encoder = JSONEncoder() guard let json = try? encoder.encode(Employee.testValue) else { expectUnreachable("Unable to encode Employee.") return } let decoder = JSONDecoder() guard let decoded = try? decoder.decode(Employee.self as Person.Type, from: json) else { expectUnreachable("Failed to decode Employee as Person from JSON.") return } expectEqual(type(of: decoded), Employee.self, "Expected decoded value to be of type Employee; got \(type(of: decoded)) instead.") } // MARK: - Encoder State // SR-6078 func testEncoderStateThrowOnEncode() { struct ReferencingEncoderWrapper<T : Encodable> : Encodable { let value: T init(_ value: T) { self.value = value } func encode(to encoder: Encoder) throws { // This approximates a subclass calling into its superclass, where the superclass encodes a value that might throw. // The key here is that getting the superEncoder creates a referencing encoder. var container = encoder.unkeyedContainer() let superEncoder = container.superEncoder() // Pushing a nested container on leaves the referencing encoder with multiple containers. var nestedContainer = superEncoder.unkeyedContainer() try nestedContainer.encode(value) } } // The structure that would be encoded here looks like // // [[[Float.infinity]]] // // The wrapper asks for an unkeyed container ([^]), gets a super encoder, and creates a nested container into that ([[^]]). // We then encode an array into that ([[[^]]]), which happens to be a value that causes us to throw an error. // // The issue at hand reproduces when you have a referencing encoder (superEncoder() creates one) that has a container on the stack (unkeyedContainer() adds one) that encodes a value going through box_() (Array does that) that encodes something which throws (Float.infinity does that). // When reproducing, this will cause a test failure via fatalError(). _ = try? JSONEncoder().encode(ReferencingEncoderWrapper([Float.infinity])) } func testEncoderStateThrowOnEncodeCustomDate() { // This test is identical to testEncoderStateThrowOnEncode, except throwing via a custom Date closure. struct ReferencingEncoderWrapper<T : Encodable> : Encodable { let value: T init(_ value: T) { self.value = value } func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() let superEncoder = container.superEncoder() var nestedContainer = superEncoder.unkeyedContainer() try nestedContainer.encode(value) } } // The closure needs to push a container before throwing an error to trigger. let encoder = JSONEncoder() encoder.dateEncodingStrategy = .custom({ _, encoder in let _ = encoder.unkeyedContainer() enum CustomError : Error { case foo } throw CustomError.foo }) _ = try? encoder.encode(ReferencingEncoderWrapper(Date())) } func testEncoderStateThrowOnEncodeCustomData() { // This test is identical to testEncoderStateThrowOnEncode, except throwing via a custom Data closure. struct ReferencingEncoderWrapper<T : Encodable> : Encodable { let value: T init(_ value: T) { self.value = value } func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() let superEncoder = container.superEncoder() var nestedContainer = superEncoder.unkeyedContainer() try nestedContainer.encode(value) } } // The closure needs to push a container before throwing an error to trigger. let encoder = JSONEncoder() encoder.dataEncodingStrategy = .custom({ _, encoder in let _ = encoder.unkeyedContainer() enum CustomError : Error { case foo } throw CustomError.foo }) _ = try? encoder.encode(ReferencingEncoderWrapper(Data())) } // MARK: - Decoder State // SR-6048 func testDecoderStateThrowOnDecode() { // The container stack here starts as [[1,2,3]]. Attempting to decode as [String] matches the outer layer (Array), and begins decoding the array. // Once Array decoding begins, 1 is pushed onto the container stack ([[1,2,3], 1]), and 1 is attempted to be decoded as String. This throws a .typeMismatch, but the container is not popped off the stack. // When attempting to decode [Int], the container stack is still ([[1,2,3], 1]), and 1 fails to decode as [Int]. let json = "[1,2,3]".data(using: .utf8)! let _ = try! JSONDecoder().decode(EitherDecodable<[String], [Int]>.self, from: json) } func testDecoderStateThrowOnDecodeCustomDate() { // This test is identical to testDecoderStateThrowOnDecode, except we're going to fail because our closure throws an error, not because we hit a type mismatch. let decoder = JSONDecoder() decoder.dateDecodingStrategy = .custom({ decoder in enum CustomError : Error { case foo } throw CustomError.foo }) let json = "{\"value\": 1}".data(using: .utf8)! let _ = try! decoder.decode(EitherDecodable<TopLevelWrapper<Date>, TopLevelWrapper<Int>>.self, from: json) } func testDecoderStateThrowOnDecodeCustomData() { // This test is identical to testDecoderStateThrowOnDecode, except we're going to fail because our closure throws an error, not because we hit a type mismatch. let decoder = JSONDecoder() decoder.dataDecodingStrategy = .custom({ decoder in enum CustomError : Error { case foo } throw CustomError.foo }) let json = "{\"value\": 1}".data(using: .utf8)! let _ = try! decoder.decode(EitherDecodable<TopLevelWrapper<Data>, TopLevelWrapper<Int>>.self, from: json) } // MARK: - Helper Functions private var _jsonEmptyDictionary: Data { return "{}".data(using: .utf8)! } private func _testEncodeFailure<T : Encodable>(of value: T) { do { let _ = try JSONEncoder().encode(value) expectUnreachable("Encode of top-level \(T.self) was expected to fail.") } catch {} } private func _testRoundTrip<T>(of value: T, expectedJSON json: Data? = nil, outputFormatting: JSONEncoder.OutputFormatting = [], dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64, dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64, keyEncodingStrategy: JSONEncoder.KeyEncodingStrategy = .useDefaultKeys, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw, nonConformingFloatDecodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .throw) where T : Codable, T : Equatable { var payload: Data! = nil do { let encoder = JSONEncoder() encoder.outputFormatting = outputFormatting encoder.dateEncodingStrategy = dateEncodingStrategy encoder.dataEncodingStrategy = dataEncodingStrategy encoder.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy encoder.keyEncodingStrategy = keyEncodingStrategy payload = try encoder.encode(value) } catch { expectUnreachable("Failed to encode \(T.self) to JSON: \(error)") } if let expectedJSON = json { expectEqual(expectedJSON, payload, "Produced JSON not identical to expected JSON.") } do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = dateDecodingStrategy decoder.dataDecodingStrategy = dataDecodingStrategy decoder.nonConformingFloatDecodingStrategy = nonConformingFloatDecodingStrategy decoder.keyDecodingStrategy = keyDecodingStrategy let decoded = try decoder.decode(T.self, from: payload) expectEqual(decoded, value, "\(T.self) did not round-trip to an equal value.") } catch { expectUnreachable("Failed to decode \(T.self) from JSON: \(error)") } } private func _testRoundTripTypeCoercionFailure<T,U>(of value: T, as type: U.Type) where T : Codable, U : Codable { do { let data = try JSONEncoder().encode(value) let _ = try JSONDecoder().decode(U.self, from: data) expectUnreachable("Coercion from \(T.self) to \(U.self) was expected to fail.") } catch {} } } // MARK: - Helper Global Functions func expectEqualPaths(_ lhs: [CodingKey], _ rhs: [CodingKey], _ prefix: String) { if lhs.count != rhs.count { expectUnreachable("\(prefix) [CodingKey].count mismatch: \(lhs.count) != \(rhs.count)") return } for (key1, key2) in zip(lhs, rhs) { switch (key1.intValue, key2.intValue) { case (.none, .none): break case (.some(let i1), .none): expectUnreachable("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != nil") return case (.none, .some(let i2)): expectUnreachable("\(prefix) CodingKey.intValue mismatch: nil != \(type(of: key2))(\(i2))") return case (.some(let i1), .some(let i2)): guard i1 == i2 else { expectUnreachable("\(prefix) CodingKey.intValue mismatch: \(type(of: key1))(\(i1)) != \(type(of: key2))(\(i2))") return } break } expectEqual(key1.stringValue, key2.stringValue, "\(prefix) CodingKey.stringValue mismatch: \(type(of: key1))('\(key1.stringValue)') != \(type(of: key2))('\(key2.stringValue)')") } } // MARK: - Test Types /* FIXME: Import from %S/Inputs/Coding/SharedTypes.swift somehow. */ // MARK: - Empty Types fileprivate struct EmptyStruct : Codable, Equatable { static func ==(_ lhs: EmptyStruct, _ rhs: EmptyStruct) -> Bool { return true } } fileprivate class EmptyClass : Codable, Equatable { static func ==(_ lhs: EmptyClass, _ rhs: EmptyClass) -> Bool { return true } } // MARK: - Single-Value Types /// A simple on-off switch type that encodes as a single Bool value. fileprivate enum Switch : Codable { case off case on init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() switch try container.decode(Bool.self) { case false: self = .off case true: self = .on } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .off: try container.encode(false) case .on: try container.encode(true) } } } /// A simple timestamp type that encodes as a single Double value. fileprivate struct Timestamp : Codable, Equatable { let value: Double init(_ value: Double) { self.value = value } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() value = try container.decode(Double.self) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.value) } static func ==(_ lhs: Timestamp, _ rhs: Timestamp) -> Bool { return lhs.value == rhs.value } } /// A simple referential counter type that encodes as a single Int value. fileprivate final class Counter : Codable, Equatable { var count: Int = 0 init() {} init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() count = try container.decode(Int.self) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.count) } static func ==(_ lhs: Counter, _ rhs: Counter) -> Bool { return lhs === rhs || lhs.count == rhs.count } } // MARK: - Structured Types /// A simple address type that encodes as a dictionary of values. fileprivate struct Address : Codable, Equatable { let street: String let city: String let state: String let zipCode: Int let country: String init(street: String, city: String, state: String, zipCode: Int, country: String) { self.street = street self.city = city self.state = state self.zipCode = zipCode self.country = country } static func ==(_ lhs: Address, _ rhs: Address) -> Bool { return lhs.street == rhs.street && lhs.city == rhs.city && lhs.state == rhs.state && lhs.zipCode == rhs.zipCode && lhs.country == rhs.country } static var testValue: Address { return Address(street: "1 Infinite Loop", city: "Cupertino", state: "CA", zipCode: 95014, country: "United States") } } /// A simple person class that encodes as a dictionary of values. fileprivate class Person : Codable, Equatable { let name: String let email: String let website: URL? init(name: String, email: String, website: URL? = nil) { self.name = name self.email = email self.website = website } private enum CodingKeys : String, CodingKey { case name case email case website } // FIXME: Remove when subclasses (Employee) are able to override synthesized conformance. required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) email = try container.decode(String.self, forKey: .email) website = try container.decodeIfPresent(URL.self, forKey: .website) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(email, forKey: .email) try container.encodeIfPresent(website, forKey: .website) } func isEqual(_ other: Person) -> Bool { return self.name == other.name && self.email == other.email && self.website == other.website } static func ==(_ lhs: Person, _ rhs: Person) -> Bool { return lhs.isEqual(rhs) } class var testValue: Person { return Person(name: "Johnny Appleseed", email: "appleseed@apple.com") } } /// A class which shares its encoder and decoder with its superclass. fileprivate class Employee : Person { let id: Int init(name: String, email: String, website: URL? = nil, id: Int) { self.id = id super.init(name: name, email: email, website: website) } enum CodingKeys : String, CodingKey { case id } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(Int.self, forKey: .id) try super.init(from: decoder) } override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try super.encode(to: encoder) } override func isEqual(_ other: Person) -> Bool { if let employee = other as? Employee { guard self.id == employee.id else { return false } } return super.isEqual(other) } override class var testValue: Employee { return Employee(name: "Johnny Appleseed", email: "appleseed@apple.com", id: 42) } } /// A simple company struct which encodes as a dictionary of nested values. fileprivate struct Company : Codable, Equatable { let address: Address var employees: [Employee] init(address: Address, employees: [Employee]) { self.address = address self.employees = employees } static func ==(_ lhs: Company, _ rhs: Company) -> Bool { return lhs.address == rhs.address && lhs.employees == rhs.employees } static var testValue: Company { return Company(address: Address.testValue, employees: [Employee.testValue]) } } /// An enum type which decodes from Bool?. fileprivate enum EnhancedBool : Codable { case `true` case `false` case fileNotFound init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self = .fileNotFound } else { let value = try container.decode(Bool.self) self = value ? .true : .false } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .true: try container.encode(true) case .false: try container.encode(false) case .fileNotFound: try container.encodeNil() } } } /// A type which encodes as an array directly through a single value container. struct Numbers : Codable, Equatable { let values = [4, 8, 15, 16, 23, 42] init() {} init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let decodedValues = try container.decode([Int].self) guard decodedValues == values else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "The Numbers are wrong!")) } } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(values) } static func ==(_ lhs: Numbers, _ rhs: Numbers) -> Bool { return lhs.values == rhs.values } static var testValue: Numbers { return Numbers() } } /// A type which encodes as a dictionary directly through a single value container. fileprivate final class Mapping : Codable, Equatable { let values: [String : URL] init(values: [String : URL]) { self.values = values } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() values = try container.decode([String : URL].self) } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(values) } static func ==(_ lhs: Mapping, _ rhs: Mapping) -> Bool { return lhs === rhs || lhs.values == rhs.values } static var testValue: Mapping { return Mapping(values: ["Apple": URL(string: "http://apple.com")!, "localhost": URL(string: "http://127.0.0.1")!]) } } struct NestedContainersTestType : Encodable { let testSuperEncoder: Bool init(testSuperEncoder: Bool = false) { self.testSuperEncoder = testSuperEncoder } enum TopLevelCodingKeys : Int, CodingKey { case a case b case c } enum IntermediateCodingKeys : Int, CodingKey { case one case two } func encode(to encoder: Encoder) throws { if self.testSuperEncoder { var topLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self) expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.") expectEqualPaths(topLevelContainer.codingPath, [], "New first-level keyed container has non-empty codingPath.") let superEncoder = topLevelContainer.superEncoder(forKey: .a) expectEqualPaths(encoder.codingPath, [], "Top-level Encoder's codingPath changed.") expectEqualPaths(topLevelContainer.codingPath, [], "First-level keyed container's codingPath changed.") expectEqualPaths(superEncoder.codingPath, [TopLevelCodingKeys.a], "New superEncoder had unexpected codingPath.") _testNestedContainers(in: superEncoder, baseCodingPath: [TopLevelCodingKeys.a]) } else { _testNestedContainers(in: encoder, baseCodingPath: []) } } func _testNestedContainers(in encoder: Encoder, baseCodingPath: [CodingKey]) { expectEqualPaths(encoder.codingPath, baseCodingPath, "New encoder has non-empty codingPath.") // codingPath should not change upon fetching a non-nested container. var firstLevelContainer = encoder.container(keyedBy: TopLevelCodingKeys.self) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "New first-level keyed container has non-empty codingPath.") // Nested Keyed Container do { // Nested container for key should have a new key pushed on. var secondLevelContainer = firstLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .a) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "New second-level keyed container had unexpected codingPath.") // Inserting a keyed container should not change existing coding paths. let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self, forKey: .one) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.one], "New third-level keyed container had unexpected codingPath.") // Inserting an unkeyed container should not change existing coding paths. let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer(forKey: .two) expectEqualPaths(encoder.codingPath, baseCodingPath + [], "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath + [], "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.a], "Second-level keyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.a, IntermediateCodingKeys.two], "New third-level unkeyed container had unexpected codingPath.") } // Nested Unkeyed Container do { // Nested container for key should have a new key pushed on. var secondLevelContainer = firstLevelContainer.nestedUnkeyedContainer(forKey: .b) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "New second-level keyed container had unexpected codingPath.") // Appending a keyed container should not change existing coding paths. let thirdLevelContainerKeyed = secondLevelContainer.nestedContainer(keyedBy: IntermediateCodingKeys.self) expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "Second-level unkeyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerKeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 0)], "New third-level keyed container had unexpected codingPath.") // Appending an unkeyed container should not change existing coding paths. let thirdLevelContainerUnkeyed = secondLevelContainer.nestedUnkeyedContainer() expectEqualPaths(encoder.codingPath, baseCodingPath, "Top-level Encoder's codingPath changed.") expectEqualPaths(firstLevelContainer.codingPath, baseCodingPath, "First-level keyed container's codingPath changed.") expectEqualPaths(secondLevelContainer.codingPath, baseCodingPath + [TopLevelCodingKeys.b], "Second-level unkeyed container's codingPath changed.") expectEqualPaths(thirdLevelContainerUnkeyed.codingPath, baseCodingPath + [TopLevelCodingKeys.b, _TestKey(index: 1)], "New third-level unkeyed container had unexpected codingPath.") } } } // MARK: - Helper Types /// A key type which can take on any string or integer value. /// This needs to mirror _JSONKey. fileprivate struct _TestKey : CodingKey { var stringValue: String var intValue: Int? init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } } /// Wraps a type T so that it can be encoded at the top level of a payload. fileprivate struct TopLevelWrapper<T> : Codable, Equatable where T : Codable, T : Equatable { let value: T init(_ value: T) { self.value = value } static func ==(_ lhs: TopLevelWrapper<T>, _ rhs: TopLevelWrapper<T>) -> Bool { return lhs.value == rhs.value } } /// Wraps a type T (as T?) so that it can be encoded at the top level of a payload. fileprivate struct OptionalTopLevelWrapper<T> : Codable, Equatable where T : Codable, T : Equatable { let value: T? init(_ value: T) { self.value = value } // Provide an implementation of Codable to encode(forKey:) instead of encodeIfPresent(forKey:). private enum CodingKeys : String, CodingKey { case value } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) value = try container.decode(T?.self, forKey: .value) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(value, forKey: .value) } static func ==(_ lhs: OptionalTopLevelWrapper<T>, _ rhs: OptionalTopLevelWrapper<T>) -> Bool { return lhs.value == rhs.value } } fileprivate struct FloatNaNPlaceholder : Codable, Equatable { init() {} func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(Float.nan) } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let float = try container.decode(Float.self) if !float.isNaN { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN.")) } } static func ==(_ lhs: FloatNaNPlaceholder, _ rhs: FloatNaNPlaceholder) -> Bool { return true } } fileprivate struct DoubleNaNPlaceholder : Codable, Equatable { init() {} func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(Double.nan) } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let double = try container.decode(Double.self) if !double.isNaN { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Couldn't decode NaN.")) } } static func ==(_ lhs: DoubleNaNPlaceholder, _ rhs: DoubleNaNPlaceholder) -> Bool { return true } } fileprivate enum EitherDecodable<T : Decodable, U : Decodable> : Decodable { case t(T) case u(U) init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() do { self = .t(try container.decode(T.self)) } catch { self = .u(try container.decode(U.self)) } } } // MARK: - Run Tests #if !FOUNDATION_XCTEST var JSONEncoderTests = TestSuite("TestJSONEncoder") JSONEncoderTests.test("testEncodingTopLevelEmptyStruct") { TestJSONEncoder().testEncodingTopLevelEmptyStruct() } JSONEncoderTests.test("testEncodingTopLevelEmptyClass") { TestJSONEncoder().testEncodingTopLevelEmptyClass() } JSONEncoderTests.test("testEncodingTopLevelSingleValueEnum") { TestJSONEncoder().testEncodingTopLevelSingleValueEnum() } JSONEncoderTests.test("testEncodingTopLevelSingleValueStruct") { TestJSONEncoder().testEncodingTopLevelSingleValueStruct() } JSONEncoderTests.test("testEncodingTopLevelSingleValueClass") { TestJSONEncoder().testEncodingTopLevelSingleValueClass() } JSONEncoderTests.test("testEncodingTopLevelStructuredStruct") { TestJSONEncoder().testEncodingTopLevelStructuredStruct() } JSONEncoderTests.test("testEncodingTopLevelStructuredClass") { TestJSONEncoder().testEncodingTopLevelStructuredClass() } JSONEncoderTests.test("testEncodingTopLevelStructuredSingleStruct") { TestJSONEncoder().testEncodingTopLevelStructuredSingleStruct() } JSONEncoderTests.test("testEncodingTopLevelStructuredSingleClass") { TestJSONEncoder().testEncodingTopLevelStructuredSingleClass() } JSONEncoderTests.test("testEncodingTopLevelDeepStructuredType") { TestJSONEncoder().testEncodingTopLevelDeepStructuredType()} JSONEncoderTests.test("testEncodingClassWhichSharesEncoderWithSuper") { TestJSONEncoder().testEncodingClassWhichSharesEncoderWithSuper() } JSONEncoderTests.test("testEncodingTopLevelNullableType") { TestJSONEncoder().testEncodingTopLevelNullableType() } JSONEncoderTests.test("testEncodingOutputFormattingDefault") { TestJSONEncoder().testEncodingOutputFormattingDefault() } JSONEncoderTests.test("testEncodingOutputFormattingPrettyPrinted") { TestJSONEncoder().testEncodingOutputFormattingPrettyPrinted() } JSONEncoderTests.test("testEncodingOutputFormattingSortedKeys") { TestJSONEncoder().testEncodingOutputFormattingSortedKeys() } JSONEncoderTests.test("testEncodingOutputFormattingPrettyPrintedSortedKeys") { TestJSONEncoder().testEncodingOutputFormattingPrettyPrintedSortedKeys() } JSONEncoderTests.test("testEncodingDate") { TestJSONEncoder().testEncodingDate() } JSONEncoderTests.test("testEncodingDateSecondsSince1970") { TestJSONEncoder().testEncodingDateSecondsSince1970() } JSONEncoderTests.test("testEncodingDateMillisecondsSince1970") { TestJSONEncoder().testEncodingDateMillisecondsSince1970() } JSONEncoderTests.test("testEncodingDateISO8601") { TestJSONEncoder().testEncodingDateISO8601() } JSONEncoderTests.test("testEncodingDateFormatted") { TestJSONEncoder().testEncodingDateFormatted() } JSONEncoderTests.test("testEncodingDateCustom") { TestJSONEncoder().testEncodingDateCustom() } JSONEncoderTests.test("testEncodingDateCustomEmpty") { TestJSONEncoder().testEncodingDateCustomEmpty() } JSONEncoderTests.test("testEncodingData") { TestJSONEncoder().testEncodingData() } JSONEncoderTests.test("testEncodingDataBase64") { TestJSONEncoder().testEncodingDataBase64() } JSONEncoderTests.test("testEncodingDataCustom") { TestJSONEncoder().testEncodingDataCustom() } JSONEncoderTests.test("testEncodingDataCustomEmpty") { TestJSONEncoder().testEncodingDataCustomEmpty() } JSONEncoderTests.test("testEncodingNonConformingFloats") { TestJSONEncoder().testEncodingNonConformingFloats() } JSONEncoderTests.test("testEncodingNonConformingFloatStrings") { TestJSONEncoder().testEncodingNonConformingFloatStrings() } JSONEncoderTests.test("testEncodingKeyStrategySnake") { TestJSONEncoder().testEncodingKeyStrategySnake() } JSONEncoderTests.test("testEncodingKeyStrategyCustom") { TestJSONEncoder().testEncodingKeyStrategyCustom() } JSONEncoderTests.test("testEncodingKeyStrategyPath") { TestJSONEncoder().testEncodingKeyStrategyPath() } JSONEncoderTests.test("testDecodingKeyStrategyCamel") { TestJSONEncoder().testDecodingKeyStrategyCamel() } JSONEncoderTests.test("testDecodingKeyStrategyCustom") { TestJSONEncoder().testDecodingKeyStrategyCustom() } JSONEncoderTests.test("testEncodingKeyStrategySnakeGenerated") { TestJSONEncoder().testEncodingKeyStrategySnakeGenerated() } JSONEncoderTests.test("testDecodingKeyStrategyCamelGenerated") { TestJSONEncoder().testDecodingKeyStrategyCamelGenerated() } JSONEncoderTests.test("testKeyStrategySnakeGeneratedAndCustom") { TestJSONEncoder().testKeyStrategySnakeGeneratedAndCustom() } JSONEncoderTests.test("testKeyStrategyDuplicateKeys") { TestJSONEncoder().testKeyStrategyDuplicateKeys() } JSONEncoderTests.test("testNestedContainerCodingPaths") { TestJSONEncoder().testNestedContainerCodingPaths() } JSONEncoderTests.test("testSuperEncoderCodingPaths") { TestJSONEncoder().testSuperEncoderCodingPaths() } JSONEncoderTests.test("testInterceptDecimal") { TestJSONEncoder().testInterceptDecimal() } JSONEncoderTests.test("testInterceptURL") { TestJSONEncoder().testInterceptURL() } JSONEncoderTests.test("testTypeCoercion") { TestJSONEncoder().testTypeCoercion() } JSONEncoderTests.test("testDecodingConcreteTypeParameter") { TestJSONEncoder().testDecodingConcreteTypeParameter() } JSONEncoderTests.test("testEncoderStateThrowOnEncode") { TestJSONEncoder().testEncoderStateThrowOnEncode() } JSONEncoderTests.test("testEncoderStateThrowOnEncodeCustomDate") { TestJSONEncoder().testEncoderStateThrowOnEncodeCustomDate() } JSONEncoderTests.test("testEncoderStateThrowOnEncodeCustomData") { TestJSONEncoder().testEncoderStateThrowOnEncodeCustomData() } JSONEncoderTests.test("testDecoderStateThrowOnDecode") { TestJSONEncoder().testDecoderStateThrowOnDecode() } JSONEncoderTests.test("testDecoderStateThrowOnDecodeCustomDate") { TestJSONEncoder().testDecoderStateThrowOnDecodeCustomDate() } JSONEncoderTests.test("testDecoderStateThrowOnDecodeCustomData") { TestJSONEncoder().testDecoderStateThrowOnDecodeCustomData() } runAllTests() #endif
apache-2.0
cf5f2ac88ba4c27775a0f3afddb69c4f
41.975888
288
0.686727
4.965179
false
true
false
false
nvkiet/XYZHappyCoding
XYZPlugin/NSObject_Extension.swift
1
1528
// // NSObject_Extension.swift // // Created by Kiet Nguyen on 12/24/15. // Copyright © 2015 Kiet Nguyen. All rights reserved. // import Foundation import AppKit extension NSObject { class func pluginDidLoad(bundle: NSBundle) { let appName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? NSString if appName == "Xcode" { if sharedPlugin == nil { sharedPlugin = XYZPlugin(bundle: bundle) } } } func xyz_initWithIcon(icon: AnyObject?, message: String, parentWindow: AnyObject, duration: Double) -> AnyObject? { if icon != nil && XYZTogglingHandler.isEnabled() && message.containsString("Succeeded") { let imageIcon = NSBundle(identifier: "com.kietnguyen.XYZPlugin")!.imageForResource(XYZFaceFactory.createFace()) self.xyz_initWithIcon(imageIcon!, message: message, parentWindow: parentWindow, duration: duration) if self.isKindOfClass(NSPanel) { let panel = self as! NSPanel if panel.contentView!.isKindOfClass(NSVisualEffectView) { let visualEffectView = panel.contentView as! NSVisualEffectView visualEffectView.material = NSVisualEffectMaterial.Titlebar imageIcon?.template = false } } return self } return self.xyz_initWithIcon(icon, message: message, parentWindow: parentWindow, duration: duration) } }
mit
73fc9cfcc2b782ebaf1b8a0234806e80
36.268293
123
0.62017
4.909968
false
false
false
false
huangboju/GesturePassword
GesturePassword/Classes/LockCenter.swift
1
6299
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // let PASSWORD_KEY = "gesture_password_key_" public struct LockCenter { static var storage: Storagable = LockUserDefaults() public static func hasPassword(for key: String? = nil) -> Bool { return storage.str(forKey: suffix(with: key)) != nil } public static func removePassword(for key: String? = nil) { storage.removeValue(forKey: suffix(with: key)) removeErrorTimes(forKey: LockCenter.passwordKeySuffix) } public static func set(_ password: String, forKey key: String? = nil) { storage.set(password, forKey: suffix(with: key)) } public static func password(forKey key: String? = nil) -> String? { return storage.str(forKey: suffix(with: key)) } public static func setErrorTimes(_ value: Int, forKey key: String? = nil) { let key = errorTimesKey(with: key) storage.set(value, forKey: key) } public static func errorTimes(forKey key: String? = nil) -> Int { let key = errorTimesKey(with: key) var result = storage.integer(forKey: key) if result == 0 && storage.str(forKey: key) == nil { result = errorTimes storage.set(result, forKey: key) } return result } public static func removeErrorTimes(forKey key: String? = nil) { let key = errorTimesKey(with: key) storage.removeValue(forKey: key) } public static func errorTimesKey(with suffix: String?) -> String { return PASSWORD_KEY + "error_times_" + (suffix ?? LockCenter.passwordKeySuffix) } private static func suffix(with str: String?) -> String { return PASSWORD_KEY + (str ?? LockCenter.passwordKeySuffix) } } extension LockCenter { /// 密码后缀 public static var passwordKeySuffix = "" // MARK: - 存放格式 public static var usingKeychain: Bool = false // MARK: - 设置密码("设置手势密码") public static var settingTittle = "setPasswordTitle".localized /// 设置密码提示文字("绘制解锁图案") public static var setPasswordDescTitle = "setPasswordDescTitle".localized /// 重绘密码提示文字("再次绘制解锁图案") public static var secondPassword = "setPasswordAgainTitle".localized /// 设置密码提示文字("与上一次绘制不一致,请重新绘制") public static var differentPassword = "setPasswordMismatchTitle".localized /// 设置密码重绘按钮(重绘) public static var redraw = "redraw".localized /// 最低设置密码数目 public static var passwordMinCount = 4 /// "至少连接$个点,请重新输入" public static func tooShortTitle(with count: Int = LockCenter.passwordMinCount) -> String { let title = "setPasswordTooShortTitle".localized return title.replacingOccurrences(of: "$", with: count.description) } public static func invalidPasswordTitle(with times: Int) -> String { let title = "invalidPasswordTitle".localized return title.replacingOccurrences(of: "$", with: times.description) } // MARK: - 验证密码 /// 密码错误次数 /// Default 5 static var errorTimes = 5 public static var verifyPasswordTitle = "verifyPasswordTitle".localized public static var forgotBtnTitle = "forgotParttern".localized // MARK: - 修改密码 // public static var resetPatternTitle = "resetPatternTitle".localized // MARK: - UI /// 圆的半径 /// Default: 66 public static var itemDiameter: CGFloat = 66 /// 选中圆大小的线宽 /// Default: 1 public static var lineWidth: CGFloat = 1 /// 背景色 /// Default: UIColor(r: 255, g: 255, b: 255) public static var backgroundColor = UIColor(r: 255, g: 255, b: 255) /// 外环线条颜色:默认 /// Default: UIColor(r: 173, g: 216, b: 230) public static var lineNormalColor = UIColor(r: 173, g: 216, b: 230) /// 外环线条颜色:选中 /// Default: UIColor(r: 0, g: 191, b: 255) public static var lineHighlightColor = UIColor(r: 0, g: 191, b: 255) /// 外环线条颜色:错误 /// Default: warningTitleColor public static var lineWarnColor = warningTitleColor /// 警示文字颜色 /// Default: UIColor.red public static var warningTitleColor = UIColor.red /// 普通文字颜色 /// Default: UIColor(r: 192, g: 192, b: 192) public static var normalTitleColor = UIColor(r: 192, g: 192, b: 192) /// 导航栏titleColor /// Default: UIColor.black public static var barTittleColor = UIColor.black /// 导航栏底部黑线是否隐藏 /// Default: false public static var hideBarBottomLine = false /// barButton文字颜色 /// Default: UIColor.red public static var barTintColor = UIColor.red /// barButton文字大小 /// Default: UIFont.systemFont(ofSize: 18) public static var barTittleFont = UIFont.systemFont(ofSize: 18) /// 导航栏背景颜色 /// Default: nil public static var barBackgroundColor: UIColor? /// 状态栏字体颜色 /// Default: UIStatusBarStyle.default public static var statusBarStyle: UIStatusBarStyle = .default } @discardableResult public func showSetPattern(in controller: UIViewController) -> SetPatternController { let vc = SetPatternController() controller.navigationController?.pushViewController(vc, animated: true) return vc } @discardableResult public func showVerifyPattern(in controller: UIViewController) -> VerifyPatternController { let vc = VerifyPatternController() controller.present(LockMainNav(rootViewController: vc), animated: true, completion: nil) return vc } @discardableResult public func showModifyPattern(in controller: UIViewController) -> ResetPatternController { let vc = ResetPatternController() controller.navigationController?.pushViewController(vc, animated: true) return vc } func delay(_ interval: TimeInterval, handle: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + interval, execute: handle) }
mit
9130ab310cc2955b60eb0125e2ba56b7
29.712042
95
0.656325
4.157335
false
false
false
false
xiongbearbear/Weibo
Weibo/Weibo/Classes/View/Main/XBBBaseViewController.swift
1
3460
// // XBBBaseViewController.swift // Weibo // // Created by xiong on 16/11/28. // Copyright © 2016年 xiong. All rights reserved. // import UIKit // 面试图: OC 中支持多继承嘛? 如果不支持,如何替代? 答案:使用协议替代: // Swift 的写法更类似于多继承 // class XBBBaseViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { // Swift 中 利用 extension 可以把"函数"功能分类,便于管理 // 注意: // 1.extension 中不能有属性 // 2.extension 中不能重新父类方法!重新父类方法,是子类的职责,扩展是对类的扩展! // 所有住控制器的基类控制器 class XBBBaseViewController: UIViewController{ // 表格视图 - 如果用户没有登录就不创建 var tableView:UITableView? // 自定义导航条 lazy var navigationBar:UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64)) // 自定义导航条目 - 以后设置导航栏内容,统一使用 navItem lazy var navItem = UINavigationItem() override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } /// 重写 title 的 didSet override var title: String? { didSet{ navItem.title = title } } // 加载数据 - 具体的实验由子类负责 func loadData(){ } } // MARK: - 设置界面 extension XBBBaseViewController{ func setupUI(){ view.backgroundColor = UIColor.cz_random() // 取消自动缩进 - 如果隐藏了导航栏,会缩进 20 个点 automaticallyAdjustsScrollViewInsets = false setupNavigationBar() setupTableView() } // 设置表格视图 private func setupTableView(){ tableView = UITableView(frame: view.bounds, style: .plain) view.insertSubview(tableView!, belowSubview: navigationBar) // 设置数据源&代理 -> 目的:子类直接实现数据方法 tableView?.delegate = self tableView?.dataSource = self tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0) } // 设置导航条 private func setupNavigationBar(){ // 添加导航 view.addSubview(navigationBar) //将 item 设置给 bar navigationBar.items = [navItem] // 设置 navBar 的渲染颜色 navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6) // 设置 navBar 的字体颜色 navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray] } } // MARK: - UITableViewDelegate,UITableViewDataSource extension XBBBaseViewController:UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } // 基类只是准备方法,子类扶着具体的实现 // 子类的数据源方法不需要 super func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 只是保证没有语法错误! return UITableViewCell() } }
mit
995b6defb6b96352fd71022ecf8f9622
25.935185
133
0.610519
4.434451
false
false
false
false
EMart86/WhitelabelApp
Whitelabel/UIColor+Hex.swift
1
1770
// // UIColor+Hex.swift // Golfclub-liebenau // // Created by Martin Eberl on 27.03.17. // Copyright © 2017 Martin Eberl. All rights reserved. // import UIKit extension UIColor { convenience init?(hex: String) { guard let normalizedString = UIColor.normalize(string: hex) else { return nil } var rgbValue:UInt32 = 0 Scanner(string: normalizedString).scanHexInt32(&rgbValue) var red: CGFloat? = nil var green: CGFloat? = nil var blue: CGFloat? = nil var alpha: CGFloat = 1 if normalizedString.characters.count == 6 { red = CGFloat((rgbValue & 0xFF0000) >> 16) green = CGFloat((rgbValue & 0x00FF00) >> 8) blue = CGFloat(rgbValue & 0x0000FF) } else if normalizedString.characters.count == 8 { red = CGFloat((rgbValue & 0xFF000000) >> 32) green = CGFloat((rgbValue & 0x00FF0000) >> 16) blue = CGFloat((rgbValue & 0x0000FF00) >> 8) alpha = CGFloat(rgbValue & 0x000000FF) } guard let _red = red, let _green = green, let _blue = blue else { return nil } self.init( red: _red / 255.0, green: _green / 255.0, blue: _blue / 255.0, alpha: alpha ) } private static func normalize(string: String) -> String? { var cString = string.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if cString.hasPrefix("#") { cString.remove(at: cString.startIndex) } return (cString.characters.count == 6 || cString.characters.count == 8) ? cString : nil } }
apache-2.0
b208c5742e67dd401105a3eb0eecae4d
29.5
95
0.539288
4.272947
false
false
false
false
not4mj/think
Think Golf/Services/BaseService.swift
1
4976
// // BaseService.swift // AppleMocks // // Created by Mohsin Jamadar on 7/15/15. // Copyright (c) 2015 Mohsin Jamadar. All rights reserved. // import Foundation import UIKit import SVProgressHUD import AFNetworking enum RequestStatus : Int { case loginFailed case invalidCredential = 400 case notAuthorized } open class BaseService { let baseUrlScheme = ConfigurationManager.sharedInstance.baseUrlComponents()[ConfigurationManager.schemePlistKey]! let baseUrl = ConfigurationManager.sharedInstance.baseUrlComponents()[ConfigurationManager.baseUrlPlistKey]! var logoutBlock: BasicBlock? static let timeOut = 200.0 typealias SuccessBlock = (AnyObject?) -> (Void) typealias FailureBlock = (Int) -> (Void) func submitRequest(_ urlRequest: NSMutableURLRequest, headers: Dictionary<String, String>, queryStringParams: Dictionary<String, String>?, body: Data?, method: String, success: @escaping SuccessBlock, failure: @escaping FailureBlock) { self.addHeaders(headers, request: urlRequest) urlRequest.httpBody = body urlRequest.httpMethod = method urlRequest.timeoutInterval = 20 self.logRequest(urlRequest as URLRequest) let operation = AFHTTPRequestOperation(request: urlRequest as URLRequest) operation.setCompletionBlockWithSuccess( { (operation:AFHTTPRequestOperation?, responseData: Any) -> Void in success(responseData as AnyObject?) }, failure: { (op, error) -> Void in let httpResponse = operation.response! as HTTPURLResponse if httpResponse.statusCode == 401 { print("----->LOG OUT") self.LogOffFromApp() } else if httpResponse.statusCode > 204 { failure((httpResponse.statusCode)) } } ) operation.start() } // MARK: Log-Off - Remove: Token, user_guid func LogOffFromApp() { if let l = self.logoutBlock { l() } //After Log-Off delete the user guid id and token and clear all values let common:CommonMethods = CommonMethods() common.DeleteKeyFromKeyChain("access_token") common.DeleteKeyFromKeyChain("user_guid") CredentialManager.sharedInstance.clearAuthorization() //Clear the hud if any SVProgressHUD.dismiss() //get the presented view controller var rootViewController = UIApplication.shared.keyWindow?.rootViewController if let navigationController = rootViewController as? UINavigationController { rootViewController = navigationController.viewControllers.first } //dismisss the presented view controller to go back to Login view dismissModalStack(rootViewController!.presentedViewController!, animated: true, completionBlock: nil) //Display token expiry prompt showAlert("Attention", message: "Your session is expired. Please login again to continue.", buttonTitle: "Ok", source:rootViewController! ) } func logRequest(_ urlRequest: URLRequest) { print("Submitting request \(urlRequest.url)") print("Method \(urlRequest.httpMethod)") if let b = urlRequest.httpBody { print("body: \(NSString(data: b, encoding: String.Encoding.utf8.rawValue))") } } func addHeaders(_ headers: Dictionary<String, String>, request: NSMutableURLRequest) { for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } } func headers() -> Dictionary<String, String> { var headers = Dictionary<String, String>() headers["Content-Type"] = "application/json"; headers["Accept"] = "application/json"; // Optionally add authorization tokens, request nonces etc. if let h = self.authorizationHeader() { headers["Authorization"] = h } return headers; } func authorizationHeader() -> String? { let token = CommonMethods().RetriveKeyFromKeyChain("access_token") if let t = token { return "Bearer \(t)" } return nil } func absoluteUrl(_ scheme: String, host: String, relativeUrl: String?, queryStringParams: Dictionary<String, String>?) -> URL { var nsUrlComponents = URLComponents() nsUrlComponents.scheme = scheme nsUrlComponents.host = host if let r = relativeUrl { nsUrlComponents.path = ConfigurationManager.sharedInstance.baseUrlComponents()[ConfigurationManager.relativePathPlistKey]! + r } if let q = queryStringParams { nsUrlComponents.query = q.toEncodedQueryParamString() } return nsUrlComponents.url! } }
apache-2.0
46f56542360eb6719cea13e37a00bcc9
35.321168
239
0.63324
5.260042
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Shepard Tab/Shepard Appearance/Slider/ShepardAppearanceSliderCell.swift
1
3318
// // ShepardAppearanceSliderCell.swift // MEGameTracker // // Created by Emily Ivie on 2/24/2016. // Copyright © 2016 urdnot. All rights reserved. // import UIKit final public class ShepardAppearanceSliderCell: UITableViewCell { // MARK: Types public typealias OnAppearanceSliderChange = ((_ attribute: Shepard.Appearance.AttributeType, _ value: Int) -> Void) // MARK: Constants // MARK: Outlets @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var slider: UISlider! @IBOutlet weak var sliderValueLabel: UILabel! @IBOutlet weak var noticeLabel: UILabel! @IBOutlet weak var errorLabel: UILabel! // MARK: Properties var attributeType: Shepard.Appearance.AttributeType? var value: Int? var maxValue: Int = 0 var title: String? var notice: String? var error: String? var onChange: OnAppearanceSliderChange? // MARK: Change Listeners And Change Status Flags private var isDefined = false // MARK: Lifecycle Events public override func layoutSubviews() { if !isDefined { clearRow() } super.layoutSubviews() } // MARK: Initialization /// Sets up the row - expects to be in main/UI dispatch queue. /// Also, table layout needs to wait for this, /// so don't run it asynchronously or the layout will be wrong. public func define( attributeType: Shepard.Appearance.AttributeType?, value: Int? = nil, maxValue: Int? = 0, title: String?, notice: String? = nil, error: String? = nil, onChange: OnAppearanceSliderChange? = nil ) { isDefined = true self.attributeType = attributeType self.value = value ?? self.value self.maxValue = maxValue ?? self.maxValue self.title = title self.notice = notice self.error = error self.onChange = onChange setup() } // MARK: Populate Data private func setup() { guard titleLabel != nil else { return } titleLabel?.text = "\(title ?? "?"):" let valueString = value != nil ? "\(value!)" : "?" sliderValueLabel?.text = "\(valueString)/\(maxValue)" slider?.minimumValue = 1 slider?.maximumValue = Float(maxValue) slider?.value = min(slider.maximumValue, Float(value ?? 0)) slider?.addTarget(self, action: #selector(ShepardAppearanceSliderCell.sliderChanged(_:)), for: UIControl.Event.valueChanged ) slider?.setThumbImage(UIImage(named: "Slider Thumb"), for: .normal) slider?.setThumbImage(UIImage(named: "Slider Thumb"), for: .highlighted) noticeLabel?.text = notice noticeLabel?.isHidden = !(notice?.isEmpty == false) errorLabel?.text = error errorLabel?.isHidden = !(error?.isEmpty == false) } /// Resets all text in the cases where row UI loads before data/setup. /// (I prefer to use sample UI data in nib, so I need it to disappear before UI displays.) private func clearRow() { titleLabel?.text = "" sliderValueLabel?.text = "" slider?.minimumValue = 0.0 slider?.maximumValue = 0.0 slider?.value = 0.0 noticeLabel?.isHidden = true errorLabel?.isHidden = true } // MARK: Supporting Functions @objc func sliderChanged(_ sender: UISlider) { value = Int(sender.value) sender.value = Float(value ?? 0) let valueString = value != nil ? "\(value!)" : "?" sliderValueLabel?.text = "\(valueString)/\(maxValue)" if let attributeType = self.attributeType, let value = self.value { onChange?(attributeType, value) } } }
mit
1d0a3155097aa0535d151658c616f36d
28.353982
116
0.698523
3.706145
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/WMFCaptchaViewController.swift
1
8830
import UIKit // Presently it is assumed this view controller will be used only as a // child view controller of another view controller. extension UIStackView { fileprivate var wmf_isCollapsed: Bool { get { for subview in arrangedSubviews { if !subview.isHidden { return false } } return true } set { for subview in arrangedSubviews { subview.isHidden = newValue } } } } @objc public protocol WMFCaptchaViewControllerDelegate { func captchaReloadPushed(_ sender: AnyObject) func captchaSolutionChanged(_ sender: AnyObject, solutionText: String?) func captchaSiteURL() -> URL func captchaKeyboardReturnKeyTapped() func captchaHideSubtitle() -> Bool } class WMFCaptchaViewController: UIViewController, UITextFieldDelegate, Themeable { @IBOutlet fileprivate var captchaImageView: UIImageView! @IBOutlet fileprivate var captchaTextFieldTitleLabel: UILabel! @IBOutlet fileprivate var captchaTextField: ThemeableTextField! @IBOutlet fileprivate var stackView: UIStackView! @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var subTitleLabel: WMFAuthLinkLabel! @IBOutlet fileprivate var infoButton: UIButton! @IBOutlet fileprivate var refreshButton: UIButton! @objc public weak var captchaDelegate: WMFCaptchaViewControllerDelegate? fileprivate let captchaResetter = WMFCaptchaResetter() fileprivate var theme = Theme.standard @objc var captcha: WMFCaptcha? { didSet { guard let captcha = captcha else { captchaTextField.text = nil stackView.wmf_isCollapsed = true return } stackView.wmf_isCollapsed = false captchaTextField.text = "" refreshImage(for: captcha) if let captchaDelegate = captchaDelegate { subTitleLabel.isHidden = captchaDelegate.captchaHideSubtitle() } } } @objc var solution:String? { guard let captchaSolution = captchaTextField.text, !captchaSolution.isEmpty else { return nil } return captchaTextField.text } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == captchaTextField { guard let captchaDelegate = captchaDelegate else { assertionFailure("Expected delegate not set") return true } captchaDelegate.captchaKeyboardReturnKeyTapped() } return true } fileprivate func refreshImage(for captcha: WMFCaptcha) { guard let fullCaptchaImageURL = fullCaptchaImageURL(from: captcha.captchaURL) else { assertionFailure("Unable to determine fullCaptchaImageURL") return } captchaImageView.wmf_setImage(with: fullCaptchaImageURL, detectFaces: false, onGPU: false, failure: { (error) in }) { } } public func captchaTextFieldBecomeFirstResponder() { // Reminder: captchaTextField is private so this vc maintains control over the captcha solution. captchaTextField.becomeFirstResponder() } fileprivate func fullCaptchaImageURL(from captchaURL: URL) -> URL? { guard let components = URLComponents(url: captchaURL, resolvingAgainstBaseURL: false) else { assertionFailure("Could not extract url components") return nil } return components.url(relativeTo: captchaBaseURL()) } fileprivate func captchaBaseURL() -> URL? { guard let captchaDelegate = captchaDelegate else { assertionFailure("Expected delegate not set") return nil } let captchaSiteURL = captchaDelegate.captchaSiteURL() guard var components = URLComponents(url: captchaSiteURL, resolvingAgainstBaseURL: false) else { assertionFailure("Could not extract url components") return nil } components.queryItems = nil guard let url = components.url else { assertionFailure("Could not extract url") return nil } return url } @IBAction func textFieldDidChange(_ sender: UITextField) { captchaDelegate?.captchaSolutionChanged(self, solutionText:sender.text) } override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() guard let captchaDelegate = captchaDelegate else { assertionFailure("Required delegate is unset") return } assert(stackView.wmf_firstArrangedSubviewWithRequiredNonZeroHeightConstraint() == nil, stackView.wmf_anArrangedSubviewHasRequiredNonZeroHeightConstraintAssertString()) captcha = nil captchaTextFieldTitleLabel.text = WMFLocalizedString("field-captcha-title", value:"Enter the text you see above", comment: "Title for captcha field") captchaTextField.placeholder = WMFLocalizedString("field-captcha-placeholder", value:"CAPTCHA text", comment: "Placeholder text shown inside captcha field until user taps on it") titleLabel.text = WMFLocalizedString("account-creation-captcha-title", value:"CAPTCHA security check", comment: "Title for account creation CAPTCHA interface") // Reminder: used a label instead of a button for subtitle because of multi-line string issues with UIButton. subTitleLabel.strings = WMFAuthLinkLabelStrings(dollarSignString: WMFLocalizedString("account-creation-captcha-cannot-see-image", value:"Can't see the image? %1$@", comment: "Text asking the user if they cannot see the captcha image. %1$@ is the message {{msg-wm|Wikipedia-ios-account-creation-captcha-request-account}}"), substitutionString: WMFLocalizedString("account-creation-captcha-request-account", value:"Request account.", comment: "Text for link to 'Request an account' page.")) subTitleLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(requestAnAccountTapped(_:)))) subTitleLabel.isHidden = (captcha == nil) || captchaDelegate.captchaHideSubtitle() view.wmf_configureSubviewsForDynamicType() apply(theme: theme) } @objc func requestAnAccountTapped(_ recognizer: UITapGestureRecognizer) { navigate(to: URL(string: "https://en.wikipedia.org/wiki/Wikipedia:Request_an_account")) } @IBAction fileprivate func infoButtonTapped(withSender sender: UIButton) { navigate(to: URL(string: "https://en.wikipedia.org/wiki/Special:Captcha/help")) } @IBAction fileprivate func refreshButtonTapped(withSender sender: UIButton) { captchaDelegate?.captchaReloadPushed(self) let failure: WMFErrorHandler = {error in } WMFAlertManager.sharedInstance.showAlert(WMFLocalizedString("account-creation-captcha-obtaining", value:"Obtaining a new CAPTCHA...", comment: "Alert shown when user wants a new captcha when creating account"), sticky: false, dismissPreviousAlerts: true, tapCallBack: nil) self.captchaResetter.resetCaptcha(siteURL: captchaBaseURL()!, success: { result in DispatchQueue.main.async { guard let previousCaptcha = self.captcha else { assertionFailure("If resetting a captcha, expect to have a previous one here") return } let previousCaptchaURL = previousCaptcha.captchaURL let previousCaptchaNSURL = previousCaptchaURL as NSURL let newCaptchaID = result.index // Resetter only fetches captchaID, so use previous captchaURL changing its wpCaptchaId. let newCaptchaURL = previousCaptchaNSURL.wmf_url(withValue: newCaptchaID, forQueryKey:"wpCaptchaId") let newCaptcha = WMFCaptcha.init(captchaID: newCaptchaID, captchaURL: newCaptchaURL) self.captcha = newCaptcha } }, failure:failure) } func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } titleLabel.textColor = theme.colors.primaryText captchaTextFieldTitleLabel.textColor = theme.colors.secondaryText subTitleLabel.apply(theme: theme) view.backgroundColor = theme.colors.paperBackground captchaTextField.apply(theme: theme) view.tintColor = theme.colors.link } }
mit
101adc4ed8f1431abf52948a19102791
41.248804
496
0.656738
5.543001
false
false
false
false
gzios/SystemLearn
SwiftBase/元组.playground/Contents.swift
1
585
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var array = [Any]() //数组的使用 array.append("why") array.append(18) array.append(1.88) array var dic = [String:Any]() dic["name"] = "why" dic["age"] = 18 dic["height"] = 1.88 //1.创建 元组使用小括号 let info = ("why",18,1.88) info.0 info.1 //取别名 let info1 = (name:"why",age:18,height:1.88) info1.name info1.0 //别名就是元素 let (name,age,height) = ("why",18,1.88) name age height let yz = (str,array,dic,info,info1,name) yz //2.
apache-2.0
7f8dcfd61466c1a81313c7de4a535fa6
8.293103
52
0.619666
2.40625
false
false
false
false
DivineDominion/mac-appdev-code
DDDViewDataExample/ProvisioningService.swift
1
869
import Foundation open class ProvisioningService { let repository: BoxRepository var eventPublisher: DomainEventPublisher { return DomainEventPublisher.sharedInstance } public init(repository: BoxRepository) { self.repository = repository } open func provisionBox() { let boxId = repository.nextId() let box = Box(boxId: boxId, title: "New Box") repository.addBox(box) eventPublisher.publish(BoxProvisionedEvent(boxId: boxId, title: box.title)) } open func provisionItem(inBox box: Box) { let itemId = repository.nextItemId() let item = Item(itemId: itemId, title: "New Item") box.addItem(item) eventPublisher.publish(BoxItemProvisionedEvent(boxId: box.boxId, itemId: itemId, itemTitle: item.title)) } }
mit
bcf04ae807101fefe03a474f0753dd6d
27.032258
112
0.640967
4.45641
false
false
false
false
OlehKulykov/OKAlertController
OKAlertController/Controller/OKAlertController/OKAlertController.swift
1
9988
/* * Copyright (c) 2016 Oleh Kulykov <info@resident.name> * * 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 // Public controller interface. /** Wraps and manages standart `UIAlertController` look. First ctreate controller, fill with actions and only than make customiztion before show. It's recommended to create extension for you application, override show function and before show make you application specific customization. - Note: All variables have default value as `nil`, which means this parameter will not be applied/changed. Example: ```swift // Create alert. let alert = OKAlertController(title: "Some title", message: "Alert message") // Add actions alert.addAction("Ut enim ad minim veniam", style: .Default) { _ in } alert.addAction("Cancel", style: .Cancel) { _ in } //TODO: setup controller with custom colors, fonts, etc. alert.shadowColor = UIColor(white: 1, alpha: 0.79) alert.backgroundColor = UIColor.whiteColor() // Finaly show controller alert.show(fromController: self, animated: true) ``` */ open class OKAlertController { /// Actual `UIAlertController` for setup and show. fileprivate var alert: UIAlertController! /// Main setup logic. fileprivate var proxy = OKAlertControllerProxy() /** Get/set alert title text color. The default value is `nil` - standart title text color. Provide `nil` to remove/ignore title text color modification and use standart. */ open var titleColor: UIColor? { get { return proxy[.title, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.title, paramType: .color, value: newValue) } } /** Get/set alert title font. The default value is `nil` - standart title font. Provide `nil` to remove/ignore title font modification and use standart. */ open var titleFont: UIFont? { get { return proxy[.title, .font]?.getValue() } set { let _ = proxy.updateTypeValue(.title, paramType: .font, value: newValue) } } /** Get/set alert message text color. The default value is `nil` - standart message text color. Provide `nil` to remove/ignore message text color modification and use standart. */ open var messageColor: UIColor? { get { return proxy[.message, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.message, paramType: .color, value: newValue) } } /** Get/set alert message font. The default value is `nil` - standart message font. Provide `nil` to remove/ignore message font modification and use standart. */ open var messageFont: UIFont? { get { return proxy[.message, .font]?.getValue() } set { let _ = proxy.updateTypeValue(.message, paramType: .font, value: newValue) } } /** Get/set alert background window color. The default value is `nil` - standart background window color. Provide `nil` to remove/ignore background window color modification and use standart. */ open var backgroundColor: UIColor? { get { return proxy[.background, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.background, paramType: .color, value: newValue) } } /** Get/set alert default actions text font. The default value is `nil` - standart default actions text font. Provide `nil` to remove/ignore default actions text font modification and use standart. */ open var allDefaultActionsFont: UIFont? { get { return proxy[.allDefaultActions, .font]?.getValue() } set { let _ = proxy.updateTypeValue(.allDefaultActions, paramType: .font, value: newValue) } } /** Get/set alert default actions text color. The default value is `nil` - standart default actions text color. Provide `nil` to remove/ignore default actions text color modification and use standart. */ open var allDefaultActionsColor: UIColor? { get { return proxy[.allDefaultActions, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.allDefaultActions, paramType: .color, value: newValue) } } /** Get/set alert cancel actions text font. The default value is `nil` - standart cancel actions text font. Provide `nil` to remove/ignore cancel actions text font modification and use standart. */ open var allCancelActionsFont: UIFont? { get { return proxy[.allCancelActions, .font]?.getValue() } set { let _ = proxy.updateTypeValue(.allCancelActions, paramType: .font, value: newValue) } } /** Get/set alert cancel actions text color. The default value is `nil` - standart cancel actions text color. Provide `nil` to remove/ignore cancel actions color color modification and use standart. */ open var allCancelActionsColor: UIColor? { get { return proxy[.allCancelActions, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.allCancelActions, paramType: .color, value: newValue) } } /** Get/set alert destructive actions text font. The default value is `nil` - standart destructive actions text font. Provide `nil` to remove/ignore destructive actions text font modification and use standart. */ open var allDestructiveActionsFont: UIFont? { get { return proxy[.allDestructiveActions, .font]?.getValue() } set { let _ = proxy.updateTypeValue(.allDestructiveActions, paramType: .font, value: newValue) } } /** Get/set alert destructive actions text color. The default value is `nil` - standart destructive actions text color. Provide `nil` to remove/ignore destructive actions text color modification and use standart. */ open var allDestructiveActionsColor: UIColor? { get { return proxy[.allDestructiveActions, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.allDestructiveActions, paramType: .color, value: newValue) } } /** Get/set alert shadow color. The default value is `nil` - standart shadow color. Provide `nil` to remove/ignore destructive shadow color modification and use standart. */ open var shadowColor: UIColor? { get { return proxy[.shadow, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.shadow, paramType: .color, value: newValue) } } /** Get/set alert window border color. The default value is `nil` - standart window border color. Provide `nil` to remove/ignore destructive window border color modification and use standart. */ open var borderColor: UIColor? { get { return proxy[.border, .color]?.getValue() } set { let _ = proxy.updateTypeValue(.border, paramType: .color, value: newValue) } } /** Get/set alert window border line width. The default and minimum value is 0. */ open var borderWidth: CGFloat { get { if let number: NSNumber = proxy[.border, .width]?.getValue() { return CGFloat(number.floatValue) } return 0 } set { let newWidth = max(0, newValue) let _ = proxy.updateTypeValue(.border, paramType: .width, value: NSNumber(value: Float(newWidth) as Float)) } } /** Show/present alert controller. - Warning: Before calling this function need to set all required parameters, e.g. setup controller. - Parameters: - fromController: Presenter view controller for the alert. - animated: Animating flag for presenting. */ open func show(fromController from: UIViewController, animated: Bool) { proxy.prepareAlert(alert, presenter: from) from.present(alert, animated: animated) { _ = self // hold strongly `self` } } /** Add alert action. - Parameters: - title: The title string of the action. - style: Action style. Look at `UIAlertActionStyle`. - handler: Handler to insform outside logic that the action was trigered. */ open func addAction(_ title: String?, style: UIAlertActionStyle, handler: ((UIAlertAction) -> Void)?) { let type: OKAlertControllerProxy.ElementType switch style { case .default: type = .allDefaultActions case .cancel: type = .allCancelActions case .destructive: type = .allDestructiveActions } let element = OKAlertControllerProxy.Element(type: type, tag: proxy.nextTag, param: OKAlertControllerProxy.Param(type: .text, value: title as AnyObject)) proxy.elements.append(element) alert.addAction(UIAlertAction(title: element.key, style: style, handler: handler)) } /** Initialize controller with style and optional title and message. - Parameters: - title: Title of the alert controller. - message: Descriptive text that provides more details about the reason for the alert. - preferredStyle: The style of the alert controller. Default value is `.Alert`. For more information look at `UIAlertControllerStyle`. - Returns: Initialized alert controller. */ public init(title: String?, message: String?, preferredStyle: UIAlertControllerStyle = .alert) { let titleElement = proxy.updateTypeValue(.title, paramType: .text, value: title as AnyObject?) let messageElement = proxy.updateTypeValue(.message, paramType: .text, value: message as AnyObject?) alert = UIAlertController(title: titleElement.key, message: messageElement.key, preferredStyle: preferredStyle) } }
mit
75d193694022243e21eb182798a1a1ba
27.867052
155
0.720364
3.714392
false
false
false
false
meetkei/KeiSwiftFramework
KeiSwiftFramework/Concurrency/GCD.swift
1
3215
// // GCD.swift // // Copyright (c) 2016 Keun young Kim <app@meetkei.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 GCD { open class var highPriority: DispatchQoS.QoSClass { return .userInitiated } open class var defaultPriority: DispatchQoS.QoSClass { return .default } open class var lowPriority: DispatchQoS.QoSClass { return .utility } open class var backgroundPriority: DispatchQoS.QoSClass { return .background } } open class AsyncGCD: GCD { open class func performOnMainQueue(_ checkCurrentQueue: Bool = true, _ block: @escaping ()->()) { if checkCurrentQueue { if Thread.isMainThread { block() return } } performDelayedOnMainQueue(0.0, block) } open class func performDelayedOnMainQueue(_ delay: Double = 0.0, _ block: @escaping ()->()) { let queue = DispatchQueue.main if delay > 0.0 { let when = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: when, execute: block) } else { performOnQueue(queue, block) } } open class func performOnGlobalQueue(_ priority: DispatchQoS.QoSClass = .default, _ block: @escaping ()->()) { performDelayedOnGlobalQueue(0.0, priority, block) } open class func performDelayedOnGlobalQueue(_ delay: Double = 0.0, _ priority: DispatchQoS.QoSClass = .default, _ block: @escaping ()->()) { let queue = DispatchQueue.global(qos: priority) if delay > 0.0 { let when = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: when, execute: block) } else { performOnQueue(queue, block) } } open class func performOnQueue(_ queue: DispatchQueue, _ block: @escaping ()->()) { queue.async(execute: block) } }
mit
d7571696ceddbfd4d7da5165229083ec
30.519608
144
0.632659
4.560284
false
false
false
false
manavgabhawala/swift
test/stdlib/Dispatch.swift
1
13509
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Dispatch import Foundation import StdlibUnittest defer { runAllTests() } var DispatchAPI = TestSuite("DispatchAPI") DispatchAPI.test("constants") { expectEqual(2147483648, DispatchSource.ProcessEvent.exit.rawValue) expectEqual(0, DispatchData.empty.endIndex) // This is a lousy test, but really we just care that // DISPATCH_QUEUE_CONCURRENT comes through at all. _ = DispatchQueue.Attributes.concurrent } DispatchAPI.test("OS_OBJECT support") { let mainQueue = DispatchQueue.main as AnyObject expectTrue(mainQueue is DispatchQueue) // This should not be optimized out, and should succeed. expectNotNil(mainQueue as? DispatchQueue) } DispatchAPI.test("DispatchGroup creation") { let group = DispatchGroup() expectNotNil(group) } DispatchAPI.test("dispatch_block_t conversions") { var counter = 0 let closure = { () -> Void in counter += 1 } typealias Block = @convention(block) () -> () let block = closure as Block block() expectEqual(1, counter) let closureAgain = block as () -> Void closureAgain() expectEqual(2, counter) } if #available(OSX 10.10, iOS 8.0, *) { DispatchAPI.test("dispatch_block_t identity") { let block = DispatchWorkItem(flags: .inheritQoS) { _ = 1 } DispatchQueue.main.async(execute: block) // This will trap if the block's pointer identity is not preserved. block.cancel() } } DispatchAPI.test("dispatch_data_t enumeration") { // Ensure we can iterate the empty iterator for x in DispatchData.empty { _ = 1 } } DispatchAPI.test("dispatch_data_t deallocator") { let q = DispatchQueue(label: "dealloc queue") var t = 0 autoreleasepool { let size = 1024 let p = UnsafeMutablePointer<UInt8>.allocate(capacity: size) let d = DispatchData(bytesNoCopy: UnsafeRawBufferPointer(start: p, count: size), deallocator: .custom(q, { t = 1 })) } q.sync { expectEqual(1, t) } } DispatchAPI.test("DispatchTime comparisons") { do { let now = DispatchTime.now() checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: { return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt }) } do { let now = DispatchWallTime.now() checkComparable([now, now + .milliseconds(1), .distantFuture], oracle: { return $0 < $1 ? .lt : $0 == $1 ? .eq : .gt }) } } DispatchAPI.test("DispatchTime.addSubtract") { var then = DispatchTime.now() + Double.infinity expectEqual(DispatchTime.distantFuture, then) then = DispatchTime.now() + Double.nan expectEqual(DispatchTime.distantFuture, then) then = DispatchTime.now() - Double.infinity expectEqual(DispatchTime(uptimeNanoseconds: 1), then) then = DispatchTime.now() - Double.nan expectEqual(DispatchTime(uptimeNanoseconds: 1), then) } DispatchAPI.test("DispatchWallTime.addSubtract") { var then = DispatchWallTime.now() + Double.infinity expectEqual(DispatchWallTime.distantFuture, then) then = DispatchWallTime.now() + Double.nan expectEqual(DispatchWallTime.distantFuture, then) then = DispatchWallTime.now() - Double.infinity expectEqual(DispatchWallTime.distantFuture.rawValue - UInt64(1), then.rawValue) then = DispatchWallTime.now() - Double.nan expectEqual(DispatchWallTime.distantFuture.rawValue - UInt64(1), then.rawValue) } DispatchAPI.test("DispatchTime.uptimeNanos") { let seconds = 1 let nowMach = DispatchTime.now() let oneSecondFromNowMach = nowMach + .seconds(seconds) let nowNanos = nowMach.uptimeNanoseconds let oneSecondFromNowNanos = oneSecondFromNowMach.uptimeNanoseconds let diffNanos = oneSecondFromNowNanos - nowNanos expectEqual(NSEC_PER_SEC, diffNanos) } DispatchAPI.test("DispatchData.copyBytes") { let source1: [UInt8] = [0, 1, 2, 3] let srcPtr1 = UnsafeBufferPointer(start: source1, count: source1.count) var dest: [UInt8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] var destPtr = UnsafeMutableBufferPointer(start: UnsafeMutablePointer(&dest), count: dest.count) var dispatchData = DispatchData(bytes: srcPtr1) // Copy from offset 0 var count = dispatchData.copyBytes(to: destPtr, from: 0..<2) expectEqual(count, 2) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2 count = dispatchData.copyBytes(to: destPtr, from: 2..<4) expectEqual(count, 2) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Add two more regions let source2: [UInt8] = [0x10, 0x11, 0x12, 0x13] let srcPtr2 = UnsafeBufferPointer(start: source2, count: source2.count) dispatchData.append(DispatchData(bytes: srcPtr2)) let source3: [UInt8] = [0x14, 0x15, 0x16] let srcPtr3 = UnsafeBufferPointer(start: source3, count: source3.count) dispatchData.append(DispatchData(bytes: srcPtr3)) // Copy from offset 0. Copies across the first two regions count = dispatchData.copyBytes(to: destPtr, from: 0..<6) expectEqual(count, 6) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 2) expectEqual(destPtr[3], 3) expectEqual(destPtr[4], 0x10) expectEqual(destPtr[5], 0x11) // Copy from offset 2. Copies across the first two regions count = dispatchData.copyBytes(to: destPtr, from: 2..<8) expectEqual(count, 6) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0x10) expectEqual(destPtr[3], 0x11) expectEqual(destPtr[4], 0x12) expectEqual(destPtr[5], 0x13) // Copy from offset 3. Copies across all three regions count = dispatchData.copyBytes(to: destPtr, from: 3..<9) expectEqual(count, 6) expectEqual(destPtr[0], 3) expectEqual(destPtr[1], 0x10) expectEqual(destPtr[2], 0x11) expectEqual(destPtr[3], 0x12) expectEqual(destPtr[4], 0x13) expectEqual(destPtr[5], 0x14) // Copy from offset 5. Skips the first region and the first byte of the second count = dispatchData.copyBytes(to: destPtr, from: 5..<11) expectEqual(count, 6) expectEqual(destPtr[0], 0x11) expectEqual(destPtr[1], 0x12) expectEqual(destPtr[2], 0x13) expectEqual(destPtr[3], 0x14) expectEqual(destPtr[4], 0x15) expectEqual(destPtr[5], 0x16) // Copy from offset 8. Skips the first two regions destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 8..<11) expectEqual(count, 3) expectEqual(destPtr[0], 0x14) expectEqual(destPtr[1], 0x15) expectEqual(destPtr[2], 0x16) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9. Skips the first two regions and the first byte of the third destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 9..<11) expectEqual(count, 2) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0x16) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9, but only 1 byte. Ends before the end of the data destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 9..<10) expectEqual(count, 1) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2, but only 1 byte. This copy is bounded within the // first region. destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF count = dispatchData.copyBytes(to: destPtr, from: 2..<3) expectEqual(count, 1) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) } DispatchAPI.test("DispatchData.copyBytesUnsafeRawBufferPointer") { let source1: [UInt8] = [0, 1, 2, 3] let srcPtr1 = UnsafeRawBufferPointer(start: source1, count: source1.count) var dest: [UInt8] = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] let destPtr = UnsafeMutableRawBufferPointer(start: UnsafeMutablePointer(&dest), count: dest.count) var dispatchData = DispatchData(bytes: srcPtr1) // Copy from offset 0 dispatchData.copyBytes(to: destPtr, from: 0..<2) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2 dispatchData.copyBytes(to: destPtr, from: 2..<4) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Add two more regions let source2: [UInt8] = [0x10, 0x11, 0x12, 0x13] let srcPtr2 = UnsafeRawBufferPointer(start: source2, count: source2.count) dispatchData.append(DispatchData(bytes: srcPtr2)) let source3: [UInt8] = [0x14, 0x15, 0x16] let srcPtr3 = UnsafeRawBufferPointer(start: source3, count: source3.count) dispatchData.append(DispatchData(bytes: srcPtr3)) // Copy from offset 0. Copies across the first two regions dispatchData.copyBytes(to: destPtr, from: 0..<6) expectEqual(destPtr[0], 0) expectEqual(destPtr[1], 1) expectEqual(destPtr[2], 2) expectEqual(destPtr[3], 3) expectEqual(destPtr[4], 0x10) expectEqual(destPtr[5], 0x11) // Copy from offset 2. Copies across the first two regions dispatchData.copyBytes(to: destPtr, from: 2..<8) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 3) expectEqual(destPtr[2], 0x10) expectEqual(destPtr[3], 0x11) expectEqual(destPtr[4], 0x12) expectEqual(destPtr[5], 0x13) // Copy from offset 3. Copies across all three regions dispatchData.copyBytes(to: destPtr, from: 3..<9) expectEqual(destPtr[0], 3) expectEqual(destPtr[1], 0x10) expectEqual(destPtr[2], 0x11) expectEqual(destPtr[3], 0x12) expectEqual(destPtr[4], 0x13) expectEqual(destPtr[5], 0x14) // Copy from offset 5. Skips the first region and the first byte of the second dispatchData.copyBytes(to: destPtr, from: 5..<11) expectEqual(destPtr[0], 0x11) expectEqual(destPtr[1], 0x12) expectEqual(destPtr[2], 0x13) expectEqual(destPtr[3], 0x14) expectEqual(destPtr[4], 0x15) expectEqual(destPtr[5], 0x16) // Copy from offset 8. Skips the first two regions destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 8..<11) expectEqual(destPtr[0], 0x14) expectEqual(destPtr[1], 0x15) expectEqual(destPtr[2], 0x16) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9. Skips the first two regions and the first byte of the third destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 9..<11) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0x16) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 9, but only 1 byte. Ends before the end of the data destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 9..<10) expectEqual(destPtr[0], 0x15) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) // Copy from offset 2, but only 1 byte. This copy is bounded within the // first region. destPtr[1] = 0xFF destPtr[2] = 0xFF destPtr[3] = 0xFF destPtr[4] = 0xFF destPtr[5] = 0xFF dispatchData.copyBytes(to: destPtr, from: 2..<3) expectEqual(destPtr[0], 2) expectEqual(destPtr[1], 0xFF) expectEqual(destPtr[2], 0xFF) expectEqual(destPtr[3], 0xFF) expectEqual(destPtr[4], 0xFF) expectEqual(destPtr[5], 0xFF) } DispatchAPI.test("DispatchData.buffers") { let bytes = [UInt8(0), UInt8(1), UInt8(2), UInt8(2)] var ptr = UnsafeBufferPointer<UInt8>(start: bytes, count: bytes.count) var data = DispatchData(bytes: ptr) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } ptr = UnsafeBufferPointer<UInt8>(start: nil, count: 0) data = DispatchData(bytes: ptr) expectEqual(data.count, 0) data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(data.count, 0) } DispatchAPI.test("DispatchData.bufferUnsafeRawBufferPointer") { let bytes = [UInt8(0), UInt8(1), UInt8(2), UInt8(2)] var ptr = UnsafeRawBufferPointer(start: bytes, count: bytes.count) var data = DispatchData(bytes: ptr) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(bytes.count, data.count) for i in 0..<data.count { expectEqual(data[i], bytes[i]) } ptr = UnsafeRawBufferPointer(start: nil, count: 0) data = DispatchData(bytes: ptr) expectEqual(data.count, 0) data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) expectEqual(data.count, 0) }
apache-2.0
f59dda2d6cbcc48bd8a2a259ebade7ff
28.821192
108
0.71804
3.158522
false
false
false
false
Djecksan/MobiTask
MobiTask/Controllers/MainViewController/MainViewController+YesterdayRate.swift
1
2085
// // MainViewController+YesterdayRate.swift // MobiTask // // Created by Evgenyi Tyulenev on 02.08.15. // Copyright (c) 2015 VoltMobi. All rights reserved. // import UIKit extension MainViewController:YesterdayRate { func loadYesterdayRates() { var yesterday = NSDate(timeIntervalSinceNow: -86400) var sYesterday = yesterday.stringDateWithFormat("YYYY-MM-dd") APIClient.rates("latest?base=\(DEFAULT_BASE_CURRENCY)&date=\(sYesterday)&symbols=RUB", success: { [weak self] (result) -> Void in if let yesterdayFixer = result as? Fixer { self!.calculateDifference(yesterdayFixer) } }) { (error, operation) -> Void in println("Вывести ошибку") } } private func calculateDifference(yesterdayFixer:Fixer) { let yesterdayValue = yesterdayFixer.rates![DEFAULT_CURRENCY]! let todayValue = todayFixer!.rates![DEFAULT_CURRENCY]! var result = round((todayValue / yesterdayValue) * 100 - 100) if result < 0 { self.dollarUpdate.text = "currancy_fell".loc() + " \(abs(Int(result))) " + "percents".loc() self.dollarUpdate.textColor = UIColor.redColor() } else if result > 0 { self.dollarUpdate.text = "currancy_rose".loc() + " \(abs(Int(result))) " + "percents".loc() self.dollarUpdate.textColor = UIColor(red: 126/255.0, green: 211/255.0, blue: 33/255.0, alpha: 1.0) } else { /* Здесь можно обработать случай когда изменений не было. Сервис Fixer на выходных не обновляет информацию и отдает значение последнего рабочего дня */ } //TODO: Написать хелпер для обработки окончаний чтобы не было надписей типа "7 процента" } }
mit
ce9213e8076be15ea24d347aee966807
36.019608
137
0.593005
3.774
false
false
false
false
tenebreux/realm-cocoa
RealmSwift-swift2.0/Tests/KVOTests.swift
3
12853
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift var pkCounter = 0 func nextPrimaryKey() -> Int { return ++pkCounter } class KVOObject: Object { dynamic var pk = nextPrimaryKey() // primary key for equality dynamic var ignored: Int = 0 dynamic var boolCol: Bool = false dynamic var int8Col: Int8 = 1 dynamic var int16Col: Int16 = 2 dynamic var int32Col: Int32 = 3 dynamic var int64Col: Int64 = 4 dynamic var floatCol: Float = 5 dynamic var doubleCol: Double = 6 dynamic var stringCol: String = "" dynamic var binaryCol: NSData = NSData() dynamic var dateCol: NSDate = NSDate(timeIntervalSince1970: 0) dynamic var objectCol: KVOObject? let arrayCol = List<KVOObject>() let optIntCol = RealmOptional<Int>() let optFloatCol = RealmOptional<Float>() let optDoubleCol = RealmOptional<Double>() let optBoolCol = RealmOptional<Bool>() dynamic var optStringCol: String? dynamic var optBinaryCol: NSData? dynamic var optDateCol: NSDate? override class func primaryKey() -> String { return "pk" } override class func ignoredProperties() -> [String] { return ["ignored"] } } // Most of the testing of KVO functionality is done in the obj-c tests // These tests just verify that it also works on Swift types class KVOTests: TestCase { var realm: Realm! = nil override func setUp() { super.setUp() realm = try! Realm() realm.beginWrite() } override func tearDown() { realm.cancelWrite() realm = nil super.tearDown() } var changeDictionary: [NSObject: AnyObject]? override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { changeDictionary = change } func observeChange(obj: NSObject, _ key: String, _ old: AnyObject, _ new: AnyObject, fileName: String = __FILE__, lineNumber: UInt = __LINE__, _ block: () -> Void) { obj.addObserver(self, forKeyPath: key, options: [.Old, .New], context: nil) block() obj.removeObserver(self, forKeyPath: key) XCTAssert(changeDictionary != nil, "Did not get a notification", file: fileName, line: lineNumber) if changeDictionary == nil { return } let actualOld: AnyObject = changeDictionary![NSKeyValueChangeOldKey]! let actualNew: AnyObject = changeDictionary![NSKeyValueChangeNewKey]! XCTAssert(actualOld.isEqual(old), "Old value: expected \(old), got \(actualOld)", file: fileName, line: lineNumber) XCTAssert(actualNew.isEqual(new), "New value: expected \(new), got \(actualNew)", file: fileName, line: lineNumber) changeDictionary = nil } func observeListChange(obj: NSObject, _ key: String, _ kind: NSKeyValueChange, _ indexes: NSIndexSet, fileName: String = __FILE__, lineNumber: UInt = __LINE__, _ block: () -> Void) { obj.addObserver(self, forKeyPath: key, options: [.Old, .New], context: nil) block() obj.removeObserver(self, forKeyPath: key) XCTAssert(changeDictionary != nil, "Did not get a notification", file: fileName, line: lineNumber) if changeDictionary == nil { return } let actualKind = NSKeyValueChange(rawValue: (changeDictionary![NSKeyValueChangeKindKey] as! NSNumber).unsignedLongValue)! let actualIndexes = changeDictionary![NSKeyValueChangeIndexesKey]! as! NSIndexSet XCTAssert(actualKind == kind, "Change kind: expected \(kind), got \(actualKind)", file: fileName, line: lineNumber) XCTAssert(actualIndexes.isEqual(indexes), "Changed indexes: expected \(indexes), got \(actualIndexes)", file: fileName, line: lineNumber) changeDictionary = nil } // Actual tests follow func testAllPropertyTypesStandalone() { let obj = KVOObject() observeChange(obj, "boolCol", false, true) { obj.boolCol = true } observeChange(obj, "int8Col", 1, 10) { obj.int8Col = 10 } observeChange(obj, "int16Col", 2, 10) { obj.int16Col = 10 } observeChange(obj, "int32Col", 3, 10) { obj.int32Col = 10 } observeChange(obj, "int64Col", 4, 10) { obj.int64Col = 10 } observeChange(obj, "floatCol", 5, 10) { obj.floatCol = 10 } observeChange(obj, "doubleCol", 6, 10) { obj.doubleCol = 10 } observeChange(obj, "stringCol", "", "abc") { obj.stringCol = "abc" } observeChange(obj, "objectCol", NSNull(), obj) { obj.objectCol = obj } let data = "abc".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! observeChange(obj, "binaryCol", NSData(), data) { obj.binaryCol = data } let date = NSDate(timeIntervalSince1970: 1) observeChange(obj, "dateCol", NSDate(timeIntervalSince1970: 0), date) { obj.dateCol = date } observeListChange(obj, "arrayCol", .Insertion, NSIndexSet(index: 0)) { obj.arrayCol.append(obj) } observeListChange(obj, "arrayCol", .Removal, NSIndexSet(index: 0)) { obj.arrayCol.removeAll() } observeChange(obj, "optIntCol", NSNull(), 10) { obj.optIntCol.value = 10 } observeChange(obj, "optFloatCol", NSNull(), 10) { obj.optFloatCol.value = 10 } observeChange(obj, "optDoubleCol", NSNull(), 10) { obj.optDoubleCol.value = 10 } observeChange(obj, "optBoolCol", NSNull(), true) { obj.optBoolCol.value = true } observeChange(obj, "optStringCol", NSNull(), "abc") { obj.optStringCol = "abc" } observeChange(obj, "optBinaryCol", NSNull(), data) { obj.optBinaryCol = data } observeChange(obj, "optDateCol", NSNull(), date) { obj.optDateCol = date } observeChange(obj, "optIntCol", 10, NSNull()) { obj.optIntCol.value = nil } observeChange(obj, "optFloatCol", 10, NSNull()) { obj.optFloatCol.value = nil } observeChange(obj, "optDoubleCol", 10, NSNull()) { obj.optDoubleCol.value = nil } observeChange(obj, "optBoolCol", true, NSNull()) { obj.optBoolCol.value = nil } observeChange(obj, "optStringCol", "abc", NSNull()) { obj.optStringCol = nil } observeChange(obj, "optBinaryCol", data, NSNull()) { obj.optBinaryCol = nil } observeChange(obj, "optDateCol", date, NSNull()) { obj.optDateCol = nil } } func testAllPropertyTypesPersisted() { let obj = KVOObject() realm.add(obj) observeChange(obj, "boolCol", false, true) { obj.boolCol = true } observeChange(obj, "int8Col", 1, 10) { obj.int8Col = 10 } observeChange(obj, "int16Col", 2, 10) { obj.int16Col = 10 } observeChange(obj, "int32Col", 3, 10) { obj.int32Col = 10 } observeChange(obj, "int64Col", 4, 10) { obj.int64Col = 10 } observeChange(obj, "floatCol", 5, 10) { obj.floatCol = 10 } observeChange(obj, "doubleCol", 6, 10) { obj.doubleCol = 10 } observeChange(obj, "stringCol", "", "abc") { obj.stringCol = "abc" } observeChange(obj, "objectCol", NSNull(), obj) { obj.objectCol = obj } let data = "abc".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! observeChange(obj, "binaryCol", NSData(), data) { obj.binaryCol = data } let date = NSDate(timeIntervalSince1970: 1) observeChange(obj, "dateCol", NSDate(timeIntervalSince1970: 0), date) { obj.dateCol = date } observeListChange(obj, "arrayCol", .Insertion, NSIndexSet(index: 0)) { obj.arrayCol.append(obj) } observeListChange(obj, "arrayCol", .Removal, NSIndexSet(index: 0)) { obj.arrayCol.removeAll() } observeChange(obj, "optIntCol", NSNull(), 10) { obj.optIntCol.value = 10 } observeChange(obj, "optFloatCol", NSNull(), 10) { obj.optFloatCol.value = 10 } observeChange(obj, "optDoubleCol", NSNull(), 10) { obj.optDoubleCol.value = 10 } observeChange(obj, "optBoolCol", NSNull(), true) { obj.optBoolCol.value = true } observeChange(obj, "optStringCol", NSNull(), "abc") { obj.optStringCol = "abc" } observeChange(obj, "optBinaryCol", NSNull(), data) { obj.optBinaryCol = data } observeChange(obj, "optDateCol", NSNull(), date) { obj.optDateCol = date } observeChange(obj, "optIntCol", 10, NSNull()) { obj.optIntCol.value = nil } observeChange(obj, "optFloatCol", 10, NSNull()) { obj.optFloatCol.value = nil } observeChange(obj, "optDoubleCol", 10, NSNull()) { obj.optDoubleCol.value = nil } observeChange(obj, "optBoolCol", true, NSNull()) { obj.optBoolCol.value = nil } observeChange(obj, "optStringCol", "abc", NSNull()) { obj.optStringCol = nil } observeChange(obj, "optBinaryCol", data, NSNull()) { obj.optBinaryCol = nil } observeChange(obj, "optDateCol", date, NSNull()) { obj.optDateCol = nil } observeChange(obj, "invalidated", false, true) { self.realm.delete(obj) } let obj2 = KVOObject() realm.add(obj2) observeChange(obj2, "arrayCol.invalidated", false, true) { self.realm.delete(obj2) } } func testAllPropertyTypesMultipleAccessors() { let obj = KVOObject() realm.add(obj) let obs = realm.objectForPrimaryKey(KVOObject.self, key: obj.pk)! observeChange(obs, "boolCol", false, true) { obj.boolCol = true } observeChange(obs, "int8Col", 1, 10) { obj.int8Col = 10 } observeChange(obs, "int16Col", 2, 10) { obj.int16Col = 10 } observeChange(obs, "int32Col", 3, 10) { obj.int32Col = 10 } observeChange(obs, "int64Col", 4, 10) { obj.int64Col = 10 } observeChange(obs, "floatCol", 5, 10) { obj.floatCol = 10 } observeChange(obs, "doubleCol", 6, 10) { obj.doubleCol = 10 } observeChange(obs, "stringCol", "", "abc") { obj.stringCol = "abc" } observeChange(obs, "objectCol", NSNull(), obj) { obj.objectCol = obj } let data = "abc".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! observeChange(obs, "binaryCol", NSData(), data) { obj.binaryCol = data } let date = NSDate(timeIntervalSince1970: 1) observeChange(obs, "dateCol", NSDate(timeIntervalSince1970: 0), date) { obj.dateCol = date } observeListChange(obs, "arrayCol", .Insertion, NSIndexSet(index: 0)) { obj.arrayCol.append(obj) } observeListChange(obs, "arrayCol", .Removal, NSIndexSet(index: 0)) { obj.arrayCol.removeAll() } observeChange(obj, "optIntCol", NSNull(), 10) { obj.optIntCol.value = 10 } observeChange(obj, "optFloatCol", NSNull(), 10) { obj.optFloatCol.value = 10 } observeChange(obj, "optDoubleCol", NSNull(), 10) { obj.optDoubleCol.value = 10 } observeChange(obj, "optBoolCol", NSNull(), true) { obj.optBoolCol.value = true } observeChange(obj, "optStringCol", NSNull(), "abc") { obj.optStringCol = "abc" } observeChange(obj, "optBinaryCol", NSNull(), data) { obj.optBinaryCol = data } observeChange(obj, "optDateCol", NSNull(), date) { obj.optDateCol = date } observeChange(obj, "optIntCol", 10, NSNull()) { obj.optIntCol.value = nil } observeChange(obj, "optFloatCol", 10, NSNull()) { obj.optFloatCol.value = nil } observeChange(obj, "optDoubleCol", 10, NSNull()) { obj.optDoubleCol.value = nil } observeChange(obj, "optBoolCol", true, NSNull()) { obj.optBoolCol.value = nil } observeChange(obj, "optStringCol", "abc", NSNull()) { obj.optStringCol = nil } observeChange(obj, "optBinaryCol", data, NSNull()) { obj.optBinaryCol = nil } observeChange(obj, "optDateCol", date, NSNull()) { obj.optDateCol = nil } observeChange(obs, "invalidated", false, true) { self.realm.delete(obj) } let obj2 = KVOObject() realm.add(obj2) let obs2 = realm.objectForPrimaryKey(KVOObject.self, key: obj2.pk)! observeChange(obs2, "arrayCol.invalidated", false, true) { self.realm.delete(obj2) } } }
apache-2.0
d21ae0a02e7bd89070082cf9066eaee7
47.319549
186
0.633393
4.251737
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/add-one-row-to-tree.swift
2
5215
/** * https://leetcode.com/problems/add-one-row-to-tree/ * * */ // Date: Tue Mar 9 13:36:32 PST 2021 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? { if d == 1 { return TreeNode(v, root, nil) } else if d == 2 { let left = root?.left let right = root?.right root?.left = TreeNode(v, left, nil) root?.right = TreeNode(v, nil, right) return root } root?.left = addOneRow(root?.left, v, d - 1) root?.right = addOneRow(root?.right, v, d - 1) return root } }/** * https://leetcode.com/problems/add-one-row-to-tree/ * * */ // Date: Tue Mar 9 13:55:29 PST 2021 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? { if d == 1 { return TreeNode(v, root, nil) } guard let root = root else { return nil } var queue = [root] var level = 0 while queue.isEmpty == false { level += 1 var size = queue.count while size > 0 { size -= 1 let node = queue.removeFirst() if level + 1 == d { node.left = TreeNode(v, node.left, nil) node.right = TreeNode(v, nil, node.right) } else { if let left = node.left { queue.append(left) } if let right = node.right { queue.append(right) } } } if level + 1 == d { queue = [] } } return root } } class Solution { func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? { if d == 1 { return TreeNode(v, root, nil) } guard let root = root else { return nil } var queue = [root] var toUpdateList: [TreeNode] = [] var level = 0 while queue.isEmpty == false { level += 1 var size = queue.count while size > 0 { size -= 1 let node = queue.removeFirst() if level + 1 < d { if let left = node.left { queue.append(left) } if let right = node.right { queue.append(right) } } else { toUpdateList.append(node) } } } for node in toUpdateList { node.left = TreeNode(v, node.left, nil) node.right = TreeNode(v, nil, node.right) } return root } }/** * https://leetcode.com/problems/add-one-row-to-tree/ * * */ // Date: Tue Mar 9 15:37:42 PST 2021 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { func addOneRow(_ root: TreeNode?, _ v: Int, _ d: Int) -> TreeNode? { if d == 1 { return TreeNode(v, root, nil) } guard let root = root else { return nil } var queue = [root] var depth = [1] var toUpdateList: [TreeNode] = [] while queue.isEmpty == false { let node = queue.removeLast() let level = depth.removeLast() if level + 1 < d { if let left = node.left { queue.append(left) depth.append(level + 1) } if let right = node.right { queue.append(right) depth.append(level + 1) } } else { toUpdateList.append(node) } } for node in toUpdateList { node.left = TreeNode(v, node.left, nil) node.right = TreeNode(v, nil, node.right) } return root } }
mit
6fbd55f08bccf8b93ac728b9e94bc63a
30.233533
85
0.479386
3.770788
false
false
false
false
TTVS/NightOut
Clubber/PhotoViewerViewController.swift
1
4171
//// //// PhotoViewerViewController.swift //// Clubber //// //// Created by Terra on 26/6/15. //// Copyright (c) 2015 Dino Media Asia. All rights reserved. //// // //import UIKit //import FastImageCache // //class PhotoViewerViewController: UIViewController, UIScrollViewDelegate { // // let scrollView = UIScrollView() // let imageView = UIImageView() // let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) // // var photoInfo: PhotoInfo? // // // MARK: Life-Cycle // // override func viewDidLoad() { // super.viewDidLoad() // setupView() // // } // // func setupView() { // // scrollView.frame = view.bounds // scrollView.delegate = self // scrollView.minimumZoomScale = 1.0 // scrollView.maximumZoomScale = 2.0 // scrollView.zoomScale = 1.0 // view.addSubview(scrollView) // // spinner.center = CGPoint(x: view.center.x, y: view.center.y - view.bounds.origin.y / 2.0) // spinner.hidesWhenStopped = true // spinner.startAnimating() // view.addSubview(spinner) // // imageView.contentMode = .ScaleAspectFill // scrollView.addSubview(imageView) // // let width = scrollView.frame.size.width // self.imageView.frame = CGRectMake(0, scrollView.frame.size.height/2 - width/2, width, width) // // let sharedImageCache = FICImageCache.sharedImageCache() // var photo: UIImage? // let exists = sharedImageCache.retrieveImageForEntity(photoInfo, withFormatName: KMBigImageFormatName, completionBlock: { // (photoInfo, _, image) -> Void in // self.imageView.image = image // self.spinner.stopAnimating() // }) // // let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleTap:") // doubleTapRecognizer.numberOfTapsRequired = 2 // doubleTapRecognizer.numberOfTouchesRequired = 1 // scrollView.addGestureRecognizer(doubleTapRecognizer) // } // // override func viewDidLayoutSubviews() { // super.viewDidLayoutSubviews() // centerScrollViewContents() // } // // // MARK: Gesture Recognizers // // func handleDoubleTap(recognizer: UITapGestureRecognizer!) { // let pointInView = recognizer.locationInView(self.imageView) // self.zoomInZoomOut(pointInView) // } // // // MARK: ScrollView // // func scrollViewDidZoom(scrollView: UIScrollView) { // self.centerScrollViewContents() // } // // func centerScrollViewContents() { // let boundsSize = scrollView.frame // var contentsFrame = self.imageView.frame // // if contentsFrame.size.width < boundsSize.width { // contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 // } else { // contentsFrame.origin.x = 0.0 // } // // if contentsFrame.size.height < boundsSize.height { // contentsFrame.origin.y = (boundsSize.height - scrollView.scrollIndicatorInsets.top - scrollView.scrollIndicatorInsets.bottom - contentsFrame.size.height) / 2.0 // } else { // contentsFrame.origin.y = 0.0 // } // // self.imageView.frame = contentsFrame // } // // func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { // return self.imageView // } // // func zoomInZoomOut(point: CGPoint!) { // let newZoomScale = self.scrollView.zoomScale > (self.scrollView.maximumZoomScale/2) ? self.scrollView.minimumZoomScale : self.scrollView.maximumZoomScale // // let scrollViewSize = self.scrollView.bounds.size // // let width = scrollViewSize.width / newZoomScale // let height = scrollViewSize.height / newZoomScale // let x = point.x - (width / 2.0) // let y = point.y - (height / 2.0) // // let rectToZoom = CGRect(x: x, y: y, width: width, height: height) // // self.scrollView.zoomToRect(rectToZoom, animated: true) // } //}
apache-2.0
7b8aaec8397f509ac8cc2e976985aaf6
34.649573
173
0.609446
4.158524
false
false
false
false
andrea-prearo/ContactList
ContactList/ViewControllers/ContactDetailViewController.swift
1
1950
// // ContactDetailViewController.swift // ContactList // // Created by Andrea Prearo on 3/19/16. // Copyright © 2016 Andrea Prearo // import UIKit import AlamofireImage class ContactDetailViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! var contact: Contact? @IBOutlet weak var avatar: UIImageView! @IBOutlet weak var username: UILabel! @IBOutlet weak var company: UILabel! @IBOutlet weak var address: UILabel! @IBOutlet weak var customBackgroundView: UIView! @IBOutlet weak var mainInfoView: UIView! override func viewDidLoad() { super.viewDidLoad() setUpStyle() configure() } override func viewWillLayoutSubviews() { scrollView.contentOffset = CGPoint(x: 0, y: 0) let screenSize = UIScreen.main.bounds scrollView.contentSize = CGSize(width: screenSize.width, height: screenSize.height + 1) } func setUpStyle() { view.backgroundColor = UIColor.defaultGradientBackgroundColor() mainInfoView.layer.cornerRadius = CGFloat(2.5) automaticallyAdjustsScrollViewInsets = false scrollView.translatesAutoresizingMaskIntoConstraints = false } } // MARK: Private Methods private extension ContactDetailViewController { func configure() { guard let contact = contact else { return } let viewModel = ContactDetailViewModel(contact: contact) if let urlString = viewModel.avatarUrl, let url = URL(string: urlString) { let filter = RoundedCornersFilter(radius: avatar.frame.size.width * 0.5) avatar.af_setImage(withURL: url, placeholderImage: UIImage.defaultAvatarImage(), filter: filter) } username.text = viewModel.username company.text = viewModel.company address.text = viewModel.address } }
mit
786eca0379ecefc2529b5099d2d543f9
27.246377
95
0.658799
5.102094
false
false
false
false
vermont42/Conjugar
Conjugar/SoundPlayer.swift
1
1229
// // SoundPlayer.swift // Conjugar // // Created by Josh Adams on 11/18/15. // Copyright © 2015 Josh Adams. All rights reserved. // import AVFoundation class SoundPlayer { private static let soundPlayer = SoundPlayer() private var sounds: [String: AVAudioPlayer] private static let soundExtension = "mp3" private init () { sounds = Dictionary() do { try AVAudioSession.sharedInstance().setCategory(.playback) // was ambient } catch let error as NSError { print("\(error.localizedDescription)") } } static func play(_ sound: Sound) { if soundPlayer.sounds[sound.rawValue] == nil { if let audioUrl = Bundle.main.url(forResource: sound.rawValue, withExtension: soundExtension) { do { try soundPlayer.sounds[sound.rawValue] = AVAudioPlayer.init(contentsOf: audioUrl) } catch let error as NSError { print("\(error.localizedDescription)") } } } soundPlayer.sounds[sound.rawValue]?.play() } static func playRandomApplause() { let applauses: [Sound] = [.applause1, .applause2, .applause3] let applauseIndex = Int.random(in: 0 ... (applauses.count - 1)) SoundPlayer.play(applauses[applauseIndex]) } }
agpl-3.0
74f3aeaff0d682e9fe62d7263532d50a
27.55814
101
0.662866
3.84953
false
false
false
false
hsusmita/SHResponsiveLabel
SHResponsiveLabel/Source/TruncationHandler.swift
1
7772
// // TruncationHandler.swift // SHResponsiveLabel // // Created by hsusmita on 31/07/15. // Copyright (c) 2015 hsusmita.com. All rights reserved. // import Foundation extension SHResponsiveLabel { func removeTokenIfPresent() { if truncationTokenAppended() { if let currentString = textStorage.string as NSString? { let truncationRange = currentString.rangeOfString(attributedTruncationToken!.string) var finalString = NSMutableAttributedString(attributedString: textStorage) if truncationRange.location != NSNotFound { let rangeOfTuncatedString = NSMakeRange(truncationRange.location, self.attributedText.length-truncationRange.location) let truncatedString = attributedText.attributedSubstringFromRange(rangeOfTuncatedString) finalString.replaceCharactersInRange(truncationRange, withAttributedString: truncatedString) } updateTextStorage(finalString) } } } func updateTruncationToken(truncationToken:NSAttributedString,action:PatternTapResponder) { //Disable old pattern if present if let tokenString = attributedTruncationToken as NSAttributedString? { let patternKey = kRegexFormatForSearchWord + tokenString.string if let descriptor = patternDescriptorDictionary[patternKey] { disablePatternDetection(descriptor) } } attributedTruncationToken = truncationToken var error = NSErrorPointer() let patternKey = kRegexFormatForSearchWord + truncationToken.string let regex = NSRegularExpression(pattern: patternKey, options: NSRegularExpressionOptions.allZeros, error: error) if let currentRegex = regex as NSRegularExpression? { if let tokenAction = action as PatternTapResponder? { let descriptor = PatternDescriptor(regularExpression: regex!, searchType: PatternSearchType.Last, patternAttributes:[RLTapResponderAttributeName:action]) enablePatternDetection(descriptor) }else { let descriptor = PatternDescriptor(regularExpression: regex!, searchType: PatternSearchType.Last,patternAttributes:nil) enablePatternDetection(descriptor) } } } func shouldAppendTruncationToken()-> Bool { var shouldAppend = false if textStorage.length > 0 { if attributedTruncationToken?.length > 0 { // shouldAppend = customTruncationEnabled && numberOfLines != 0 shouldAppend = customTruncationEnabled } } return shouldAppend } func appendTokenIfNeeded() { if (shouldAppendTruncationToken() && !truncationTokenAppended()) { if isNewLinePresent() { //Append token string at the end of last visible line let range = rangeForTokenInsertionForStringWithNewLine() if range.length > 0 { textStorage.replaceCharactersInRange(range, withAttributedString: attributedTruncationToken!) } } //Check for truncation range and append truncation token if required let tokenRange = rangeForTokenInsertion() if (tokenRange.length > 0 && tokenRange.location >= 0) { self.textStorage.replaceCharactersInRange(tokenRange, withAttributedString:attributedTruncationToken!) self.redrawTextForRange(NSMakeRange(0, textStorage.length)) } //Apply attributes if truncation token appended let truncationRange = rangeOfTruncationToken() if (truncationRange.location != NSNotFound) { removeAttributeForTruncatedRange() //Apply attributes to the truncation token let patternKey = kRegexFormatForSearchWord + attributedTruncationToken!.string if let descriptor = patternDescriptorDictionary[patternKey] { if let attributes = descriptor.patternAttributes { textStorage.addAttributes(descriptor.patternAttributes!, range: truncationRange) } } } } } // MARK: Truncation Handlers func isNewLinePresent()-> Bool { let currentString = textStorage.string as NSString return currentString.rangeOfCharacterFromSet(NSCharacterSet.newlineCharacterSet()).location != NSNotFound } func rangeForTokenInsertionForStringWithNewLine()-> NSRange { let numberOfGlyphs = layoutManager.numberOfGlyphs var index = 0 var lineRange = NSMakeRange(NSNotFound, 0); let approximateNumberOfLines = Int(layoutManager.usedRectForTextContainer(textContainer).height) / Int(font.lineHeight) for (var lineNumber = 0, index = 0; index < numberOfGlyphs; lineNumber++) { layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange) if (lineNumber == approximateNumberOfLines - 1){ break} index = NSMaxRange(lineRange); } let rangeOfText = NSMakeRange(lineRange.location + lineRange.length - 1, self.textStorage.length - lineRange.location - lineRange.length + 1) return rangeOfText } func rangeOfTruncationToken()-> NSRange { println("number of line = \(numberOfLines)") // if (numberOfLines == 0) { // return NSMakeRange(NSNotFound, 0) // } if (attributedTruncationToken?.length > 0 && customTruncationEnabled == true) { var currentString:NSString = textStorage.string as NSString return currentString.rangeOfString(attributedTruncationToken!.string) }else { return rangeForTokenInsertion() } } func rangeForTokenInsertion()-> NSRange { textContainer.size = self.bounds.size println("size = \(textContainer.size.width) x \(textContainer.size.height)") println("label size = \(self.frame.size.width) x \(self.frame.size.height)") println("length \(textStorage.length)") let glyphIndex = layoutManager.glyphIndexForCharacterAtIndex(textStorage.length-1) println("glyph index = \(glyphIndex)") var range = layoutManager.truncatedGlyphRangeInLineFragmentForGlyphAtIndex(glyphIndex) println("range = \(range.location) x \(range.length)") if (range.length > 0 && customTruncationEnabled) { range.length += attributedTruncationToken!.length range.location -= attributedTruncationToken!.length } return range } // This method removes attributes from the truncated range. // TruncatedRange is defined as the pattern range which overlaps the range of // truncation token. When the truncation token is set, the attributes of the // truncated range should be removed. func removeAttributeForTruncatedRange() { let truncationRange = rangeOfTruncationToken() for (key,descriptor) in patternDescriptorDictionary { let ranges = descriptor.patternRangesForString(attributedText.string) for range in ranges { let truncationRange = rangeOfTruncationToken() let isTruncationRange = NSEqualRanges(range, truncationRange) let intersectionRange = NSIntersectionRange(range, truncationRange) let isRangeTruncated = (intersectionRange.length > 0) && (range.location < truncationRange.location) //Remove attributes if the range is truncated if (isRangeTruncated) { let visibleRange = NSMakeRange(range.location,range.length - intersectionRange.length); if let attributes = descriptor.patternAttributes { for (name,NSObject) in attributes { textStorage.removeAttribute(name, range: visibleRange) } redrawTextForRange(range) } } } } } func truncationTokenAppended()-> Bool { var isAppended = false if let truncationToken = attributedTruncationToken { if let string = textStorage.string as NSString? { isAppended = string.rangeOfString(attributedTruncationToken!.string).location != NSNotFound } } return isAppended } }
mit
a0de631465be0e74c7505c13bd0740bb
39.691099
161
0.714874
5.106439
false
false
false
false
onmyway133/Github.swift
Carthage/Checkouts/Sugar/Source/Shared/Extensions/Array+Queueable.swift
1
488
public protocol Queueable { func process() -> Bool } public extension Array where Element : Queueable { public mutating func processQueue(from: Int = 0, _ to: Int? = nil, process: ((element: Element) -> Void)? = nil) { let to = to != nil ? to! : count let currentQueue = self[from..<to] for (index, element) in currentQueue.enumerate() where element.process() { process?(element: element) removeAtIndex(index - (currentQueue.count - self.count)) } } }
mit
d66a04ecf8e49a9ee58089b156f8b69b
31.533333
116
0.64959
3.873016
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/Cells.swift
2
774
// // Cells.swift // Neocom // // Created by Artem Shimanski on 28.08.2018. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation class RowCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() selectedBackgroundView = UIView(frame: bounds) selectedBackgroundView?.backgroundColor = .separator tintColor = .caption } override var indentationLevel: Int { didSet { layoutMargins.left = layoutMargins.right + indentationWidth * max(CGFloat(indentationLevel - 1), 0) } } } class HeaderCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() selectedBackgroundView = UIView(frame: bounds) selectedBackgroundView?.backgroundColor = .cellBackground tintColor = .caption } }
lgpl-2.1
34325cbb71ec1e5aeffe932a3bf63234
21.735294
102
0.737387
4.13369
false
false
false
false
TheLittleBoy/Swift-Code
MyPlayground5.playground/section-1.swift
1
14486
// Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" //////////////////////// //扩展(Extensions) //扩展和 Objective-C 中的分类(categories)类似。(不过与Objective-C不同的是,Swift 的扩展没有名字。) //Swift 中的扩展可以: //添加计算型属性和计算静态属性 //定义实例方法和类型方法 //提供新的构造器 //定义下标 //定义和使用新的嵌套类型 //使一个已有类型符合某个协议 //extension extension Double { var km:Double { return self * 1_000.0 } //计算型属性 var m:Double {return self} var cm:Double {return self / 100.0} var mm: Double { return self / 1_000.0 } var ft: Double { return self / 3.28084 } } let oneInch = 25.2.mm println("One inch is \(oneInch) meters") // prints "One inch is 0.0254 meters" let threeFeet = 3.ft println("Three feet is \(threeFeet) meters") // prints "Three feet is 0.914399970739201 meters" let aMarathon = 42.km + 195.m println("A marathon is \(aMarathon) meters long") // 打印输出:"A marathon is 42495.0 meters long" //扩展可以添加新的计算属性,但是不可以添加存储属性,也不可以向已有属性添加属性观测器(property observers)。 //扩展可以向已有类型添加新的构造器。 //扩展能向类中添加新的便利构造器,但是它们不能向类中添加新的指定构造器或析构函数。指定构造器和析构函数必须总是由原始的类实现来提供。 struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() } let defaultRect = Rect() let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) extension Rect { init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // centerRect的原点是 (2.5, 2.5),大小是 (3.0, 3.0) //扩展可以向已有类型添加新的实例方法和类型方法。 extension Int { func repetitions(task: () -> ()) { for i in 0..<self { task() } } } 3.repetitions({ println("Hello!") }) // Hello! // Hello! // Hello! //可以使用 trailing 闭包使调用更加简洁: 3.repetitions{ println("Goodbye!") } // Goodbye! // Goodbye! // Goodbye! //通过扩展添加的实例方法也可以修改该实例本身。 extension Int { mutating func square() { //结构体和枚举类型中修改self或其属性的方法必须将该实例方法标注为mutating self = self * self } } var someInt = 3 someInt.square() // someInt 现在值是 9 //扩展可以向一个已有类型添加新下标。 extension Int { subscript(digitIndex:Int) -> Int{ var decimalBase = 1 for _ in 1...digitIndex{ decimalBase *= 10 } return (self/decimalBase) % 10 } } 746381295[0] // returns 5 746381295[1] // returns 9 746381295[2] // returns 2 746381295[8] // returns 7 //下标越界了,不过结果还是正确滴 746381295[9] //returns 0, 即等同于: 0746381295[9] //扩展可以向已有的类、结构体和枚举添加新的嵌套类型 extension Character { enum Kind { case Vowel, Consonant, Other } var kind: Kind { switch String(self).lowercaseString { case "a", "e", "i", "o", "u": return .Vowel case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": return .Consonant default: return .Other } } } func printLetterKinds(word: String) { println("'\(word)' is made up of the following kinds of letters:") for character in word { switch character.kind { case .Vowel: print("vowel ") case .Consonant: print("consonant ") case .Other: print("other ") } } print("\n") } printLetterKinds("Hello") // 'Hello' is made up of the following kinds of letters: // consonant vowel consonant consonant vowel ///////////////////// //协议 //类,结构体,枚举通过提供协议所要求的方法,属性的具体实现来采用(adopt)协议 //协议中的属性经常被加以var前缀声明其为变量属性,在声明后加上{ set get }来表示属性是可读写的,只读的属性则写作{ get },如下所示: protocol SomeProtocol { var musBeSettable : Int { get set } var doesNotNeedToBeSettable: Int { get } } //如果一个类在含有父类的同时也采用了协议,应当把父类放在所有的协议之前 //如下所示,通常在协议的定义中使用class前缀表示该属性为类成员;在枚举和结构体实现协议时中,需要使用static关键字作为前缀。 protocol AnotherProtocol { class var someTypeProperty: Int { get set } } protocol FullyNamed { var fullName: String { get } } struct Person: FullyNamed{ var fullName: String } let john = Person(fullName: "John Appleseed") //john.fullName 为 "John Appleseed" class Starship: FullyNamed { var prefix: String? var name: String init(name: String, prefix: String? = nil ) { self.name = name self.prefix = prefix } var fullName: String { //实现为只读的计算型属性 return (prefix ? prefix! + " " : " ") + name } } var ncc1701 = Starship(name: "Enterprise", prefix: "USS") // ncc1701.fullName == "USS Enterprise" //协议中的方法支持变长参数(variadic parameter),不支持参数默认值(default value) protocol SomeProtocol2 { class func someTypeMethod() } //实例方法的的协议 protocol RandomNumberGenerator { func random() -> Double } class LinearCongruentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 139968.0 let a = 3877.0 let c = 29573.0 func random() -> Double { lastRandom = ((lastRandom * a + c) % m) return lastRandom / m } } let generator = LinearCongruentialGenerator() println("Here's a random number: \(generator.random())") // 输出 : "Here's a random number: 0.37464991998171" println("And another one: \(generator.random())") // 输出 : "And another one: 0.729023776863283" //用类实现协议中的mutating方法时,不用写mutating关键字;用结构体,枚举实现协议中的mutating方法时,必须写mutating关键字。 protocol Togglable { mutating func toggle() } enum OnOffSwitch: Togglable { case Off, On mutating func toggle() { switch self { case Off: self = On case On: self = Off } } } var lightSwitch = OnOffSwitch.Off lightSwitch.toggle() //lightSwitch 现在的值为 .On ////// //尽管协议本身并不实现任何功能,但是协议可以被当做类型来使用。 //使用场景: //协议类型作为函数、方法或构造器中的参数类型或返回值类型 //协议类型作为常量、变量或属性的类型 //协议类型作为数组、字典或其他容器中的元素类型 class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } var d6 = Dice(sides: 6,generator: LinearCongruentialGenerator()) for _ in 1...5 { println("Random dice roll is \(d6.roll())") } //////////委托(代理)模式 protocol DiceGame { var dice: Dice { get } func play() } protocol DiceGameDelegate { func gameDidStart(game: DiceGame) func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll:Int) func gameDidEnd(game: DiceGame) } class SnakesAndLadders: DiceGame { let finalSquare = 25 let dice = Dice(sides: 6, generator: LinearCongruentialGenerator()) var square = 0 var board: [Int] init() { board = [Int](count: finalSquare + 1, repeatedValue: 0) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 } var delegate: DiceGameDelegate? //可选的。若delegate属性为nil, 则delegate所调用的方法失效。若delegate不为nil,则方法能够被调用 func play() { square = 0 delegate?.gameDidStart(self) gameLoop: while square != finalSquare { let diceRoll = dice.roll() delegate?.game(self,didStartNewTurnWithDiceRoll: diceRoll) switch square + diceRoll { case finalSquare: break gameLoop case let newSquare where newSquare > finalSquare: continue gameLoop default: square += diceRoll square += board[square] } } delegate?.gameDidEnd(self) } } class DiceGameTracker: DiceGameDelegate { var numberOfTurns = 0 func gameDidStart(game: DiceGame) { numberOfTurns = 0 if game is SnakesAndLadders { println("Started a new game of Snakes and Ladders") } println("The game is using a \(game.dice.sides)-sided dice") } func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) { ++numberOfTurns println("Rolled a \(diceRoll)") } func gameDidEnd(game: DiceGame) { println("The game lasted for \(numberOfTurns) turns") } } let tracker = DiceGameTracker() let game = SnakesAndLadders() game.delegate = tracker game.play() // Started a new game of Snakes and Ladders // The game is using a 6-sided dice // Rolled a 3 // Rolled a 5 // Rolled a 4 // Rolled a 5 // The game lasted for 4 turns //////// //通过扩展为已存在的类型遵循协议时,该类型的所有实例也会随之添加协议中的方法 protocol TextRepresentable { func asText() -> String } extension Dice: TextRepresentable { func asText() -> String { return "A \(sides)-sided dice" } } let d12 = Dice(sides: 12,generator: LinearCongruentialGenerator()) println(d12.asText()) // 输出 "A 12-sided dice" extension SnakesAndLadders: TextRepresentable { func asText() -> String { return "A game of Snakes and Ladders with \(finalSquare) squares" } } println(game.asText()) // 输出 "A game of Snakes and Ladders with 25 squares" /////通过扩展补充协议声明 //当一个类型已经实现了协议中的所有要求,却没有声明时,可以通过扩展来补充协议声明: struct Hamster { var name: String func asText() -> String { return "A hamster named \(name)" } } extension Hamster: TextRepresentable {} //从现在起,Hamster的实例可以作为TextRepresentable类型使用 let simonTheHamster = Hamster(name: "Simon") let somethingTextRepresentable: TextRepresentable = simonTheHamster println(somethingTextRepresentable.asText()) // 输出 "A hamster named Simon" ///////集合中的协议类型 let things: [TextRepresentable] = [game,d12,simonTheHamster] //仅能调用asText方法 for thing in things { println(thing.asText()) } //议能够继承一到多个其他协议。语法与类的继承相似,多个协议间用逗号,分隔 protocol PrettyTextRepresentable: TextRepresentable { func asPrettyText() -> String } extension SnakesAndLadders: PrettyTextRepresentable { func asPrettyText() -> String { var output = asText() + ":\n" for index in 1...finalSquare { switch board[index] { case let ladder where ladder > 0: output += "▲ " case let snake where snake < 0: output += "▼ " default: output += "○ " } } return output } } println(game.asPrettyText()) //////////////// //协议合成Protocol Composition protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } struct Person2: Named, Aged { var name: String var age: Int } func wishHappyBirthday(celebrator: protocol<Named, Aged>) { println("Happy birthday \(celebrator.name) - you're \(celebrator.age)!") } let birthdayPerson = Person2(name: "Malcolm", age: 21) wishHappyBirthday(birthdayPerson) // 输出 "Happy birthday Malcolm - you're 21! //////////////// //检验协议的一致性 @objc protocol HasArea { @optional var area: Double { get } } class Circle: HasArea { let pi = 3.1415927 var radius: Double //var area: Double { return pi * radius * radius } init(radius: Double) { self.radius = radius } } class Country: HasArea { var area: Double init(area: Double) { self.area = area } } class Animal { var legs: Int init(legs: Int) { self.legs = legs } } let objects: [AnyObject] = [ Circle(radius: 2.0), Country(area: 243_610), Animal(legs: 4) ] for object : AnyObject in objects { if let objectWithArea = object as? HasArea { println("Area is \(objectWithArea.area)") } else { println("Something that doesn't have an area") } } ///////////// @objc protocol CounterDataSource { @optional func incrementForCount(count: Int) -> Int @optional var fixedIncrement: Int { get } } @objc class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.incrementForCount?(count) { count += amount } else if let amount = dataSource?.fixedIncrement? { count += amount } } } class ThreeSource: CounterDataSource { let fixedIncrement = 3 } var counter = Counter() counter.dataSource = ThreeSource() for _ in 1...4 { counter.increment() println(counter.count) } class TowardsZeroSource: CounterDataSource { func incrementForCount(count: Int) -> Int { if count == 0 { return 0 } else if count < 0 { return 1 } else { return -1 } } } counter.count = -4 counter.dataSource = TowardsZeroSource() for _ in 1...5 { counter.increment() println(counter.count) }
mit
d259e1cd6c8b6a7e0876af65069232e3
21.230496
103
0.625698
3.37315
false
false
false
false
muneebm/AsterockX
AsterockX/PickerViewController.swift
1
1877
// // PickerViewController.swift // AsterockX // // Created by Muneeb Rahim Abdul Majeed on 1/3/16. // Copyright © 2016 beenum. All rights reserved. // import UIKit protocol PickerViewControllerDelegate { func picker(picker: PickerViewController, didPickItem item: String?) } class PickerViewController: UIViewController { var delegate: PickerViewControllerDelegate? var lastPage: String! var initialSelectedItem: String! var items = [String]() @IBOutlet weak var pickerView: UIPickerView! override func viewDidLoad() { super.viewDidLoad() if let initialIndex = items.indexOf(initialSelectedItem) { pickerView.selectRow(initialIndex, inComponent: 0, animated: true) } } @IBAction func done(sender: UIButton) { dismissViewControllerAnimated(false) { () -> Void in let selectedIndex = self.pickerView.selectedRowInComponent(0) let selectedItem = self.items[selectedIndex] if self.initialSelectedItem != selectedItem { self.delegate?.picker(self, didPickItem: selectedItem) } } } @IBAction func cancel(sender: UIButton) { dismissViewControllerAnimated(false, completion: nil) } } extension PickerViewController: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1; } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return items.count; } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return items[row] } }
mit
33769146657bf543f67e906cecd501c8
24.013333
109
0.6258
5.421965
false
false
false
false
Minecodecraft/EstateBand
EstateBand/UserCollectionViewController.swift
1
5724
// // UserCollectionViewController.swift // EstateBand // // Created by Minecode on 2017/6/27. // Copyright © 2017年 org.minecode. All rights reserved. // import UIKit import Charts class UserCollectionViewController: UIViewController, ChartViewDelegate{ // 控件 @IBOutlet weak var chartView1: LineChartView! @IBOutlet weak var chartView2: LineChartView! // 数据 override func viewDidLoad() { super.viewDidLoad() loadChart() } func loadChart() { chartView1.delegate = self chartView1.chartDescription?.enabled = false chartView1.dragEnabled = true chartView1.setScaleEnabled(true) chartView1.pinchZoomEnabled = true chartView1.drawGridBackgroundEnabled = false chartView1.leftAxis.removeAllLimitLines() chartView1.leftAxis.axisMinimum = 50 chartView1.leftAxis.axisMaximum = 150 // 关闭背景线 chartView1.leftAxis.drawGridLinesEnabled = false chartView1.rightAxis.drawGridLinesEnabled = false chartView1.xAxis.drawGridLinesEnabled = false chartView1.legend.form = .line chartView1.animate(xAxisDuration: 1.0, yAxisDuration: 3.0) // chart 2 chartView2.delegate = self chartView2.chartDescription?.enabled = false chartView2.dragEnabled = true chartView2.setScaleEnabled(true) chartView2.pinchZoomEnabled = true chartView2.drawGridBackgroundEnabled = false chartView2.leftAxis.removeAllLimitLines() chartView2.leftAxis.axisMinimum = 30 chartView2.leftAxis.axisMaximum = 100 // 关闭背景线 chartView2.leftAxis.drawGridLinesEnabled = false chartView2.rightAxis.drawGridLinesEnabled = false chartView2.xAxis.drawGridLinesEnabled = false chartView2.legend.form = .line // 装载数据 updateChartData() // 设置线条类型 // 设置线条类型 for set in (chartView1.data?.dataSets)! { let lineSet: ILineChartDataSet = set as! ILineChartDataSet lineSet.mode = .cubicBezier } chartView1.setNeedsDisplay() for set in (chartView2.data?.dataSets)! { let lineSet: ILineChartDataSet = set as! ILineChartDataSet lineSet.mode = .cubicBezier } chartView2.setNeedsDisplay() chartView1.animate(xAxisDuration: 1.0, yAxisDuration: 3.0) chartView2.animate(xAxisDuration: 1.0, yAxisDuration: 3.0) } func updateChartData() { setDataCount1(count: 7, range: 70) setDataCount2(count: 12, range: 50) } func setDataCount1(count: Int, range: Double) { var values = NSMutableArray.init() for i in 0..<count { var val: Double = Double(arc4random_uniform(UInt32(range)) + 50) values.add(ChartDataEntry(x: Double(i), y: val)) } var set1 = LineChartDataSet.init(values: values as! [ChartDataEntry], label: "Mason Amount") set1.drawIconsEnabled = false set1.lineDashLengths = [5.0, 0] set1.setColor(UIColor.black) set1.setCircleColor(UIColor.blue) set1.lineWidth = 1.0 set1.circleRadius = 5.0 set1.drawCircleHoleEnabled = true set1.valueFont = UIFont.systemFont(ofSize: 10) set1.formLineDashLengths = [5.0, 0] set1.formLineWidth = 1.0 set1.formSize = 15 let gradientColors: NSArray = [ChartColorTemplates.colorFromString("#ffffff").cgColor, ChartColorTemplates.colorFromString("#0000ff").cgColor] let gradient = CGGradient(colorsSpace: nil, colors: gradientColors, locations: nil) set1.fillAlpha = 1.0 set1.fill = Fill(linearGradient: gradient!, angle: 90) set1.drawFilledEnabled = true let dataSets1 = NSMutableArray.init() dataSets1.add(set1) let data1 = LineChartData.init(dataSets: dataSets1 as? [IChartDataSet]) chartView1.data = data1 } func setDataCount2(count: Int, range: Double) { var values = NSMutableArray.init() for i in 0..<count { var val: Double = Double(arc4random_uniform(UInt32(range)) + 40) values.add(ChartDataEntry(x: Double(i), y: val)) } var set2 = LineChartDataSet.init(values: values as! [ChartDataEntry], label: "Tecnicial Amount") set2.drawIconsEnabled = false set2.lineDashLengths = [5.0, 0] set2.setColor(UIColor.black) set2.setCircleColor(UIColor.blue) set2.lineWidth = 1.0 set2.circleRadius = 5.0 set2.drawCircleHoleEnabled = true set2.valueFont = UIFont.systemFont(ofSize: 10) set2.formLineDashLengths = [5.0, 0] set2.formLineWidth = 1.0 set2.formSize = 15 let gradientColors: NSArray = [ChartColorTemplates.colorFromString("#ffffff").cgColor, ChartColorTemplates.colorFromString("#00ff00").cgColor] let gradient = CGGradient(colorsSpace: nil, colors: gradientColors, locations: nil) set2.fillAlpha = 1.0 set2.fill = Fill(linearGradient: gradient!, angle: 90) set2.drawFilledEnabled = true let dataSets2 = NSMutableArray.init() dataSets2.add(set2) let data2 = LineChartData.init(dataSets: dataSets2 as? [IChartDataSet]) chartView2.data = data2 } }
mit
8cfbda2ef64a4fe68b49857e7c337d16
32.898204
104
0.614202
4.733278
false
false
false
false
proxyco/RxBluetoothKit
Source/Peripheral+Convenience.swift
1
13977
// The MIT License (MIT) // // Copyright (c) 2016 Polidea // // 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 CoreBluetooth import RxSwift // swiftlint:disable line_length extension Peripheral { /** Function used to receive service with given identifier. It's taken from cache if it's available, or directly by `discoverServices` call - Parameter identifier: Unique identifier of Service - Returns: Observation which emits `Next` event, when specified service has been found. Immediately after that `.Complete` is emitted. */ public func serviceWithIdentifier(identifier: ServiceIdentifier) -> Observable<Service> { return Observable.deferred { if let services = self.services, let service = services.findElement({ $0.UUID == identifier.UUID }) { return Observable.just(service) } else { return Observable.from(self.discoverServices([identifier.UUID])) } } } /** Function used to receive characteristic with given identifier. If it's available it's taken from cache. Otherwise - directly by `discoverCharacteristics` call - Parameter identifier: Unique identifier of Characteristic, that has information about service which characteristic belongs to. - Returns: Observation which emits `Next` event, when specified characteristic has been found. Immediately after that `.Complete` is emitted. */ public func characteristicWithIdentifier(identifier: CharacteristicIdentifier) -> Observable<Characteristic> { return Observable.deferred { return self.serviceWithIdentifier(identifier.service) .flatMap { service -> Observable<Characteristic> in if let characteristics = service.characteristics, let characteristic = characteristics.findElement({ $0.UUID == identifier.UUID }) { return Observable.just(characteristic) } else { return Observable.from(service.discoverCharacteristics([identifier.UUID])) } } } } /** Function used to receive descriptor with given identifier. If it's available it's taken from cache. Otherwise - directly by `discoverDescriptor` call - Parameter identifier: Unique identifier of Descriptor, that has information about characteristic which descriptor belongs to. - Returns: Observation which emits `Next` event, when specified descriptor has been found. Immediately after that `.Complete` is emitted. */ public func descriptorWithIdentifier(identifier: DescriptorIdentifier) -> Observable<Descriptor> { return Observable.deferred { return self.characteristicWithIdentifier(identifier.characteristic) .flatMap { characteristic -> Observable<Descriptor> in if let descriptors = characteristic.descriptors, let descriptor = descriptors.findElement({ $0.UUID == identifier.UUID }) { return Observable.just(descriptor) } else { return Observable.from(characteristic.discoverDescriptors()) .filter { $0.UUID == identifier.UUID } .take(1) } } } } /** Function that allow to monitor writes that happened for characteristic. - Parameter identifier: Identifier of characteristic of which value writes should be monitored. - Returns: Observable that emits `Next` with `Characteristic` instance every time when write has happened. It's **infinite** stream, so `.Complete` is never called. */ public func monitorWriteForCharacteristicWithIdentifier(identifier: CharacteristicIdentifier) -> Observable<Characteristic> { return characteristicWithIdentifier(identifier) .flatMap { return self.monitorWriteForCharacteristic($0) } } /** Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made. Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/swift/enum/c:@E@CBCharacteristicWriteType), so be sure to check this out before usage of the method. - parameter data: Data that'll be written written to `Characteristic` instance - parameter forCharacteristicWithIdentifier: unique identifier of service, which also holds information about service characteristic belongs to. `Descriptor` instance to write value to. - parameter type: Type of write operation. Possible values: `.WithResponse`, `.WithoutResponse` - returns: Observable that emition depends on `CBCharacteristicWriteType` passed to the function call. Behavior is following: - `WithResponse` - Observable emits `Next` with `Characteristic` instance write was confirmed without any errors. Immediately after that `Complete` is called. If any problem has happened, errors are emitted. - `WithoutResponse` - Observable emits `Next` with `Characteristic` instance once write was called. Immediately after that `.Complete` is called. Result of this call is not checked, so as a user you are not sure if everything completed successfully. Errors are not emitted */ public func writeValue(data: NSData, forCharacteristicWithIdentifier identifier: CharacteristicIdentifier, type: CBCharacteristicWriteType) -> Observable<Characteristic> { return characteristicWithIdentifier(identifier) .flatMap { return self.writeValue(data, forCharacteristic: $0, type: type) } } /** Function that allow to monitor value updates for `Characteristic` instance. - Parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. - Returns: Observable that emits `Next` with `Characteristic` instance every time when value has changed. It's **infinite** stream, so `.Complete` is never called. */ public func monitorValueUpdateForCharacteristicWithIdentifier(identifier: CharacteristicIdentifier) -> Observable<Characteristic> { return characteristicWithIdentifier(identifier) .flatMap { return self.monitorValueUpdateForCharacteristic($0) } } /** Function that triggers read of current value of the `Characteristic` instance. Read is called after subscription to `Observable` is made. - Parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. - Returns: Observable which emits `Next` with given characteristic when value is ready to read. Immediately after that `.Complete` is emitted. */ public func readValueForCharacteristicWithIdentifier(identifier: CharacteristicIdentifier) -> Observable<Characteristic> { return characteristicWithIdentifier(identifier) .flatMap { return self.readValueForCharacteristic($0) } } /** Function that triggers set of notification state of the `Characteristic`. This change is called after subscribtion to `Observable` is made. - warning: This method is not responsible for emitting values every time that `Characteristic` value is changed. For this, refer to other method: `monitorValueUpdateForCharacteristic(_)`. These two are often called together. - parameter enabled: New value of notifications state. Specify `true` if you're interested in getting values - parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. - returns: Observable which emits `Next` with Characteristic that state was changed. Immediately after `.Complete` is emitted */ public func setNotifyValue(enabled: Bool, forCharacteristicWithIdentifier identifier: CharacteristicIdentifier) -> Observable<Characteristic> { return characteristicWithIdentifier(identifier) .flatMap { return self.setNotifyValue(enabled, forCharacteristic: $0) } } /** Function that triggers set of notification state of the `Characteristic`, and monitor for any incoming updates. Notification is set after subscribtion to `Observable` is made. - parameter identifier: unique identifier of service, which also holds information about service that characteristic belongs to. - returns: Observable which emits `Next`, when characteristic value is updated. This is **infinite** stream of values. */ public func setNotificationAndMonitorUpdatesForCharacteristicWithIdentifier(identifier: CharacteristicIdentifier) -> Observable<Characteristic> { return characteristicWithIdentifier(identifier) .flatMap { return self.setNotificationAndMonitorUpdatesForCharacteristic($0) } } /** Function that triggers descriptors discovery for characteristic - Parameter characteristic: `Characteristic` instance for which descriptors should be discovered. - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. - Returns: Observable that emits `Next` with array of `Descriptor` instances, once they're discovered. Immediately after that `.Complete` is emitted. */ public func discoverDescriptorsForCharacteristicWithIdentifier(identifier: CharacteristicIdentifier) -> Observable<[Descriptor]> { return characteristicWithIdentifier(identifier) .flatMap { return self.discoverDescriptorsForCharacteristic($0) } } /** Function that allow to monitor writes that happened for descriptor. - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. - Returns: Observable that emits `Next` with `Descriptor` instance every time when write has happened. It's **infinite** stream, so `.Complete` is never called. */ public func monitorWriteForDescriptorWithIdentifier(identifier: DescriptorIdentifier) -> Observable<Descriptor> { return descriptorWithIdentifier(identifier) .flatMap { return self.monitorWriteForDescriptor($0) } } /** Function that triggers write of data to descriptor. Write is called after subscribtion to `Observable` is made. - Parameter data: `NSData` that'll be written to `Descriptor` instance - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. - Returns: Observable that emits `Next` with `Descriptor` instance, once value is written successfully. Immediately after that `.Complete` is emitted. */ public func writeValue(data: NSData, forDescriptorWithIdentifier identifier: DescriptorIdentifier) -> Observable<Descriptor> { return descriptorWithIdentifier(identifier) .flatMap { return self.writeValue(data, forDescriptor: $0) } } /** Function that allow to monitor value updates for `Descriptor` instance. - parameter identifier: unique identifier of descriptor, which also holds information about characteristic that descriptor belongs to. - Returns: Observable that emits `Next` with `Descriptor` instance every time when value has changed. It's **infinite** stream, so `.Complete` is never called. */ public func monitorValueUpdateForDescriptorWithIdentifier(identifier: DescriptorIdentifier) -> Observable<Descriptor> { return descriptorWithIdentifier(identifier) .flatMap { return self.monitorValueUpdateForDescriptor($0) } } /** Function that triggers read of current value of the `Descriptor` instance. Read is called after subscription to `Observable` is made. - Parameter descriptor: `Descriptor` to read value from - Returns: Observable which emits `Next` with given descriptor when value is ready to read. Immediately after that `.Complete` is emitted. */ public func readValueForDescriptorWithIdentifier(identifier: DescriptorIdentifier) -> Observable<Descriptor> { return descriptorWithIdentifier(identifier) .flatMap { return self.readValueForDescriptor($0) } } }
mit
0a31e9e1fab481b0375235b9564148bc
51.943182
289
0.702511
5.617765
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Controllers/me/user/GsMeInfoViewController.swift
1
7971
// // GsMeInfoViewController.swift // GitHubStar // // Created by midoks on 16/1/15. // Copyright © 2016年 midoks. All rights reserved. // import UIKit import SwiftyJSON class GsMeInfoViewController: GsViewController, UITableViewDataSource, UITableViewDelegate { var _tableView: UITableView? var _tableUserData:JSON? //第一个用户信息cell的高度 let userHeadHeight = 80 override func viewDidLoad() { super.viewDidLoad() self.initData() self.initView() } override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.tabBarController?.tabBar.isHidden = false } func initData(){ let userData = UserModelList.instance().selectCurrentUser() let userInfo = userData["info"] as! String let userJsonData = JSON.parse(userInfo) self._tableUserData = userJsonData } func initView(){ self.title = "个人信息" self.view.backgroundColor = UIColor.white _tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.grouped) _tableView?.dataSource = self _tableView?.delegate = self self.view.addSubview(_tableView!) } //Mark: - UITableViewDataSource - private func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 5 } return 5 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 && indexPath.row == 0 { return CGFloat(userHeadHeight) } return 44 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) cell.textLabel?.text = "text" if indexPath.section == 0 { if indexPath.row == 0 { cell.textLabel?.text = "头像" let avatar_url = self._tableUserData?["avatar_url"].stringValue let data:NSData? = MDCacheImageCenter.readCacheFromUrl(url: avatar_url!) let setting_myqr:UIImage? if data == nil { setting_myqr = UIImage(named: "avatar_default") }else{ setting_myqr = UIImage(data: data! as Data) } let setting_myQrView = UIImageView(image: setting_myqr) setting_myQrView.layer.cornerRadius = 5 setting_myQrView.frame = CGRect(x: self.view.frame.size.width - 50 - 30, y: (CGFloat(userHeadHeight) - 50)/2, width: 50, height: 50) cell.addSubview(setting_myQrView) cell.accessoryType = .disclosureIndicator } else if indexPath.row == 1 { cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: nil) cell.textLabel?.text = "名字" cell.detailTextLabel?.text = self._tableUserData?["name"].stringValue cell.accessoryType = .disclosureIndicator } else if indexPath.row == 2 { cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: nil) cell.textLabel?.text = "登录名" cell.detailTextLabel?.text = self._tableUserData?["login"].stringValue //cell.accessoryType = .DisclosureIndicator } else if indexPath.row == 3 { cell.textLabel?.text = "我的二维码" let setting_myQR = UIImage(named: "setting_myQR") let setting_myQrView = UIImageView(image: setting_myQR) setting_myQrView.frame = CGRect(x: self.view.frame.size.width - setting_myQR!.size.width - 30, y: (CGFloat(44) - setting_myQR!.size.height)/2, width: setting_myQR!.size.width, height:setting_myQR!.size.height) cell.addSubview(setting_myQrView) cell.accessoryType = .disclosureIndicator } else { cell.textLabel?.text = "愿意接受工作" let touchID = UISwitch(frame: CGRect(x: self.view.frame.size.width-55, y: fabs(cell.frame.size.height-50), width: 50, height: 50)) cell.addSubview(touchID) let hireable = self._tableUserData?["hireable"].stringValue if hireable == "true" { touchID.isOn = true } else { touchID.isOn = false } } } else if indexPath.section == 1{ cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: nil) if indexPath.row == 0 { cell.textLabel?.text = "公司" let v = self._tableUserData?["company"].stringValue if v == "" { cell.detailTextLabel?.text = "无" }else{ cell.detailTextLabel?.text = v } cell.accessoryType = .disclosureIndicator } else if indexPath.row == 1 { cell.textLabel?.text = "地址" let v = self._tableUserData?["location"].stringValue if v == "" { cell.detailTextLabel?.text = "无" }else{ cell.detailTextLabel?.text = v } cell.accessoryType = .disclosureIndicator } else if indexPath.row == 2 { cell.textLabel?.text = "邮件" let v = self._tableUserData?["email"].stringValue if v == "" { cell.detailTextLabel?.text = "无" }else{ cell.detailTextLabel?.text = v } cell.accessoryType = .disclosureIndicator } else if indexPath.row == 3 { cell.textLabel?.text = "博客" let v = self._tableUserData?["blog"].stringValue if v == "" { cell.detailTextLabel?.text = "无" }else{ cell.detailTextLabel?.text = v } cell.accessoryType = .disclosureIndicator } else if indexPath.row == 4 { cell.textLabel?.text = "加入时间" let v = self._tableUserData?["created_at"].stringValue if v == "" { cell.detailTextLabel?.text = "无" }else{ cell.detailTextLabel?.text = gitTime(time: v!) } } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) if indexPath.section == 0 { if indexPath.row == 3 { let qrcode = GsMeQrcodeViewController() self.push(v: qrcode) } } else { } } }
apache-2.0
a4d6d72ada355d32e2ffd7bbfeae0f0a
34.61086
149
0.494536
5.40151
false
false
false
false
Djecksan/MobiTask
MobiTask/Controllers/MainViewController/MainViewController+Menu.swift
1
1161
// // MainViewController+Menu.swift // MobiTask // // Created by Evgenyi Tyulenev on 02.08.15. // Copyright (c) 2015 VoltMobi. All rights reserved. // import UIKit extension MainViewController:Menu { @IBAction func toggleMenu(sender:AnyObject?) { let screenCenter = CGRectGetHeight(self.view.bounds) / 2 let heightInfoBlock = CGRectGetHeight(infoBlock.frame) if topCurrencyLabelConstraint.constant == 0 { topCurrencyLabelConstraint.constant = screenCenter - ((heightInfoBlock / 2) + 20) topRatesConstraint.constant = -(CGRectGetHeight(self.view.bounds) - (heightInfoBlock + 20)) bottomRatesConstraint.constant = 0 } else { topCurrencyLabelConstraint.constant = 0 topRatesConstraint.constant = 0 } UIView.animateWithDuration(0.8, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.2, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.view.layoutIfNeeded() }) { (finish) -> Void in self.updateViewConstraints() } } }
mit
298a7211e4cfcbd5939f00f9a65346be
35.28125
184
0.641688
4.535156
false
false
false
false
kesun421/firefox-ios
Shared/Extensions/NSURLExtensions.swift
1
19064
/* 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 private struct ETLDEntry: CustomStringConvertible { let entry: String var isNormal: Bool { return isWild || !isException } var isWild: Bool = false var isException: Bool = false init(entry: String) { self.entry = entry self.isWild = entry.hasPrefix("*") self.isException = entry.hasPrefix("!") } fileprivate var description: String { return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }" } } private typealias TLDEntryMap = [String: ETLDEntry] private func loadEntriesFromDisk() -> TLDEntryMap? { if let data = String.contentsOfFileWithResourceName("effective_tld_names", ofType: "dat", fromBundle: Bundle(identifier: "org.mozilla.Shared")!, encoding: String.Encoding.utf8, error: nil) { let lines = data.components(separatedBy: "\n") let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" } var entries = TLDEntryMap() for line in trimmedLines { let entry = ETLDEntry(entry: line) let key: String if entry.isWild { // Trim off the '*.' part of the line key = line.substring(from: line.characters.index(line.startIndex, offsetBy: 2)) } else if entry.isException { // Trim off the '!' part of the line key = line.substring(from: line.characters.index(line.startIndex, offsetBy: 1)) } else { key = line } entries[key] = entry } return entries } return nil } private var etldEntries: TLDEntryMap? = { return loadEntriesFromDisk() }() // MARK: - Local Resource URL Extensions extension URL { public func allocatedFileSize() -> Int64 { // First try to get the total allocated size and in failing that, get the file allocated size return getResourceLongLongForKey(URLResourceKey.totalFileAllocatedSizeKey.rawValue) ?? getResourceLongLongForKey(URLResourceKey.fileAllocatedSizeKey.rawValue) ?? 0 } public func getResourceValueForKey(_ key: String) -> Any? { let resourceKey = URLResourceKey(key) let keySet = Set<URLResourceKey>([resourceKey]) var val: Any? do { let values = try resourceValues(forKeys: keySet) val = values.allValues[resourceKey] } catch _ { return nil } return val } public func getResourceLongLongForKey(_ key: String) -> Int64? { return (getResourceValueForKey(key) as? NSNumber)?.int64Value } public func getResourceBoolForKey(_ key: String) -> Bool? { return getResourceValueForKey(key) as? Bool } public var isRegularFile: Bool { return getResourceBoolForKey(URLResourceKey.isRegularFileKey.rawValue) ?? false } public func lastComponentIsPrefixedBy(_ prefix: String) -> Bool { return (pathComponents.last?.hasPrefix(prefix) ?? false) } } // The list of permanent URI schemes has been taken from http://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml private let permanentURISchemes = ["aaa", "aaas", "about", "acap", "acct", "cap", "cid", "coap", "coaps", "crid", "data", "dav", "dict", "dns", "example", "file", "ftp", "geo", "go", "gopher", "h323", "http", "https", "iax", "icap", "im", "imap", "info", "ipp", "ipps", "iris", "iris.beep", "iris.lwz", "iris.xpc", "iris.xpcs", "jabber", "ldap", "mailto", "mid", "msrp", "msrps", "mtqp", "mupdate", "news", "nfs", "ni", "nih", "nntp", "opaquelocktoken", "pkcs11", "pop", "pres", "reload", "rtsp", "rtsps", "rtspu", "service", "session", "shttp", "sieve", "sip", "sips", "sms", "snmp", "soap.beep", "soap.beeps", "stun", "stuns", "tag", "tel", "telnet", "tftp", "thismessage", "tip", "tn3270", "turn", "turns", "tv", "urn", "vemmi", "vnc", "ws", "wss", "xcon", "xcon-userid", "xmlrpc.beep", "xmlrpc.beeps", "xmpp", "z39.50r", "z39.50s"] extension URL { public func withQueryParams(_ params: [URLQueryItem]) -> URL { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! var items = (components.queryItems ?? []) for param in params { items.append(param) } components.queryItems = items return components.url! } public func withQueryParam(_ name: String, value: String) -> URL { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! let item = URLQueryItem(name: name, value: value) components.queryItems = (components.queryItems ?? []) + [item] return components.url! } public func getQuery() -> [String: String] { var results = [String: String]() let keyValues = self.query?.components(separatedBy: "&") if keyValues?.count ?? 0 > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results[kv[0]] = kv[1] } } } return results } public var hostPort: String? { if let host = self.host { if let port = (self as NSURL).port?.int32Value { return "\(host):\(port)" } return host } return nil } public var origin: String? { guard isWebPage(includeDataURIs: false), let hostPort = self.hostPort, let scheme = scheme else { return nil } return "\(scheme)://\(hostPort)" } /** * Returns the second level domain (SLD) of a url. It removes any subdomain/TLD * * E.g., https://m.foo.com/bar/baz?noo=abc#123 => foo **/ public var hostSLD: String { guard let publicSuffix = self.publicSuffix, let baseDomain = self.baseDomain else { return self.normalizedHost ?? self.absoluteString } return baseDomain.replacingOccurrences(of: ".\(publicSuffix)", with: "") } public var normalizedHostAndPath: String? { if let normalizedHost = self.normalizedHost { return normalizedHost + self.path } return nil } public var absoluteDisplayString: String { var urlString = self.absoluteString // For http URLs, get rid of the trailing slash if the path is empty or '/' if (self.scheme == "http" || self.scheme == "https") && (self.path == "/") && urlString.endsWith("/") { urlString = urlString.substring(to: urlString.characters.index(urlString.endIndex, offsetBy: -1)) } // If it's basic http, strip out the string but leave anything else in if urlString.hasPrefix("http://") { return urlString.substring(from: urlString.characters.index(urlString.startIndex, offsetBy: 7)) } else { return urlString } } /// String suitable for displaying outside of the app, for example in notifications, were Data Detectors will /// linkify the text and make it into a openable-in-Safari link. public var absoluteDisplayExternalString: String { return self.absoluteDisplayString.replacingOccurrences(of: ".", with: "\u{2024}") } public var displayURL: URL? { if self.isReaderModeURL { return self.decodeReaderModeURL?.havingRemovedAuthorisationComponents() } if self.isErrorPageURL { if let decodedURL = self.originalURLFromErrorURL { return decodedURL.displayURL } else { return nil } } if !self.isAboutURL { return self.havingRemovedAuthorisationComponents() } return nil } /** Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc). :returns: The base domain string for the given host name. */ public var baseDomain: String? { guard !isIPv6, let host = host else { return nil } // If this is just a hostname and not a FQDN, use the entire hostname. if !host.contains(".") { return host } return publicSuffixFromHost(host, withAdditionalParts: 1) } /** * Returns just the domain, but with the same scheme, and a trailing '/'. * * E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/ * * Any failure? Return this URL. */ public var domainURL: URL { if let normalized = self.normalizedHost { // Use NSURLComponents instead of NSURL since the former correctly preserves // brackets for IPv6 hosts, whereas the latter escapes them. var components = URLComponents() components.scheme = self.scheme components.host = normalized components.path = "/" return components.url ?? self } return self } public var normalizedHost: String? { // Use components.host instead of self.host since the former correctly preserves // brackets for IPv6 hosts, whereas the latter strips them. guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), var host = components.host, host != "" else { return nil } if let range = host.range(of: "^(www|mobile|m)\\.", options: .regularExpression) { host.replaceSubrange(range, with: "") } return host } /** Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/. For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk. :returns: The public suffix for within the given hostname. */ public var publicSuffix: String? { if let host = self.host { return publicSuffixFromHost(host, withAdditionalParts: 0) } else { return nil } } public func isWebPage(includeDataURIs: Bool = true) -> Bool { let schemes = includeDataURIs ? ["http", "https", "data"] : ["http", "https"] if let scheme = scheme, schemes.contains(scheme) { return true } return false } // This helps find local urls that we do not want to show loading bars on. // These utility pages should be invisible to the user public var isLocalUtility: Bool { guard self.isLocal else { return false } let utilityURLs = ["/errors", "/about/sessionrestore", "/about/home", "/reader-mode"] return utilityURLs.contains { self.path.startsWith($0) } } public var isLocal: Bool { guard isWebPage(includeDataURIs: false) else { return false } // iOS forwards hostless URLs (e.g., http://:6571) to localhost. guard let host = host, !host.isEmpty else { return true } return host.lowercased() == "localhost" || host == "127.0.0.1" } public var isIPv6: Bool { return host?.contains(":") ?? false } /** Returns whether the URL's scheme is one of those listed on the official list of URI schemes. This only accepts permanent schemes: historical and provisional schemes are not accepted. */ public var schemeIsValid: Bool { guard let scheme = scheme else { return false } return permanentURISchemes.contains(scheme.lowercased()) } public func havingRemovedAuthorisationComponents() -> URL { guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: false) else { return self } urlComponents.user = nil urlComponents.password = nil if let url = urlComponents.url { return url } return self } } // Extensions to deal with ReaderMode URLs extension URL { public var isReaderModeURL: Bool { let scheme = self.scheme, host = self.host, path = self.path return scheme == "http" && host == "localhost" && path == "/reader-mode/page" } public var decodeReaderModeURL: URL? { if self.isReaderModeURL { if let components = URLComponents(url: self, resolvingAgainstBaseURL: false), let queryItems = components.queryItems, queryItems.count == 1 { if let queryItem = queryItems.first, let value = queryItem.value { return URL(string: value) } } } return nil } public func encodeReaderModeURL(_ baseReaderModeURL: String) -> URL? { if let encodedURL = absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) { if let aboutReaderURL = URL(string: "\(baseReaderModeURL)?url=\(encodedURL)") { return aboutReaderURL } } return nil } } // Helpers to deal with ErrorPage URLs extension URL { public var isErrorPageURL: Bool { if let host = self.host { return self.scheme == "http" && host == "localhost" && path == "/errors/error.html" } return false } public var originalURLFromErrorURL: URL? { let components = URLComponents(url: self, resolvingAgainstBaseURL: false) if let queryURL = components?.queryItems?.find({ $0.name == "url" })?.value { return URL(string: queryURL) } return nil } } // Helpers to deal with About URLs extension URL { public var isAboutHomeURL: Bool { if let urlString = self.getQuery()["url"]?.unescape(), isErrorPageURL { let url = URL(string: urlString) ?? self return url.aboutComponent == "home" } return self.aboutComponent == "home" } public var isAboutURL: Bool { return self.aboutComponent != nil } /// If the URI is an about: URI, return the path after "about/" in the URI. /// For example, return "home" for "http://localhost:1234/about/home/#panel=0". public var aboutComponent: String? { let aboutPath = "/about/" guard let scheme = self.scheme, let host = self.host else { return nil } if scheme == "http" && host == "localhost" && path.startsWith(aboutPath) { return path.substring(from: aboutPath.endIndex) } return nil } } //MARK: Private Helpers private extension URL { func publicSuffixFromHost( _ host: String, withAdditionalParts additionalPartCount: Int) -> String? { if host.isEmpty { return nil } // Check edge case where the host is either a single or double '.'. if host.isEmpty || NSString(string: host).lastPathComponent == "." { return "" } /** * The following algorithm breaks apart the domain and checks each sub domain against the effective TLD * entries from the effective_tld_names.dat file. It works like this: * * Example Domain: test.bbc.co.uk * TLD Entry: bbc * * 1. Start off by checking the current domain (test.bbc.co.uk) * 2. Also store the domain after the next dot (bbc.co.uk) * 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks: * i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches * since it satisfies the wildcard requirement. * ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then * currentDomain is a valid TLD * iii. If the entry we matched is an exception case, then the base domain is the part after the next dot * * On the next run through the loop, we set the new domain to check as the part after the next dot, * update the next dot reference to be the string after the new next dot, and check the TLD entries again. * If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the * top domain level so we use it by default. */ let tokens = host.components(separatedBy: ".") let tokenCount = tokens.count var suffix: String? var previousDomain: String? = nil var currentDomain: String = host for offset in 0..<tokenCount { // Store the offset for use outside of this scope so we can add additional parts if needed let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joined(separator: ".") : nil if let entry = etldEntries?[currentDomain] { if entry.isWild && (previousDomain != nil) { suffix = previousDomain break } else if entry.isNormal || (nextDot == nil) { suffix = currentDomain break } else if entry.isException { suffix = nextDot break } } previousDomain = currentDomain if let nextDot = nextDot { currentDomain = nextDot } else { break } } var baseDomain: String? if additionalPartCount > 0 { if let suffix = suffix { // Take out the public suffixed and add in the additional parts we want. let literalFromEnd: NSString.CompareOptions = [NSString.CompareOptions.literal, // Match the string exactly. NSString.CompareOptions.backwards, // Search from the end. NSString.CompareOptions.anchored] // Stick to the end. let suffixlessHost = host.replacingOccurrences(of: suffix, with: "", options: literalFromEnd, range: nil) let suffixlessTokens = suffixlessHost.components(separatedBy: ".").filter { $0 != "" } let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount) let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count] let partsString = additionalParts.joined(separator: ".") baseDomain = [partsString, suffix].joined(separator: ".") } else { return nil } } else { baseDomain = suffix } return baseDomain } }
mpl-2.0
4a85bae4d1e95c4608c82dc2ea95a6d3
37.281124
835
0.596779
4.459415
false
false
false
false
tardieu/swift
test/multifile/constant-struct-with-padding/Other.swift
27
130
// RUN: true struct t { var a = false // (or e.g. var a: Int32 = 0) var b = 0.0 // (or e.g. var b: Int64 = 0) } var g = t()
apache-2.0
6f31b1dabaac68ebb9abe58be0bb5fc7
15.25
45
0.476923
2.131148
false
false
false
false
firebase/SwiftLint
Source/SwiftLintFramework/Reporters/CheckstyleReporter.swift
2
1850
// // CheckstyleReporter.swift // SwiftLint // // Created by JP Simard on 12/25/15. // Copyright © 2015 Realm. All rights reserved. // import Foundation public struct CheckstyleReporter: Reporter { public static let identifier = "checkstyle" public static let isRealtime = false public var description: String { return "Reports violations as Checkstyle XML." } public static func generateReport(_ violations: [StyleViolation]) -> String { return [ "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<checkstyle version=\"4.3\">", violations .group(by: { ($0.location.file ?? "<nopath>").escapedForXML() }) .sorted(by: { $0.key < $1.key }) .map(generateForViolationFile).joined(), "\n</checkstyle>" ].joined() } private static func generateForViolationFile(_ file: String, violations: [StyleViolation]) -> String { return [ "\n\t<file name=\"", file, "\">\n", violations.map(generateForSingleViolation).joined(), "\t</file>" ].joined() } private static func generateForSingleViolation(_ violation: StyleViolation) -> String { let line: Int = violation.location.line ?? 0 let col: Int = violation.location.character ?? 0 let severity: String = violation.severity.rawValue let reason: String = violation.reason.escapedForXML() let identifier: String = violation.ruleDescription.identifier let source: String = "swiftlint.rules.\(identifier)".escapedForXML() return [ "\t\t<error line=\"\(line)\" ", "column=\"\(col)\" ", "severity=\"", severity, "\" ", "message=\"", reason, "\" ", "source=\"\(source)\"/>\n" ].joined() } }
mit
569756cbd8dbea94cd69102028e88d88
33.886792
106
0.576528
4.391924
false
false
false
false
wujianguo/GitHubKit
Sources/AuthorizationRequest.swift
1
14982
// // AuthorizationRequest.swift // GitHubKit // // Created by wujianguo on 16/7/26. // // import Foundation import Alamofire import ObjectMapper public typealias AuthorizationCompletion = (access_token: String?, token_type: String?) -> Void public let GitHubAuthorizationNotificationName = "GitHubAuthorizationNotificationName" public let GitHubCurrentUserInfoNotificationName = "GitHubCurrentUserInfoNotificationName" public func login() { if GitHubAuthorization.sharedInstance.access_token == nil { GitHubAuthorization.sharedInstance.authorize() } } public var currentUser: User? public class GitHubAuthorization { static let sharedInstance = GitHubAuthorization() public class func config(access_token: String?, token_type: String? = "bearer", performAuthorizationRequire: ((completion: AuthorizationCompletion) -> Void)) { if let type = token_type { sharedInstance.token_type = type } if let token = access_token { sharedInstance.access_token = token } sharedInstance.performAuthorizationRequire = performAuthorizationRequire } private init() { } let queue = dispatch_queue_create("GitHubAuthorization", DISPATCH_QUEUE_SERIAL) var access_token: String? { didSet { updateCurrentUser() } } var token_type = "bearer" var performAuthorizationRequire: ((completion: AuthorizationCompletion) -> Void)? var authorizing: Bool = false var validAuthorized: Bool { return access_token != nil } func authorize() { dispatch_async(queue) { guard !self.validAuthorized && !self.authorizing else { return } self.authorizing = true self.performAuthorizationRequire? { (token, type) in dispatch_async(self.queue) { if let t = type { self.token_type = t } self.access_token = token self.authorizing = false NSNotificationCenter.defaultCenter().postNotificationName(GitHubAuthorizationNotificationName, object: nil, userInfo: nil) } } } } func updateCurrentUser() { guard access_token != nil else { currentUser = nil return } currentUserRequest().responseObject { (response: Response<User, NSError>) in currentUser = response.result.value NSNotificationCenter.defaultCenter().postNotificationName(GitHubCurrentUserInfoNotificationName, object: nil, userInfo: nil) } } } public class AuthorizationRequest { public let url: String let eTag: String? let lastModified: NSDate? let loginRequired: Bool var additionalHeaders: [String: String] = [:] var method: Alamofire.Method = .GET public init(url: String, eTag: String? = nil, lastModified: NSDate? = nil, loginRequired: Bool = false, method: Alamofire.Method = .GET, additionalHeaders: [String: String] = [:]) { self.url = url self.eTag = eTag self.lastModified = lastModified self.loginRequired = loginRequired self.additionalHeaders = additionalHeaders self.method = method } var cancelled: Bool = false var req: Request? public func cancel() { cancelled = true req?.cancel() } public func responseObject<T: GitHubObject>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, mapToObject object: T? = nil, context: MapContext? = nil, completionHandler: Response<T, NSError> -> Void) { let completionBlock: Response<T, NSError> -> Void = { (response) in if response.result.isSuccess, let ret = response.result.value { if let e = ret.eTag { if self.eTag == e { self.responseFailure(queue, failureReason: "Not Modified", code: 304, completionHandler: completionHandler) return } } if let d = ret.lastModified { if self.lastModified == d { self.responseFailure(queue, failureReason: "Not Modified", code: 304, completionHandler: completionHandler) return } } completionHandler(response) } } if loginRequired && !GitHubAuthorization.sharedInstance.validAuthorized { dispatch_async(GitHubAuthorization.sharedInstance.queue) { if !GitHubAuthorization.sharedInstance.validAuthorized { NSNotificationCenter.defaultCenter().addObserverForName(GitHubAuthorizationNotificationName, object: nil, queue: nil) { (notification) in NSNotificationCenter.defaultCenter().removeObserver(self, name: GitHubAuthorizationNotificationName, object: nil) if self.cancelled { self.responseFailure(queue, failureReason: "RequestCancelled", code: AuthorizationRequest.Code.RequestCancelled.rawValue, completionHandler: completionHandler) return } if !GitHubAuthorization.sharedInstance.validAuthorized { self.responseFailure(queue, failureReason: "RequestMissingAccessToken", code: AuthorizationRequest.Code.RequestMissingAccessToken.rawValue, completionHandler: completionHandler) return } self.req = self.request(self.url, eTag: self.eTag, lastModified: self.lastModified) self.req?.responseObject(queue: queue, keyPath: keyPath, mapToObject: object, context: context, completionHandler: completionBlock) } GitHubAuthorization.sharedInstance.authorize() } else { self.req = self.request(self.url, eTag: self.eTag, lastModified: self.lastModified) self.req?.responseObject(queue: queue, keyPath: keyPath, mapToObject: object, context: context, completionHandler: completionBlock) } } return } req = request(url, eTag: eTag, lastModified: lastModified) req?.responseObject(queue: queue, keyPath: keyPath, mapToObject: object, context: context, completionHandler: completionBlock) } public func responseArray<T: Mappable>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: Response<GitHubArray<T>, NSError> -> Void) { let completionBlock: Response<GitHubArray<T>, NSError> -> Void = { (response) in if response.result.isSuccess, let ret = response.result.value { if let e = ret.eTag { if self.eTag == e { self.responseFailure(queue, failureReason: "Not Modified", code: 304, completionHandler: completionHandler) return } } if let d = ret.lastModified { if self.lastModified == d { self.responseFailure(queue, failureReason: "Not Modified", code: 304, completionHandler: completionHandler) return } } completionHandler(response) } } if loginRequired && !GitHubAuthorization.sharedInstance.validAuthorized { dispatch_async(GitHubAuthorization.sharedInstance.queue) { if !GitHubAuthorization.sharedInstance.validAuthorized { NSNotificationCenter.defaultCenter().addObserverForName(GitHubAuthorizationNotificationName, object: nil, queue: nil) { (notification) in NSNotificationCenter.defaultCenter().removeObserver(self, name: GitHubAuthorizationNotificationName, object: nil) if self.cancelled { self.responseFailure(queue, failureReason: "RequestCancelled", code: AuthorizationRequest.Code.RequestCancelled.rawValue, completionHandler: completionHandler) return } if !GitHubAuthorization.sharedInstance.validAuthorized { self.responseFailure(queue, failureReason: "RequestMissingAccessToken", code: AuthorizationRequest.Code.RequestMissingAccessToken.rawValue, completionHandler: completionHandler) return } self.req = self.request(self.url, eTag: self.eTag, lastModified: self.lastModified) self.req?.responseArray(queue: queue, keyPath: keyPath, context: context, completionHandler: completionBlock) } GitHubAuthorization.sharedInstance.authorize() } else { self.req = self.request(self.url, eTag: self.eTag, lastModified: self.lastModified) self.req?.responseArray(queue: queue, keyPath: keyPath, context: context, completionHandler: completionBlock) } } return } req = request(url, eTag: eTag, lastModified: lastModified) req?.responseArray(queue: queue, keyPath: keyPath, context: context, completionHandler: completionBlock) } public func responseBoolen(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, completionHandler: Response<Bool, NSError> -> Void) { let completionBlock: ((NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) = { (request, response, data, error) in if let status = response?.statusCode { if status == 204 || status == 404 { let result = Result<Bool, NSError>.Success(status == 204) let response = Response( request: request, response: response, data: data, result: result ) completionHandler(response) return } let failureReason = NSHTTPURLResponse.localizedStringForStatusCode(status) self.responseFailure(queue, failureReason: failureReason, code: status, completionHandler: completionHandler) return } self.responseFailureError(queue, error: error!, completionHandler: completionHandler) } if loginRequired && !GitHubAuthorization.sharedInstance.validAuthorized { dispatch_async(GitHubAuthorization.sharedInstance.queue) { if !GitHubAuthorization.sharedInstance.validAuthorized { NSNotificationCenter.defaultCenter().addObserverForName(GitHubAuthorizationNotificationName, object: nil, queue: nil) { (notification) in NSNotificationCenter.defaultCenter().removeObserver(self, name: GitHubAuthorizationNotificationName, object: nil) if self.cancelled { self.responseFailure(queue, failureReason: "RequestCancelled", code: AuthorizationRequest.Code.RequestCancelled.rawValue, completionHandler: completionHandler) return } if !GitHubAuthorization.sharedInstance.validAuthorized { self.responseFailure(queue, failureReason: "RequestMissingAccessToken", code: AuthorizationRequest.Code.RequestMissingAccessToken.rawValue, completionHandler: completionHandler) return } self.req = self.request(self.url, eTag: self.eTag, lastModified: self.lastModified) self.req?.response(queue: queue, completionHandler: completionBlock) } GitHubAuthorization.sharedInstance.authorize() } else { self.req = self.request(self.url, eTag: self.eTag, lastModified: self.lastModified) self.req?.response(queue: queue, completionHandler: completionBlock) } } return } req = request(url, eTag: eTag, lastModified: lastModified) req?.response(queue: queue, completionHandler: completionBlock) } public static let Domain = "com.githubkit.error" public enum Code: Int { case RequestCancelled = -7000 case RequestMissingAccessToken = -7001 } func responseFailure<T> (queue: dispatch_queue_t? = nil, failureReason: String, code: Int, completionHandler: Response<T, NSError> -> Void) { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: Error.Domain, code: code, userInfo: userInfo) let result = Result<T, NSError>.Failure(error) let response = Response( request: req?.request, response: nil, data: nil, result: result ) if let q = queue { dispatch_async(q) { completionHandler(response) } } else { dispatch_async(dispatch_get_main_queue()) { completionHandler(response) } } } func responseFailureError<T> (queue: dispatch_queue_t? = nil, error: NSError, completionHandler: Response<T, NSError> -> Void) { let result = Result<T, NSError>.Failure(error) let response = Response( request: req?.request, response: nil, data: nil, result: result ) if let q = queue { dispatch_async(q) { completionHandler(response) } } else { dispatch_async(dispatch_get_main_queue()) { completionHandler(response) } } } func request(url: String, eTag: String? = nil, lastModified: NSDate? = nil) -> Request { var headers = [String: String]() if let token = GitHubAuthorization.sharedInstance.access_token { headers["Authorization"] = "token \(token)" } if let e = eTag { headers["If-None-Match"] = e } else if let d = lastModified { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEEE, dd LLL yyyy hh:mm:ss zzz" headers["If-Modified-Since"] = dateFormatter.stringFromDate(d) } for header in additionalHeaders { headers[header.0] = header.1 } if headers.count > 0 { return Alamofire.request(method, url, headers: headers) } else { return Alamofire.request(method, url) } } }
mit
68d21c9625ba9bd6c36840620836f970
45.676012
218
0.595648
5.44602
false
false
false
false
alblue/swift-corelibs-foundation
Foundation/NSURL.swift
1
60371
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif #if os(macOS) || os(iOS) internal let kCFURLPOSIXPathStyle = CFURLPathStyle.cfurlposixPathStyle internal let kCFURLWindowsPathStyle = CFURLPathStyle.cfurlWindowsPathStyle #endif private func _standardizedPath(_ path: String) -> String { if !path.absolutePath { return path._nsObject.standardizingPath } return path } internal func _pathComponents(_ path: String?) -> [String]? { guard let p = path else { return nil } var result = [String]() if p.length == 0 { return result } else { let characterView = p var curPos = characterView.startIndex let endPos = characterView.endIndex if characterView[curPos] == "/" { result.append("/") } while curPos < endPos { while curPos < endPos && characterView[curPos] == "/" { curPos = characterView.index(after: curPos) } if curPos == endPos { break } var curEnd = curPos while curEnd < endPos && characterView[curEnd] != "/" { curEnd = characterView.index(after: curEnd) } result.append(String(characterView[curPos ..< curEnd])) curPos = curEnd } } if p.length > 1 && p.hasSuffix("/") { result.append("/") } return result } public struct URLResourceKey : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public init(_ rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return rawValue.hashValue } public static func ==(lhs: URLResourceKey, rhs: URLResourceKey) -> Bool { return lhs.rawValue == rhs.rawValue } } extension URLResourceKey { public static let keysOfUnsetValuesKey = URLResourceKey(rawValue: "NSURLKeysOfUnsetValuesKey") public static let nameKey = URLResourceKey(rawValue: "NSURLNameKey") public static let localizedNameKey = URLResourceKey(rawValue: "NSURLLocalizedNameKey") public static let isRegularFileKey = URLResourceKey(rawValue: "NSURLIsRegularFileKey") public static let isDirectoryKey = URLResourceKey(rawValue: "NSURLIsDirectoryKey") public static let isSymbolicLinkKey = URLResourceKey(rawValue: "NSURLIsSymbolicLinkKey") public static let isVolumeKey = URLResourceKey(rawValue: "NSURLIsVolumeKey") public static let isPackageKey = URLResourceKey(rawValue: "NSURLIsPackageKey") public static let isApplicationKey = URLResourceKey(rawValue: "NSURLIsApplicationKey") public static let applicationIsScriptableKey = URLResourceKey(rawValue: "NSURLApplicationIsScriptableKey") public static let isSystemImmutableKey = URLResourceKey(rawValue: "NSURLIsSystemImmutableKey") public static let isUserImmutableKey = URLResourceKey(rawValue: "NSURLIsUserImmutableKey") public static let isHiddenKey = URLResourceKey(rawValue: "NSURLIsHiddenKey") public static let hasHiddenExtensionKey = URLResourceKey(rawValue: "NSURLHasHiddenExtensionKey") public static let creationDateKey = URLResourceKey(rawValue: "NSURLCreationDateKey") public static let contentAccessDateKey = URLResourceKey(rawValue: "NSURLContentAccessDateKey") public static let contentModificationDateKey = URLResourceKey(rawValue: "NSURLContentModificationDateKey") public static let attributeModificationDateKey = URLResourceKey(rawValue: "NSURLAttributeModificationDateKey") public static let linkCountKey = URLResourceKey(rawValue: "NSURLLinkCountKey") public static let parentDirectoryURLKey = URLResourceKey(rawValue: "NSURLParentDirectoryURLKey") public static let volumeURLKey = URLResourceKey(rawValue: "NSURLVolumeURLKey") public static let typeIdentifierKey = URLResourceKey(rawValue: "NSURLTypeIdentifierKey") public static let localizedTypeDescriptionKey = URLResourceKey(rawValue: "NSURLLocalizedTypeDescriptionKey") public static let labelNumberKey = URLResourceKey(rawValue: "NSURLLabelNumberKey") public static let labelColorKey = URLResourceKey(rawValue: "NSURLLabelColorKey") public static let localizedLabelKey = URLResourceKey(rawValue: "NSURLLocalizedLabelKey") public static let effectiveIconKey = URLResourceKey(rawValue: "NSURLEffectiveIconKey") public static let customIconKey = URLResourceKey(rawValue: "NSURLCustomIconKey") public static let fileResourceIdentifierKey = URLResourceKey(rawValue: "NSURLFileResourceIdentifierKey") public static let volumeIdentifierKey = URLResourceKey(rawValue: "NSURLVolumeIdentifierKey") public static let preferredIOBlockSizeKey = URLResourceKey(rawValue: "NSURLPreferredIOBlockSizeKey") public static let isReadableKey = URLResourceKey(rawValue: "NSURLIsReadableKey") public static let isWritableKey = URLResourceKey(rawValue: "NSURLIsWritableKey") public static let isExecutableKey = URLResourceKey(rawValue: "NSURLIsExecutableKey") public static let fileSecurityKey = URLResourceKey(rawValue: "NSURLFileSecurityKey") public static let isExcludedFromBackupKey = URLResourceKey(rawValue: "NSURLIsExcludedFromBackupKey") public static let tagNamesKey = URLResourceKey(rawValue: "NSURLTagNamesKey") public static let pathKey = URLResourceKey(rawValue: "NSURLPathKey") public static let canonicalPathKey = URLResourceKey(rawValue: "NSURLCanonicalPathKey") public static let isMountTriggerKey = URLResourceKey(rawValue: "NSURLIsMountTriggerKey") public static let generationIdentifierKey = URLResourceKey(rawValue: "NSURLGenerationIdentifierKey") public static let documentIdentifierKey = URLResourceKey(rawValue: "NSURLDocumentIdentifierKey") public static let addedToDirectoryDateKey = URLResourceKey(rawValue: "NSURLAddedToDirectoryDateKey") public static let quarantinePropertiesKey = URLResourceKey(rawValue: "NSURLQuarantinePropertiesKey") public static let fileResourceTypeKey = URLResourceKey(rawValue: "NSURLFileResourceTypeKey") public static let thumbnailDictionaryKey = URLResourceKey(rawValue: "NSURLThumbnailDictionaryKey") public static let thumbnailKey = URLResourceKey(rawValue: "NSURLThumbnailKey") public static let fileSizeKey = URLResourceKey(rawValue: "NSURLFileSizeKey") public static let fileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLFileAllocatedSizeKey") public static let totalFileSizeKey = URLResourceKey(rawValue: "NSURLTotalFileSizeKey") public static let totalFileAllocatedSizeKey = URLResourceKey(rawValue: "NSURLTotalFileAllocatedSizeKey") public static let isAliasFileKey = URLResourceKey(rawValue: "NSURLIsAliasFileKey") public static let volumeLocalizedFormatDescriptionKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedFormatDescriptionKey") public static let volumeTotalCapacityKey = URLResourceKey(rawValue: "NSURLVolumeTotalCapacityKey") public static let volumeAvailableCapacityKey = URLResourceKey(rawValue: "NSURLVolumeAvailableCapacityKey") public static let volumeResourceCountKey = URLResourceKey(rawValue: "NSURLVolumeResourceCountKey") public static let volumeSupportsPersistentIDsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsPersistentIDsKey") public static let volumeSupportsSymbolicLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSymbolicLinksKey") public static let volumeSupportsHardLinksKey = URLResourceKey(rawValue: "NSURLVolumeSupportsHardLinksKey") public static let volumeSupportsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsJournalingKey") public static let volumeIsJournalingKey = URLResourceKey(rawValue: "NSURLVolumeIsJournalingKey") public static let volumeSupportsSparseFilesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSparseFilesKey") public static let volumeSupportsZeroRunsKey = URLResourceKey(rawValue: "NSURLVolumeSupportsZeroRunsKey") public static let volumeSupportsCaseSensitiveNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCaseSensitiveNamesKey") public static let volumeSupportsCasePreservedNamesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCasePreservedNamesKey") public static let volumeSupportsRootDirectoryDatesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRootDirectoryDatesKey") public static let volumeSupportsVolumeSizesKey = URLResourceKey(rawValue: "NSURLVolumeSupportsVolumeSizesKey") public static let volumeSupportsRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsRenamingKey") public static let volumeSupportsAdvisoryFileLockingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsAdvisoryFileLockingKey") public static let volumeSupportsExtendedSecurityKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExtendedSecurityKey") public static let volumeIsBrowsableKey = URLResourceKey(rawValue: "NSURLVolumeIsBrowsableKey") public static let volumeMaximumFileSizeKey = URLResourceKey(rawValue: "NSURLVolumeMaximumFileSizeKey") public static let volumeIsEjectableKey = URLResourceKey(rawValue: "NSURLVolumeIsEjectableKey") public static let volumeIsRemovableKey = URLResourceKey(rawValue: "NSURLVolumeIsRemovableKey") public static let volumeIsInternalKey = URLResourceKey(rawValue: "NSURLVolumeIsInternalKey") public static let volumeIsAutomountedKey = URLResourceKey(rawValue: "NSURLVolumeIsAutomountedKey") public static let volumeIsLocalKey = URLResourceKey(rawValue: "NSURLVolumeIsLocalKey") public static let volumeIsReadOnlyKey = URLResourceKey(rawValue: "NSURLVolumeIsReadOnlyKey") public static let volumeCreationDateKey = URLResourceKey(rawValue: "NSURLVolumeCreationDateKey") public static let volumeURLForRemountingKey = URLResourceKey(rawValue: "NSURLVolumeURLForRemountingKey") public static let volumeUUIDStringKey = URLResourceKey(rawValue: "NSURLVolumeUUIDStringKey") public static let volumeNameKey = URLResourceKey(rawValue: "NSURLVolumeNameKey") public static let volumeLocalizedNameKey = URLResourceKey(rawValue: "NSURLVolumeLocalizedNameKey") public static let volumeIsEncryptedKey = URLResourceKey(rawValue: "NSURLVolumeIsEncryptedKey") public static let volumeIsRootFileSystemKey = URLResourceKey(rawValue: "NSURLVolumeIsRootFileSystemKey") public static let volumeSupportsCompressionKey = URLResourceKey(rawValue: "NSURLVolumeSupportsCompressionKey") public static let volumeSupportsFileCloningKey = URLResourceKey(rawValue: "NSURLVolumeSupportsFileCloningKey") public static let volumeSupportsSwapRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsSwapRenamingKey") public static let volumeSupportsExclusiveRenamingKey = URLResourceKey(rawValue: "NSURLVolumeSupportsExclusiveRenamingKey") public static let isUbiquitousItemKey = URLResourceKey(rawValue: "NSURLIsUbiquitousItemKey") public static let ubiquitousItemHasUnresolvedConflictsKey = URLResourceKey(rawValue: "NSURLUbiquitousItemHasUnresolvedConflictsKey") public static let ubiquitousItemIsDownloadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsDownloadingKey") public static let ubiquitousItemIsUploadedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadedKey") public static let ubiquitousItemIsUploadingKey = URLResourceKey(rawValue: "NSURLUbiquitousItemIsUploadingKey") public static let ubiquitousItemDownloadingStatusKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingStatusKey") public static let ubiquitousItemDownloadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadingErrorKey") public static let ubiquitousItemUploadingErrorKey = URLResourceKey(rawValue: "NSURLUbiquitousItemUploadingErrorKey") public static let ubiquitousItemDownloadRequestedKey = URLResourceKey(rawValue: "NSURLUbiquitousItemDownloadRequestedKey") public static let ubiquitousItemContainerDisplayNameKey = URLResourceKey(rawValue: "NSURLUbiquitousItemContainerDisplayNameKey") } public struct URLFileResourceType : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(rawValue: String) { self.rawValue = rawValue } public init(_ rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return rawValue.hashValue } public static func ==(lhs: URLFileResourceType, rhs: URLFileResourceType) -> Bool { return lhs.rawValue == rhs.rawValue } } extension URLFileResourceType { public static let namedPipe = URLFileResourceType(rawValue: "NSURLFileResourceTypeNamedPipe") public static let characterSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeCharacterSpecial") public static let directory = URLFileResourceType(rawValue: "NSURLFileResourceTypeDirectory") public static let blockSpecial = URLFileResourceType(rawValue: "NSURLFileResourceTypeBlockSpecial") public static let regular = URLFileResourceType(rawValue: "NSURLFileResourceTypeRegular") public static let symbolicLink = URLFileResourceType(rawValue: "NSURLFileResourceTypeSymbolicLink") public static let socket = URLFileResourceType(rawValue: "NSURLFileResourceTypeSocket") public static let unknown = URLFileResourceType(rawValue: "NSURLFileResourceTypeUnknown") } open class NSURL : NSObject, NSSecureCoding, NSCopying { typealias CFType = CFURL internal var _base = _CFInfo(typeID: CFURLGetTypeID()) internal var _flags : UInt32 = 0 internal var _encoding : CFStringEncoding = 0 internal var _string : UnsafeMutablePointer<CFString>? = nil internal var _baseURL : UnsafeMutablePointer<CFURL>? = nil internal var _extra : OpaquePointer? = nil internal var _resourceInfo : OpaquePointer? = nil internal var _range1 = NSRange(location: 0, length: 0) internal var _range2 = NSRange(location: 0, length: 0) internal var _range3 = NSRange(location: 0, length: 0) internal var _range4 = NSRange(location: 0, length: 0) internal var _range5 = NSRange(location: 0, length: 0) internal var _range6 = NSRange(location: 0, length: 0) internal var _range7 = NSRange(location: 0, length: 0) internal var _range8 = NSRange(location: 0, length: 0) internal var _range9 = NSRange(location: 0, length: 0) internal var _cfObject : CFType { if type(of: self) === NSURL.self { return unsafeBitCast(self, to: CFType.self) } else { return CFURLCreateWithString(kCFAllocatorSystemDefault, relativeString._cfObject, self.baseURL?._cfObject) } } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSURL else { return false } return CFEqual(_cfObject, other._cfObject) } open override var description: String { if self.relativeString != self.absoluteString { return "\(self.relativeString) -- \(self.baseURL!)" } else { return self.absoluteString } } deinit { _CFDeinit(self) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } public static var supportsSecureCoding: Bool { return true } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let base = aDecoder.decodeObject(of: NSURL.self, forKey:"NS.base")?._swiftObject let relative = aDecoder.decodeObject(of: NSString.self, forKey:"NS.relative") if relative == nil { return nil } self.init(string: String._unconditionallyBridgeFromObjectiveC(relative!), relativeTo: base) } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.baseURL?._nsObject, forKey:"NS.base") aCoder.encode(self.relativeString._bridgeToObjectiveC(), forKey:"NS.relative") } public init(fileURLWithPath path: String, isDirectory isDir: Bool, relativeTo baseURL: URL?) { super.init() let thePath = _standardizedPath(path) if thePath.length > 0 { _CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir, baseURL?._cfObject) } else if let baseURL = baseURL { _CFURLInitWithFileSystemPathRelativeToBase(_cfObject, baseURL.path._cfObject, kCFURLPOSIXPathStyle, baseURL.hasDirectoryPath, nil) } } public convenience init(fileURLWithPath path: String, relativeTo baseURL: URL?) { let thePath = _standardizedPath(path) var isDir: ObjCBool = false if thePath.hasSuffix("/") { isDir = true } else { let absolutePath: String if let absPath = baseURL?.appendingPathComponent(path).path { absolutePath = absPath } else { absolutePath = path } let _ = FileManager.default.fileExists(atPath: absolutePath, isDirectory: &isDir) } self.init(fileURLWithPath: thePath, isDirectory: isDir.boolValue, relativeTo: baseURL) } public convenience init(fileURLWithPath path: String, isDirectory isDir: Bool) { self.init(fileURLWithPath: path, isDirectory: isDir, relativeTo: nil) } public init(fileURLWithPath path: String) { let thePath: String let pathString = NSString(string: path) if !pathString.isAbsolutePath { thePath = pathString.standardizingPath } else { thePath = path } var isDir: ObjCBool = false if thePath.hasSuffix("/") { isDir = true } else { if !FileManager.default.fileExists(atPath: path, isDirectory: &isDir) { isDir = false } } super.init() _CFURLInitWithFileSystemPathRelativeToBase(_cfObject, thePath._cfObject, kCFURLPOSIXPathStyle, isDir.boolValue, nil) } public convenience init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory isDir: Bool, relativeTo baseURL: URL?) { let pathString = String(cString: path) self.init(fileURLWithPath: pathString, isDirectory: isDir, relativeTo: baseURL) } public convenience init?(string URLString: String) { self.init(string: URLString, relativeTo:nil) } public init?(string URLString: String, relativeTo baseURL: URL?) { super.init() if !_CFURLInitWithURLString(_cfObject, URLString._cfObject, true, baseURL?._cfObject) { return nil } } public init(dataRepresentation data: Data, relativeTo baseURL: URL?) { super.init() // _CFURLInitWithURLString does not fail if checkForLegalCharacters == false data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), false) { _CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject) } else if let str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), false) { _CFURLInitWithURLString(_cfObject, str, false, baseURL?._cfObject) } else { fatalError() } } } public init(absoluteURLWithDataRepresentation data: Data, relativeTo baseURL: URL?) { super.init() data.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Void in if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingUTF8), baseURL?._cfObject) { return } if _CFURLInitAbsoluteURLWithBytes(_cfObject, ptr, data.count, CFStringEncoding(kCFStringEncodingISOLatin1), baseURL?._cfObject) { return } fatalError() } } /* Returns the data representation of the URL's relativeString. If the URL was initialized with -initWithData:relativeTo:, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the relativeString encoded with NSUTF8StringEncoding. */ open var dataRepresentation: Data { let bytesNeeded = CFURLGetBytes(_cfObject, nil, 0) assert(bytesNeeded > 0) let buffer = malloc(bytesNeeded)!.bindMemory(to: UInt8.self, capacity: bytesNeeded) let bytesFilled = CFURLGetBytes(_cfObject, buffer, bytesNeeded) if bytesFilled == bytesNeeded { return Data(bytesNoCopy: buffer, count: bytesNeeded, deallocator: .free) } else { fatalError() } } open var absoluteString: String { if let absURL = CFURLCopyAbsoluteURL(_cfObject) { return CFURLGetString(absURL)._swiftObject } return CFURLGetString(_cfObject)._swiftObject } // The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString open var relativeString: String { return CFURLGetString(_cfObject)._swiftObject } open var baseURL: URL? { return CFURLGetBaseURL(_cfObject)?._swiftObject } // if the receiver is itself absolute, this will return self. open var absoluteURL: URL? { return CFURLCopyAbsoluteURL(_cfObject)?._swiftObject } /* Any URL is composed of these two basic pieces. The full URL would be the concatenation of [myURL scheme], ':', [myURL resourceSpecifier] */ open var scheme: String? { return CFURLCopyScheme(_cfObject)?._swiftObject } internal var _isAbsolute : Bool { return self.baseURL == nil && self.scheme != nil } open var resourceSpecifier: String? { // Note that this does NOT have the same meaning as CFURL's resource specifier, which, for decomposeable URLs is merely that portion of the URL which comes after the path. NSURL means everything after the scheme. if !_isAbsolute { return self.relativeString } else { let cf = _cfObject guard CFURLCanBeDecomposed(cf) else { return CFURLCopyResourceSpecifier(cf)?._swiftObject } guard baseURL == nil else { return CFURLGetString(cf)?._swiftObject } let netLoc = CFURLCopyNetLocation(cf)?._swiftObject let path = CFURLCopyPath(cf)?._swiftObject let theRest = CFURLCopyResourceSpecifier(cf)?._swiftObject if let netLoc = netLoc { let p = path ?? "" let rest = theRest ?? "" return "//\(netLoc)\(p)\(rest)" } else if let path = path { let rest = theRest ?? "" return "\(path)\(rest)" } else { return theRest } } } /* If the URL conforms to rfc 1808 (the most common form of URL), the following accessors will return the various components; otherwise they return nil. The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is @"//". In all cases, they return the component's value after resolving the receiver against its base URL. */ open var host: String? { return CFURLCopyHostName(_cfObject)?._swiftObject } open var port: NSNumber? { let port = CFURLGetPortNumber(_cfObject) if port == -1 { return nil } else { return NSNumber(value: port) } } open var user: String? { return CFURLCopyUserName(_cfObject)?._swiftObject } open var password: String? { let absoluteURL = CFURLCopyAbsoluteURL(_cfObject) #if os(Linux) || os(Android) || CYGWIN let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, kCFURLComponentPassword, nil) #else let passwordRange = CFURLGetByteRangeForComponent(absoluteURL, .password, nil) #endif guard passwordRange.location != kCFNotFound else { return nil } // For historical reasons, the password string should _not_ have its percent escapes removed. let bufSize = CFURLGetBytes(absoluteURL, nil, 0) var buf = [UInt8](repeating: 0, count: bufSize) guard CFURLGetBytes(absoluteURL, &buf, bufSize) >= 0 else { return nil } let passwordBuf = buf[passwordRange.location ..< passwordRange.location+passwordRange.length] return passwordBuf.withUnsafeBufferPointer { ptr in NSString(bytes: ptr.baseAddress!, length: passwordBuf.count, encoding: String.Encoding.utf8.rawValue)?._swiftObject } } open var path: String? { let absURL = CFURLCopyAbsoluteURL(_cfObject) return CFURLCopyFileSystemPath(absURL, kCFURLPOSIXPathStyle)?._swiftObject } open var fragment: String? { return CFURLCopyFragment(_cfObject, nil)?._swiftObject } open var parameterString: String? { return CFURLCopyParameterString(_cfObject, nil)?._swiftObject } open var query: String? { return CFURLCopyQueryString(_cfObject, nil)?._swiftObject } // The same as path if baseURL is nil open var relativePath: String? { return CFURLCopyFileSystemPath(_cfObject, kCFURLPOSIXPathStyle)?._swiftObject } /* Determines if a given URL string's path represents a directory (i.e. the path component in the URL string ends with a '/' character). This does not check the resource the URL refers to. */ open var hasDirectoryPath: Bool { return CFURLHasDirectoryPath(_cfObject) } /* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. */ open func getFileSystemRepresentation(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferLength: Int) -> Bool { return buffer.withMemoryRebound(to: UInt8.self, capacity: maxBufferLength) { CFURLGetFileSystemRepresentation(_cfObject, true, $0, maxBufferLength) } } /* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength: if it needs to store the representation outside of the autorelease context in which the representation is created. */ // Memory leak. See https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/Issues.md open var fileSystemRepresentation: UnsafePointer<Int8> { let bufSize = Int(PATH_MAX + 1) let _fsrBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: bufSize) _fsrBuffer.initialize(repeating: 0, count: bufSize) if getFileSystemRepresentation(_fsrBuffer, maxLength: bufSize) { return UnsafePointer(_fsrBuffer) } // FIXME: This used to return nil, but the corresponding Darwin // implementation is marked as non-nullable. fatalError("URL cannot be expressed in the filesystem representation;" + "use getFileSystemRepresentation to handle this case") } // Whether the scheme is file:; if myURL.isFileURL is true, then myURL.path is suitable for input into FileManager or NSPathUtilities. open var isFileURL: Bool { return _CFURLIsFileURL(_cfObject) } /* A string constant for the "file" URL scheme. If you are using this to compare to a URL's scheme to see if it is a file URL, you should instead use the NSURL fileURL property -- the fileURL property is much faster. */ open var standardized: URL? { guard (path != nil) else { return nil } let URLComponents = NSURLComponents(string: relativeString) guard ((URLComponents != nil) && (URLComponents!.path != nil)) else { return nil } guard (URLComponents!.path!.contains("..") || URLComponents!.path!.contains(".")) else{ return URLComponents!.url(relativeTo: baseURL) } URLComponents!.path! = _pathByRemovingDots(pathComponents!) return URLComponents!.url(relativeTo: baseURL) } /* Returns whether the URL's resource exists and is reachable. This method synchronously checks if the resource's backing store is reachable. Checking reachability is appropriate when making decisions that do not require other immediate operations on the resource, e.g. periodic maintenance of UI state that depends on the existence of a specific document. When performing operations such as opening a file or copying resource properties, it is more efficient to simply try the operation and handle failures. If this method returns NO, the optional error is populated. This method is currently applicable only to URLs for file system resources. For other URL types, NO is returned. Symbol is present in iOS 4, but performs no operation. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future // TODO: should be `checkResourceIsReachableAndReturnError` with autoreleased error parameter. // Currently Autoreleased pointers is not supported on Linux. open func checkResourceIsReachable() throws -> Bool { guard isFileURL, let path = path else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.Code.fileReadUnsupportedScheme.rawValue) } guard FileManager.default.fileExists(atPath: path) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.Code.fileReadNoSuchFile.rawValue, userInfo: [ "NSURL" : self, "NSFilePath" : path]) } return true } /* Returns a file path URL that refers to the same resource as a specified URL. File path URLs use a file system style path. An error will occur if the url parameter is not a file URL. A file reference URL's resource must exist and be reachable to be converted to a file path URL. Symbol is present in iOS 4, but performs no operation. */ open var filePathURL: URL? { guard isFileURL else { return nil } return URL(string: absoluteString) } override open var _cfTypeID: CFTypeID { return CFURLGetTypeID() } open func removeAllCachedResourceValues() { NSUnimplemented() } open func removeCachedResourceValue(forKey key: URLResourceKey) { NSUnimplemented() } open func resourceValues(forKeys keys: [URLResourceKey]) throws -> [URLResourceKey : Any] { NSUnimplemented() } open func setResourceValue(_ value: Any?, forKey key: URLResourceKey) throws { NSUnimplemented() } open func setResourceValues(_ keyedValues: [URLResourceKey : Any]) throws { NSUnimplemented() } open func setTemporaryResourceValue(_ value: Any?, forKey key: URLResourceKey) { NSUnimplemented() } } extension NSCharacterSet { // Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:. // Returns a character set containing the characters allowed in an URL's user subcomponent. open class var urlUserAllowed: CharacterSet { return _CFURLComponentsGetURLUserAllowedCharacterSet()._swiftObject } // Returns a character set containing the characters allowed in an URL's password subcomponent. open class var urlPasswordAllowed: CharacterSet { return _CFURLComponentsGetURLPasswordAllowedCharacterSet()._swiftObject } // Returns a character set containing the characters allowed in an URL's host subcomponent. open class var urlHostAllowed: CharacterSet { return _CFURLComponentsGetURLHostAllowedCharacterSet()._swiftObject } // Returns a character set containing the characters allowed in an URL's path component. ';' is a legal path character, but it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the URLPathAllowedCharacterSet). open class var urlPathAllowed: CharacterSet { return _CFURLComponentsGetURLPathAllowedCharacterSet()._swiftObject } // Returns a character set containing the characters allowed in an URL's query component. open class var urlQueryAllowed: CharacterSet { return _CFURLComponentsGetURLQueryAllowedCharacterSet()._swiftObject } // Returns a character set containing the characters allowed in an URL's fragment component. open class var urlFragmentAllowed: CharacterSet { return _CFURLComponentsGetURLFragmentAllowedCharacterSet()._swiftObject } } extension NSString { // Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored. open func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String? { return _CFStringCreateByAddingPercentEncodingWithAllowedCharacters(kCFAllocatorSystemDefault, self._cfObject, allowedCharacters._cfObject)._swiftObject } // Returns a new string made from the receiver by replacing all percent encoded sequences with the matching UTF-8 characters. open var removingPercentEncoding: String? { return _CFStringCreateByRemovingPercentEncoding(kCFAllocatorSystemDefault, self._cfObject)?._swiftObject } } extension NSURL { /* The following methods work on the path portion of a URL in the same manner that the NSPathUtilities methods on NSString do. */ open class func fileURL(withPathComponents components: [String]) -> URL? { let path = NSString.pathWithComponents(components) if components.last == "/" { return URL(fileURLWithPath: path, isDirectory: true) } else { return URL(fileURLWithPath: path) } } internal func _pathByFixingSlashes(compress : Bool = true, stripTrailing: Bool = true) -> String? { guard let p = path else { return nil } if p == "/" { return p } var result = p if compress { let startPos = result.startIndex var endPos = result.endIndex var curPos = startPos while curPos < endPos { if result[curPos] == "/" { var afterLastSlashPos = curPos while afterLastSlashPos < endPos && result[afterLastSlashPos] == "/" { afterLastSlashPos = result.index(after: afterLastSlashPos) } if afterLastSlashPos != result.index(after: curPos) { result.replaceSubrange(curPos ..< afterLastSlashPos, with: ["/"]) endPos = result.endIndex } curPos = afterLastSlashPos } else { curPos = result.index(after: curPos) } } } if stripTrailing && result.hasSuffix("/") { result.remove(at: result.index(before: result.endIndex)) } return result } open var pathComponents: [String]? { return _pathComponents(path) } open var lastPathComponent: String? { guard let fixedSelf = _pathByFixingSlashes() else { return nil } if fixedSelf.length <= 1 { return fixedSelf } return String(fixedSelf.suffix(from: fixedSelf._startOfLastPathComponent)) } open var pathExtension: String? { guard let fixedSelf = _pathByFixingSlashes() else { return nil } if fixedSelf.length <= 1 { return "" } if let extensionPos = fixedSelf._startOfPathExtension { return String(fixedSelf.suffix(from: extensionPos)) } else { return "" } } open func appendingPathComponent(_ pathComponent: String) -> URL? { var result : URL? = appendingPathComponent(pathComponent, isDirectory: false) if !pathComponent.hasSuffix("/") && isFileURL { if let urlWithoutDirectory = result { var isDir: ObjCBool = false if FileManager.default.fileExists(atPath: urlWithoutDirectory.path, isDirectory: &isDir) && isDir.boolValue { result = self.appendingPathComponent(pathComponent, isDirectory: true) } } } return result } open func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) -> URL? { return CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, _cfObject, pathComponent._cfObject, isDirectory)?._swiftObject } open var deletingLastPathComponent: URL? { return CFURLCreateCopyDeletingLastPathComponent(kCFAllocatorSystemDefault, _cfObject)?._swiftObject } open func appendingPathExtension(_ pathExtension: String) -> URL? { return CFURLCreateCopyAppendingPathExtension(kCFAllocatorSystemDefault, _cfObject, pathExtension._cfObject)?._swiftObject } open var deletingPathExtension: URL? { return CFURLCreateCopyDeletingPathExtension(kCFAllocatorSystemDefault, _cfObject)?._swiftObject } /* The following methods work only on `file:` scheme URLs; for non-`file:` scheme URLs, these methods return the URL unchanged. */ open var standardizingPath: URL? { // Documentation says it should expand initial tilde, but it does't do this on OS X. // In remaining cases it works just like URLByResolvingSymlinksInPath. return resolvingSymlinksInPath } open var resolvingSymlinksInPath: URL? { return _resolveSymlinksInPath(excludeSystemDirs: true) } internal func _resolveSymlinksInPath(excludeSystemDirs: Bool) -> URL? { guard isFileURL else { return URL(string: absoluteString) } guard let selfPath = path else { return URL(string: absoluteString) } let absolutePath: String if selfPath.hasPrefix("/") { absolutePath = selfPath } else { let workingDir = FileManager.default.currentDirectoryPath absolutePath = workingDir._bridgeToObjectiveC().appendingPathComponent(selfPath) } var components = URL(fileURLWithPath: absolutePath).pathComponents guard !components.isEmpty else { return URL(string: absoluteString) } var resolvedPath = components.removeFirst() for component in components { switch component { case "", ".": break case "..": resolvedPath = resolvedPath._bridgeToObjectiveC().deletingLastPathComponent default: resolvedPath = resolvedPath._bridgeToObjectiveC().appendingPathComponent(component) if let destination = FileManager.default._tryToResolveTrailingSymlinkInPath(resolvedPath) { resolvedPath = destination } } } // It might be a responsibility of NSURL(fileURLWithPath:). Check it. var isExistingDirectory: ObjCBool = false let _ = FileManager.default.fileExists(atPath: resolvedPath, isDirectory: &isExistingDirectory) if excludeSystemDirs { resolvedPath = resolvedPath._tryToRemovePathPrefix("/private") ?? resolvedPath } if isExistingDirectory.boolValue && !resolvedPath.hasSuffix("/") { resolvedPath += "/" } return URL(fileURLWithPath: resolvedPath) } fileprivate func _pathByRemovingDots(_ comps: [String]) -> String { var components = comps if(components.last == "/") { components.removeLast() } guard !components.isEmpty else { return self.path! } let isAbsolutePath = components.first == "/" var result : String = components.removeFirst() for component in components { switch component { case ".": break case ".." where isAbsolutePath: result = result._bridgeToObjectiveC().deletingLastPathComponent default: result = result._bridgeToObjectiveC().appendingPathComponent(component) } } if(self.path!.hasSuffix("/")) { result += "/" } return result } } // NSURLQueryItem encapsulates a single query name-value pair. The name and value strings of a query name-value pair are not percent encoded. For use with the NSURLComponents queryItems property. open class NSURLQueryItem : NSObject, NSSecureCoding, NSCopying { public init(name: String, value: String?) { self.name = name self.value = value } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } public static var supportsSecureCoding: Bool { return true } required public init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let encodedName = aDecoder.decodeObject(forKey: "NS.name") as! NSString self.name = encodedName._swiftObject let encodedValue = aDecoder.decodeObject(forKey: "NS.value") as? NSString self.value = encodedValue?._swiftObject } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.name._bridgeToObjectiveC(), forKey: "NS.name") aCoder.encode(self.value?._bridgeToObjectiveC(), forKey: "NS.value") } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSURLQueryItem else { return false } return other === self || (other.name == self.name && other.value == self.value) } open private(set) var name: String open private(set) var value: String? } open class NSURLComponents: NSObject, NSCopying { private let _components : CFURLComponentsRef! deinit { if let component = _components { __CFURLComponentsDeallocate(component) } } open override func copy() -> Any { return copy(with: nil) } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSURLComponents else { return false } return self === other || (scheme == other.scheme && user == other.user && password == other.password && host == other.host && port == other.port && path == other.path && query == other.query && fragment == other.fragment) } open override var hash: Int { var hasher = Hasher() hasher.combine(scheme) hasher.combine(user) hasher.combine(password) hasher.combine(host) hasher.combine(port) hasher.combine(path) hasher.combine(query) hasher.combine(fragment) return hasher.finalize() } open func copy(with zone: NSZone? = nil) -> Any { let copy = NSURLComponents() copy.scheme = self.scheme copy.user = self.user copy.password = self.password copy.host = self.host copy.port = self.port copy.path = self.path copy.query = self.query copy.fragment = self.fragment return copy } // Initialize a NSURLComponents with the components of a URL. If resolvingAgainstBaseURL is YES and url is a relative URL, the components of [url absoluteURL] are used. If the url string from the NSURL is malformed, nil is returned. public init?(url: URL, resolvingAgainstBaseURL resolve: Bool) { _components = _CFURLComponentsCreateWithURL(kCFAllocatorSystemDefault, url._cfObject, resolve) super.init() if _components == nil { return nil } } // Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned. public init?(string URLString: String) { _components = _CFURLComponentsCreateWithString(kCFAllocatorSystemDefault, URLString._cfObject) super.init() if _components == nil { return nil } } public override init() { _components = _CFURLComponentsCreate(kCFAllocatorSystemDefault) } // Returns a URL created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. open var url: URL? { guard let result = _CFURLComponentsCopyURL(_components) else { return nil } return unsafeBitCast(result, to: URL.self) } // Returns a URL created from the NSURLComponents relative to a base URL. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. open func url(relativeTo baseURL: URL?) -> URL? { if let componentString = string { return URL(string: componentString, relativeTo: baseURL) } return nil } // Returns a URL string created from the NSURLComponents. If the NSURLComponents has an authority component (user, password, host or port) and a path component, then the path must either begin with "/" or be an empty string. If the NSURLComponents does not have an authority component (user, password, host or port) and has a path component, the path component must not start with "//". If those requirements are not met, nil is returned. open var string: String? { return _CFURLComponentsCopyString(_components)?._swiftObject } // Warning: IETF STD 66 (rfc3986) says the use of the format "user:password" in the userinfo subcomponent of a URI is deprecated because passing authentication information in clear text has proven to be a security risk. However, there are cases where this practice is still needed, and so the user and password components and methods are provided. // Getting these properties removes any percent encoding these components may have (if the component allows percent encoding). Setting these properties assumes the subcomponent or component string is not percent encoded and will add percent encoding (if the component allows percent encoding). // Attempting to set the scheme with an invalid scheme string will cause an exception. open var scheme: String? { get { return _CFURLComponentsCopyScheme(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetScheme(_components, new?._cfObject) { fatalError() } } } open var user: String? { get { return _CFURLComponentsCopyUser(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetUser(_components, new?._cfObject) { fatalError() } } } open var password: String? { get { return _CFURLComponentsCopyPassword(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPassword(_components, new?._cfObject) { fatalError() } } } open var host: String? { get { return _CFURLComponentsCopyHost(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetHost(_components, new?._cfObject) { fatalError() } } } // Attempting to set a negative port number will cause an exception. open var port: NSNumber? { get { if let result = _CFURLComponentsCopyPort(_components) { return unsafeBitCast(result, to: NSNumber.self) } else { return nil } } set(new) { if !_CFURLComponentsSetPort(_components, new?._cfObject) { fatalError() } } } open var path: String? { get { return _CFURLComponentsCopyPath(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPath(_components, new?._cfObject) { fatalError() } } } open var query: String? { get { return _CFURLComponentsCopyQuery(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetQuery(_components, new?._cfObject) { fatalError() } } } open var fragment: String? { get { return _CFURLComponentsCopyFragment(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetFragment(_components, new?._cfObject) { fatalError() } } } // Getting these properties retains any percent encoding these components may have. Setting these properties assumes the component string is already correctly percent encoded. Attempting to set an incorrectly percent encoded string will cause an exception. Although ';' is a legal path character, it is recommended that it be percent-encoded for best compatibility with NSURL (-stringByAddingPercentEncodingWithAllowedCharacters: will percent-encode any ';' characters if you pass the urlPathAllowed). open var percentEncodedUser: String? { get { return _CFURLComponentsCopyPercentEncodedUser(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedUser(_components, new?._cfObject) { fatalError() } } } open var percentEncodedPassword: String? { get { return _CFURLComponentsCopyPercentEncodedPassword(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedPassword(_components, new?._cfObject) { fatalError() } } } open var percentEncodedHost: String? { get { return _CFURLComponentsCopyPercentEncodedHost(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedHost(_components, new?._cfObject) { fatalError() } } } open var percentEncodedPath: String? { get { return _CFURLComponentsCopyPercentEncodedPath(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedPath(_components, new?._cfObject) { fatalError() } } } open var percentEncodedQuery: String? { get { return _CFURLComponentsCopyPercentEncodedQuery(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedQuery(_components, new?._cfObject) { fatalError() } } } open var percentEncodedFragment: String? { get { return _CFURLComponentsCopyPercentEncodedFragment(_components)?._swiftObject } set(new) { if !_CFURLComponentsSetPercentEncodedFragment(_components, new?._cfObject) { fatalError() } } } /* These properties return the character range of a component in the URL string returned by -[NSURLComponents string]. If the component does not exist in the NSURLComponents object, {NSNotFound, 0} is returned. Note: Zero length components are legal. For example, the URL string "scheme://:@/?#" has a zero length user, password, host, query and fragment; the URL strings "scheme:" and "" both have a zero length path. */ open var rangeOfScheme: NSRange { return NSRange(_CFURLComponentsGetRangeOfScheme(_components)) } open var rangeOfUser: NSRange { return NSRange(_CFURLComponentsGetRangeOfUser(_components)) } open var rangeOfPassword: NSRange { return NSRange(_CFURLComponentsGetRangeOfPassword(_components)) } open var rangeOfHost: NSRange { return NSRange(_CFURLComponentsGetRangeOfHost(_components)) } open var rangeOfPort: NSRange { return NSRange(_CFURLComponentsGetRangeOfPort(_components)) } open var rangeOfPath: NSRange { return NSRange(_CFURLComponentsGetRangeOfPath(_components)) } open var rangeOfQuery: NSRange { return NSRange(_CFURLComponentsGetRangeOfQuery(_components)) } open var rangeOfFragment: NSRange { return NSRange(_CFURLComponentsGetRangeOfFragment(_components)) } // The getter method that underlies the queryItems property parses the query string based on these delimiters and returns an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string. Note that a name may appear more than once in a single query string, so the name values are not guaranteed to be unique. If the NSURLComponents object has an empty query component, queryItems returns an empty NSArray. If the NSURLComponents object has no query component, queryItems returns nil. // The setter method that underlies the queryItems property combines an NSArray containing any number of NSURLQueryItem objects, each of which represents a single key-value pair, into a query string and sets the NSURLComponents' query property. Passing an empty NSArray to setQueryItems sets the query component of the NSURLComponents object to an empty string. Passing nil to setQueryItems removes the query component of the NSURLComponents object. // Note: If a name-value pair in a query is empty (i.e. the query string starts with '&', ends with '&', or has "&&" within it), you get a NSURLQueryItem with a zero-length name and and a nil value. If a query's name-value pair has nothing before the equals sign, you get a zero-length name. If a query's name-value pair has nothing after the equals sign, you get a zero-length value. If a query's name-value pair has no equals sign, the query name-value pair string is the name and you get a nil value. open var queryItems: [URLQueryItem]? { get { // This CFURL implementation returns a CFArray of CFDictionary; each CFDictionary has an entry for name and optionally an entry for value guard let queryArray = _CFURLComponentsCopyQueryItems(_components) else { return nil } let count = CFArrayGetCount(queryArray) return (0..<count).map { idx in let oneEntry = unsafeBitCast(CFArrayGetValueAtIndex(queryArray, idx), to: NSDictionary.self) let swiftEntry = oneEntry._swiftObject let entryName = swiftEntry["name"] as! String let entryValue = swiftEntry["value"] as? String return URLQueryItem(name: entryName, value: entryValue) } } set(new) { guard let new = new else { self.percentEncodedQuery = nil return } // The CFURL implementation requires two CFArrays, one for names and one for values var names = [CFTypeRef]() var values = [CFTypeRef]() for entry in new { names.append(entry.name._cfObject) if let v = entry.value { values.append(v._cfObject) } else { values.append(kCFNull) } } _CFURLComponentsSetQueryItems(_components, names._cfObject, values._cfObject) } } } extension NSURL: _CFBridgeable, _SwiftBridgeable { typealias SwiftType = URL internal var _swiftObject: SwiftType { return URL(reference: self) } } extension CFURL : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSURL typealias SwiftType = URL internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: SwiftType { return _nsObject._swiftObject } } extension URL : _NSBridgeable, _CFBridgeable { typealias NSType = NSURL typealias CFType = CFURL internal var _nsObject: NSType { return self.reference } internal var _cfObject: CFType { return _nsObject._cfObject } } extension NSURL : _StructTypeBridgeable { public typealias _StructType = URL public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } } extension NSURLComponents : _StructTypeBridgeable { public typealias _StructType = URLComponents public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } } extension NSURLQueryItem : _StructTypeBridgeable { public typealias _StructType = URLQueryItem public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } }
apache-2.0
ef6ead49cf7e1c65459bba57edd2bdee
44.187874
740
0.674993
5.541674
false
false
false
false
abertelrud/swift-package-manager
Sources/PackageCollections/Utility.swift
2
1254
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import PackageModel import SourceControl struct MultipleErrors: Error, CustomStringConvertible { let errors: [Error] init(_ errors: [Error]) { self.errors = errors } var description: String { "\(self.errors)" } } struct NotFoundError: Error { let item: String init(_ item: String) { self.item = item } } internal extension Result { var failure: Failure? { switch self { case .failure(let failure): return failure case .success: return nil } } var success: Success? { switch self { case .failure: return nil case .success(let value): return value } } }
apache-2.0
c53d4b15dbdbff70580c5a4e6c93ec08
22.222222
80
0.527113
4.97619
false
false
false
false
ArthurKK/Kingfisher
Kingfisher/WKInterfaceImage+Kingfisher.swift
2
14206
// // WKInterfaceImage+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/5/1. // // Copyright (c) 2015 Wei Wang <onevcat@gmail.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 WatchKit public typealias WatchImageCompletionHandler = ((error: NSError?, cacheType: CacheType, imageURL: NSURL?, cachedInWatch: Bool) -> ()) public extension WKInterfaceImage { /** Set an image with a URL. It will ask for Kingfisher's manager to get the image for the URL. The device-side (Apple Watch) cache will be searched first by using the key of URL. If not found, Kingfisher will try to search it from iPhone/iPad memory and disk instead. If the manager does not find it yet, it will try to download the image at this URL and store it in iPhone/iPad for next use. You can use `KingfisherOptions.CacheInWatch` to store it in watch cache for better performance if you access this image often. :param: URL The URL of image. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask? { return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a placeholder image. It will ask for Kingfisher's manager to get the image for the URL. The device-side (Apple Watch) cache will be searched first by using the key of URL. If not found, Kingfisher will try to search it from iPhone/iPad memory and disk instead. If the manager does not find it yet, it will try to download the image at this URL and store it in iPhone/iPad for next use. You can use `KingfisherOptions.CacheInWatch` to store it in watch cache for better performance if you access this image often. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?) -> RetrieveImageTask? { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a named image resource file as placeholder. :param: URL The URL of image. :param: name The name of an image in WatchKit app bundle or the device-side cache. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL, placeholderImageNamed name: String?) -> RetrieveImageTask? { return kf_setImageWithURL(URL, placeholderImageNamed: name, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placaholder image and options. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask? { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a named image resource file as placeholder and options. :param: URL The URL of image. :param: name The name of an image in WatchKit app bundle or the device-side cache. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL, placeholderImageNamed name: String?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask? { return kf_setImageWithURL(URL, placeholderImageNamed: name, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placeholder image, options and completion handler. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: WatchImageCompletionHandler?) -> RetrieveImageTask? { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL and a named image resource file as placeholder, options and completion handler. :param: URL The URL of image. :param: name The name of an image in WatchKit app bundle or the device-side cache. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL, placeholderImageNamed name: String?, optionsInfo: KingfisherOptionsInfo?, completionHandler: WatchImageCompletionHandler?) -> RetrieveImageTask? { return kf_setImageWithURL(URL, placeholderImageNamed: name, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: progressBlock Called when the image downloading progress gets updated. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: WatchImageCompletionHandler?) -> RetrieveImageTask? { let preSet = kf_prepareImageURL(URL, optionsInfo: optionsInfo, completionHandler: completionHandler) if preSet.set { return nil } else { setImage(placeholderImage) return kf_retrieveImageWithURL(URL, optionsInfo: optionsInfo, cacheInWatch: preSet.cacheInWatch, progressBlock: progressBlock, completionHandler: completionHandler) } } /** Set an image with a URL and a named image resource file as placeholder, options progress handler and completion handler. :param: URL The URL of image. :param: name The name of an image in WatchKit app bundle or the device-side cache. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: progressBlock Called when the image downloading progress gets updated. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retrieving process or `nil` if device cache is used. */ public func kf_setImageWithURL(URL: NSURL, placeholderImageNamed name: String?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: WatchImageCompletionHandler?) -> RetrieveImageTask? { let preSet = kf_prepareImageURL(URL, optionsInfo: optionsInfo, completionHandler: completionHandler) if preSet.set { return nil } else { setImageNamed(name) return kf_retrieveImageWithURL(URL, optionsInfo: optionsInfo, cacheInWatch: preSet.cacheInWatch, progressBlock: progressBlock, completionHandler: completionHandler) } } /** Get the hash for a URL in Watch side cache. You can use the returned string to check whether the corresponding image is cached in watch or not, by using `WKInterfaceDevice.currentDevice().cachedImages` :param: string The absolute string of a URL. :returns: The hash string used when cached in Watch side cache. */ public class func kf_cacheKeyForURLString(string: String) -> String { return string.kf_MD5() } } // MARK: - Private methods extension WKInterfaceImage { private func kf_prepareImageURL(URL: NSURL, optionsInfo: KingfisherOptionsInfo?, completionHandler: WatchImageCompletionHandler?) -> (set: Bool, cacheInWatch: Bool) { kf_setWebURL(URL) let cacheInWatch: Bool let forceRefresh: Bool if let options = optionsInfo?[.Options] as? KingfisherOptions { cacheInWatch = ((options & KingfisherOptions.CacheInWatch) != KingfisherOptions.None) forceRefresh = ((options & KingfisherOptions.ForceRefresh) != KingfisherOptions.None) } else { cacheInWatch = false forceRefresh = false } let imageKey: String if let URLString = URL.absoluteString { imageKey = WKInterfaceImage.kf_cacheKeyForURLString(URLString) } else { return (false, cacheInWatch) } if forceRefresh { WKInterfaceDevice.currentDevice().removeCachedImageWithName(imageKey) } if WKInterfaceDevice.currentDevice().cachedImages[imageKey] != nil { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.setImageNamed(imageKey) completionHandler?(error: nil, cacheType: .Watch, imageURL: URL, cachedInWatch: true) }) return (true, cacheInWatch) } return (false, cacheInWatch) } private func kf_retrieveImageWithURL(URL: NSURL, optionsInfo: KingfisherOptionsInfo?, cacheInWatch: Bool, progressBlock: DownloadProgressBlock?, completionHandler: WatchImageCompletionHandler?) -> RetrieveImageTask? { let task = KingfisherManager.sharedManager.retrieveImageWithURL(URL, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }) { (image, error, cacheType, imageURL) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in var cachedInWatch: Bool = false if (imageURL == self.kf_webURL && image != nil) { self.setImage(image) if cacheInWatch { if let URLString = URL.absoluteString { let key = WKInterfaceImage.kf_cacheKeyForURLString(URLString) cachedInWatch = WKInterfaceDevice.currentDevice().addCachedImage(image!, name: key) } } } completionHandler?(error: error, cacheType: cacheType, imageURL: imageURL, cachedInWatch: cachedInWatch) }) } return task } } // MARK: - Associated Object private var lastURLkey: Void? public extension WKInterfaceImage { /// Get the image URL binded to this image view. public var kf_webURL: NSURL? { get { return objc_getAssociatedObject(self, &lastURLkey) as? NSURL } } private func kf_setWebURL(URL: NSURL) { objc_setAssociatedObject(self, &lastURLkey, URL, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } }
mit
3bee3732d43977afe571f06b6e3db3d9
44.977346
428
0.654583
5.247876
false
false
false
false
turingcorp/gattaca
gattaca/Model/Home/Abstract/MHomeDownloadGif.swift
1
3187
import Foundation extension MHome { private static let kKeyGif:String = "gif" private static let kKeySharingName:String = "sharing_name" private static let kTimeout:TimeInterval = 30 private class func factorySharingName() -> String? { guard let urlMap:[String:AnyObject] = MRequest.factoryUrlMap(), let gif:[String:AnyObject] = urlMap[kKeyGif] as? [String:AnyObject] else { return nil } let sharingName:String? = gif[kKeySharingName] as? String return sharingName } func downloadGif(completion:@escaping((URL?) -> ())) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.asyncDownloadGif(completion:completion) } } //MARK: private private func asyncDownloadGif(completion:@escaping((URL?) -> ())) { guard let item:MHomeItem = items.first, let identifier:String = item.gif?.identifier, let url:URL = MGiphy.factoryShareGifUrl( identifier:identifier) else { completion(nil) return } downloadGif(url:url, completion:completion) } private func downloadGif( url:URL, completion:@escaping((URL?) -> ())) { let request:URLRequest = MRequest.factoryGetRequest( url:url, timeout:MHome.kTimeout) let downloadTask:URLSessionDownloadTask = urlSession.downloadTask( with:request) { [weak self] (fileUrl:URL?, urlResponse:URLResponse?, error:Error?) in if error == nil { self?.requestSuccess(url:url, completion:completion) } else { completion(nil) } } downloadTask.resume() } private func requestSuccess( url:URL, completion:@escaping((URL?) -> ())) { let data:Data do { try data = Data(contentsOf:url) } catch { completion(nil) return } requestSuccess(data:data, completion:completion) } private func requestSuccess( data:Data, completion:@escaping((URL?) -> ())) { guard let sharingName:String = MHome.factorySharingName() else { completion(nil) return } let directoryUrl:URL = URL(fileURLWithPath:NSTemporaryDirectory()) let fileUrl:URL = directoryUrl.appendingPathComponent(sharingName) do { try data.write( to:fileUrl, options:Data.WritingOptions.atomicWrite) } catch { completion(nil) return } completion(fileUrl) } }
mit
ee69935cb10f193a7bc688cc197e3a2d
22.783582
79
0.49294
5.374368
false
false
false
false
alltheflow/copypasta
Carthage/Checkouts/VinceRP/vincerp/Common/Util/WeakSet.swift
1
1460
// // Created by Viktor Belenyesi on 18/04/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // public class WeakSet<T: Hashable where T: AnyObject> { private var _array: [WeakReference<T>] public init() { _array = Array() } public init(_ array: [T]) { _array = array.map { WeakReference($0) } } public var set: Set<T> { return Set(self.array()) } public func insert(member: T) { for e in _array { if e.hashValue == member.hashValue { return } } _array.append(WeakReference(member)) } public func filter(@noescape includeElement: (T) -> Bool) -> WeakSet<T> { return WeakSet(self.array().filter(includeElement)) } public func hasElementPassingTest(@noescape filterFunc: (T) -> Bool) -> Bool { return self.array().hasElementPassingTest(filterFunc) } public func map<U>(@noescape transform: (T) -> U) -> WeakSet<U> { return WeakSet<U>(self.array().map(transform)) } public func flatMap<U>(@noescape transform: (T) -> U?) -> WeakSet<U> { return WeakSet<U>(self.array().flatMap(transform)) } private func array() -> Array<T> { var result = Array<T>() for item in _array { if let v = item.value { result.append(v) } } return result } }
mit
b8a60487695d1bcbe4df742f58444abf
24.172414
82
0.541781
3.978202
false
false
false
false
calkinssean/TIY-Assignments
Day 39/matchbox20FanClub/matchbox20FanClub/Event.swift
1
2318
// // Event.swift // matchbox20FanClub // // Created by Sean Calkins on 3/24/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import Foundation import Firebase class Event { var key: String = "" var userKey: String = "" var name: String = "" var genre: String = "" var startDate = NSDate() var endDate = NSDate() var hasSeededTimeSlots: Bool = false var ref: Firebase? var eventRef = Firebase(url: "https://matchbox20fanclub.firebaseio.com/events") init (){} init(key: String, dict: [String: AnyObject]) { self.key = key if let name = dict["name"] as? String { self.name = name } else { print("couldnt parse name") } if let genre = dict["genre"] as? String { self.genre = genre } else { print("Couldnt print genre") } if let startDate = dict["startDate"] as? NSTimeInterval { self.startDate = NSDate(timeIntervalSince1970: startDate) } else { print("coudlnt parse startDate") } if let endDate = dict["endDate"] as? NSTimeInterval { self.endDate = NSDate(timeIntervalSince1970: endDate) } else { print("cant parse endDate") } if let hasSeededTimeSlots = dict["hasSeededTimeSlots"] as? Bool { self.hasSeededTimeSlots = hasSeededTimeSlots } else { print("Couldn't parse hasSeededTimeSlots") } } func save() { print("save called") let startDateInt = self.startDate.timeIntervalSince1970 let endDateInt = self.endDate.timeIntervalSince1970 let dict = [ "name": self.name, "genre": self.genre, "startDate": startDateInt, "endDate": endDateInt, "hasSeededTimeSlots": self.hasSeededTimeSlots ] let firebaseQuestion = self.eventRef.childByAutoId() firebaseQuestion.setValue(dict) } }
cc0-1.0
6a330b0d0b61d3be1fb9a41b1eb4333b
21.950495
83
0.503669
4.929787
false
false
false
false
TellMeAMovieTeam/TellMeAMovie_iOSApp
TellMeAMovie/Pods/TMDBSwift/Sources/Models/TVSeasonsMDB.swift
1
3997
// // SeasonsMDB.swift // MDBSwiftWrapper // // Created by George Kye on 2016-02-17. // Copyright © 2016 George KyeKye. All rights reserved. // import Foundation public struct TVSeasonsMDB: ArrayObject{ public var air_date: String! public var episodes = [TVEpisodesMDB]() public var name: String! public var overview: String! public var id: Int! public var poster_path: String! public var season_number: Int! public init(results: JSON){ air_date = results["air_date"].string episodes = TVEpisodesMDB.initialize(json: results["episodes"]) name = results["name"].string overview = results["overview"].string id = results["id"].int poster_path = results["poster_path"].string season_number = results["season_number"].int } ///Get the primary information about a TV season by its season number. public static func season_number(_ api_key: String, tvShowId: Int!, seasonNumber: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: TVSeasonsMDB?) -> ()) -> (){ let urltype = String(tvShowId) + "/season/" + String(seasonNumber) Client.Seasons(urltype, api_key: api_key, language: language){ apiReturn in var data: TVSeasonsMDB? if(apiReturn.error == nil){ data = TVSeasonsMDB(results: apiReturn.json!) } completion(apiReturn, data) } } ///Get the cast & crew credits for a TV season by season number. public static func credits(_ api_key: String, tvShowId: Int!, seasonNumber: Int!, language: String?, completion: @escaping (_ clientReturn: ClientReturn, _ data: TVCreditsMDB?) -> ()) -> (){ // [/tv/11/season/1/credits] let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/credits" Client.Seasons(urltype, api_key: api_key, language: language){ apiReturn in var data: TVCreditsMDB? if(apiReturn.error == nil){ data = TVCreditsMDB.init(results: apiReturn.json!) } completion(apiReturn, data) } } ///Get the external ids that we have stored for a TV season by season number. public static func externalIDS(_ api_key: String, tvShowId: Int!, seasonNumber: Int!, language: String, completion: @escaping (_ clientReturn: ClientReturn, _ data: ExternalIdsMDB?) -> ()) -> (){ let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/external_ids" Client.Seasons(urltype, api_key: api_key, language: language){ apiReturn in var data: ExternalIdsMDB? if(apiReturn.error == nil){ data = ExternalIdsMDB.init(results: apiReturn.json!) } completion(apiReturn, data) } } ///Get the images (posters) that we have stored for a TV season by season number. **[backdrops] returned in ImagesMDB will be `nil` public static func images(_ api_key: String, tvShowId: Int!, seasonNumber: Int!, language: String, completion: @escaping (_ clientReturn: ClientReturn, _ data: ImagesMDB?) -> ()) -> (){ let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/images" Client.Seasons(urltype, api_key: api_key, language: language){ apiReturn in var data: ImagesMDB? if(apiReturn.error == nil){ data = ImagesMDB.init(results: apiReturn.json!) } completion(apiReturn, data) } } ///Get the videos that have been added to a TV season (trailers, teasers, etc...) public static func videos(_ api_key: String, tvShowId: Int!, seasonNumber: Int!, language: String, completion: @escaping (_ clientReturn: ClientReturn, _ data: [VideosMDB]?)-> ()) -> (){ // [/tv/11/season/1/credits] let urltype = String(tvShowId) + "/season/" + String(seasonNumber) + "/videos" Client.Seasons(urltype, api_key: api_key, language: language){ apiReturn in var data: [VideosMDB]? if(apiReturn.error == nil){ data = VideosMDB.initialize(json: apiReturn.json!["results"]) } completion(apiReturn, data) } } }
apache-2.0
7ebeb49a80d8008bb7cf938d7997c367
39.363636
198
0.657157
3.809342
false
false
false
false
sindresorhus/dark-mode
Sources/DarkMode.swift
1
592
import AppKit struct DarkMode { private static let prefix = "tell application \"System Events\" to tell appearance preferences to" static var isEnabled: Bool { get { if #available(macOS 10.14, *) { return NSAppearance.current.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua } else { return UserDefaults.standard.string(forKey: "AppleInterfaceStyle") == "Dark" } } set { toggle(force: newValue) } } static func toggle(force: Bool? = nil) { let value = force.map(String.init) ?? "not dark mode" runAppleScript("\(prefix) set dark mode to \(value)") } }
mit
25319bad3c434331078ec3ee4457f662
24.73913
99
0.670608
3.270718
false
false
false
false
sahandnayebaziz/Dana-Hills
Pods/PromiseKit/Sources/Error.swift
3
5431
import Foundation public enum PMKError: Error { /** The ErrorType for a rejected `join`. - Parameter 0: The promises passed to this `join` that did not *all* fulfill. - Note: The array is untyped because Swift generics are fussy with enums. */ case join([AnyObject]) /** The completionHandler with form (T?, ErrorType?) was called with (nil, nil) This is invalid as per Cocoa/Apple calling conventions. */ case invalidCallingConvention /** A handler returned its own promise. 99% of the time, this is likely a programming error. It is also invalid per Promises/A+. */ case returnedSelf /** `when()` was called with a concurrency of <= 0 */ case whenConcurrentlyZero /** AnyPromise.toPromise failed to cast as requested */ case castError(Any.Type) } extension PMKError: LocalizedError { public var errorDescription: String? { switch self { case .invalidCallingConvention: return "A closure was called with an invalid calling convention, probably (nil, nil)" case .returnedSelf: return "A promise handler returned itself" case .whenConcurrentlyZero, .join: return "Bad input was provided to a PromiseKit function" case .castError(let type): return "Promise chain sequence failed to cast an object to \(type)." } } } public enum PMKURLError: Error { /** The URLRequest succeeded but a valid UIImage could not be decoded from the data that was received. */ case invalidImageData(URLRequest, Data) /** The HTTP request returned a non-200 status code. */ case badResponse(URLRequest, Data?, URLResponse?) /** The data could not be decoded using the encoding specified by the HTTP response headers. */ case stringEncoding(URLRequest, Data, URLResponse) /** Usually the `URLResponse` is actually an `HTTPURLResponse`, if so you can access it using this property. Since it is returned as an unwrapped optional: be sure. */ public var NSHTTPURLResponse: Foundation.HTTPURLResponse! { switch self { case .invalidImageData: return nil case .badResponse(_, _, let rsp): return rsp as! Foundation.HTTPURLResponse case .stringEncoding(_, _, let rsp): return rsp as! Foundation.HTTPURLResponse } } } extension PMKURLError: LocalizedError { public var errorDescription: String? { switch self { case let .badResponse(rq, data, rsp): if let data = data, let str = String(data: data, encoding: .utf8), let rsp = rsp { return "PromiseKit: badResponse: \(rq): \(rsp)\n\(str)" } else { fallthrough } default: return "\(self)" } } } public enum JSONError: Error { /// The JSON response was different to that requested case unexpectedRootNode(Any) } //////////////////////////////////////////////////////////// Cancellation public protocol CancellableError: Error { var isCancelled: Bool { get } } #if !SWIFT_PACKAGE private struct ErrorPair: Hashable { let domain: String let code: Int init(_ d: String, _ c: Int) { domain = d; code = c } var hashValue: Int { return "\(domain):\(code)".hashValue } } private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool { return lhs.domain == rhs.domain && lhs.code == rhs.code } extension NSError { @objc public class func cancelledError() -> NSError { let info = [NSLocalizedDescriptionKey: "The operation was cancelled"] return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info) } /** - Warning: You must call this method before any promises in your application are rejected. Failure to ensure this may lead to concurrency crashes. - Warning: You must call this method on the main thread. Failure to do this may lead to concurrency crashes. */ @objc public class func registerCancelledErrorDomain(_ domain: String, code: Int) { cancelledErrorIdentifiers.insert(ErrorPair(domain, code)) } /// - Returns: true if the error represents cancellation. @objc public var isCancelled: Bool { return (self as Error).isCancelledError } } private var cancelledErrorIdentifiers = Set([ ErrorPair(PMKErrorDomain, PMKOperationCancelled), ErrorPair(NSCocoaErrorDomain, NSUserCancelledError), ErrorPair(NSURLErrorDomain, NSURLErrorCancelled), ]) #endif extension Error { public var isCancelledError: Bool { if let ce = self as? CancellableError { return ce.isCancelled } else { #if SWIFT_PACKAGE return false #else let ne = self as NSError return cancelledErrorIdentifiers.contains(ErrorPair(ne.domain, ne.code)) #endif } } } //////////////////////////////////////////////////////// Unhandled Errors class ErrorConsumptionToken { var consumed = false let error: Error init(_ error: Error) { self.error = error } deinit { if !consumed { #if os(Linux) || os(Android) PMKUnhandledErrorHandler(error) #else PMKUnhandledErrorHandler(error as NSError) #endif } } }
mit
1d3a4c6a66999b1d82ff97d453663e07
28.042781
152
0.624379
4.685936
false
false
false
false
ulrikdamm/Sqlable
Sources/Sqlable/Column.swift
1
4390
// // Column.swift // Simplyture // // Created by Ulrik Damm on 27/10/2015. // Copyright © 2015 Robocat. All rights reserved. // /// Protocol for everything that can be an additional option for a SQL table column public protocol ColumnOption : SqlPrintable { } /// Defines the primary key of a table public struct PrimaryKey : ColumnOption { /// Wether or not the primay key should have autoincrement public let autoincrement : Bool /// Create a primary key option /// /// - Parameters: /// - autoincrement: Wether or not the primary key should automatically increment on insertion (SQLite autoincrement) public init(autoincrement : Bool) { self.autoincrement = autoincrement } public var sqlDescription : String { var sql = ["primary key"] if autoincrement { sql.append("autoincrement") } return sql.joined(separator: " ") } } /// Rules for handling updates or deletions public enum Rule : SqlPrintable { /// Ignore the update or deletion case ignore /// Perform a cascading delete case cascade /// Set the updated or deleted reference to null case setNull /// Set the updated or deleted reference to the default value case setDefault public var sqlDescription : String { switch self { case .ignore: return "no action" case .cascade: return "cascade" case .setNull: return "set null" case .setDefault: return "set default" } } } /// Defines a foreign key to another table public struct ForeignKey<To : Sqlable> : ColumnOption, SqlPrintable { /// Which column in the other table to use for identification public let column : Column /// What to do when the referenced row is deleted public let onDelete : Rule /// What to do when the referenced row is updated public let onUpdate : Rule /// Create a foreign key constraint /// /// - Parameters: /// - column: The column in the other Sqlable to reference for identification (default is the 'id' column) /// - onDelete: What to do when the referenced row is deleted (default is ignore) /// - onUpdate: What to do when the referenced row is updated (default is ignore) public init(column : Column = Column("id", .integer), onDelete : Rule = .ignore, onUpdate : Rule = .ignore) { self.column = column self.onDelete = onDelete self.onUpdate = onUpdate } public var sqlDescription : String { var sql = ["references \(To.tableName)(\(column.name))"] if onUpdate != .ignore { sql.append("on update \(onUpdate.sqlDescription)") } if onDelete != .ignore { sql.append("on delete \(onDelete.sqlDescription)") } return sql.joined(separator: " ") } } /// A column in a SQL table public struct Column : Equatable { /// The SQL name of the column public let name : String /// The SQL type of the column public let type : SqlType /// Additional options and constraints public let options : [ColumnOption] let modifiers : [String] /// Create a new column /// /// - Parameters: /// - name: The SQL name of the column /// - type: The SQL type of the column /// - options: Additional options and constraints public init(_ name : String, _ type : SqlType, _ options : ColumnOption...) { self.name = name self.type = type self.options = options self.modifiers = [] } init(_ name : String, _ type : SqlType, _ options : [ColumnOption], modifiers : [String]) { self.name = name self.type = type self.options = options self.modifiers = modifiers } } extension Column { /// Choose the column with an uppercase modifier (for use in filters) public func uppercase() -> Column { return Column(name, type, options, modifiers: modifiers + ["upper"]) } /// Choose the column with a lowercase modifier (for use in filters) public func lowercase() -> Column { return Column(name, type, options, modifiers: modifiers + ["lower"]) } var expressionName : String { return modifiers.reduce(name) { name, modifier in "\(modifier)(\(name))" } } } public func ==(lhs : Column, rhs : Column) -> Bool { return lhs.name == rhs.name && lhs.type == rhs.type } public func ~=(lhs : Column, rhs : Column) -> Bool { return lhs.name == rhs.name } extension Column : SqlPrintable { public var sqlDescription : String { var statement = ["\(name) \(type.sqlDescription)"] for option in options { statement.append(option.sqlDescription) } return statement.joined(separator: " ") } }
mit
e26d11e9745b1ef22ad0831b241e33ce
26.26087
119
0.686489
3.606409
false
false
false
false
ps2/rileylink_ios
MinimedKit/Models/PumpModel.swift
1
7384
// // PumpModel.swift // RileyLink // // Created by Pete Schwamb on 3/7/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // /// Represents a pump model and its defining characteristics. /// This class implements the `RawRepresentable` protocol public enum PumpModel: String { case model508 = "508" case model511 = "511" case model711 = "711" case model512 = "512" case model712 = "712" case model515 = "515" case model715 = "715" case model522 = "522" case model722 = "722" case model523 = "523" case model723 = "723" case model530 = "530" case model730 = "730" case model540 = "540" case model740 = "740" case model551 = "551" case model751 = "751" case model554 = "554" case model754 = "754" private var size: Int { return Int(rawValue)! / 100 } private var generation: Int { return Int(rawValue)! % 100 } /// Identifies pumps that support a major-generation shift in record format, starting with the x23. /// Mirrors the "larger" flag as defined by decoding-carelink public var larger: Bool { return generation >= 23 } // On newer pumps, square wave boluses are added to history on start of delivery, and updated in place // when delivery is finished public var appendsSquareWaveToHistoryOnStartOfDelivery: Bool { return generation >= 23 } public var hasMySentry: Bool { return generation >= 23 } var hasLowSuspend: Bool { return generation >= 51 } public var recordsBasalProfileStartEvents: Bool { return generation >= 23 } /// Newer models allow higher precision delivery, and have bit packing to accomodate this. public var insulinBitPackingScale: Int { return (generation >= 23) ? 40 : 10 } /// Pulses per unit is the inverse of the minimum volume of delivery. public var pulsesPerUnit: Int { return (generation >= 23) ? 40 : 20 } public var reservoirCapacity: Int { switch size { case 5: return 176 case 7: return 300 default: fatalError("Unknown reservoir capacity for PumpModel.\(self)") } } /// Even though this is capped by the system at 250 / 10 U, the message takes a UInt16. var usesTwoBytesForMaxBolus: Bool { return generation >= 23 } public var supportedBasalRates: [Double] { if generation >= 23 { // 0.025 units (for rates between 0.0-0.975 U/h) let rateGroup1 = ((0...39).map { Double($0) / Double(pulsesPerUnit) }) // 0.05 units (for rates between 1-9.95 U/h) let rateGroup2 = ((20...199).map { Double($0) / Double(pulsesPerUnit/2) }) // 0.1 units (for rates between 10-35 U/h) let rateGroup3 = ((100...350).map { Double($0) / Double(pulsesPerUnit/4) }) return rateGroup1 + rateGroup2 + rateGroup3 } else { // 0.05 units for rates between 0.0-35U/hr return (0...700).map { Double($0) / Double(pulsesPerUnit) } } } public var maximumBolusVolume: Int { return 25 } public var maximumBasalRate: Double { return 35 } public var supportedBolusVolumes: [Double] { if generation >= 23 { let breakpoints: [Int] = [0,1,10,maximumBolusVolume] let scales: [Int] = [40,20,10] let scalingGroups = zip(scales, (zip(breakpoints, breakpoints[1...]).map {($0.0)...$0.1})) let segments = scalingGroups.map { (scale, range) -> [Double] in let scaledRanges = ((range.lowerBound*scale+1)...(range.upperBound*scale)) return scaledRanges.map { Double($0) / Double(scale) } } return segments.flatMap { $0 } } else { return (1...(maximumBolusVolume*10)).map { Double($0) / 10.0 } } } public var maximumBasalScheduleEntryCount: Int { return 48 } public var minimumBasalScheduleEntryDuration: TimeInterval { return .minutes(30) } public var isDeliveryRateVariable: Bool { return generation >= 23 } public func bolusDeliveryTime(units: Double) -> TimeInterval { let unitsPerMinute: Double if isDeliveryRateVariable { switch units { case let u where u < 1.0: unitsPerMinute = 0.75 case let u where u > 7.5: unitsPerMinute = units / 5 default: unitsPerMinute = 1.5 } } else { unitsPerMinute = 1.5 } return TimeInterval(minutes: units / unitsPerMinute) } public func estimateTempBasalProgress(unitsPerHour: Double, duration: TimeInterval, elapsed: TimeInterval) -> (deliveredUnits: Double, progress: Double) { let roundedVolume = round(unitsPerHour * elapsed.hours * Double(pulsesPerUnit)) / Double(pulsesPerUnit) return (deliveredUnits: roundedVolume, progress: min(elapsed / duration, 1)) } public func estimateBolusProgress(elapsed: TimeInterval, programmedUnits: Double) -> (deliveredUnits: Double, progress: Double) { let duration = bolusDeliveryTime(units: programmedUnits) let timeProgress = min(elapsed / duration, 1) let updateResolution: Double let unroundedVolume: Double if isDeliveryRateVariable { if programmedUnits < 1 { updateResolution = 40 // Resolution = 0.025 unroundedVolume = timeProgress * programmedUnits } else { var remainingUnits = programmedUnits var baseDuration: TimeInterval = 0 var overlay1Duration: TimeInterval = 0 var overlay2Duration: TimeInterval = 0 let baseDeliveryRate = 1.5 / TimeInterval(minutes: 1) baseDuration = min(duration, remainingUnits / baseDeliveryRate) remainingUnits -= baseDuration * baseDeliveryRate overlay1Duration = min(duration, remainingUnits / baseDeliveryRate) remainingUnits -= overlay1Duration * baseDeliveryRate overlay2Duration = min(duration, remainingUnits / baseDeliveryRate) remainingUnits -= overlay2Duration * baseDeliveryRate unroundedVolume = (min(elapsed, baseDuration) + min(elapsed, overlay1Duration) + min(elapsed, overlay2Duration)) * baseDeliveryRate if overlay1Duration > elapsed { updateResolution = 10 // Resolution = 0.1 } else { updateResolution = 20 // Resolution = 0.05 } } } else { updateResolution = 20 // Resolution = 0.05 unroundedVolume = timeProgress * programmedUnits } let roundedVolume = round(unroundedVolume * updateResolution) / updateResolution return (deliveredUnits: roundedVolume, progress: roundedVolume / programmedUnits) } } extension PumpModel: CustomStringConvertible { public var description: String { return rawValue } }
mit
b62ee2398b6ec03d6347eca518b59831
33.661972
159
0.592036
4.551788
false
false
false
false
fightjc/Paradise_Lost
Paradise Lost/Classes/ViewControllers/Tool/PaintingVC.swift
3
4333
// // PaintingVC.swift // Paradise Lost // // Created by jason on 26/9/2017. // Copyright © 2017 Jason Chen. All rights reserved. // import UIKit class PaintingVC: UIViewController, PaintingViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var mainView: PaintingView! var toolView: PaintingToolView! var colorView: PaintingColorView! /// flag of current picture whether has been saved var isCurrentPicSave: Bool = true // MARK: life cycle override var prefersStatusBarHidden: Bool { get { return true } } override var shouldAutorotate : Bool { return true } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return .portrait } override func viewDidLoad() { super.viewDidLoad() let rect = UIScreen.main.bounds let toolheigh = rect.height / 13 let colorheight = CGFloat(40) mainView = PaintingView(frame: rect) mainView.delegate = self view.addSubview(mainView) toolView = PaintingToolView(frame: CGRect(x: 0, y: (rect.height - toolheigh), width: rect.width, height: toolheigh)) toolView.delegate = self view.addSubview(toolView) colorView = PaintingColorView(frame: CGRect(x: 0, y: (rect.height - toolheigh - colorheight), width: rect.width, height: colorheight)) colorView.isHidden = true view.addSubview(colorView) } // MARK: PaintingViewDelegate func exit() { self.dismiss(animated: false, completion: nil) } func savePic() { savePicToPhotoLibrary(nil) } func getPic() { if (mainView.hasImage && !isCurrentPicSave) { AlertManager.showTipsWithContinue(self, message: LanguageManager.getToolString(forKey: "paint.getImage.message"), handler: savePicToPhotoLibrary, cHandler: nil) } getPicFromPhotoLibrary() } func changePenMode() { if (toolView.currentMode == .pen) { colorView.isHidden = false } else { colorView.isHidden = true } } func changeResizeMode() { colorView.isHidden = true } func changeTextMode() { colorView.isHidden = true } // MARK: UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerEditedImage] as? UIImage { mainView.loadImage(rawImage: image) isCurrentPicSave = false } else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { mainView.loadImage(rawImage: image) isCurrentPicSave = false } else { AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.getImage.error"), handler: nil) } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } // MARK: private methods fileprivate func getPicFromPhotoLibrary() { let picker = UIImagePickerController() picker.delegate = self //picker.allowsEditing = true picker.sourceType = .photoLibrary self.present(picker, animated: true, completion: nil) } fileprivate func savePicToPhotoLibrary(_ alert: UIAlertAction?) { if let image = mainView.getImage() { UIImageWriteToSavedPhotosAlbum(image, self, #selector(PaintingVC.image(_:didFinishSavingWithError:contextInfo:)), nil) } } @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { if let _ = error { // fail AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.saveImage.fail"), handler: nil) } else { // success AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.saveImage.success"), handler: nil) isCurrentPicSave = true } } }
mit
649072251ab9321ada268656b617d75d
31.328358
172
0.633887
4.950857
false
false
false
false
charmaex/JDTransition
JDTransition/JDSegueScaleOut.swift
1
1176
// // JDSegueScaleOut.swift // JDSegues // // Created by Jan Dammshäuser on 29.08.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit /// Segue where the current screen scales out to a point or the center of the screen. @objc open class JDSegueScaleOut: UIStoryboardSegue, JDSegueOriginable { /// Defines at which point the animation should start /// - parameter Default: center of the screen open var animationOrigin: CGPoint? /// Time the transition animation takes /// - parameter Default: 0.5 seconds open var transitionTime: TimeInterval = 0.5 /// Animation Curve /// - parameter Default: CurveLinear open var animationOption: UIViewAnimationOptions = .curveLinear open override func perform() { let fromVC = source let toVC = destination guard let window = fromVC.view.window else { return NSLog("[JDTransition] JDSegueScaleOut could not get views window") } JDAnimationScale.out(inWindow: window, fromVC: fromVC, toVC: toVC, duration: transitionTime, options: animationOption) { _ in self.finishSegue(nil) } } }
mit
5149d6d5b5cd14b169b2c2057c79e1d2
29.076923
133
0.681159
4.582031
false
false
false
false
inamiy/ReactiveCocoaCatalog
ReactiveCocoaCatalog/Utilities/Helpers.swift
1
1567
// // Helpers.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2015-09-16. // Copyright © 2015 Yasuhiro Inami. All rights reserved. // import Foundation // MARK: Logging private let _maxLogCharacterCount = 200 func logSink<T>(_ name: String) -> (T) -> () { return { arg in var argChars = "\(arg)".characters argChars = argChars.prefix(_maxLogCharacterCount) if argChars.count == _maxLogCharacterCount { argChars.append("…") } print(" 🚦[\(name)] \(String(argChars))") } } func deinitMessage(_ object: AnyObject) -> String { return String(format: "[deinit] %@ %p", String(describing: type(of: object)), Unmanaged.passUnretained(object).toOpaque().hashValue) } // MARK: DateString private let _dateFormatter: DateFormatter = { let formatter = DateFormatter() // formatter.dateFormat = "yyyy/MM/dd HH:mm:ss.SSS" formatter.dateFormat = "HH:mm:ss.SSS" return formatter }() func stringFromDate(_ date: Date) -> String { return _dateFormatter.string(from: date) } // MARK: Random func random(_ upperBound: Int) -> Int { return Int(arc4random_uniform(UInt32(upperBound))) } /// Picks random `count` elements from `sequence`. func pickRandom<S: Sequence>(_ sequence: S, _ count: Int) -> [S.Iterator.Element] { var array = Array(sequence) var pickedArray = Array<S.Iterator.Element>() for _ in 0..<count { if array.isEmpty { break } pickedArray.append(array.remove(at: random(array.count))) } return pickedArray }
mit
d00e3fa9065765a6cfd32023ceb0341c
22.651515
136
0.649584
3.638695
false
false
false
false
externl/ice
swift/test/Ice/hold/AllTests.swift
4
5392
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice import PromiseKit import TestCommon class Condition { var _lock = os_unfair_lock() var _value: Bool init(value: Bool) { _value = value } func set(value: Bool) { withLock(&_lock) { self._value = value } } func value() -> Bool { return withLock(&_lock) { self._value } } } func allTests(_ helper: TestHelper) throws { func test(_ value: Bool, file: String = #file, line: Int = #line) throws { try helper.test(value, file: file, line: line) } let output = helper.getWriter() let communicator = helper.communicator() output.write("testing stringToProxy... ") let base = try communicator.stringToProxy("hold:\(helper.getTestEndpoint(num: 0))")! let baseSerialized = try communicator.stringToProxy("hold:\(helper.getTestEndpoint(num: 1))")! output.writeLine("ok") output.write("testing checked cast... ") let hold = try checkedCast(prx: base, type: HoldPrx.self)! let holdOneway = uncheckedCast(prx: base.ice_oneway(), type: HoldPrx.self) try test(hold == base) let holdSerialized = try checkedCast(prx: baseSerialized, type: HoldPrx.self)! let holdSerializedOneway = uncheckedCast(prx: baseSerialized.ice_oneway(), type: HoldPrx.self) try test(holdSerialized == baseSerialized) output.writeLine("ok") output.write("changing state between active and hold rapidly... ") for _ in 0 ..< 100 { try hold.putOnHold(0) } for _ in 0 ..< 100 { try holdOneway.putOnHold(0) } for _ in 0 ..< 100 { try holdSerialized.putOnHold(0) } for _ in 0 ..< 100 { try holdSerializedOneway.putOnHold(0) } output.writeLine("ok") output.write("testing without serialize mode... ") do { let cond = Condition(value: true) var value: Int32 = 0 var completed: Promise<Int32>! var sent: Promise<Bool>! while cond.value() { let expected = value sent = Promise<Bool> { seal in completed = hold.setAsync(value: value + 1, delay: Int32.random(in: 0 ..< 5)) { seal.fulfill($0) } } _ = completed!.done { (v: Int32) throws -> Void in if v != expected { cond.set(value: false) } } value += 1 if value % 100 == 0 { _ = try sent.wait() } if value > 100_000 { // Don't continue, it's possible that out-of-order dispatch doesn't occur // after 100000 iterations and we don't want the test to last for too long // when this occurs. break } } try test(value > 100_000 || !cond.value()) _ = try sent.wait() } output.writeLine("ok") output.write("testing with serialize mode... ") do { let cond = Condition(value: true) var value: Int32 = 0 var completed: Promise<Int32>? while value < 3000, cond.value() { let expected = value let sent = Promise<Bool> { seal in completed = holdSerialized.setAsync(value: value + 1, delay: 0) { seal.fulfill($0) } } _ = completed!.done { (v: Int32) throws -> Void in if v != expected { cond.set(value: false) } } value += 1 if value % 100 == 0 { _ = try sent.wait() } } _ = try completed!.wait() try test(cond.value()) for i in 0 ..< 10000 { try holdSerializedOneway.setOneway(value: value + 1, expected: value) value += 1 if i % 100 == 0 { try holdSerializedOneway.putOnHold(1) } } } output.writeLine("ok") output.write("testing serialization... ") do { var value: Int32 = 0 _ = try holdSerialized.set(value: value, delay: 0) var completed: Promise<Void>! for i in 0 ..< 10000 { // Create a new proxy for each request completed = holdSerialized.ice_oneway().setOnewayAsync(value: value + 1, expected: value) value += 1 if (i % 100) == 0 { try completed.wait() try holdSerialized.ice_ping() // Ensure everything's dispatched. try holdSerialized.ice_getConnection()!.close(.GracefullyWithWait) } } try completed.wait() } output.writeLine("ok") output.write("testing waitForHold... ") do { try hold.waitForHold() try hold.waitForHold() for i in 0 ..< 1000 { try holdOneway.ice_ping() if (i % 20) == 0 { try hold.putOnHold(0) } } try hold.putOnHold(-1) try hold.ice_ping() try hold.putOnHold(-1) try hold.ice_ping() } output.writeLine("ok") output.write("changing state to hold and shutting down server... ") try hold.shutdown() output.writeLine("ok") }
gpl-2.0
ec0580fe519c09f07ea30506474f5440
27.989247
101
0.520401
4.225705
false
true
false
false
galblank/equawait
EquaBar.swift
1
1834
// // EquaBar.swift // PeopleLinx // // Created by Blank, Gal on 10/6/16. // Copyright © 2009 - Present Gal Blank. All rights reserved. // import UIKit protocol barCycleDelegate { func finishedCycle() } class EquaBar: CALayer { var cycleDelegate:barCycleDelegate? = nil var timer:Timer? = nil var isExpanding = true var maxHeight:CGFloat = 0.0 var minHeight:CGFloat = 0.0 override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(EquaBar.expandCollaps), name: NSNotification.Name(rawValue: "internal.expandcollaps"), object: nil) } override init(layer: Any) { super.init(layer: layer) } func start() { timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(EquaBar.expandCollaps), userInfo: nil, repeats: true) } func expand() { DispatchQueue.main.async { self.frame.size.height += 7 self.frame.origin.y -= 3.5 } } func collaps() { DispatchQueue.main.async { self.frame.size.height -= 7 self.frame.origin.y += 3.5 } } func expandCollaps() { if isExpanding{ if self.frame.size.height >= maxHeight{ isExpanding = false collaps() return } expand() } else{ if self.frame.size.height <= minHeight{ timer?.invalidate() isExpanding = true cycleDelegate?.finishedCycle() return } collaps() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
9aa306743e2aa6819ece6fe728c9991b
22.805195
172
0.543372
4.2529
false
false
false
false
rcobelli/GameOfficials
Eureka-master/Source/Rows/Common/FieldRow.swift
1
16238
// FieldRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( 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 public protocol InputTypeInitiable { init?(string stringValue: String) } public protocol FieldRowConformance : FormatterConformance { var textFieldPercentage : CGFloat? { get set } var placeholder : String? { get set } var placeholderColor : UIColor? { get set } } extension Int: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue, radix: 10) } } extension Float: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } extension String: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } extension URL: InputTypeInitiable {} extension Double: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell { /// A formatter to be used to format the user's input open var formatter: Formatter? /// If the formatter should be used while the user is editing the text. open var useFormatterDuringInput = false open var useFormatterOnDidBeginEditing: Bool? public required init(tag: String?) { super.init(tag: tag) displayValueFor = { [unowned self] value in guard let v = value else { return nil } guard let formatter = self.formatter else { return String(describing: v) } if (self.cell.textInput as? UIView)?.isFirstResponder == true { return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v) } return formatter.string(for: v) } } } open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell { /// Configuration for the keyboardReturnType of this row open var keyboardReturnType : KeyboardReturnTypeConfiguration? /// The percentage of the cell that should be occupied by the textField open var textFieldPercentage : CGFloat? /// The placeholder for the textField open var placeholder : String? /// The textColor for the textField's placeholder open var placeholderColor : UIColor? public required init(tag: String?) { super.init(tag: tag) } } /** * Protocol for cells that contain a UITextField */ public protocol TextInputCell { var textInput : UITextInput { get } } public protocol TextFieldCell: TextInputCell { var textField: UITextField { get } } extension TextFieldCell { public var textInput: UITextInput { return textField } } open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable { public var textField: UITextField open var titleLabel : UILabel? { textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(500, for: .horizontal) textLabel?.setContentCompressionResistancePriority(1000, for: .horizontal) return textLabel } open var dynamicConstraints = [NSLayoutConstraint]() public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false super.init(style: style, reuseIdentifier: reuseIdentifier) NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil){ [weak self] notification in guard let me = self else { return } me.titleLabel?.removeObserver(me, forKeyPath: "text") } NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil){ [weak self] notification in self?.titleLabel?.addObserver(self!, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil) } NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil){ [weak self] notification in self?.setNeedsUpdateConstraints() } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { textField.delegate = nil textField.removeTarget(self, action: nil, for: .allEvents) titleLabel?.removeObserver(self, forKeyPath: "text") imageView?.removeObserver(self, forKeyPath: "image") NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil) } open override func setup() { super.setup() selectionStyle = .none contentView.addSubview(titleLabel!) contentView.addSubview(textField) titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil) imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.old.union(.new), context: nil) textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged) } open override func update() { super.update() detailTextLabel?.text = nil if let title = row.title { textField.textAlignment = title.isEmpty ? .left : .right textField.clearButtonMode = title.isEmpty ? .whileEditing : .never } else{ textField.textAlignment = .left textField.clearButtonMode = .whileEditing } textField.delegate = self textField.text = row.displayValueFor?(row.value) textField.isEnabled = !row.isDisabled textField.textColor = row.isDisabled ? .gray : .black textField.font = .preferredFont(forTextStyle: .body) if let placeholder = (row as? FieldRowConformance)?.placeholder { if let color = (row as? FieldRowConformance)?.placeholderColor { textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color]) } else{ textField.placeholder = (row as? FieldRowConformance)?.placeholder } } if row.isHighlighted { textLabel?.textColor = tintColor } } open override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textField.canBecomeFirstResponder } open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool { return textField.becomeFirstResponder() } open override func cellResignFirstResponder() -> Bool { return textField.resignFirstResponder() } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let obj = object as AnyObject? if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey], ((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) && (changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue { setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } // Mark: Helpers open func customConstraints() { contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views : [String: AnyObject] = ["textField": textField] dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[textField]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["textField": textField]) if let label = titleLabel, let text = label.text, !text.isEmpty { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[titleLabel]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["titleLabel": label]) dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0)) } if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["label"] = titleLabel dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-[textField]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .equal : .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else{ dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views) } } else{ if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["label"] = titleLabel dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-[textField]-|", options: [], metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .equal : .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else{ dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views) } } contentView.addConstraints(dynamicConstraints) } open override func updateConstraints(){ customConstraints() super.updateConstraints() } open func textFieldDidChange(_ textField : UITextField){ guard let textValue = textField.text else { row.value = nil return } guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else { row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value) return } if fieldRow.useFormatterDuringInput { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) { row.value = value.pointee as? T guard var selStartPos = textField.selectedTextRange?.start else { return } let oldVal = textField.text textField.text = row.displayValueFor?(row.value) selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos) return } } else { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) { row.value = value.pointee as? T } else{ row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value) } } } //Mark: Helpers private func displayValue(useFormatter: Bool) -> String? { guard let v = row.value else { return nil } if let formatter = (row as? FormatterConformance)?.formatter, useFormatter { return textField.isFirstResponder ? formatter.editingString(for: v) : formatter.string(for: v) } return String(describing: v) } //MARK: TextFieldDelegate open func textFieldDidBeginEditing(_ textField: UITextField) { formViewController()?.beginEditing(of: self) formViewController()?.textInputDidBeginEditing(textField, cell: self) if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput { textField.text = displayValue(useFormatter: true) } else { textField.text = displayValue(useFormatter: false) } } open func textFieldDidEndEditing(_ textField: UITextField) { formViewController()?.endEditing(of: self) formViewController()?.textInputDidEndEditing(textField, cell: self) textFieldDidChange(textField) textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil) } open func textFieldShouldReturn(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true } open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true } open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true } open func textFieldShouldClear(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldClear(textField, cell: self) ?? true } open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true } }
mit
717002bf67a62b0afcb0946f8eac95e1
44.231198
324
0.675453
5.337936
false
false
false
false
playbasis/native-sdk-ios
PlaybasisSDK/Classes/PBForm/PBRecentActivityForm.swift
1
1346
// // PBRecentActivityForm.swift // Pods // // Created by Médéric Petit on 9/20/2559 BE. // // import UIKit public enum PBRecentActivityMode:String { case All = "all" case Player = "player" } public class PBRecentActivityForm: PBForm { // Optional public var playerId:String? public var offset:Int? = 0 public var limit:Int? = 20 public var lastReadActivityId:String? public var mode:PBRecentActivityMode = .All public var eventType:String? public var actionName:String? override public func params() -> [String : String] { var params:[String:String] = [:] params["mode"] = self.mode.rawValue if let mPlayerId = self.playerId { params["player_id"] = mPlayerId } if let mOffset = self.offset { params["offset"] = String(mOffset) } if let mLimit = self.limit { params["limit"] = String(mLimit) } if let mLastReadActivityId = self.lastReadActivityId { params["last_read_activity_id"] = mLastReadActivityId } if let mEventType = self.eventType { params["event_type"] = mEventType } if let mActionName = self.actionName { params["action_name"] = mActionName } return params } }
mit
39d0e70f8d5576271e92d37f006475ed
24.358491
65
0.588542
4.036036
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Common/Zip/DataImport.swift
2
2840
// // DataImport.swift // SmartReceipts // // Created by Bogdan Evsenev on 11/06/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Zip import RxSwift class DataImport: NSObject { var inputPath: String! var outputPath: String! init(inputFile: String, output: String) { super.init() self.inputPath = inputFile self.outputPath = output Zip.addCustomFileExtension(inputPath.asNSString.pathExtension) } func execute(overwrite: Bool = false) -> Observable<Void> { return Observable<Void>.create({ [unowned self] observer -> Disposable in do { try FileManager.default.createDirectory(atPath: self.outputPath, withIntermediateDirectories: true, attributes: nil) try Zip.unzipFile(self.inputPath.asFileURL, destination: self.outputPath.asFileURL, overwrite: true, password: nil) // DB let backupPath = FileManager.pathInDocuments(relativePath: SmartReceiptsDatabaseExportName) if Database.sharedInstance().importData(fromBackup: backupPath, overwrite: overwrite) { // Preferences let prefPath = self.outputPath.asNSString.appendingPathComponent(SmartReceiptsPreferencesExportName) if let prefData = try? Data(contentsOf: prefPath.asFileURL) { WBPreferences.setFromXmlString(String(data: prefData, encoding: .utf8)) try? FileManager.default.removeItem(at: prefPath.asFileURL.deletingLastPathComponent()) } // Trips let trips = self.outputPath.asNSString.appendingPathComponent(SmartReceiptsTripsDirectoryName).asFileURL (try? FileManager.default.contentsOfDirectory(atPath: self.outputPath))?.forEach({ item in if item == SmartReceiptsTripsDirectoryName || item == SmartReceiptsDatabaseName || item == SmartReceiptsDatabaseExportName { return } let itemURL = self.outputPath.asNSString.appendingPathComponent(item).asFileURL try? FileManager.default.moveItem(at: itemURL, to: trips.appendingPathComponent(item)) }) observer.onNext(()) observer.onCompleted() } else { observer.onError(NSError(domain: "wb.import.db.error", code: 0, userInfo: nil)) } FileManager.deleteIfExists(filepath: backupPath) } catch { observer.onError(error) } return Disposables.create() }) } }
agpl-3.0
cb6c236a5eb2e1a2f04e47d1c586df84
44.063492
132
0.586122
5.480695
false
false
false
false
loudnate/Loop
Common/Extensions/SampleValue.swift
1
802
// // SampleValue.swift // Loop // // Copyright © 2018 LoopKit Authors. All rights reserved. // import HealthKit import LoopKit extension Collection where Element == SampleValue { /// O(n) var quantityRange: ClosedRange<HKQuantity>? { var lowest: HKQuantity? var highest: HKQuantity? for sample in self { if let l = lowest { lowest = Swift.min(l, sample.quantity) } else { lowest = sample.quantity } if let h = highest { highest = Swift.max(h, sample.quantity) } else { highest = sample.quantity } } guard let l = lowest, let h = highest else { return nil } return l...h } }
apache-2.0
a50e1c7d0c52b20378c63b531dfa2743
20.078947
58
0.508115
4.603448
false
false
false
false
twostraws/HackingWithSwift
SwiftUI/project12/Project12/SceneDelegate.swift
1
3411
// // SceneDelegate.swift // Project12 // // Created by Paul Hudson on 17/02/2020. // Copyright © 2020 Paul Hudson. All rights reserved. // import CoreData import SwiftUI import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Get the managed object context from the shared persistent container. let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = ContentView().environment(\.managedObjectContext, context) // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
unlicense
6e79967f20072f6f148df85ad35bf6c7
45.712329
147
0.715543
5.482315
false
false
false
false
willowtreeapps/PinkyPromise
PinkyPromise.playground/Pages/Promise.xcplaygroundpage/Contents.swift
1
7737
/*: [<< Result](@previous) • [Index](Index) # Promise PinkyPromise's `Promise` type represents an asynchronous operation that produces a value or an error after you start it. You start a `Promise<T>` by passing a completion block to the `call` method. When the work completes, it returns the value or error to the completion block as a `Result<T, Error>`. There are lots of implementations of Promises out there. This one is intended to be lightweight and hip to the best parts of Swift. > Promises will make more sense if you understand [Results](Result) first. */ import Foundation import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true struct ExampleError: Error {} let someError = ExampleError() //: Here are some simplistic Promises. When you use the `call` method, they will complete with their given value. let trivialSuccess: Promise<String> = Promise(value: "8675309") let trivialFailure: Promise<String> = Promise(error: someError) let trivialResult: Promise<String> = Promise(result: Result { "Hello, world" }) trivialSuccess.call { result in print(result) } /*: If you have a returning-or-throwing function, you can wrap it in a Promise. The promise will run the function and return its success or failure value. */ func dashedLine() throws -> String { let width = Int(arc4random_uniform(20)) - 10 guard 0 <= width else { throw someError } return Array(repeating: "-", count: width).joined(separator: "") } let dashedLinePromise = Promise.lift(dashedLine) /*: ## Asynchronous operations Most of the time you want a Promise to run an asynchronous operation that can succeed or fail. The usual asynchronous operation pattern on iOS is a function that takes arguments and a completion block, then begins the work. The completion block will receive an optional value and an optional error when the work completes. */ func getString(withArgument argument: String, completion: ((String?, Error?) -> Void)?) { delay(interval: .seconds(1)) { let value = "Completing: \(argument)" completion?(value, nil) } } getString(withArgument: "foo") { value, error in if let value = value { print(value) } else { print(String(describing: error)) } } /*: This is a loose contract not guaranteed by the compiler. We have only assumed that `error` is not nil when `value` is nil. Here's how you'd write that operation as a Promise, with a tighter contract. To make a new Promise, you create it with a task. A task is a block that itself has a completion block, usually called `fulfill`. The Promise runs the task to do its work, and when it's done, the task passes a `Result` to `fulfill`. Results must be a success or failure. */ func getStringPromise(withArgument argument: String) -> Promise<String> { return Promise { fulfill in delay(interval: .seconds(2)) { let value = "Completing: \(argument)" fulfill(Result { value }) } } } let stringPromise = getStringPromise(withArgument: "bar") /*: `stringPromise` has captured its task, and the task has captured the argument. It is an operation waiting to begin. So with Promises you can create operations and then start them later. You can start them more than once, or not at all. Next, we ask `stringPromise` to run by passing a completion block to the `call` method. `call` runs the task and routes the Result back to the completion block. When the Promise completes, our completion block will receive the Result. */ stringPromise.call { result in do { print(try result.get()) } catch { print(error) } } /*: As we've seen, with Promises, supplying the arguments and supplying the completion block are separate events. The greatest strength of a Promise is that in between those two events, the Promise is a value. ## Value transformations Just like `Result` values, we can transform `Promise` values in useful ways: - `zip` to combine many Promises into one Promise that produces a tuple or array. - `map` to transform a produced success value. (`Promise` is a functor.) - `flatMap` to transform a produced success value by running a whole new Promise that can succeed or fail. (`Promise` is a monad.) - `recover` to handle a failure by running another Promise that might succeed. - `retry` to repeat the Promise until it's successful, or until a failure count is reached. - `inBackground` to run a Promise in the background, then complete on the main queue. - `inDispatchGroup` to run a Promise as a task in a GCD dispatch group. - `onResult` to add a step to perform without modifying the result. - `onSuccess` to add a step to perform only when successful. - `onFailure` to add a step to perform only when failing. > Remember that a `Promise` value is an operation that hasn't been started yet and that can produce a value or error. We are transforming operations that haven't been started into other operations that we can start instead. */ let intPromise = stringPromise.map { Int($0) } let stringAndIntPromise = zip(stringPromise, intPromise) let twoStepPromise = stringPromise.flatMap { string in getStringPromise(withArgument: "\(string) baz") } let multipleOfTwoPromise = Promise<Int> { fulfill in let number = Int(arc4random_uniform(100)) fulfill(Result { if number % 2 == 0 { return number } else { throw someError } }) } let complexPromise = zip( multipleOfTwoPromise.recover { _ in return Promise(value: 2) }, getStringPromise(withArgument: "computed in the background") .inBackground() .map { "\($0) then extended on the main queue" } ) .retry(attemptCount: 3) .onResult { result in print("Complex promise produced success or failure: \(result)") } .onSuccess { int, string in print("Complex promise succeeded. Multiple of two: \(int), string: \(string)") } .onFailure { error in print("Complex promise failed: \(error)") } /*: Each of these transformations produced a new Promise but did not start it. When we transformed Results, the transformation always used the success or failure value of the first Result to produce the new Result. Transforming a Promise dosen't mean running it right away to get its Result. It means creating a second Promise that runs the first Promise as part of its own task. That means that all those nested calls that produced `complexPromise` haven't done any work. They've just described one big task to be done. Next we'll call that Promise and see what it produces. > If you thought this last Promise was complicated, imagine writing it with nested completion blocks! Because Promises are composable, transformable values, we can rely on transformations and just write one completion block. */ complexPromise.call { result in do { print(try result.get()) } catch { print(error) } } /*: ## PromiseQueue Promises of the same type can be run one at a time in a queue. */ let stringQueue = PromiseQueue<String>() //: Use `enqueue` instead of `call` to add promises one at a time and run them immediately. stringPromise.enqueue(in: stringQueue) twoStepPromise.enqueue(in: stringQueue) //: A queue can also make a batch promise that enqueues many promises and returns when the last has finished. let batchPromise = stringQueue.batch(promises: [stringPromise, twoStepPromise]) batchPromise.call { result in print("Batch produced successes or failure: \(result)") PlaygroundPage.current.finishExecution() } //: [<< Result](@previous) • [Index](Index)
mit
cbe286d2694f16ec4f466ee55317cfc3
37.282178
301
0.714212
4.274737
false
false
false
false
RajatDhasmana/rajat_appinventiv
GridAndTableView/GridAndTableView/TableVC.swift
1
2011
// // TableVC.swift // GridAndTableView // // Created by Mohd Sultan on 13/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit class TableVC: UIViewController { @IBOutlet weak var NameTableView: UITableView! let names = [ ["name" : "Rajat Dhasmana" , "color":UIColor.black], ["name" : "Rajat Dhasmana" , "color":UIColor.yellow], ["name" : "Rajat Dhasmana" , "color":UIColor.red], ["name" : "Rajat Dhasmana" , "color":UIColor.gray], ["name" : "Rajat Dhasmana" , "color":UIColor.blue], ["name" : "Rajat Dhasmana" , "color":UIColor.green], ["name" : "Rajat Dhasmana" , "color":UIColor.brown] ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. NameTableView.dataSource = self NameTableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension TableVC : UITableViewDataSource , UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tablecell = tableView.dequeueReusableCell(withIdentifier: "TableCellID", for: indexPath) as! TableCell let classobj = NameModel(dict: names[indexPath.row]) tablecell.configurecell(data: classobj) return tablecell } } class TableCell : UITableViewCell { @IBOutlet weak var tableImage: UIImageView! @IBOutlet weak var tableLabel: UILabel! func configurecell(data : NameModel) { tableImage.backgroundColor = data.color tableLabel.text = data.name } }
mit
2e07237418d386dd9ec708dcd1ec1ada
19.510204
114
0.610448
4.369565
false
false
false
false
mgfigueroa/Pterattack
Pterattack/Pterattack/GameScene.swift
1
6826
// // GameScene.swift // Pterattack // // Created by Michael Figueroa on 12/4/15. // Copyright (c) 2015 __MyCompanyName__. All rights reserved. // import SpriteKit import CoreMotion let UPGRADE_BITMASK : UInt32 = 0b1000 let PROJECTILE_BITMASK : UInt32 = 0b0100 let METEOR_BITMASK : UInt32 = 0b0010 let SHIP_BITMASK : UInt32 = 0b0001 let BLANK_BITMASK : UInt32 = 0b0000 class GameScene: SKScene, SKPhysicsContactDelegate { let THRESHOLD = 0.05 let VELOCITY = CGFloat(5.0) private static var instance : SKScene? private var motionManager = CMMotionManager() private var tilt = 0.0 private var ship : SpaceShip? private var level : Level? private var meteors = [Meteor]() private var projectiles = [Projectile]() private var upgrades = [Upgrade]() private var meteorsCreated = 0 private var healthBar : HealthBar? override func didMoveToView(view: SKView) { if motionManager.accelerometerAvailable == true { motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: { data, error in self.tilt = data!.acceleration.x }) } self.backgroundColor = SKColor.blackColor() self.physicsWorld.contactDelegate = self; self.physicsWorld.gravity = CGVectorMake(0, 0) ship = SpaceShip.getInstance() ship!.position = CGPointMake(size.width/2, size.height * 0.1) level = Level() self.addChild(ship!) healthBar = HealthBar() healthBar!.position = CGPointMake(size.width/2, size.height - 20) healthBar!.setProgress(1) addChild(healthBar!) let starField = SKEmitterNode(fileNamed: "StarField") starField!.position = CGPointMake(size.width/2,size.height) starField!.zPosition = -10 starField!.particlePositionRange = CGVectorMake(size.width, 0) addChild(starField!) } override func update(currentTime: CFTimeInterval) { updateShipPosition() createMeteors() createUpgrades() updateMeteors() updateProjectiles() updateUpgrades() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { projectiles.append((ship?.shoot())!) } func didBeginContact(contact: SKPhysicsContact) { var firstBody : SKPhysicsBody var secondBody : SKPhysicsBody if(contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } if((firstBody.categoryBitMask & SHIP_BITMASK > 0) && (secondBody.categoryBitMask & METEOR_BITMASK > 0)) { if(firstBody.node == nil || secondBody.node == nil){ return } let damageFromMeteor = (secondBody.node as! Meteor).damage meteors.remove(secondBody.node as! Meteor) secondBody.node?.removeFromParent() healthBar!.setProgress(CGFloat(ship!.health - damageFromMeteor) / CGFloat(ship!.maxHealth)) ship!.damage(damageFromMeteor) } else if((firstBody.categoryBitMask & METEOR_BITMASK > 0) && (secondBody.categoryBitMask & PROJECTILE_BITMASK > 0)) { firstBody.node?.removeFromParent() secondBody.node?.removeFromParent() } else if(secondBody.node != nil && (firstBody.categoryBitMask & SHIP_BITMASK > 0) && (secondBody.categoryBitMask & UPGRADE_BITMASK > 0)) { ship?.upgrade(secondBody.node as! Upgrade) upgrades.remove(secondBody.node as! Upgrade) secondBody.node?.removeFromParent() } } private func updateProjectiles() { for projectile in projectiles { projectile.position.y += CGFloat(projectile.velocity) } //Filters offscreen objects for projectile in projectiles.filter({ $0.position.y - $0.size.height / 2 > self.size.height }) { projectiles.remove(projectile) projectile.removeFromParent() } } private func updateMeteors() { if meteorsCreated >= level?.numberOfMeteors && meteors.isEmpty { level?.levelUp() meteorsCreated = 0 print("LEVEL UP BYTCHES") } for meteor in meteors { meteor.position.y -= CGFloat(meteor.velocity) } //Filters offscreen objects for meteor in meteors.filter({ $0.position.y + $0.size.height / 2 < 0 }) { meteors.remove(meteor) meteor.removeFromParent() } } private func createMeteors() { if meteorsCreated < level?.numberOfMeteors { if let meteor = level?.spawnMeteor() { addChild(meteor) meteors.append(meteor) meteorsCreated++ } } } private func updateUpgrades() { for upgrade in upgrades { upgrade.position.y -= CGFloat(upgrade.velocity) } //Filters offscreen objects for upgrade in upgrades.filter({ $0.position.y + $0.size.height / 2 < 0 }) { upgrades.remove(upgrade) upgrade.removeFromParent() } } private func createUpgrades() { if let upgrade = level?.spawnUpgrade() { addChild(upgrade) upgrades.append(upgrade) } } private func updateShipPosition() { if(abs(self.tilt) > THRESHOLD) { let offset = self.tilt > 0 ? VELOCITY : -VELOCITY ship!.position.x += offset ship!.mainShip!.zRotation = CGFloat(round(-self.tilt*10000)/10000) ship!.ghostShip!.zRotation = CGFloat(round(-self.tilt*10000)/10000) } else { ship!.mainShip!.zRotation = 0 ship!.ghostShip!.zRotation = 0 } if(ship!.position.x > self.size.width - (ship?.size.width)! / 2) { ship!.position.x -= self.size.width } else if(ship!.position.x < -ship!.size.width / 2) { ship!.position.x += self.size.width } } func shipDeath() { ship!.removeFromParent() } static func getInstance() -> SKScene? { if instance == nil { instance = GameScene(fileNamed:"GameScene") } return instance! } static func getInstance(size: CGSize) -> SKScene? { if instance == nil { instance = GameScene(size: size) } return instance! } }
apache-2.0
a378856b551f09985f782882d4d4ea14
32.135922
145
0.582625
4.487837
false
false
false
false
aatalyk/swift-algorithm-club
Graph/Graph/Vertex.swift
2
684
// // Vertex.swift // Graph // // Created by Andrew McKnight on 5/8/16. // import Foundation public struct Vertex<T>: Equatable where T: Equatable, T: Hashable { public var data: T public let index: Int } extension Vertex: CustomStringConvertible { public var description: String { get { return "\(index): \(data)" } } } extension Vertex: Hashable { public var hashValue: Int { get { return "\(data)\(index)".hashValue } } } public func ==<T: Equatable>(lhs: Vertex<T>, rhs: Vertex<T>) -> Bool { guard lhs.index == rhs.index else { return false } guard lhs.data == rhs.data else { return false } return true }
mit
a35176baa8dc761f5ee6b19756bbc568
13.553191
70
0.615497
3.5625
false
false
false
false
gottesmm/swift
test/SILGen/existential_erasure.swift
2
4638
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s protocol P { func downgrade(_ m68k: Bool) -> Self func upgrade() throws -> Self } protocol Q {} struct X: P, Q { func downgrade(_ m68k: Bool) -> X { return self } func upgrade() throws -> X { return self } } func makePQ() -> P & Q { return X() } func useP(_ x: P) { } func throwingFunc() throws -> Bool { return true } // CHECK-LABEL: sil hidden @_T019existential_erasure5PQtoPyyF : $@convention(thin) () -> () { func PQtoP() { // CHECK: [[PQ_PAYLOAD:%.*]] = open_existential_addr [[PQ:%.*]] : $*P & Q to $*[[OPENED_TYPE:@opened(.*) P & Q]] // CHECK: [[P_PAYLOAD:%.*]] = init_existential_addr [[P:%.*]] : $*P, $[[OPENED_TYPE]] // CHECK: copy_addr [take] [[PQ_PAYLOAD]] to [initialization] [[P_PAYLOAD]] // CHECK: deinit_existential_addr [[PQ]] // CHECK-NOT: destroy_addr [[P]] // CHECK-NOT: destroy_addr [[P_PAYLOAD]] // CHECK-NOT: destroy_addr [[PQ]] // CHECK-NOT: destroy_addr [[PQ_PAYLOAD]] useP(makePQ()) } // Make sure uninitialized existentials are properly deallocated when we // have an early return. // CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP1yAA1P_pKF func openExistentialToP1(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.downgrade!1, [[OPEN]] // CHECK: [[FUNC:%.*]] = function_ref @_T019existential_erasure12throwingFuncSbyKF // CHECK: try_apply [[FUNC]]() // // CHECK: bb1([[SUCCESS:%.*]] : $Bool): // CHECK: apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[SUCCESS]], [[OPEN]]) // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: return // // CHECK: bb2([[FAILURE:%.*]] : $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: throw [[FAILURE]] // try useP(p.downgrade(throwingFunc())) } // CHECK-LABEL: sil hidden @_T019existential_erasure19openExistentialToP2yAA1P_pKF func openExistentialToP2(_ p: P) throws { // CHECK: bb0(%0 : $*P): // CHECK: [[OPEN:%.*]] = open_existential_addr %0 : $*P to $*[[OPEN_TYPE:@opened\(.*\) P]] // CHECK: [[RESULT:%.*]] = alloc_stack $P // CHECK: [[RESULT_ADDR:%.*]] = init_existential_addr [[RESULT]] : $*P, $[[OPEN_TYPE]] // CHECK: [[METHOD:%.*]] = witness_method $[[OPEN_TYPE]], #P.upgrade!1, [[OPEN]] // CHECK: try_apply [[METHOD]]<[[OPEN_TYPE]]>([[RESULT_ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: return // // CHECK: bb2([[FAILURE:%.*]]: $Error): // CHECK: deinit_existential_addr [[RESULT]] // CHECK: dealloc_stack [[RESULT]] // CHECK: destroy_addr %0 // CHECK: throw [[FAILURE]] // try useP(p.upgrade()) } // Same as above but for boxed existentials extension Error { func returnOrThrowSelf() throws -> Self { throw self } } // CHECK-LABEL: sil hidden @_T019existential_erasure12errorHandlers5Error_psAC_pKF func errorHandler(_ e: Error) throws -> Error { // CHECK: bb0(%0 : $Error): // CHECK: debug_value %0 : $Error // CHECK: [[OPEN:%.*]] = open_existential_box %0 : $Error to $*[[OPEN_TYPE:@opened\(.*\) Error]] // CHECK: [[RESULT:%.*]] = alloc_existential_box $Error, $[[OPEN_TYPE]] // CHECK: [[ADDR:%.*]] = project_existential_box $[[OPEN_TYPE]] in [[RESULT]] : $Error // CHECK: [[FUNC:%.*]] = function_ref @_T0s5ErrorP19existential_erasureE17returnOrThrowSelf{{[_0-9a-zA-Z]*}}F // CHECK: try_apply [[FUNC]]<[[OPEN_TYPE]]>([[ADDR]], [[OPEN]]) // // CHECK: bb1 // CHECK: destroy_value %0 : $Error // CHECK: return [[RESULT]] : $Error // // CHECK: bb2([[FAILURE:%.*]] : $Error): // CHECK: dealloc_existential_box [[RESULT]] // CHECK: destroy_value %0 : $Error // CHECK: throw [[FAILURE]] : $Error // return try e.returnOrThrowSelf() } // rdar://problem/22003864 -- SIL verifier crash when init_existential_addr // references dynamic Self type class EraseDynamicSelf { required init() {} // CHECK-LABEL: sil hidden @_T019existential_erasure16EraseDynamicSelfC7factoryACXDyFZ : $@convention(method) (@thick EraseDynamicSelf.Type) -> @owned EraseDynamicSelf // CHECK: [[ANY:%.*]] = alloc_stack $Any // CHECK: init_existential_addr [[ANY]] : $*Any, $@dynamic_self EraseDynamicSelf // class func factory() -> Self { let instance = self.init() let _: Any = instance return instance } }
apache-2.0
36a1e72e6ee478a7b3feb8334172fc0a
33.61194
167
0.617508
3.254737
false
false
false
false
nostramap/nostra-sdk-sample-ios
SearchSample/Swift/SearchSample/LocalCategoryViewController.swift
1
2661
// // LocalCategoryViewController.swift // SearchSample // // Copyright © 2559 Globtech. All rights reserved. // import UIKit import NOSTRASDK class LocalCategoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var localCateogries: [NTLocalCategoryResult]! = []; @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. NTLocalCategoryService.executeAsync(nil, Completion: { (resultSet, error) in DispatchQueue.main.async(execute: { if error == nil { self.localCateogries = resultSet?.results; } else { print("error \(error?.description)"); } self.tableView.reloadData(); }) }); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "localCategorytoResultSegue" { let resultViewController = segue.destination as! ResultViewController; resultViewController.searchByLocalCategory(sender as? String); } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let category = localCateogries[indexPath.row]; self.performSegue(withIdentifier: "localCategorytoResultSegue", sender: category.categoryCode); } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell"); let category = localCateogries[indexPath.row]; cell?.textLabel?.text = category.name_E; return cell!; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return localCateogries != nil ? (localCateogries?.count)! : 0; } func numberOfSections(in tableView: UITableView) -> Int { return 1 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
dd82b4811957760bb4e16e3abd37ef0b
30.294118
106
0.628571
5.373737
false
false
false
false
JadenGeller/Handbag
Sources/BagIndex.swift
1
827
// // BagIndex.swift // Handbag // // Created by Jaden Geller on 1/11/16. // Copyright © 2016 Jaden Geller. All rights reserved. // public struct BagIndex<Element: Hashable> { internal let offset: Int internal init(offset: Int) { self.offset = offset } } extension BagIndex: Equatable, Comparable { } public func ==<Element>(lhs: BagIndex<Element>, rhs: BagIndex<Element>) -> Bool { return lhs.offset == rhs.offset } public func <<Element>(lhs: BagIndex<Element>, rhs: BagIndex<Element>) -> Bool { return lhs.offset < rhs.offset } extension BagIndex: BidirectionalIndexType { public func successor() -> BagIndex { return BagIndex(offset: offset.successor()) } public func predecessor() -> BagIndex { return BagIndex(offset: offset.predecessor()) } }
mit
1754ab59ac465fa2d16105c29c449cf4
24.060606
81
0.659806
3.859813
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/SpeechToTextV1/Models/Word.swift
1
3855
/** * (C) Copyright IBM Corp. 2017, 2020. * * 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 /** Information about a word from a custom language model. */ public struct Word: Codable, Equatable { /** A word from the custom model's words resource. The spelling of the word is used to train the model. */ public var word: String /** _For a custom model that is based on a previous-generation model_, an array of as many as five pronunciations for the word. The array can include the sounds-like pronunciation that is automatically generated by the service if none is provided when the word is added to the custom model; the service adds this pronunciation when it finishes processing the word. _For a custom model that is based on a next-generation model_, this field does not apply. Custom models based on next-generation models do not support the `sounds_like` field, which is ignored. */ public var soundsLike: [String] /** The spelling of the word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. */ public var displayAs: String /** _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before it is added by any corpora or grammars, the count begins at `1`; if the word is added from a corpus or grammar first and later modified, the count reflects only the number of times it is found in corpora and grammars. _For a custom model that is based on a next-generation model_, the `count` field for any word is always `1`. */ public var count: Int /** An array of sources that describes how the word was added to the custom model's words resource. * _For a custom model that is based on previous-generation model,_ the field includes the name of each corpus and grammar from which the service extracted the word. For OOV that are added by multiple corpora or grammars, the names of all corpora and grammars are listed. If you modified or added the word directly, the field includes the string `user`. * _For a custom model that is based on a next-generation model,_ this field shows only `user` for custom words that were added directly to the custom model. Words from corpora and grammars are not added to the words resource for custom models that are based on next-generation models. */ public var source: [String] /** If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. */ public var error: [WordError]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case word = "word" case soundsLike = "sounds_like" case displayAs = "display_as" case count = "count" case source = "source" case error = "error" } }
apache-2.0
b950e5f2c30b4c1b8c9d8409751de9e8
45.445783
120
0.709728
4.370748
false
false
false
false
parkera/swift-corelibs-foundation
Foundation/URLResponse.swift
1
19628
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /// An `URLResponse` object represents a URL load response in a /// manner independent of protocol and URL scheme. /// /// `URLResponse` encapsulates the metadata associated /// with a URL load. Note that URLResponse objects do not contain /// the actual bytes representing the content of a URL. See /// `URLSession` for more information about receiving the content /// data for a URL load. open class URLResponse : NSObject, NSSecureCoding, NSCopying { static public var supportsSecureCoding: Bool { return true } public required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if let encodedUrl = aDecoder.decodeObject(forKey: "NS.url") as? NSURL { self.url = encodedUrl._swiftObject } if let encodedMimeType = aDecoder.decodeObject(forKey: "NS.mimeType") as? NSString { self.mimeType = encodedMimeType._swiftObject } self.expectedContentLength = aDecoder.decodeInt64(forKey: "NS.expectedContentLength") if let encodedEncodingName = aDecoder.decodeObject(forKey: "NS.textEncodingName") as? NSString { self.textEncodingName = encodedEncodingName._swiftObject } if let encodedFilename = aDecoder.decodeObject(forKey: "NS.suggestedFilename") as? NSString { self.suggestedFilename = encodedFilename._swiftObject } } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.url?._bridgeToObjectiveC(), forKey: "NS.url") aCoder.encode(self.mimeType?._bridgeToObjectiveC(), forKey: "NS.mimeType") aCoder.encode(self.expectedContentLength, forKey: "NS.expectedContentLength") aCoder.encode(self.textEncodingName?._bridgeToObjectiveC(), forKey: "NS.textEncodingName") aCoder.encode(self.suggestedFilename?._bridgeToObjectiveC(), forKey: "NS.suggestedFilename") } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } /// Initialize an URLResponse with the provided values. /// /// This is the designated initializer for URLResponse. /// - Parameter URL: the URL /// - Parameter mimeType: the MIME content type of the response /// - Parameter expectedContentLength: the expected content length of the associated data /// - Parameter textEncodingName the name of the text encoding for the associated data, if applicable, else nil /// - Returns: The initialized URLResponse. public init(url: URL, mimeType: String?, expectedContentLength length: Int, textEncodingName name: String?) { self.url = url self.mimeType = mimeType self.expectedContentLength = Int64(length) self.textEncodingName = name let c = url.lastPathComponent self.suggestedFilename = c.isEmpty ? "Unknown" : c } /// The URL of the receiver. /*@NSCopying*/ open private(set) var url: URL? /// The MIME type of the receiver. /// /// The MIME type is based on the information provided /// from an origin source. However, that value may be changed or /// corrected by a protocol implementation if it can be determined /// that the origin server or source reported the information /// incorrectly or imprecisely. An attempt to guess the MIME type may /// be made if the origin source did not report any such information. open fileprivate(set) var mimeType: String? /// The expected content length of the receiver. /// /// Some protocol implementations report a content length /// as part of delivering load metadata, but not all protocols /// guarantee the amount of data that will be delivered in actuality. /// Hence, this method returns an expected amount. Clients should use /// this value as an advisory, and should be prepared to deal with /// either more or less data. /// /// The expected content length of the receiver, or `-1` if /// there is no expectation that can be arrived at regarding expected /// content length. open fileprivate(set) var expectedContentLength: Int64 /// The name of the text encoding of the receiver. /// /// This name will be the actual string reported by the /// origin source during the course of performing a protocol-specific /// URL load. Clients can inspect this string and convert it to an /// NSStringEncoding or CFStringEncoding using the methods and /// functions made available in the appropriate framework. open fileprivate(set) var textEncodingName: String? /// A suggested filename if the resource were saved to disk. /// /// The method first checks if the server has specified a filename /// using the content disposition header. If no valid filename is /// specified using that mechanism, this method checks the last path /// component of the URL. If no valid filename can be obtained using /// the last path component, this method uses the URL's host as the /// filename. If the URL's host can't be converted to a valid /// filename, the filename "unknown" is used. In mose cases, this /// method appends the proper file extension based on the MIME type. /// /// This method always returns a valid filename. open fileprivate(set) var suggestedFilename: String? } /// A Response to an HTTP URL load. /// /// An HTTPURLResponse object represents a response to an /// HTTP URL load. It is a specialization of URLResponse which /// provides conveniences for accessing information specific to HTTP /// protocol responses. open class HTTPURLResponse : URLResponse { /// Initializer for HTTPURLResponse objects. /// /// - Parameter url: the URL from which the response was generated. /// - Parameter statusCode: an HTTP status code. /// - Parameter httpVersion: The version of the HTTP response as represented by the server. This is typically represented as "HTTP/1.1". /// - Parameter headerFields: A dictionary representing the header keys and values of the server response. /// - Returns: the instance of the object, or `nil` if an error occurred during initialization. public init?(url: URL, statusCode: Int, httpVersion: String?, headerFields: [String : String]?) { self.statusCode = statusCode self.allHeaderFields = headerFields ?? [:] super.init(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil) expectedContentLength = getExpectedContentLength(fromHeaderFields: headerFields) ?? -1 suggestedFilename = getSuggestedFilename(fromHeaderFields: headerFields) ?? "Unknown" if let type = ContentTypeComponents(headerFields: headerFields) { mimeType = type.mimeType.lowercased() textEncodingName = type.textEncoding?.lowercased() } } public required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } self.statusCode = aDecoder.decodeInteger(forKey: "NS.statusCode") if let encodedHeaders = aDecoder.decodeObject(forKey: "NS.allHeaderFields") as? NSDictionary { self.allHeaderFields = encodedHeaders._swiftObject } else { self.allHeaderFields = [:] } super.init(coder: aDecoder) } open override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) //Will fail if .allowsKeyedCoding == false aCoder.encode(self.statusCode, forKey: "NS.statusCode") aCoder.encode(self.allHeaderFields._bridgeToObjectiveC(), forKey: "NS.allHeaderFields") } /// The HTTP status code of the receiver. public let statusCode: Int /// Returns a dictionary containing all the HTTP header fields /// of the receiver. /// /// By examining this header dictionary, clients can see /// the "raw" header information which was reported to the protocol /// implementation by the HTTP server. This may be of use to /// sophisticated or special-purpose HTTP clients. /// /// - Returns: A dictionary containing all the HTTP header fields of the /// receiver. /// /// - Important: This is an *experimental* change from the /// `[NSObject: AnyObject]` type that Darwin Foundation uses. public let allHeaderFields: [AnyHashable : Any] /// Convenience method which returns a localized string /// corresponding to the status code for this response. /// - Parameter forStatusCode: the status code to use to produce a localized string. open class func localizedString(forStatusCode statusCode: Int) -> String { switch statusCode { case 100: return "Continue" case 101: return "Switching Protocols" case 102: return "Processing" case 100...199: return "Informational" case 200: return "OK" case 201: return "Created" case 202: return "Accepted" case 203: return "Non-Authoritative Information" case 204: return "No Content" case 205: return "Reset Content" case 206: return "Partial Content" case 207: return "Multi-Status" case 208: return "Already Reported" case 226: return "IM Used" case 200...299: return "Success" case 300: return "Multiple Choices" case 301: return "Moved Permanently" case 302: return "Found" case 303: return "See Other" case 304: return "Not Modified" case 305: return "Use Proxy" case 307: return "Temporary Redirect" case 308: return "Permanent Redirect" case 300...399: return "Redirection" case 400: return "Bad Request" case 401: return "Unauthorized" case 402: return "Payment Required" case 403: return "Forbidden" case 404: return "Not Found" case 405: return "Method Not Allowed" case 406: return "Not Acceptable" case 407: return "Proxy Authentication Required" case 408: return "Request Timeout" case 409: return "Conflict" case 410: return "Gone" case 411: return "Length Required" case 412: return "Precondition Failed" case 413: return "Payload Too Large" case 414: return "URI Too Long" case 415: return "Unsupported Media Type" case 416: return "Range Not Satisfiable" case 417: return "Expectation Failed" case 421: return "Misdirected Request" case 422: return "Unprocessable Entity" case 423: return "Locked" case 424: return "Failed Dependency" case 426: return "Upgrade Required" case 428: return "Precondition Required" case 429: return "Too Many Requests" case 431: return "Request Header Fields Too Large" case 451: return "Unavailable For Legal Reasons" case 400...499: return "Client Error" case 500: return "Internal Server Error" case 501: return "Not Implemented" case 502: return "Bad Gateway" case 503: return "Service Unavailable" case 504: return "Gateway Timeout" case 505: return "HTTP Version Not Supported" case 506: return "Variant Also Negotiates" case 507: return "Insufficient Storage" case 508: return "Loop Detected" case 510: return "Not Extended" case 511: return "Network Authentication Required" case 500...599: return "Server Error" default: return "Server Error" } } /// A string that represents the contents of the HTTPURLResponse Object. /// This property is intended to produce readable output. override open var description: String { var result = "<\(type(of: self)) \(Unmanaged.passUnretained(self).toOpaque())> { URL: \(url!.absoluteString) }{ status: \(statusCode), headers {\n" for(aKey, aValue) in allHeaderFields { guard let key = aKey as? String, let value = aValue as? String else { continue } //shouldn't typically fail here if((key.lowercased() == "content-disposition" && suggestedFilename != "Unknown") || key.lowercased() == "content-type") { result += " \"\(key)\" = \"\(value)\";\n" } else { result += " \"\(key)\" = \(value);\n" } } result += "} }" return result } } /// Parses the expected content length from the headers. /// /// Note that the message content length is different from the message /// transfer length. /// The transfer length can only be derived when the Transfer-Encoding is identity (default). /// For compressed content (Content-Encoding other than identity), there is not way to derive the /// content length from the transfer length. private func getExpectedContentLength(fromHeaderFields headerFields: [String : String]?) -> Int64? { guard let f = headerFields, let contentLengthS = valueForCaseInsensitiveKey("content-length", fields: f), let contentLength = Int64(contentLengthS) else { return nil } return contentLength } /// Parses the suggested filename from the `Content-Disposition` header. /// /// - SeeAlso: [RFC 2183](https://tools.ietf.org/html/rfc2183) private func getSuggestedFilename(fromHeaderFields headerFields: [String : String]?) -> String? { // Typical use looks like this: // Content-Disposition: attachment; filename="fname.ext" guard let f = headerFields, let contentDisposition = valueForCaseInsensitiveKey("content-disposition", fields: f), let field = contentDisposition.httpHeaderParts else { return nil } for part in field.parameters where part.attribute == "filename" { if let path = part.value { return _pathComponents(path)?.map{ $0 == "/" ? "" : $0}.joined(separator: "_") } else { return nil } } return nil } /// Parts corresponding to the `Content-Type` header field in a HTTP message. private struct ContentTypeComponents { /// For `text/html; charset=ISO-8859-4` this would be `text/html` let mimeType: String /// For `text/html; charset=ISO-8859-4` this would be `ISO-8859-4`. Will be /// `nil` when no `charset` is specified. let textEncoding: String? } extension ContentTypeComponents { /// Parses the `Content-Type` header field /// /// `Content-Type: text/html; charset=ISO-8859-4` would result in `("text/html", "ISO-8859-4")`, while /// `Content-Type: text/html` would result in `("text/html", nil)`. init?(headerFields: [String : String]?) { guard let f = headerFields, let contentType = valueForCaseInsensitiveKey("content-type", fields: f), let field = contentType.httpHeaderParts else { return nil } for parameter in field.parameters where parameter.attribute == "charset" { self.mimeType = field.value self.textEncoding = parameter.value return } self.mimeType = field.value self.textEncoding = nil } } /// A type with parameters /// /// RFC 2616 specifies a few types that can have parameters, e.g. `Content-Type`. /// These are specified like so /// ``` /// field = value *( ";" parameter ) /// value = token /// ``` /// where parameters are attribute/value as specified by /// ``` /// parameter = attribute "=" value /// attribute = token /// value = token | quoted-string /// ``` private struct ValueWithParameters { let value: String let parameters: [Parameter] struct Parameter { let attribute: String let value: String? } } private extension String { /// Split the string at each ";", remove any quoting. /// /// The trouble is if there's a /// ";" inside something that's quoted. And we can escape the separator and /// the quotes with a "\". var httpHeaderParts: ValueWithParameters? { var type: String? var parameters: [ValueWithParameters.Parameter] = [] let ws = CharacterSet.whitespaces func append(_ string: String) { if type == nil { type = string } else { if let r = string.range(of: "=") { let name = String(string[string.startIndex..<r.lowerBound]).trimmingCharacters(in: ws) let value = String(string[r.upperBound..<string.endIndex]).trimmingCharacters(in: ws) parameters.append(ValueWithParameters.Parameter(attribute: name, value: value)) } else { let name = string.trimmingCharacters(in: ws) parameters.append(ValueWithParameters.Parameter(attribute: name, value: nil)) } } } let escape = UnicodeScalar(0x5c)! // \ let quote = UnicodeScalar(0x22)! // " let separator = UnicodeScalar(0x3b)! // ; enum State { case nonQuoted(String) case nonQuotedEscaped(String) case quoted(String) case quotedEscaped(String) } var state = State.nonQuoted("") for next in unicodeScalars { switch (state, next) { case (.nonQuoted(let s), separator): append(s) state = .nonQuoted("") case (.nonQuoted(let s), escape): state = .nonQuotedEscaped(s + String(next)) case (.nonQuoted(let s), quote): state = .quoted(s) case (.nonQuoted(let s), _): state = .nonQuoted(s + String(next)) case (.nonQuotedEscaped(let s), _): state = .nonQuoted(s + String(next)) case (.quoted(let s), quote): state = .nonQuoted(s) case (.quoted(let s), escape): state = .quotedEscaped(s + String(next)) case (.quoted(let s), _): state = .quoted(s + String(next)) case (.quotedEscaped(let s), _): state = .quoted(s + String(next)) } } switch state { case .nonQuoted(let s): append(s) case .nonQuotedEscaped(let s): append(s) case .quoted(let s): append(s) case .quotedEscaped(let s): append(s) } guard let t = type else { return nil } return ValueWithParameters(value: t, parameters: parameters) } } private func valueForCaseInsensitiveKey(_ key: String, fields: [String: String]) -> String? { let kk = key.lowercased() for (k, v) in fields { if k.lowercased() == kk { return v } } return nil }
apache-2.0
3dfd2a9b657763380523496edbc0a6b6
41.393089
155
0.632209
4.809605
false
false
false
false
radazzouz/firefox-ios
Account/FxAClient10.swift
1
15478
/* 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 Alamofire import Shared import Foundation import FxA import Deferred import SwiftyJSON public let FxAClientErrorDomain = "org.mozilla.fxa.error" public let FxAClientUnknownError = NSError(domain: FxAClientErrorDomain, code: 999, userInfo: [NSLocalizedDescriptionKey: "Invalid server response"]) let KeyLength: Int = 32 public struct FxALoginResponse { public let remoteEmail: String public let uid: String public let verified: Bool public let sessionToken: Data public let keyFetchToken: Data } public struct FxAccountRemoteError { static let AttemptToOperateOnAnUnverifiedAccount: Int32 = 104 static let InvalidAuthenticationToken: Int32 = 110 static let EndpointIsNoLongerSupported: Int32 = 116 static let IncorrectLoginMethodForThisAccount: Int32 = 117 static let IncorrectKeyRetrievalMethodForThisAccount: Int32 = 118 static let IncorrectAPIVersionForThisAccount: Int32 = 119 static let UnknownDevice: Int32 = 123 static let DeviceSessionConflict: Int32 = 124 static let UnknownError: Int32 = 999 } public struct FxAKeysResponse { let kA: Data let wrapkB: Data } public struct FxASignResponse { let certificate: String } public struct FxAStatusResponse { let exists: Bool } public struct FxADevicesResponse { let devices: [FxADevice] } // fxa-auth-server produces error details like: // { // "code": 400, // matches the HTTP status code // "errno": 107, // stable application-level error number // "error": "Bad Request", // string description of the error type // "message": "the value of salt is not allowed to be undefined", // "info": "https://docs.dev.lcip.og/errors/1234" // link to more info on the error // } public enum FxAClientError { case remote(RemoteError) case local(NSError) } // Be aware that string interpolation doesn't work: rdar://17318018, much good that it will do. extension FxAClientError: MaybeErrorType { public var description: String { switch self { case let .remote(error): let errorString = error.error ?? NSLocalizedString("Missing error", comment: "Error for a missing remote error number") let messageString = error.message ?? NSLocalizedString("Missing message", comment: "Error for a missing remote error message") return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>" case let .local(error): return "<FxAClientError.Local Error Domain=\(error.domain) Code=\(error.code) \"\(error.localizedDescription)\">" } } } public struct RemoteError { let code: Int32 let errno: Int32 let error: String? let message: String? let info: String? var isUpgradeRequired: Bool { return errno == FxAccountRemoteError.EndpointIsNoLongerSupported || errno == FxAccountRemoteError.IncorrectLoginMethodForThisAccount || errno == FxAccountRemoteError.IncorrectKeyRetrievalMethodForThisAccount || errno == FxAccountRemoteError.IncorrectAPIVersionForThisAccount } var isInvalidAuthentication: Bool { return code == 401 } var isUnverified: Bool { return errno == FxAccountRemoteError.AttemptToOperateOnAnUnverifiedAccount } } open class FxAClient10 { let URL: URL public init(endpoint: URL? = nil) { self.URL = endpoint ?? ProductionFirefoxAccountConfiguration().authEndpointURL as URL } open class func KW(_ kw: String) -> Data { return ("identity.mozilla.com/picl/v1/" + kw).utf8EncodedData } /** * The token server accepts an X-Client-State header, which is the * lowercase-hex-encoded first 16 bytes of the SHA-256 hash of the * bytes of kB. */ open class func computeClientState(_ kB: Data) -> String? { if kB.count != 32 { return nil } return kB.sha256.subdata(in: 0..<16).hexEncodedString } open class func quickStretchPW(_ email: Data, password: Data) -> Data { var salt = KW("quickStretch") salt.append(":".utf8EncodedData) salt.append(email) return (password as NSData).derivePBKDF2HMACSHA256Key(withSalt: salt as Data!, iterations: 1000, length: 32) } open class func computeUnwrapKey(_ stretchedPW: Data) -> Data { let salt: Data = Data() let contextInfo: Data = KW("unwrapBkey") let bytes = (stretchedPW as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(KeyLength)) return bytes! } fileprivate class func remoteError(fromJSON json: JSON, statusCode: Int) -> RemoteError? { if json.error != nil || 200 <= statusCode && statusCode <= 299 { return nil } if let code = json["code"].int32 { if let errno = json["errno"].int32 { return RemoteError(code: code, errno: errno, error: json["error"].string, message: json["message"].string, info: json["info"].string) } } return nil } fileprivate class func loginResponse(fromJSON json: JSON) -> FxALoginResponse? { guard json.error == nil, let uid = json["uid"].string, let verified = json["verified"].bool, let sessionToken = json["sessionToken"].string, let keyFetchToken = json["keyFetchToken"].string else { return nil } return FxALoginResponse(remoteEmail: "", uid: uid, verified: verified, sessionToken: sessionToken.hexDecodedData, keyFetchToken: keyFetchToken.hexDecodedData) } fileprivate class func keysResponse(fromJSON keyRequestKey: Data, json: JSON) -> FxAKeysResponse? { guard json.error == nil, let bundle = json["bundle"].string else { return nil } let data = bundle.hexDecodedData guard data.count == 3 * KeyLength else { return nil } let ciphertext = data.subdata(in: 0..<(2 * KeyLength)) let MAC = data.subdata(in: (2 * KeyLength)..<(3 * KeyLength)) let salt: Data = Data() let contextInfo: Data = KW("account/keys") let bytes = (keyRequestKey as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength)) let respHMACKey = bytes?.subdata(in: 0..<KeyLength) let respXORKey = bytes?.subdata(in: KeyLength..<(3 * KeyLength)) guard let hmacKey = respHMACKey, ciphertext.hmacSha256WithKey(hmacKey) == MAC else { NSLog("Bad HMAC in /keys response!") return nil } guard let xorKey = respXORKey, let xoredBytes = ciphertext.xoredWith(xorKey) else { return nil } let kA = xoredBytes.subdata(in: 0..<KeyLength) let wrapkB = xoredBytes.subdata(in: KeyLength..<(2 * KeyLength)) return FxAKeysResponse(kA: kA, wrapkB: wrapkB) } fileprivate class func signResponse(fromJSON json: JSON) -> FxASignResponse? { guard json.error == nil, let cert = json["cert"].string else { return nil } return FxASignResponse(certificate: cert) } fileprivate class func statusResponse(fromJSON json: JSON) -> FxAStatusResponse? { guard json.error == nil, let exists = json["exists"].bool else { return nil } return FxAStatusResponse(exists: exists) } fileprivate class func devicesResponse(fromJSON json: JSON) -> FxADevicesResponse? { guard json.error == nil, let jsonDevices = json.array else { return nil } let devices = jsonDevices.flatMap { (jsonDevice) -> FxADevice? in return FxADevice.fromJSON(jsonDevice) } return FxADevicesResponse(devices: devices) } lazy fileprivate var alamofire: SessionManager = { let ua = UserAgent.fxaUserAgent let configuration = URLSessionConfiguration.ephemeral return SessionManager.managerWithUserAgent(ua, configuration: configuration) }() open func login(_ emailUTF8: Data, quickStretchedPW: Data, getKeys: Bool) -> Deferred<Maybe<FxALoginResponse>> { let authPW = (quickStretchedPW as NSData).deriveHKDFSHA256Key(withSalt: Data(), contextInfo: FxAClient10.KW("authPW"), length: 32) as NSData let parameters = [ "email": NSString(data: emailUTF8, encoding: String.Encoding.utf8.rawValue)!, "authPW": authPW.base16EncodedString(options: NSDataBase16EncodingOptions.lowerCase) as NSString, ] var URL: URL = self.URL.appendingPathComponent("/account/login") if getKeys { var components = URLComponents(url: URL, resolvingAgainstBaseURL: false)! components.query = "keys=true" URL = components.url! } var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = JSON(parameters).rawString()?.utf8EncodedData return makeRequest(mutableURLRequest, responseHandler: FxAClient10.loginResponse) } open func status(forUID uid: String) -> Deferred<Maybe<FxAStatusResponse>> { let statusURL = self.URL.appendingPathComponent("/account/status").withQueryParam("uid", value: uid) var mutableURLRequest = URLRequest(url: statusURL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") return makeRequest(mutableURLRequest, responseHandler: FxAClient10.statusResponse) } open func devices(withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevicesResponse>> { let URL = self.URL.appendingPathComponent("/account/devices") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxAClient10.devicesResponse) } open func registerOrUpdate(device: FxADevice, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevice>> { let URL = self.URL.appendingPathComponent("/account/device") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = device.toJSON().rawString()?.utf8EncodedData let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxADevice.fromJSON) } fileprivate func makeRequest<T>(_ request: URLRequest, responseHandler: @escaping (JSON) -> T?) -> Deferred<Maybe<T>> { let deferred = Deferred<Maybe<T>>() alamofire.request(request) .validate(contentType: ["application/json"]) .responseJSON { response in withExtendedLifetime(self.alamofire) { if let error = response.result.error { deferred.fill(Maybe(failure: FxAClientError.local(error as NSError))) return } if let data = response.result.value { let json = JSON(data) if let remoteError = FxAClient10.remoteError(fromJSON: json, statusCode: response.response!.statusCode) { deferred.fill(Maybe(failure: FxAClientError.remote(remoteError))) return } if let response = responseHandler(json) { deferred.fill(Maybe(success: response)) return } } deferred.fill(Maybe(failure: FxAClientError.local(FxAClientUnknownError))) } } return deferred } } extension FxAClient10: FxALoginClient { func keyPair() -> Deferred<Maybe<KeyPair>> { let result = RSAKeyPair.generate(withModulusSize: 2048)! // TODO: debate key size and extract this constant. return Deferred(value: Maybe(success: result)) } open func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let URL = self.URL.appendingPathComponent("/account/keys") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("keyFetchToken") let key = (keyFetchToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) let rangeStart = 2 * KeyLength let keyRequestKey = key.subdata(in: rangeStart..<(rangeStart + KeyLength)) return makeRequest(mutableURLRequest) { FxAClient10.keysResponse(fromJSON: keyRequestKey, json: $0) } } open func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let parameters = [ "publicKey": publicKey.jsonRepresentation() as NSDictionary, "duration": NSNumber(value: OneDayInMilliseconds), // The maximum the server will allow. ] let URL = self.URL.appendingPathComponent("/certificate/sign") var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.post.rawValue mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.httpBody = JSON(parameters as NSDictionary).rawString()?.utf8EncodedData let salt: Data = Data() let contextInfo: Data = FxAClient10.KW("sessionToken") let key = (sessionToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))! mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key) return makeRequest(mutableURLRequest, responseHandler: FxAClient10.signResponse) } }
mpl-2.0
d0cf940a9dd1a2cf6bbdc0b8a3dd1f0a
39.202597
148
0.647758
4.827823
false
false
false
false
srn214/Floral
Floral/Pods/WCDB.swift/swift/source/util/Convenience.swift
1
7096
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation extension Array { func joined(_ map: (Element) -> String, separateBy separator: String = ", ") -> String { var flag = false return reduce(into: "") { (output, element) in if flag { output.append(separator) } else { flag = true } output.append(map(element)) } } } extension Array where Element: StringProtocol { func joined(separateBy separator: String = ", ") -> String { var flag = false return reduce(into: "") { (output, element) in if flag { output.append(separator) } else { flag = true } output.append(String(element)) } } } extension Array where Element: Describable { func joined(separateBy separator: String = ", ") -> String { return joined({ $0.description }, separateBy: separator) } } extension Array where Element==ColumnResultConvertible { func joined(separateBy separator: String = ", ") -> String { return joined({ $0.asColumnResult().description }, separateBy: separator) } } extension Array where Element==ExpressionConvertible { func joined(separateBy separator: String = ", ") -> String { return joined({ $0.asExpression().description }, separateBy: separator) } } extension Array where Element==ColumnConvertible { func joined(separateBy separator: String = ", ") -> String { return joined({ $0.asColumn().description }, separateBy: separator) } } extension Array where Element==TableOrSubqueryConvertible { func joined(separateBy separator: String = ", ") -> String { return joined({ $0.asTableOrSubquery().description }, separateBy: separator) } } extension Array where Element==OrderConvertible { func joined(separateBy separator: String = ", ") -> String { return joined({ $0.asOrder().description }, separateBy: separator) } } extension Array where Element==ColumnIndexConvertible { func joined(separateBy separator: String = ", ") -> String { return joined({ $0.asIndex().description }, separateBy: separator) } func asIndexes() -> [ColumnIndex] { return map { $0.asIndex() } } } extension Array where Element==PropertyConvertible { func asCodingTableKeys() -> [CodingTableKeyBase] { return reduce(into: [CodingTableKeyBase]()) { (result, element) in result.append(element.codingTableKey) } } } extension Array { mutating func expand(toNewSize newSize: Int, fillWith value: Iterator.Element) { if count < newSize { append(contentsOf: repeatElement(value, count: count.distance(to: newSize))) } } } extension Array where Iterator.Element: FixedWidthInteger { mutating func expand(toNewSize newSize: Int) { expand(toNewSize: newSize, fillWith: 0) } } extension Dictionary { func joined(_ map: (Key, Value) -> String, separateBy separator: String = "," ) -> String { var flag = false return reduce(into: "", { (output, arg) in if flag { output.append(separator) } else { flag = true } output.append(map(arg.key, arg.value)) }) } } extension String { var lastPathComponent: String { return URL(fileURLWithPath: self).lastPathComponent } func stringByAppending(pathComponent: String) -> String { return URL(fileURLWithPath: self).appendingPathComponent(pathComponent).path } var cString: UnsafePointer<Int8>? { return UnsafePointer<Int8>((self as NSString).utf8String) } init?(bytes: UnsafeRawPointer, count: Int, encoding: String.Encoding) { self.init(data: Data(bytes: bytes, count: count), encoding: encoding) } func range(from begin: Int, to end: Int) -> Range<String.Index> { return index(startIndex, offsetBy: begin)..<index(startIndex, offsetBy: end) } func range(location: Int, length: Int) -> Range<String.Index> { return range(from: location, to: location + length) } } extension Bool { @inline(__always) func toInt32() -> Int32 { return self ? 1 : 0 } } extension Int { @inline(__always) func toInt64() -> Int64 { return Int64(self) } } extension Int8 { @inline(__always) func toInt32() -> Int32 { return Int32(self) } } extension Int16 { @inline(__always) func toInt32() -> Int32 { return Int32(self) } } extension Int32 { @inline(__always) func toBool() -> Bool { return self != 0 } @inline(__always) func toInt8() -> Int8 { return Int8(truncatingIfNeeded: self) } @inline(__always) func toInt16() -> Int16 { return Int16(truncatingIfNeeded: self) } @inline(__always) func toUInt8() -> UInt8 { return UInt8(bitPattern: Int8(truncatingIfNeeded: self)) } @inline(__always) func toUInt16() -> UInt16 { return UInt16(bitPattern: Int16(truncatingIfNeeded: self)) } @inline(__always) func toUInt32() -> UInt32 { return UInt32(bitPattern: self) } } extension Int64 { @inline(__always) func toInt() -> Int { return Int(truncatingIfNeeded: self) } @inline(__always) func toUInt() -> UInt { return UInt(bitPattern: Int(truncatingIfNeeded: self)) } @inline(__always) func toUInt64() -> UInt64 { return UInt64(bitPattern: self) } } extension UInt { @inline(__always) func toInt64() -> Int64 { return Int64(bitPattern: UInt64(self)) } } extension UInt8 { @inline(__always) func toInt32() -> Int32 { return Int32(bitPattern: UInt32(self)) } } extension UInt16 { @inline(__always) func toInt32() -> Int32 { return Int32(bitPattern: UInt32(self)) } } extension UInt32 { @inline(__always) func toInt32() -> Int32 { return Int32(bitPattern: self) } } extension UInt64 { @inline(__always) func toInt64() -> Int64 { return Int64(bitPattern: self) } } extension Float { @inline(__always) func toDouble() -> Double { return Double(self) } } extension Double { @inline(__always) func toFloat() -> Float { return Float(self) } }
mit
bb02aa421873542bf05731b23271ba3a
26.71875
95
0.619222
4.118398
false
false
false
false
bioeauty/BlastWithCamera
UploadDemo/ViewController.swift
1
11227
// // ViewController.swift // UploadDemo // // Created by FOX on 15/8/22. // Copyright (c) 2015年 mingchen'lab. All rights reserved. // import UIKit import SwiftyJSON class ViewController: UIViewController,UIAlertViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate, UIPopoverControllerDelegate,NSURLSessionDataDelegate{ @IBOutlet var myView: UIView! @IBOutlet weak var TitleLobel: UILabel! var picker:UIImagePickerController?=UIImagePickerController() var popover:UIPopoverController?=nil @IBOutlet weak var btnClickMe: UIButton! @IBOutlet weak var myImageView: UIImageView! @IBOutlet weak var myScrollView: UIScrollView! @IBOutlet weak var imageUploadProgressView: UIProgressView! @IBOutlet weak var uploadButton: UIButton! @IBOutlet weak var progressLable: UILabel! @IBOutlet weak var ocrLabel: UILabel! @IBAction func uploadButtonTapped(sender: AnyObject) { if myImageView.image == nil { print("keep") } else { myImageUploadRequest() } } @IBAction func btnImagePickerClicked(sender: AnyObject) { let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default) { UIAlertAction in self.openCamera() } let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default) { UIAlertAction in self.openGallary() } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { UIAlertAction in } // Add the actions picker?.delegate = self alert.addAction(cameraAction) alert.addAction(gallaryAction) alert.addAction(cancelAction) // Present the controller if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.presentViewController(alert, animated: true, completion: nil) } else { popover=UIPopoverController(contentViewController: alert) popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } } func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { picker!.sourceType = UIImagePickerControllerSourceType.Camera self .presentViewController(picker!, animated: true, completion: nil) } else { openGallary() } } func openGallary() { // var myPickerController = UIImagePickerController() // myPickerController.delegate = self; // myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary // self.presentViewController(myPickerController, animated: true, completion: nil) picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary if UIDevice.currentDevice().userInterfaceIdiom == .Phone { self.presentViewController(picker!, animated: true, completion: nil) } else { popover=UIPopoverController(contentViewController: picker!) popover!.presentPopoverFromRect(btnClickMe.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage self.dismissViewControllerAnimated(true, completion: nil) let currentImage = myImageView.description print("\(myImageView.image?.decreaseSize)") } func myImageUploadRequest() { let myUrl = NSURL(string: "http://www.ibiocube.com/app/ocr.php"); let request = NSMutableURLRequest(URL:myUrl!); request.HTTPMethod = "POST"; request.timeoutInterval = 180; let param = [ "firstName" : "Yincong", "lastName" : "Zhou", "userId" : "9" ] let boundary = generateBoundaryString() request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let imageData = UIImageJPEGRepresentation(myImageView.image!, 1) if(imageData==nil) { return; } request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary) // myActivityIndicator.startAnimating(); let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } // You can print out response object // print("******* response = \(response)") // Print out reponse body let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) print("\(responseString)") // print("****** response data = \(responseString!)") self.TitleLobel.textColor = UIColor.blackColor() if let json = try!NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { let jsonresult = JSON(json) let message = jsonresult["content"].stringValue print("fox") print("\(message)") print("fox") self.ocrLabel.text = message } dispatch_async(dispatch_get_main_queue(),{ // self.myActivityIndicator.stopAnimating() self.myImageView.image = nil; }); // if let parseJSON = json { // var firstNameValue = parseJSON["firstName"] as? String // println("firstNameValue: \(firstNameValue)") // } } let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue()) let task1 = session.uploadTaskWithRequest(request, fromData: imageData!) task.resume() task1.resume() } func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData { let body = NSMutableData(); let date = NSDate() let timeFormatter = NSDateFormatter() timeFormatter.dateFormat = "yyyMMddHHmmss" let strNowTime = timeFormatter.stringFromDate(date) as String if parameters != nil { for (key, value) in parameters! { body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.appendString("\(value)\r\n") } } let filename = "\(strNowTime).jpg" let mimetype = "image/jpg" body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n") body.appendString("Content-Type: \(mimetype)\r\n\r\n") body.appendData(imageDataKey) body.appendString("\r\n") body.appendString("--\(boundary)--\r\n") return body } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { print("didCompleteWithError") let myAlert = UIAlertView(title: "Alert", message: error?.localizedDescription, delegate: nil, cancelButtonTitle: "Ok") myAlert.show() self.uploadButton.enabled = true } func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { print("didSendBodyData") let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend) imageUploadProgressView.progress = uploadProgress let progressPercent = Int(uploadProgress*100) progressLable.text = "\(progressPercent)%" print(uploadProgress) upload_checked() } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { print("didReceiveResponse") print(response); self.uploadButton.enabled = true } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { print("didReceiveData") } func generateBoundaryString() -> String { return "Boundary-\(NSUUID().UUIDString)" } func upload_checked() { if(progressLable.text == "100%") { progressLable.text = "OK" } } override func viewDidLoad() { super.viewDidLoad() TitleLobel.textColor = UIColor.whiteColor() // let localNotification: UILocalNotification = UILocalNotification() // localNotification.alertAction = "Testing notifications on iOS8" // localNotification.alertBody = "what a lovely day" // localNotification.fireDate = NSDate(timeIntervalSinceNow: 60) // UIApplication.sharedApplication().scheduleLocalNotification(localNotification) self.myView.addSubview(myScrollView) self.myScrollView.addSubview(ocrLabel) } } extension NSMutableData { func appendString(string: String) { let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) appendData(data!) } } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } //
mit
27b09120d3e3ee5c2338df5dfb2a2855
30.70904
225
0.589844
5.795044
false
false
false
false
wanliming11/MurlocAlgorithms
Last/LeetCode/String/58._Length_of_Last_Word/58. Length of Last Word/main.swift
1
1412
// // main.swift // 58. Length of Last Word // // Created by FlyingPuPu on 06/02/2017. // Copyright (c) 2017 FlyingPuPu. All rights reserved. // import Foundation /* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "Hello World", return 5. */ /* Thinking: 使用系统函数,切分成数组,计算最后一个的长度即可。 不使用系统函数,反向遍历,遇到空格则终止,但要考虑从不是空格的位置开始。 */ func lengthOfLastWord(_ s: String) -> Int { let length = s.lengthOfBytes(using: .ascii) guard length > 0 else { return 0 } let charArrays = s.characters var lastWordLength = 0 for i in stride(from: length - 1, through: 0, by: -1) { let index = charArrays.index(charArrays.startIndex, offsetBy: i) if charArrays[index] != " " { lastWordLength += 1 } else { if lastWordLength != 0 { break } } } return lastWordLength } print(lengthOfLastWord("abc def")) print(lengthOfLastWord("")) print(lengthOfLastWord(" ")) print(lengthOfLastWord("abc")) print(lengthOfLastWord("abc def ghi "))
mit
1b04edbbc23562feb0cf69469c669504
21.631579
133
0.643411
3.458445
false
false
false
false
joerocca/GitHawk
Classes/Views/AttributedStringView.swift
1
5075
// // AttributedStringView.swift // Freetime // // Created by Ryan Nystrom on 6/23/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit protocol AttributedStringViewDelegate: class { func didTapURL(view: AttributedStringView, url: URL) func didTapUsername(view: AttributedStringView, username: String) func didTapEmail(view: AttributedStringView, email: String) func didTapCommit(view: AttributedStringView, commit: CommitDetails) func didTapLabel(view: AttributedStringView, label: LabelDetails) } protocol AttributedStringViewIssueDelegate: class { func didTapIssue(view: AttributedStringView, issue: IssueDetailsModel) } final class AttributedStringView: UIView { weak var delegate: AttributedStringViewDelegate? weak var issueDelegate: AttributedStringViewIssueDelegate? private var text: NSAttributedStringSizing? private var tapGesture: UITapGestureRecognizer? private var longPressGesture: UILongPressGestureRecognizer? override init(frame: CGRect) { super.init(frame: frame) translatesAutoresizingMaskIntoConstraints = false backgroundColor = .white isOpaque = true layer.contentsGravity = kCAGravityTopLeft let tap = UITapGestureRecognizer(target: self, action: #selector(onTap(recognizer:))) tap.cancelsTouchesInView = false addGestureRecognizer(tap) self.tapGesture = tap let long = UILongPressGestureRecognizer(target: self, action: #selector(onLong(recognizer:))) addGestureRecognizer(long) self.longPressGesture = long } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var canBecomeFirstResponder: Bool { return true } // MARK: UIGestureRecognizerDelegate override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard (gestureRecognizer === tapGesture || gestureRecognizer === longPressGesture), let attributes = text?.attributes(point: gestureRecognizer.location(in: self)) else { return super.gestureRecognizerShouldBegin(gestureRecognizer) } for attribute in attributes { if MarkdownAttribute.all.contains(attribute.key) { return true } } return false } // MARK: Accessibility override var accessibilityLabel: String? { get { return text?.attributedText.string } set { } } // MARK: Public API func reposition(width: CGFloat) { guard let text = text else { return } layer.contents = text.contents(width) let rect = CGRect(origin: .zero, size: text.textViewSize(width)) frame = UIEdgeInsetsInsetRect(rect, text.inset) } func configureAndSizeToFit(text: NSAttributedStringSizing, width: CGFloat) { self.text = text layer.contentsScale = text.screenScale reposition(width: width) } // MARK: Private API @objc func onTap(recognizer: UITapGestureRecognizer) { guard let attributes = text?.attributes(point: recognizer.location(in: self)) else { return } if let urlString = attributes[MarkdownAttribute.url] as? String, let url = URL(string: urlString) { delegate?.didTapURL(view: self, url: url) } else if let usernameString = attributes[MarkdownAttribute.username] as? String { delegate?.didTapUsername(view: self, username: usernameString) } else if let emailString = attributes[MarkdownAttribute.email] as? String { delegate?.didTapEmail(view: self, email: emailString) } else if let issue = attributes[MarkdownAttribute.issue] as? IssueDetailsModel { issueDelegate?.didTapIssue(view: self, issue: issue) } else if let label = attributes[MarkdownAttribute.label] as? LabelDetails { delegate?.didTapLabel(view: self, label: label) } else if let commit = attributes[MarkdownAttribute.commit] as? CommitDetails { delegate?.didTapCommit(view: self, commit: commit) } } @objc func onLong(recognizer: UILongPressGestureRecognizer) { guard recognizer.state == .began else { return } let point = recognizer.location(in: self) guard let attributes = text?.attributes(point: point) else { return } if let details = attributes[MarkdownAttribute.details] as? String { showDetailsInMenu(details: details, point: point) } } @objc func showDetailsInMenu(details: String, point: CGPoint) { becomeFirstResponder() let menu = UIMenuController.shared menu.menuItems = [ UIMenuItem(title: details, action: #selector(AttributedStringView.empty)) ] menu.setTargetRect(CGRect(origin: point, size: CGSize(width: 1, height: 1)), in: self) menu.setMenuVisible(true, animated: trueUnlessReduceMotionEnabled) } @objc func empty() {} }
mit
ce5793deed766e33a37ccf6e6823a43e
35.503597
107
0.679937
4.984283
false
false
false
false
swiftcodex/Swift-Radio-Pro
SwiftRadio/RadioStation.swift
1
1024
// // RadioStation.swift // Swift Radio // // Created by Matthew Fecher on 7/4/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit //***************************************************************** // Radio Station //***************************************************************** struct RadioStation: Codable { var name: String var streamURL: String var imageURL: String var desc: String var longDesc: String init(name: String, streamURL: String, imageURL: String, desc: String, longDesc: String = "") { self.name = name self.streamURL = streamURL self.imageURL = imageURL self.desc = desc self.longDesc = longDesc } } extension RadioStation: Equatable { static func == (lhs: RadioStation, rhs: RadioStation) -> Bool { return (lhs.name == rhs.name) && (lhs.streamURL == rhs.streamURL) && (lhs.imageURL == rhs.imageURL) && (lhs.desc == rhs.desc) && (lhs.longDesc == rhs.longDesc) } }
mit
ad9de5a044e3dd6a328901b269777189
26.675676
167
0.543945
4.302521
false
false
false
false
erduoniba/FDDUITableViewDemoSwift
FDDUITableViewDemoSwift/FDDBaseRepo/FDDTableViewConverter.swift
1
6551
// // FDDTableViewConverter.swift // FDDUITableViewDemoSwift // // Created by denglibing on 2017/2/10. // Copyright © 2017年 denglibing. All rights reserved. // Demo: https://github.com/erduoniba/FDDUITableViewDemoSwift // import UIKit extension UITableView { func cellForIndexPath(_ indexPath: IndexPath, cellClass: AnyClass?) -> FDDBaseTableViewCell? { return self.cellForIndexPath(indexPath, cellClass: cellClass, cellReuseIdentifier: nil) } func cellForIndexPath(_ indexPath: IndexPath, cellClass: AnyClass?, cellReuseIdentifier: String?) -> FDDBaseTableViewCell? { if (cellClass?.isSubclass(of: FDDBaseTableViewCell.self))! { var identifier = NSStringFromClass(cellClass!) + "ID" if cellReuseIdentifier != nil { identifier = cellReuseIdentifier! } var cell = self.dequeueReusableCell(withIdentifier: identifier) if cell == nil { self.register(cellClass, forCellReuseIdentifier: identifier) cell = self.dequeueReusableCell(withIdentifier: identifier, for: indexPath) } return cell as? FDDBaseTableViewCell } return nil } } // 通过重载来实现特殊的cell extension FDDBaseTableViewController { @objc(tableView:numberOfRowsInSection:) open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArr.count } @objc(tableView:cellForRowAtIndexPath:) open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellModel: FDDBaseCellModel = (self.dataArr.object(at: indexPath.row) as? FDDBaseCellModel)! let cell: FDDBaseTableViewCell if cellModel.cellReuseIdentifier != nil { cell = tableView.cellForIndexPath(indexPath, cellClass: cellModel.cellClass, cellReuseIdentifier: cellModel.cellReuseIdentifier)! } else { cell = tableView.cellForIndexPath(indexPath, cellClass: cellModel.cellClass)! } cell.setCellData(cellModel.cellData, delegate: self) cell.setSeperatorAtIndexPath(indexPath, numberOfRowsInSection: self.dataArr.count) return cell } @objc(tableView:heightForRowAtIndexPath:) open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let cellModel: FDDBaseCellModel = (self.dataArr.object(at: indexPath.row) as? FDDBaseCellModel)! return CGFloat(cellModel.cellHeight) } // MARK: - FDDBaseTableViewCellDelegate open func fddTableViewCell(cell: FDDBaseTableViewCell, object: AnyObject?) { if cell.isMember(of: FDDBaseTableViewCell.self) { print("FDDBaseTableViewCell的代理") } } } public typealias FddTableViewConterterBlock = (_ params: [Any]) -> AnyObject? // 通过转换类来处理通用的tableView方法,特殊需要自己处理的使用 registerTableViewMethod 方式处理 public class FDDTableViewConverter: NSObject, UITableViewDataSource, UITableViewDelegate { deinit { print(NSStringFromClass(FDDTableViewConverter.self) + " dealloc") } private var selectorBlocks = NSMutableDictionary() open var dataArr = NSMutableArray() open weak var tableViewCarrier: AnyObject? convenience public init(withTableViewCarrier tableViewCarrier: AnyObject, dataSources: NSMutableArray) { self.init() self.tableViewCarrier = tableViewCarrier self.dataArr = dataSources } open func registerTableViewMethod(selector: Selector, handleParams params: FddTableViewConterterBlock) { selectorBlocks.setObject(params, forKey: NSStringFromSelector(selector) as NSCopying) } private func converterFunction(_ function: String, params: [Any]) -> AnyObject? { let result: Bool = self.selectorBlocks.allKeys.contains { ele in if String(describing: ele) == function { return true } else { return false } } if result { let block: FddTableViewConterterBlock = (self.selectorBlocks.object(forKey: function) as? FddTableViewConterterBlock)! return block(params) as AnyObject? } return nil } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArr.count } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let selector = #selector(tableView(_:heightForRowAt:)) let cellHeight = self.converterFunction(NSStringFromSelector(selector), params: [tableView, indexPath]) if cellHeight != nil { return (cellHeight as? CGFloat)! } let cellModel: FDDBaseCellModel = (self.dataArr.object(at: indexPath.row) as? FDDBaseCellModel)! return CGFloat(cellModel.cellHeight) } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let selector = #selector(tableView(_:cellForRowAt:)) let closureCell = self.converterFunction(NSStringFromSelector(selector), params: [tableView, indexPath]) if closureCell != nil { return (closureCell as? UITableViewCell)! } let cellModel: FDDBaseCellModel = (self.dataArr.object(at: indexPath.row) as? FDDBaseCellModel)! let cell: FDDBaseTableViewCell if cellModel.cellReuseIdentifier != nil { cell = tableView.cellForIndexPath(indexPath, cellClass: cellModel.cellClass, cellReuseIdentifier: cellModel.cellReuseIdentifier)! } else { cell = tableView.cellForIndexPath(indexPath, cellClass: cellModel.cellClass)! } cell.setCellData(cellModel.cellData, delegate: (self.tableViewCarrier as? FDDBaseTableViewCellDelegate)!) cell.setSeperatorAtIndexPath(indexPath, numberOfRowsInSection: self.dataArr.count) return cell } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selector = #selector(tableView(_:didSelectRowAt:)) _ = self.converterFunction(NSStringFromSelector(selector), params: [tableView, indexPath]) } public func scrollViewDidScroll(_ scrollView: UIScrollView) { let selector = #selector(scrollViewDidScroll(_:)) _ = self.converterFunction(NSStringFromSelector(selector), params: [scrollView]) } }
mit
f1db0fbe76bff0e326ea090410a0112c
40.171975
145
0.691677
5.05
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Mocks/MockBundle.swift
1
1576
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation @testable import PrebidMobile class MockBundle: PBMBundleProtocol { var mockBundleIdentifier: String? = "Mock.Bundle.Identifier" var mockBundleName: String? = "MockBundleName" var mockBundleDisplayName: String? = "MockBundleDisplayName" var mockShouldNilInfoDictionary = false var bundleIdentifier: String? { get { return self.mockBundleIdentifier } } var infoDictionary: [String : Any]? { guard !self.mockShouldNilInfoDictionary else { return nil } var dict = [String: Any]() if let mockBundleName = mockBundleName { dict[PBMAppInfoParameterBuilder.bundleNameKey] = mockBundleName } if let mockBundleDisplayName = mockBundleDisplayName { dict[PBMAppInfoParameterBuilder.bundleDisplayNameKey] = mockBundleDisplayName } return dict } }
apache-2.0
47f380f6d89daa8c3fbc63be4700ff89
29.686275
89
0.676038
4.890625
false
false
false
false
Tomikes/eidolon
Kiosk/App/Logger.swift
8
2181
import Foundation class Logger { let destination: NSURL lazy private var dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.locale = NSLocale.currentLocale() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" return formatter }() lazy private var fileHandle: NSFileHandle? = { if let path = self.destination.path { NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil) var error: NSError? if let fileHandle = try? NSFileHandle(forWritingToURL: self.destination) { print("Successfully logging to: \(path)") return fileHandle } else { print("Serious error in logging: could not open path to log file. \(error).") } } else { print("Serious error in logging: specified destination (\(self.destination)) does not appear to have a path component.") } return nil }() init(destination: NSURL) { self.destination = destination } deinit { fileHandle?.closeFile() } func log(message: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) { let logMessage = stringRepresentation(message, function: function, file: file, line: line) printToConsole(logMessage) printToDestination(logMessage) } } private extension Logger { func stringRepresentation(message: String, function: String, file: String, line: Int) -> String { let dateString = dateFormatter.stringFromDate(NSDate()) let file = NSURL(fileURLWithPath: file).lastPathComponent ?? "(Unknown File)" return "\(dateString) [\(file):\(line)] \(function): \(message)\n" } func printToConsole(logMessage: String) { print(logMessage) } func printToDestination(logMessage: String) { if let data = logMessage.dataUsingEncoding(NSUTF8StringEncoding) { fileHandle?.writeData(data) } else { print("Serious error in logging: could not encode logged string into data.") } } }
mit
9330dea6644b89688c996306e5eda523
32.553846
132
0.62265
5.002294
false
false
false
false
bestwpw/RxSwift
RxSwift/Observables/Implementations/ObserveOn.swift
2
3373
// ObserveOn.swift // RxSwift // // Created by Krunoslav Zaher on 7/25/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ObserveOn<E> : Producer<E> { let scheduler: ImmediateScheduler let source: Observable<E> init(source: Observable<E>, scheduler: ImmediateScheduler) { self.scheduler = scheduler self.source = source #if TRACE_RESOURCES OSAtomicIncrement32(&resourceCount) #endif } override func run<O : ObserverType where O.E == E>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = ObserveOnSink(scheduler: scheduler, observer: observer, cancel: cancel) setSink(sink) return source.subscribeSafe(sink) } #if TRACE_RESOURCES deinit { OSAtomicDecrement32(&resourceCount) } #endif } enum ObserveOnState : Int32 { // pump is not running case Stopped = 0 // pump is running case Running = 1 } class ObserveOnSink<O: ObserverType> : ObserverBase<O.E> { typealias E = O.E var cancel: Disposable let scheduler: ImmediateScheduler var observer: O? var state = ObserveOnState.Stopped var queue = Queue<Event<E>>(capacity: 10) let scheduleDisposable = SerialDisposable() init(scheduler: ImmediateScheduler, observer: O, cancel: Disposable) { self.cancel = cancel self.scheduler = scheduler self.observer = observer } override func onCore(event: Event<E>) { let shouldStart = lock.calculateLocked { () -> Bool in self.queue.enqueue(event) switch self.state { case .Stopped: self.state = .Running return true case .Running: return false } } if shouldStart { scheduleDisposable.disposable = self.scheduler.scheduleRecursively((), action: self.run) } } func run(state: Void, recurse: Void -> Void) { let (nextEvent, observer) = self.lock.calculateLocked { () -> (Event<E>?, O?) in if self.queue.count > 0 { return (self.queue.dequeue(), self.observer) } else { self.state = .Stopped return (nil, self.observer) } } if let nextEvent = nextEvent { observer?.on(nextEvent) if nextEvent.isStopEvent { self.dispose() } } else { return } let shouldContinue = self.lock.calculateLocked { () -> Bool in if self.queue.count > 0 { return true } else { self.state = .Stopped return false } } if shouldContinue { recurse() } } override func dispose() { super.dispose() let toDispose = lock.calculateLocked { () -> Disposable in let originalCancel = self.cancel self.cancel = NopDisposable.instance self.scheduleDisposable.dispose() self.observer = nil return originalCancel } toDispose.dispose() } }
mit
942803b82db71330a958b3e6305d8125
24.953846
134
0.543433
4.853237
false
false
false
false
WeMadeCode/ZXPageView
ZXPageView/Classes/ZXHorizontalView.swift
1
6748
// // ZXWaterView.swift // Pods-ZXPageView_Example // // Created by Anthony on 2019/3/15. // import UIKit public protocol ZXHorizontalViewDataSource : AnyObject { func numberOfSectionsInWaterView(_ waterView : ZXHorizontalView) -> Int func waterView(_ waterView : ZXHorizontalView, numberOfItemsInSection section: Int) -> Int func waterView(_ waterView : ZXHorizontalView, cellForItemAtIndexPath indexPath : IndexPath) -> UICollectionViewCell } @objc public protocol ZXHorizontalViewDelegate : AnyObject { @objc optional func waterView(_ waterView : ZXHorizontalView, didSelectedAtIndexPath indexPath : IndexPath) } public class ZXHorizontalView: UIView { public weak var dataSource : ZXHorizontalViewDataSource? public weak var delegate : ZXHorizontalViewDelegate? private var style : ZXPageStyle private var titles : [String] private var layout : ZXHorizontalViewLayout private lazy var currentSection : Int = 0 private lazy var collectionView : UICollectionView = { let frame = CGRect(x: 0, y: style.titleHeight, width: bounds.width, height: bounds.height - style.titleHeight - style.pageControlHeight) let clv = UICollectionView(frame: frame, collectionViewLayout: layout) clv.isPagingEnabled = true clv.scrollsToTop = false clv.showsHorizontalScrollIndicator = false clv.dataSource = self clv.delegate = self return clv }() private lazy var pageControl : UIPageControl = { let frame = CGRect(x: 0, y: collectionView.frame.maxY, width: bounds.width, height: style.pageControlHeight) let page = UIPageControl(frame: frame) page.numberOfPages = 4 page.isEnabled = false return page }() private lazy var titleView: ZXTitleView = { let titleFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.style.titleHeight) let titleView = ZXTitleView(frame: titleFrame, style: self.style, titles: self.titles , defaultIndex : 0) return titleView }() public init(frame: CGRect, style : ZXPageStyle, titles : [String], layout : ZXHorizontalViewLayout) { self.style = style self.titles = titles self.layout = layout super.init(frame: frame) setupSubView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupSubView() { // 1.添加titleView self.addSubview(titleView) // 2.添加collectionView self.addSubview(collectionView) // 3.添加UIPageControl self.addSubview(pageControl) // 4.监听titleView的点击xxx self.titleView.delegate = self } } // MARK:- 实现ZXTitleView的代理方法 extension ZXHorizontalView : ZXTitleViewDelegate { public func titleView(_ titleView: ZXTitleView, nextTitle: String, nextIndex: Int) { // 1.滚动到正确的位置 let indexPath = IndexPath(item: 0, section: nextIndex) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) // 2.微调collectionView -- contentOffset collectionView.contentOffset.x -= layout.sectionInset.left // 3.改变pageControl的numberOfPages let itemCount = dataSource?.waterView(self, numberOfItemsInSection: nextIndex) ?? 0 pageControl.numberOfPages = (itemCount - 1) / (layout.rows * layout.cols) + 1 pageControl.currentPage = 0 // 4.记录最新的currentSection currentSection = nextIndex } } // MARK:- UICollectionView的数据源 extension ZXHorizontalView : UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource!.numberOfSectionsInWaterView(self) } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let itemCount = dataSource?.waterView(self, numberOfItemsInSection: section) ?? 0 if section == 0 { pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1 } return itemCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return dataSource!.waterView(self, cellForItemAtIndexPath: indexPath) } } // MARK:- UICollectionView的代理源 extension ZXHorizontalView : UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.waterView?(self, didSelectedAtIndexPath: indexPath) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { collectionViewDidEndScroll() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { collectionViewDidEndScroll() } } func collectionViewDidEndScroll() { // 1.获取当前显示页中的某一个cell的indexPath let point = CGPoint(x: layout.sectionInset.left + collectionView.contentOffset.x, y: layout.sectionInset.top) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } // 2.如果发现组(section)发生了改变, 那么重新设置pageControl的numberOfPages if indexPath.section != currentSection { // 2.1.改变pageControl的numberOfPages let itemCount = dataSource?.waterView(self, numberOfItemsInSection: indexPath.section) ?? 0 pageControl.numberOfPages = (itemCount - 1) / (layout.rows * layout.cols) + 1 // 2.2.记录最新的currentSection currentSection = indexPath.section // 2.3.让titleView选中最新的title titleView.setCurrentIndex(currentSection) } // 3.显示pageControl正确的currentPage let pageIndex = indexPath.item / 8 pageControl.currentPage = pageIndex } } // MARK:- 对外提供的函数 extension ZXHorizontalView { public func registerCell(_ cellClass : AnyClass?, identifier : String) { collectionView.register(cellClass, forCellWithReuseIdentifier: identifier) } public func registerNib(_ nib : UINib?, identifier : String) { collectionView.register(nib, forCellWithReuseIdentifier: identifier) } public func dequeueReusableCell(withReuseIdentifier : String, for indexPath : IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: withReuseIdentifier, for: indexPath) } }
mit
91433594b39925c031e2819229bac767
34.016043
144
0.687996
4.979468
false
false
false
false
wolf81/Nimbl3Survey
Nimbl3Survey/AppDelegate.swift
1
3196
// // AppDelegate.swift // Nimbl3Survey // // Created by Wolfgang Schreurs on 22/03/2017. // Copyright © 2017 Wolftrail. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) let viewController = SurveysViewController(transitionStyle: .scroll, navigationOrientation: .vertical) let navController = UINavigationController(rootViewController: viewController) self.window?.rootViewController = navController self.window?.makeKeyAndVisible() configureAppearance() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Private private func configureAppearance() { UINavigationBar.appearance().barTintColor = AppTheme.backgroundColor UINavigationBar.appearance().tintColor = AppTheme.foregroundColor UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: AppTheme.foregroundColor] UILabel.appearance().backgroundColor = .clear UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) UINavigationBar.appearance().backgroundColor = AppTheme.backgroundColor.withAlphaComponent(0.5) UINavigationBar.appearance().isTranslucent = true } }
bsd-2-clause
bf9861fd27346296ce23c1f1b3ee0404
47.409091
285
0.737715
5.894834
false
false
false
false
cuzv/ExtensionKit
Sources/Extension/UIApplication+Extension.swift
1
3589
// // UIApplication+Extension.swift // Copyright (c) 2015-2016 Red Rain (http://mochxiao.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 UIKit // MARK: - Actions public extension UIApplication { fileprivate static let _sharedApplication = UIApplication.shared public class func open(url: Foundation.URL) { if _sharedApplication.canOpenURL(url) { _sharedApplication.openURL(url) } else { logging("Can not execute the given action.") } } public class func open(urlPath: String) { if let url = URL(string: urlPath) { UIApplication.open(url: url) } } public class func makePhone(to phoneNumber: String) { open(urlPath: "telprompt:\(phoneNumber)") } public class func sendMessage(to phoneNumber: String) { open(urlPath: "sms:\(phoneNumber)") } public class func email(to email: String) { open(urlPath: "mailto:\(email)") } public class func chatQQ(to qq: String) { open(urlPath: "mqq://im/chat?chat_type=wpa&uin=\(qq)&version=1&src_type=iOS") } public class func clearIconBadge() { let badgeNumber = _sharedApplication.applicationIconBadgeNumber _sharedApplication.applicationIconBadgeNumber = 1 _sharedApplication.applicationIconBadgeNumber = 0 _sharedApplication.cancelAllLocalNotifications() _sharedApplication.applicationIconBadgeNumber = badgeNumber } public class func sendAction(_ action: Selector, fromSender sender: AnyObject?, forEvent event: UIEvent? = nil) -> Bool { // Get the target in the responder chain var target = sender while let _target = target , !_target.canPerformAction(action, withSender: sender) { target = _target.next } if let _target = target { return UIApplication.shared.sendAction(action, to: _target, from: sender, for: event) } return false } /// Setting the statusBarStyle does nothing if your application is using the default UIViewController-based status bar system. public class func makeStatusBarDark() { UIApplication.shared.statusBarStyle = .default } /// Setting the statusBarStyle does nothing if your application is using the default UIViewController-based status bar system. public class func makeStatusBarLight() { UIApplication.shared.statusBarStyle = .lightContent } }
mit
7beb432cba5ee92983f0202141c0c54d
37.591398
130
0.679298
4.772606
false
false
false
false
jessesquires/PresenterKit
Sources/HalfModalPresentationController.swift
1
3744
// // Created by Jesse Squires // https://www.jessesquires.com // // // Documentation // https://jessesquires.github.io/PresenterKit // // // GitHub // https://github.com/jessesquires/PresenterKit // // // License // Copyright © 2016-present Jesse Squires // Released under an MIT license: https://opensource.org/licenses/MIT // // swiftlint:disable type_contents_order import UIKit /// A modal presentation controller that presents the presented view controller modally, /// covering the bottom half of the presenting view controller. This presentation controller /// displays a transparent dimmed, tappable view over the top half of the presenting view controller. public final class HalfModalPresentationController: UIPresentationController { private lazy var dimmingView: UIView = { let view = UIView() view.backgroundColor = UIColor.black.withAlphaComponent(0.5) view.alpha = 0.0 let tap = UITapGestureRecognizer(target: self, action: #selector(Self.dimmingViewTapped(_:))) view.addGestureRecognizer(tap) return view }() /// :nodoc: override public init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) } /// :nodoc: override public func presentationTransitionWillBegin() { self.dimmingView.frame = containerView!.bounds self.dimmingView.alpha = 0.0 self.containerView?.insertSubview(self.dimmingView, at: 0) let animations = { self.dimmingView.alpha = 1.0 } if let transitionCoordinator = self.presentingViewController.transitionCoordinator { transitionCoordinator.animate(alongsideTransition: { _ in animations() }, completion: nil) } else { animations() } } /// :nodoc: override public func dismissalTransitionWillBegin() { let animations = { self.dimmingView.alpha = 0.0 } if let transitionCoordinator = presentingViewController.transitionCoordinator { transitionCoordinator.animate(alongsideTransition: { _ in animations() }, completion: nil) } else { animations() } } /// :nodoc: override public var adaptivePresentationStyle: UIModalPresentationStyle { .none } /// :nodoc: override public var shouldPresentInFullscreen: Bool { true } /// :nodoc: override public func size( forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize { CGSize(width: parentSize.width, height: round(parentSize.height / 2.0)) } /// :nodoc: override public func containerViewWillLayoutSubviews() { self.dimmingView.frame = self.containerView!.bounds self.presentedView?.frame = self.frameOfPresentedViewInContainerView } /// :nodoc: override public var frameOfPresentedViewInContainerView: CGRect { let size = self.size(forChildContentContainer: presentedViewController, withParentContainerSize: containerView!.bounds.size) let origin = CGPoint(x: 0.0, y: self.containerView!.frame.maxY / 2) return CGRect(origin: origin, size: size) } // MARK: Private @objc private func dimmingViewTapped(_ tap: UITapGestureRecognizer) { self.presentingViewController.dismiss(animated: true, completion: nil) } } // swiftlint:enable type_contents_order
mit
fcb549133d759395a7cf181b2da34115
30.453782
101
0.660166
5.347143
false
false
false
false
hokuron/QRCodeKit
Lib/QRCodeKit/QRCodeCaptureCamera.swift
1
7985
// // QRCodeCaptureCamera.swift // QRCodeKit // // Created by hokuron on 2015/03/20. // Copyright © 2015年 Takuma Shimizu. All rights reserved. // import AVFoundation public protocol QRCodeCaptureCameraDelegate: class { func qrCodeCaptureCamera(captureCamera: QRCodeCaptureCamera, didCaptureQRCodeMetadataObjects QRCodeMetadataObjects: [AVMetadataMachineReadableCodeObject]) } public class QRCodeCaptureCamera { public private(set) weak var delegate: QRCodeCaptureCameraDelegate? /// Whether to deliver the same capture results to the delegate. The default value is `false`. public var allowsSameValueCapturing: Bool { didSet { captureMetadataOutputObjectsDelegate.allowsSameValueCapturing = allowsSameValueCapturing } } public internal(set) lazy var previewLayer: AVCaptureVideoPreviewLayer! = AVCaptureVideoPreviewLayer(session: self.captureSession) public private(set) var captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) public let sessionQueue: dispatch_queue_t = dispatch_queue_create("com.hokuron.QRCodeKit.QRCodeCaptureCamera.sessionQueue", DISPATCH_QUEUE_SERIAL) public private(set) var captureSession = AVCaptureSession() let metadataQueue: dispatch_queue_t = dispatch_queue_create("com.hokuron.QRCodeKit.QRCodeCaptureCamera.metadataQueue", DISPATCH_QUEUE_SERIAL) lazy var metadataOutput: AVCaptureMetadataOutput = { let metadata = AVCaptureMetadataOutput() metadata.setMetadataObjectsDelegate(self.captureMetadataOutputObjectsDelegate, queue: self.metadataQueue) return metadata }() lazy var captureMetadataOutputObjectsDelegate: CaptureMetadataOutputObjectsDelegate = { let _delegate = CaptureMetadataOutputObjectsDelegate(allowsSameValueCapturing: self.allowsSameValueCapturing) { _, metadataObjects, _ in let metadataQRCodeObjects = metadataObjects.filter { $0.type == AVMetadataObjectTypeQRCode } dispatch_async(dispatch_get_main_queue()) { self.delegate?.qrCodeCaptureCamera(self, didCaptureQRCodeMetadataObjects: metadataQRCodeObjects) } } return _delegate }() /// - Parameters: /// - delegate: The delegate object to deliver when new QR code metadata objects become available. /// - allowsSameValueCapturing: The boolean value indicating whether to deliver the same capture results to the delegate. The default value is `false`. /// /// - Throws: `AVError` public init(delegate: QRCodeCaptureCameraDelegate, allowsSameValueCapturing: Bool = false) throws { self.delegate = delegate self.allowsSameValueCapturing = allowsSameValueCapturing try changeCaptureSession(captureSession) } /// Session starts running and resets focus and exposure. /// In addition, delivery to the delegate of the capture results will be enabled again. public func startSessionRunning() { captureMetadataOutputObjectsDelegate.activateCapturing() dispatch_async(sessionQueue) { self.captureSession.startRunning() } resetFocusAndExposure() } public func stopSessionRunning() { dispatch_async(sessionQueue) { self.captureSession.stopRunning() } } public func resetFocusAndExposure() { // TODO: Split into AVCaptureDevice+FocusAndExposure extension guard case .Some = try? captureDevice.lockForConfiguration() else { return print("A configuration lock cannot be acquired.") } let centerPoint = CGPoint(x: 0.5, y: 0.5) if captureDevice.focusPointOfInterestSupported && captureDevice.isFocusModeSupported(.ContinuousAutoFocus) { captureDevice.focusPointOfInterest = centerPoint captureDevice.focusMode = .ContinuousAutoFocus } if captureDevice.exposurePointOfInterestSupported && captureDevice.isExposureModeSupported(.ContinuousAutoExposure) { captureDevice.exposurePointOfInterest = centerPoint captureDevice.exposureMode = .ContinuousAutoExposure } captureDevice.unlockForConfiguration() } /// Add capture input and output to the passed `captureSession`. And change session of `previewLayer` to the passed `captureSession`. /// - Parameter captureSession: The new `AVCaptureSession` /// - Throws: `AVError` public func changeCaptureSession(captureSession: AVCaptureSession) throws { try changeCaptureDevice(captureDevice) dispatch_async(sessionQueue) { let metadataOutput = self.metadataOutput captureSession.beginConfiguration() if captureSession.canAddOutput(metadataOutput) { captureSession.addOutput(metadataOutput) metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] } if captureSession.canSetSessionPreset(AVCaptureSessionPresetPhoto) { captureSession.sessionPreset = AVCaptureSessionPresetPhoto } captureSession.commitConfiguration() } previewLayer.session = captureSession self.captureSession = captureSession } /// Change capture input for capture session /// - Parameter captureDevice: The new desired `AVCaptureDevice` /// - Throws: `AVError` public func changeCaptureDevice(captureDevice: AVCaptureDevice) throws { let deviceInput = try AVCaptureDeviceInput(device: captureDevice) let captureSession = self.captureSession dispatch_async(sessionQueue) { captureSession.beginConfiguration() (captureSession.inputs.filter { $0 is AVCaptureInput } as! [AVCaptureInput]).forEach { captureSession.removeInput($0) } if captureSession.canAddInput(deviceInput) { captureSession.addInput(deviceInput) } captureSession.commitConfiguration() } self.captureDevice = captureDevice } } // MARK: - Capture metadata output objects delegate extension QRCodeCaptureCamera { class CaptureMetadataOutputObjectsDelegate: NSObject, AVCaptureMetadataOutputObjectsDelegate { var allowsSameValueCapturing: Bool let captureHandler: (AVCaptureOutput, [AVMetadataMachineReadableCodeObject], AVCaptureConnection) -> Void var latestCapturedMetadataObjects: [CaptureMetadataQRCodeObject] = [] init(allowsSameValueCapturing: Bool, captureHandler: (AVCaptureOutput, [AVMetadataMachineReadableCodeObject], AVCaptureConnection) -> Void) { self.allowsSameValueCapturing = allowsSameValueCapturing self.captureHandler = captureHandler } func activateCapturing() { latestCapturedMetadataObjects = [] } func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { guard let metadataMachineReadableCodeObjects = metadataObjects as? [AVMetadataMachineReadableCodeObject] else { return } let captureMetadataQRCodeObjects = metadataMachineReadableCodeObjects.map { CaptureMetadataQRCodeObject(metadataObject: $0) } guard !allowsSameValueCapturing else { return captureHandler(captureOutput, metadataMachineReadableCodeObjects, connection) } guard latestCapturedMetadataObjects != captureMetadataQRCodeObjects else { return } latestCapturedMetadataObjects = captureMetadataQRCodeObjects captureHandler(captureOutput, metadataMachineReadableCodeObjects, connection) } } }
mit
76b80618ba9640d4568de0f717cc2a17
42.380435
166
0.696943
6.154202
false
false
false
false
daltonclaybrook/tween-controller
TweenController/Easing.swift
1
4978
// // Easing.swift // TweenController // // Created by Dalton Claybrook on 5/31/16. // // Copyright (c) 2017 Dalton Claybrook // // 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. // /// A collection of easing functions beautifully demonstrated at http://gizma.com/easing/ public struct Easing { // t is a time value between 0.0 - 1.0 // Return value is a value between 0.0 - 1.0 with the easing function applied public typealias Function = (_ t: Double) -> Double //MARK: Linear public static func linear(_ t: Double) -> Double { return t } //MARK: Quadratic public static func easeInQuad(_ t: Double) -> Double { return t * t } public static func easeOutQuad(_ t: Double) -> Double { return -t * (t - 2) } public static func easeInOutQuad(_ t: Double) -> Double { var _t = t / 0.5 if _t < 1.0 { return 0.5 * _t * _t } _t -= 1.0 return -0.5 * (_t * (_t - 2.0) - 1.0) } //MARK: Cubic public static func easeInCubic(_ t: Double) -> Double { return t * t * t } public static func easeOutCubic(_ t: Double) -> Double { let _t = t - 1.0 return _t * _t * _t + 1 } public static func easeInOutCubic(_ t: Double) -> Double { var _t = t / 0.5 if _t < 1.0 { return 0.5 * _t * _t * _t } _t -= 2.0 return 0.5 * (_t * _t * _t + 2.0) } //MARK: Quartic public static func easeInQuart(_ t: Double) -> Double { return t * t * t * t } public static func easeOutQuart(_ t: Double) -> Double { let _t = t - 1.0 return -(_t * _t * _t * _t + 1) } public static func easeInOutQuart(_ t: Double) -> Double { var _t = t / 0.5 if _t < 1.0 { return 0.5 * _t * _t * _t * _t } _t -= 2.0 return -0.5 * (_t * _t * _t * _t - 2.0) } //MARK: Quintic public static func easeInQuint(_ t: Double) -> Double { return t * t * t * t * t } public static func easeOutQuint(_ t: Double) -> Double { let _t = t - 1.0 return _t * _t * _t * _t * _t + 1 } public static func easeInOutQuint(_ t: Double) -> Double { var _t = t / 0.5 if _t < 1.0 { return 0.5 * _t * _t * _t * _t * _t } _t -= 2.0 return 0.5 * (_t * _t * _t * _t * _t + 2.0) } //MARK: Sinusoidal public static func easeInSine(_ t: Double) -> Double { return -cos(t * (Double.pi/2.0)) + 1.0 } public static func easeOutSine(_ t: Double) -> Double { return sin(t * (Double.pi/2.0)) } public static func easeInOutSine(_ t: Double) -> Double { return -0.5 * (cos(Double.pi * t) - 1.0) } //MARK: Exponential public static func easeInExpo(_ t: Double) -> Double { return pow(2.0, 10.0 * (t - 1.0)) } public static func easeOutExpo(_ t: Double) -> Double { return (-pow(2.0, -10.0 * t) + 1.0) } public static func easeInOutExpo(_ t: Double) -> Double { var _t = t / 0.5 if _t < 1.0 { return 0.5 * pow(2.0, 10.0 * (_t - 1.0)) } _t -= 1.0 return 0.5 * (-pow(2.0, -10.0 * _t) + 2.0) } //MARK: Circular public static func easeInCirc(_ t: Double) -> Double { return -(sqrt(1.0 - t * t) - 1.0) } public static func easeOutCirc(_ t: Double) -> Double { let _t = t - 1.0 return sqrt(1.0 - _t * _t) } public static func easeInOutCirc(_ t: Double) -> Double { var _t = t / 0.5 if _t < 1.0 { return -0.5 * (sqrt(1.0 - _t * _t) - 1.0) } _t -= 2.0 return 0.5 * (sqrt(1.0 - _t * _t) + 1.0) } }
mit
1f98644a240b9751be803e432fd02226
27.94186
89
0.52511
3.459347
false
false
false
false
proversity-org/edx-app-ios
Source/CourseCertificateView.swift
1
3886
// // CourseCertificateView.swift // edX // // Created by Salman on 05/01/2018. // Copyright © 2018 edX. All rights reserved. // import UIKit struct CourseCertificateIem { let certificateImage: UIImage let certificateUrl: String let action:(() -> Void)? } class CourseCertificateView: UIView { static let height: CGFloat = 100.0 private let certificateImageView = UIImageView() private let titleLabel = UILabel() private let subtitleLabel = UILabel() private lazy var viewCertificateButton: UIButton = { let button = UIButton() button.isUserInteractionEnabled = false button.applyButtonStyle(style: OEXStyles.shared().filledPrimaryButtonStyle, withTitle: Strings.Certificates.getCertificate) return button }() var certificateItem : CourseCertificateIem? { didSet { useItem(item: certificateItem) } } init() { super.init(frame: CGRect.zero) configureViews() } convenience init(certificateItem: CourseCertificateIem) { self.init() self.certificateItem = certificateItem useItem(item: certificateItem) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureViews() { backgroundColor = OEXStyles.shared().neutralXLight() addSubview(certificateImageView) addSubview(titleLabel) addSubview(subtitleLabel) addSubview(viewCertificateButton) certificateImageView.contentMode = .scaleAspectFit certificateImageView.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal) titleLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal) subtitleLabel.adjustsFontSizeToFitWidth = true certificateImageView.snp.makeConstraints { make in make.top.equalTo(self).offset(StandardVerticalMargin) make.bottom.equalTo(self).inset(StandardVerticalMargin) make.leading.equalTo(self).offset(StandardHorizontalMargin) } titleLabel.snp.makeConstraints { make in make.top.equalTo(certificateImageView) make.trailing.equalTo(self).inset(StandardHorizontalMargin) } subtitleLabel.snp.makeConstraints { make in make.leading.equalTo(titleLabel) make.trailing.equalTo(titleLabel) make.top.equalTo(titleLabel.snp.bottom) } viewCertificateButton.snp.makeConstraints { make in make.leading.equalTo(titleLabel) make.trailing.equalTo(titleLabel) make.bottom.equalTo(certificateImageView) } } private func useItem(item: CourseCertificateIem?) { guard let certificateItem = item else {return} certificateImageView.image = certificateItem.certificateImage let titleStyle = OEXTextStyle(weight: .normal, size: .large, color: OEXStyles.shared().primaryXDarkColor()) let subtitleStyle = OEXTextStyle(weight: .normal, size: .base, color: OEXStyles.shared().neutralDark()) titleLabel.attributedText = titleStyle.attributedString(withText: Strings.Certificates.courseCompletionTitle) subtitleLabel.attributedText = subtitleStyle.attributedString(withText: Strings.Certificates.courseCompletionSubtitle) addActionIfNeccessary() } private func addActionIfNeccessary() { guard let item = certificateItem, let action = item.action else { return } let tapGesture = UITapGestureRecognizer() tapGesture.addAction { _ in action() } addGestureRecognizer(tapGesture) } }
apache-2.0
1c4b29f31357e868bd292e1f6cb3c773
32.782609
131
0.66435
5.403338
false
false
false
false
Shopify/mobile-buy-sdk-ios
PayTests/Models/Models.swift
1
7103
// // Models.swift // PayTests // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if canImport(PassKit) import Foundation import PassKit import Pay @available(iOS 11.0, *) struct Models { static func createShippingMethod(identifier: String? = nil) -> PKShippingMethod { let method = PKShippingMethod(label: "CanadaPost", amount: 15.00 as NSDecimalNumber) method.identifier = identifier return method } static func createContact() -> PKContact { let contact = PKContact() contact.name = { var c = PersonNameComponents() c.givenName = "John" c.familyName = "Smith" return c }() contact.phoneNumber = CNPhoneNumber(stringValue: "1234567890") contact.postalAddress = self.createPostalAddress() contact.emailAddress = "john.smith@gmail.com" return contact } static func createPostalAddress() -> CNPostalAddress { let address = CNMutablePostalAddress() address.street = "80 Spadina" address.city = "Toronto" address.country = "Canada" address.state = "ON" address.postalCode = "M5V 2J4" return address.copy() as! CNPostalAddress } // ---------------------------------- // MARK: - Pay Models - // static func createSession(checkout: PayCheckout, currency: PayCurrency) -> MockPaySession { return MockPaySession(shopName: "Jaded Labs", checkout: checkout, currency: currency, merchantID: "com.merchant.identifier", controllerType: MockAuthorizationController.self) } static func createGiftCard() -> PayGiftCard { return PayGiftCard( id: "123", balance: 20.00, amount: 5.00, lastCharacters: "A1B2" ) } static func createGiftCardSecondary() -> PayGiftCard { return PayGiftCard( id: "234", balance: 10.00, amount: 2.50, lastCharacters: "C3D4" ) } static func createDiscount() -> PayDiscount { return PayDiscount(code: "WIN20", amount: 20.0) } static func createShippingDiscount() -> PayDiscount { return PayDiscount(code: "FREESHIP", amount: 10.0) } static func createAnonymousDiscount() -> PayDiscount { return PayDiscount(code: "", amount: 20.0) } static func createAnonymousShippingDiscount() -> PayDiscount { return PayDiscount(code: "", amount: 10.0) } static func createCurrency() -> PayCurrency { return PayCurrency(currencyCode: "USD", countryCode: "US") } static func createCheckout(requiresShipping: Bool = true, giftCards: [PayGiftCard]? = nil, discount: PayDiscount? = nil, shippingDiscount: PayDiscount? = nil, shippingAddress: PayAddress? = nil, shippingRate: PayShippingRate? = nil, duties: Decimal? = nil, empty: Bool = false, hasTax: Bool = true) -> PayCheckout { let lineItems = [ self.createLineItem1(), self.createLineItem2(), ] return PayCheckout( id: "123", lineItems: !empty ? lineItems : [], giftCards: giftCards, discount: discount, shippingDiscount: shippingDiscount, shippingAddress: shippingAddress, shippingRate: shippingRate, currencyCode: "CAD", totalDuties: duties, subtotalPrice: 44.0, needsShipping: requiresShipping, totalTax: hasTax ? 6.0 : 0.0, paymentDue: 50.0 ) } static func createLineItem1() -> PayLineItem { return PayLineItem(price: 16.0, quantity: 2) } static func createLineItem2() -> PayLineItem { return PayLineItem(price: 12.0, quantity: 1) } static func createAddress() -> PayAddress { return PayAddress( addressLine1: "80 Spadina", addressLine2: nil, city: "Toronto", country: "Canada", province: "ON", zip: "M5V 2J4", firstName: "John", lastName: "Smith", phone: "1234567890", email: "john.smith@gmail.com" ) } static func createShippingRate() -> PayShippingRate { return PayShippingRate(handle: "shipping-rate", title: "UPS Standard", price: 12.0) } static func createShippingRates() -> [PayShippingRate] { return [ PayShippingRate(handle: "123", title: "USPS", price: 11.0), PayShippingRate(handle: "234", title: "UPS", price: 12.0), PayShippingRate(handle: "345", title: "FexEx", price: 13.0), ] } static func createDeliveryRangeFromSingle() -> (orderDate: Date, range: PayShippingRate.DeliveryRange) { let order = Date(timeIntervalSince1970: 1483228800) let from = Date(timeIntervalSince1970: 1483315200) return (order, PayShippingRate.DeliveryRange(from: from)) } static func createDeliveryRangeFromMulti() -> (orderDate: Date, range: PayShippingRate.DeliveryRange) { let order = Date(timeIntervalSince1970: 1483228800) let from = Date(timeIntervalSince1970: 1483401600) return (order, PayShippingRate.DeliveryRange(from: from)) } static func createDeliveryRange() -> (orderDate: Date, range: PayShippingRate.DeliveryRange) { let order = Date(timeIntervalSince1970: 1483228800) let from = Date(timeIntervalSince1970: 1483315200) let to = Date(timeIntervalSince1970: 1483747200) return (order, PayShippingRate.DeliveryRange(from: from, to: to)) } } #endif
mit
01d6145b3f05df798096ecc6f373d731
35.425641
319
0.606223
4.373768
false
false
false
false
WalterCreazyBear/Swifter30
SwiftLab/SwiftLab/StringLab.swift
1
1314
// // StringLab.swift // SwiftLab // // Created by 熊伟 on 2018/8/26. // Copyright © 2018年 Bear. All rights reserved. // import Cocoa // [Swift 4 中的字符串](http://swift.gg/2018/08/09/swift-4-strings/) class StringLab { func startTest() { let single = "Pok\u{00E9}mon" let double = "Poke\u{0301}mon" print(single.count) print(double.count) print("两个字符串相等\(single == double)") let nssingle = single as NSString print(nssingle.length) let nsdouble = double as NSString print(nsdouble.length) // → 8 print(nssingle == nsdouble) // → false let chars: [Character] = [ "\u{1ECD}\u{300}", // ọ́ "\u{F2}\u{323}", // ọ́ "\u{6F}\u{323}\u{300}", // ọ́ "\u{6F}\u{300}\u{323}" // ọ́ ] chars.dropFirst().forEach { (ele) in print(ele == chars.first) } var greeting = "Hello, world!" if let comma = greeting.index(of: ",") { print(greeting[..<comma]) // → "Hello" greeting.replaceSubrange(comma..., with: " again.") } print(greeting) } }
mit
0fb8e50cba52694c9e3edee62db5c47b
20.810345
63
0.471146
3.56338
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Feature Introduction/Blogging Prompts/BloggingPromptsFeatureIntroduction.swift
1
5534
import UIKit /// This displays a Feature Introduction specifically for Blogging Prompts. class BloggingPromptsFeatureIntroduction: FeatureIntroductionViewController { var presenter: BloggingPromptsIntroductionPresenter? private var interactionType: BloggingPromptsFeatureIntroduction.InteractionType enum InteractionType { // Two buttons are displayed, both perform an action. Shows a site picker // if `blog` is `nil` and user has multiple sites. case actionable(blog: Blog?) // One button is displayed, which only dismisses the view. case informational var primaryButtonTitle: String { switch self { case .actionable: return ButtonStrings.tryIt case .informational: return ButtonStrings.gotIt } } var secondaryButtonTitle: String? { switch self { case .actionable: return ButtonStrings.remindMe default: return nil } } } class func navigationController(interactionType: BloggingPromptsFeatureIntroduction.InteractionType) -> UINavigationController { let controller = BloggingPromptsFeatureIntroduction(interactionType: interactionType) let navController = UINavigationController(rootViewController: controller) return navController } init(interactionType: BloggingPromptsFeatureIntroduction.InteractionType) { let featureDescriptionView: BloggingPromptsFeatureDescriptionView = { let featureDescriptionView = BloggingPromptsFeatureDescriptionView.loadFromNib() featureDescriptionView.translatesAutoresizingMaskIntoConstraints = false return featureDescriptionView }() let headerImage = UIImage(named: HeaderStyle.imageName)?.withTintColor(.clear) self.interactionType = interactionType super.init(headerTitle: HeaderStrings.title, headerSubtitle: HeaderStrings.subtitle, headerImage: headerImage, featureDescriptionView: featureDescriptionView, primaryButtonTitle: interactionType.primaryButtonTitle, secondaryButtonTitle: interactionType.secondaryButtonTitle) featureIntroductionDelegate = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Add the gradient after the image has been added to the view so the gradient is the correct size. addHeaderImageGradient() } override func closeButtonTapped() { WPAnalytics.track(.promptsIntroductionModalDismissed) super.closeButtonTapped() } } extension BloggingPromptsFeatureIntroduction: FeatureIntroductionDelegate { func primaryActionSelected() { guard case .actionable = interactionType else { WPAnalytics.track(.promptsIntroductionModalGotIt) super.closeButtonTapped() return } WPAnalytics.track(.promptsIntroductionModalTryItNow) presenter?.primaryButtonSelected() } func secondaryActionSelected() { guard case .actionable = interactionType else { return } WPAnalytics.track(.promptsIntroductionModalRemindMe) presenter?.secondaryButtonSelected() } } private extension BloggingPromptsFeatureIntroduction { func addHeaderImageGradient() { // Based on https://stackoverflow.com/a/54096829 let gradient = CAGradientLayer() gradient.colors = [ HeaderStyle.startGradientColor.cgColor, HeaderStyle.endGradientColor.cgColor ] // Create a gradient from top to bottom. gradient.startPoint = CGPoint(x: 0.5, y: 0) gradient.endPoint = CGPoint(x: 0.5, y: 1) gradient.frame = headerImageView.bounds // Add a mask to the gradient so the colors only apply to the image (and not the imageView). let mask = CALayer() mask.contents = headerImageView.image?.cgImage mask.frame = gradient.bounds gradient.mask = mask // Add the gradient as a sublayer to the imageView's layer. headerImageView.layer.addSublayer(gradient) } enum ButtonStrings { static let tryIt = NSLocalizedString("Try it now", comment: "Button title on the blogging prompt's feature introduction view to answer a prompt.") static let gotIt = NSLocalizedString("Got it", comment: "Button title on the blogging prompt's feature introduction view to dismiss the view.") static let remindMe = NSLocalizedString("Remind me", comment: "Button title on the blogging prompt's feature introduction view to set a reminder.") } enum HeaderStrings { static let title: String = NSLocalizedString("Introducing Prompts", comment: "Title displayed on the feature introduction view.") static let subtitle: String = NSLocalizedString("The best way to become a better writer is to build a writing habit and share with others - that’s where Prompts come in!", comment: "Subtitle displayed on the feature introduction view.") } enum HeaderStyle { static let imageName = "icon-lightbulb-outline" static let startGradientColor: UIColor = .warning(.shade30) static let endGradientColor: UIColor = .accent(.shade40) } }
gpl-2.0
f76dd18a61b40159570dc1cb751b15a5
35.88
244
0.680586
5.477228
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Command/Command+Custom.swift
1
1235
// // Command+Custom.swift // // // Created by Vladislav Fitc on 11/02/2021. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif extension Command { struct Custom: AlgoliaCommand { let method: HTTPMethod let callType: CallType let path: URL let body: Data? let requestOptions: RequestOptions? init(method: HTTPMethod, callType: CallType, path: URL, body: Data?, requestOptions: RequestOptions?) { self.method = method self.callType = callType self.path = path self.body = body self.requestOptions = requestOptions } init(callType: CallType, urlRequest: URLRequest, requestOptions: RequestOptions?) throws { self.callType = callType self.method = urlRequest.httpMethod.flatMap(HTTPMethod.init(rawValue:)) ?? .get guard let url = urlRequest.url else { throw URLRequest.FormatError.missingURL } guard let pathURL = URL(string: url.path) else { throw URLRequest.FormatError.invalidPath(url.path) } self.path = pathURL self.body = urlRequest.httpBody self.requestOptions = requestOptions } } }
mit
3389b21222ca1ca5a8f8a7ac82565a9e
22.301887
85
0.650202
4.540441
false
false
false
false
Gaea-iOS/FoundationExtension
FoundationExtension/Classes/UIKit/Markable.swift
1
7064
// // Markable.swift // Pods // // Created by 王小涛 on 2017/7/8. // // import UIKit private struct AssociatedObjectKey { static var markType = "AssociatedObjectKey_markType" static var markValue = "AssociatedObjectKey_markValue" static var markNumberColor = "AssociatedObjectKey_markNumberColor" static var markBackgroundColor = "AssociatedObjectKey_markBackgroundColor" static var markPosition = "AssociatedObjectKey_markPosition" static var markView = "AssociatedObjectKey_markView" } public enum MarkType { case dot case number } public enum MarkPosition { case topRight(CGPoint) case topLeft(CGPoint) } public protocol Markable: class { var markType: MarkType {get set} var markValue: String? {get set} var markNumberColor: UIColor? {get set} var markBackgroundColor: UIColor? {get set} var markPosition: MarkPosition {get set} var markAttachView: UIView? {get} } extension Markable { public var markType: MarkType { get { if let type = objc_getAssociatedObject(self, &AssociatedObjectKey.markType) as? MarkType { return type } else { return .dot } } set { objc_setAssociatedObject(self, &AssociatedObjectKey.markType, newValue, .OBJC_ASSOCIATION_RETAIN) update() } } public var markValue: String? { get { if let value = objc_getAssociatedObject(self, &AssociatedObjectKey.markValue) as? String { return value } else { return nil } } set { objc_setAssociatedObject(self, &AssociatedObjectKey.markValue, newValue, .OBJC_ASSOCIATION_RETAIN) update() } } public var markBackgroundColor: UIColor? { get { if let color = objc_getAssociatedObject(self, &AssociatedObjectKey.markBackgroundColor) as? UIColor { return color } else { return .red } } set { objc_setAssociatedObject(self, &AssociatedObjectKey.markBackgroundColor, newValue, .OBJC_ASSOCIATION_RETAIN) update() } } public var markNumberColor: UIColor? { get { if let color = objc_getAssociatedObject(self, &AssociatedObjectKey.markNumberColor) as? UIColor { return color } else { return .white } } set { objc_setAssociatedObject(self, &AssociatedObjectKey.markNumberColor, newValue, .OBJC_ASSOCIATION_RETAIN) update() } } public var markPosition: MarkPosition { get { if let position = objc_getAssociatedObject(self, &AssociatedObjectKey.markPosition) as? MarkPosition { return position } else { return .topRight(.zero) } } set { objc_setAssociatedObject(self, &AssociatedObjectKey.markPosition, newValue, .OBJC_ASSOCIATION_RETAIN) update() } } fileprivate var markView: MarkView { if let view = objc_getAssociatedObject(self, &AssociatedObjectKey.markView) as? MarkView { return view } else { let view = MarkView() view.isHidden = true objc_setAssociatedObject(self, &AssociatedObjectKey.markView, view, .OBJC_ASSOCIATION_RETAIN) return view } } fileprivate func update() { guard let markAttachView = markAttachView else {return} markView.removeFromSuperview() markAttachView.addSubview(markView) markAttachView.bringSubviewToFront(markView) markAttachView.clipsToBounds = false let attachViewFrame = markAttachView.frame markView.backgroundColor = markBackgroundColor markView.label.textColor = markNumberColor let text: String? = { switch markType { case .dot: return nil case .number: return markValue } }() markView.label.text = text let size: CGSize = { switch markType { case .dot: let size = CGSize(width: 8, height: 8) return size case .number: let height: CGFloat = 14 var size = markView.label.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)) size.width += 6 size.width = max(size.width, height) size.height = height return size } }() let numberAdjugeOffset = CGPoint(x: 2, y: 2) let origin: CGPoint = { switch markPosition { case let .topRight(offset): switch markType { case .dot: var origin = CGPoint(x: attachViewFrame.width, y: -(size.height / 2)) origin.x += offset.x origin.y += offset.y return origin case .number: var origin = CGPoint(x: attachViewFrame.width - size.width / 2 + numberAdjugeOffset.x, y: -(size.height / 2) + numberAdjugeOffset.y) origin.x += offset.x origin.y += offset.y return origin } case let .topLeft(offset): switch markType { case .dot: var origin = CGPoint(x: -size.width, y: -(size.height / 2)) origin.x += offset.x origin.y += offset.y return origin case .number: var origin = CGPoint(x: -(size.width / 2) - numberAdjugeOffset.x, y: -(size.height / 2) + numberAdjugeOffset.y) origin.x += offset.x origin.y += offset.y return origin } } }() let frame = CGRect(origin: origin, size: size) markView.frame = frame markView.layer.cornerRadius = frame.size.height / 2 markView.isHidden = (markValue == nil ? true : false) } } class MarkView: UIView { private(set) lazy var label: UILabel = { [unowned self] in let label = UILabel() label.backgroundColor = .clear label.numberOfLines = 1 label.font = .systemFont(ofSize: 10) label.textColor = .white label.textAlignment = .center self.addSubview(label) self.clipsToBounds = true return label }() override func layoutSubviews() { super.layoutSubviews() label.frame = bounds } }
mit
1835b2bb9693f5f267b3ec67d2e00dd4
30.368889
120
0.536271
4.925331
false
false
false
false
kjantzer/FolioReaderKit
Source/FolioReaderCenter.swift
1
43288
// // FolioReaderCenter.swift // FolioReaderKit // // Created by Heberti Almeida on 08/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import ZFDragableModalTransition let reuseIdentifier = "Cell" var pageWidth: CGFloat! var pageHeight: CGFloat! var previousPageNumber: Int! var currentPageNumber: Int! var nextPageNumber: Int! var pageScrollDirection = ScrollDirection() var isScrolling = false public class FolioReaderCenter: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { var collectionView: UICollectionView! let collectionViewLayout = UICollectionViewFlowLayout() var loadingView: UIActivityIndicatorView! var pages: [String]! var totalPages: Int! var tempFragment: String? var currentPage: FolioReaderPage? var animator: ZFModalTransitionAnimator! var pageIndicatorView: FolioReaderPageIndicator? var pageIndicatorHeight: CGFloat = 20 var recentlyScrolled = false var recentlyScrolledDelay = 2.0 // 2 second delay until we clear recentlyScrolled var recentlyScrolledTimer: NSTimer! var scrollScrubber: ScrollScrubber? private var screenBounds: CGRect! private var pointNow = CGPointZero private var pageOffsetRate: CGFloat = 0 private var tempReference: FRTocReference? private var isFirstLoad = true private var currentWebViewScrollPositions = [Int: CGPoint]() private var currentOrientation: UIInterfaceOrientation? // MARK: - View life cicle override public func viewDidLoad() { super.viewDidLoad() if (readerConfig.hideBars == true) { self.pageIndicatorHeight = 0 } screenBounds = self.view.frame setPageSize(UIApplication.sharedApplication().statusBarOrientation) // Layout collectionViewLayout.sectionInset = UIEdgeInsetsZero collectionViewLayout.minimumLineSpacing = 0 collectionViewLayout.minimumInteritemSpacing = 0 collectionViewLayout.scrollDirection = .direction() let background = isNight(readerConfig.nightModeBackground, UIColor.whiteColor()) view.backgroundColor = background // CollectionView collectionView = UICollectionView(frame: screenBounds, collectionViewLayout: collectionViewLayout) collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] collectionView.delegate = self collectionView.dataSource = self collectionView.pagingEnabled = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = background collectionView.decelerationRate = UIScrollViewDecelerationRateFast view.addSubview(collectionView) // Register cell classes collectionView!.registerClass(FolioReaderPage.self, forCellWithReuseIdentifier: reuseIdentifier) totalPages = book.spine.spineReferences.count // Configure navigation bar and layout automaticallyAdjustsScrollViewInsets = false extendedLayoutIncludesOpaqueBars = true configureNavBar() // Page indicator view pageIndicatorView = FolioReaderPageIndicator(frame: self.frameForPageIndicatorView()) if let _pageIndicatorView = pageIndicatorView { view.addSubview(_pageIndicatorView) } scrollScrubber = ScrollScrubber(frame: self.frameForScrollScrubber()) scrollScrubber?.delegate = self if let _scrollScruber = scrollScrubber { view.addSubview(_scrollScruber.slider) } // Loading indicator let style: UIActivityIndicatorViewStyle = isNight(.White, .Gray) loadingView = UIActivityIndicatorView(activityIndicatorStyle: style) loadingView.hidesWhenStopped = true loadingView.startAnimating() view.addSubview(loadingView) } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Update pages pagesForCurrentPage(currentPage) pageIndicatorView?.reloadView(updateShadow: true) } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() screenBounds = view.frame loadingView.center = view.center setPageSize(UIApplication.sharedApplication().statusBarOrientation) updateSubviewFrames() } // MARK: Layout private func updateSubviewFrames() { self.pageIndicatorView?.frame = self.frameForPageIndicatorView() self.scrollScrubber?.frame = self.frameForScrollScrubber() } private func frameForPageIndicatorView() -> CGRect { return CGRect(x: 0, y: view.frame.height-pageIndicatorHeight, width: view.frame.width, height: pageIndicatorHeight) } private func frameForScrollScrubber() -> CGRect { let scrubberY: CGFloat = ((readerConfig.shouldHideNavigationOnTap == true || readerConfig.hideBars == true) ? 50 : 74) return CGRect(x: pageWidth + 10, y: scrubberY, width: 40, height: pageHeight - 100) } func configureNavBar() { let navBackground = isNight(readerConfig.nightModeMenuBackground, UIColor.whiteColor()) let tintColor = readerConfig.tintColor let navText = isNight(UIColor.whiteColor(), UIColor.blackColor()) let font = UIFont(name: "Avenir-Light", size: 17)! setTranslucentNavigation(color: navBackground, tintColor: tintColor, titleColor: navText, andFont: font) } func configureNavBarButtons() { // Navbar buttons let shareIcon = UIImage(readerImageNamed: "icon-navbar-share")?.ignoreSystemTint() let audioIcon = UIImage(readerImageNamed: "icon-navbar-tts")?.ignoreSystemTint() //man-speech-icon let closeIcon = UIImage(readerImageNamed: "icon-navbar-close")?.ignoreSystemTint() let tocIcon = UIImage(readerImageNamed: "icon-navbar-toc")?.ignoreSystemTint() let fontIcon = UIImage(readerImageNamed: "icon-navbar-font")?.ignoreSystemTint() let space = 70 as CGFloat let menu = UIBarButtonItem(image: closeIcon, style: .Plain, target: self, action:#selector(closeReader(_:))) let toc = UIBarButtonItem(image: tocIcon, style: .Plain, target: self, action:#selector(presentChapterList(_:))) navigationItem.leftBarButtonItems = [menu, toc] var rightBarIcons = [UIBarButtonItem]() if readerConfig.allowSharing { rightBarIcons.append(UIBarButtonItem(image: shareIcon, style: .Plain, target: self, action:#selector(shareChapter(_:)))) } if book.hasAudio() || readerConfig.enableTTS { rightBarIcons.append(UIBarButtonItem(image: audioIcon, style: .Plain, target: self, action:#selector(presentPlayerMenu(_:)))) } let font = UIBarButtonItem(image: fontIcon, style: .Plain, target: self, action: #selector(presentFontsMenu)) font.width = space rightBarIcons.appendContentsOf([font]) navigationItem.rightBarButtonItems = rightBarIcons } func reloadData() { loadingView.stopAnimating() totalPages = book.spine.spineReferences.count collectionView.reloadData() configureNavBarButtons() setCollectionViewProgressiveDirection() if let position = FolioReader.defaults.valueForKey(kBookId) as? NSDictionary, let pageNumber = position["pageNumber"] as? Int where pageNumber > 0 { changePageWith(page: pageNumber) currentPageNumber = pageNumber return } currentPageNumber = 1 } // MARK: Change page progressive direction func setCollectionViewProgressiveDirection() { if FolioReader.needsRTLChange { collectionView.transform = CGAffineTransformMakeScale(-1, 1) } else { collectionView.transform = CGAffineTransformIdentity } } func setPageProgressiveDirection(page: FolioReaderPage) { if FolioReader.needsRTLChange { // if page.transform.a == -1 { return } page.transform = CGAffineTransformMakeScale(-1, 1) } else { page.transform = CGAffineTransformIdentity } } // MARK: Change layout orientation func setScrollDirection(direction: FolioReaderScrollDirection) { guard let currentPage = currentPage else { return } // Get internal page offset before layout change let pageScrollView = currentPage.webView.scrollView pageOffsetRate = pageScrollView.contentOffset.forDirection() / pageScrollView.contentSize.forDirection() // Change layout readerConfig.scrollDirection = direction collectionViewLayout.scrollDirection = .direction() currentPage.setNeedsLayout() collectionView.collectionViewLayout.invalidateLayout() collectionView.setContentOffset(frameForPage(currentPageNumber).origin, animated: false) // Page progressive direction setCollectionViewProgressiveDirection() delay(0.2) { self.setPageProgressiveDirection(currentPage) } /** * This delay is needed because the page will not be ready yet * so the delay wait until layout finished the changes. */ delay(0.1) { var pageOffset = pageScrollView.contentSize.forDirection() * self.pageOffsetRate // Fix the offset for paged scroll if readerConfig.scrollDirection == .horizontal { let page = round(pageOffset / pageWidth) pageOffset = page * pageWidth } let pageOffsetPoint = isDirection(CGPoint(x: 0, y: pageOffset), CGPoint(x: pageOffset, y: 0)) pageScrollView.setContentOffset(pageOffsetPoint, animated: true) } } // MARK: Status bar and Navigation bar func hideBars() { if readerConfig.shouldHideNavigationOnTap == false { return } let shouldHide = true FolioReader.sharedInstance.readerContainer.shouldHideStatusBar = shouldHide UIView.animateWithDuration(0.25, animations: { FolioReader.sharedInstance.readerContainer.setNeedsStatusBarAppearanceUpdate() // Show minutes indicator // self.pageIndicatorView.minutesLabel.alpha = 0 }) navigationController?.setNavigationBarHidden(shouldHide, animated: true) } func showBars() { configureNavBar() let shouldHide = false FolioReader.sharedInstance.readerContainer.shouldHideStatusBar = shouldHide UIView.animateWithDuration(0.25, animations: { FolioReader.sharedInstance.readerContainer.setNeedsStatusBarAppearanceUpdate() }) navigationController?.setNavigationBarHidden(shouldHide, animated: true) } func toggleBars() { if readerConfig.shouldHideNavigationOnTap == false { return } let shouldHide = !navigationController!.navigationBarHidden if !shouldHide { configureNavBar() } FolioReader.sharedInstance.readerContainer.shouldHideStatusBar = shouldHide UIView.animateWithDuration(0.25, animations: { FolioReader.sharedInstance.readerContainer.setNeedsStatusBarAppearanceUpdate() // Show minutes indicator // self.pageIndicatorView.minutesLabel.alpha = shouldHide ? 0 : 1 }) navigationController?.setNavigationBarHidden(shouldHide, animated: true) } // MARK: UICollectionViewDataSource public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return totalPages } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FolioReaderPage cell.pageNumber = indexPath.row+1 cell.webView.scrollView.delegate = self cell.webView.setupScrollDirection() cell.webView.frame = cell.webViewFrame() cell.delegate = self cell.backgroundColor = UIColor.clearColor() setPageProgressiveDirection(cell) // Configure the cell let resource = book.spine.spineReferences[indexPath.row].resource var html = try? String(contentsOfFile: resource.fullHref, encoding: NSUTF8StringEncoding) let mediaOverlayStyleColors = "\"\(readerConfig.mediaOverlayColor.hexString(false))\", \"\(readerConfig.mediaOverlayColor.highlightColor().hexString(false))\"" // Inject CSS let jsFilePath = NSBundle.frameworkBundle().pathForResource("Bridge", ofType: "js") let cssFilePath = NSBundle.frameworkBundle().pathForResource("Style", ofType: "css") let cssTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"\(cssFilePath!)\">" let jsTag = "<script type=\"text/javascript\" src=\"\(jsFilePath!)\"></script>" + "<script type=\"text/javascript\">setMediaOverlayStyleColors(\(mediaOverlayStyleColors))</script>" let toInject = "\n\(cssTag)\n\(jsTag)\n</head>" html = html?.stringByReplacingOccurrencesOfString("</head>", withString: toInject) // Font class name var classes = "" let currentFontName = FolioReader.currentFontName switch currentFontName { case 0: classes = "andada" break case 1: classes = "lato" break case 2: classes = "lora" break case 3: classes = "raleway" break default: break } classes += " "+FolioReader.currentMediaOverlayStyle.className() // Night mode if FolioReader.nightMode { classes += " nightMode" } // Font Size let currentFontSize = FolioReader.currentFontSize switch currentFontSize { case 0: classes += " textSizeOne" break case 1: classes += " textSizeTwo" break case 2: classes += " textSizeThree" break case 3: classes += " textSizeFour" break case 4: classes += " textSizeFive" break default: break } html = html?.stringByReplacingOccurrencesOfString("<html ", withString: "<html class=\"\(classes)\"") cell.loadHTMLString(html, baseURL: NSURL(fileURLWithPath: (resource.fullHref as NSString).stringByDeletingLastPathComponent)) return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(collectionView.frame.width, collectionView.frame.height) } // MARK: - Device rotation override public func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { guard FolioReader.isReaderReady else { return } setPageSize(toInterfaceOrientation) updateCurrentPage() if (self.currentOrientation == nil || (self.currentOrientation?.isPortrait != toInterfaceOrientation.isPortrait)) { var pageIndicatorFrame = pageIndicatorView?.frame pageIndicatorFrame?.origin.y = ((screenBounds.size.height < screenBounds.size.width) ? (self.collectionView.frame.height - pageIndicatorHeight) : (self.collectionView.frame.width - pageIndicatorHeight)) pageIndicatorFrame?.origin.x = 0 pageIndicatorFrame?.size.width = ((screenBounds.size.height < screenBounds.size.width) ? (self.collectionView.frame.width) : (self.collectionView.frame.height)) pageIndicatorFrame?.size.height = pageIndicatorHeight var scrollScrubberFrame = scrollScrubber?.slider.frame; scrollScrubberFrame?.origin.x = ((screenBounds.size.height < screenBounds.size.width) ? (view.frame.width - 100) : (view.frame.height + 10)) scrollScrubberFrame?.size.height = ((screenBounds.size.height < screenBounds.size.width) ? (self.collectionView.frame.height - 100) : (self.collectionView.frame.width - 100)) self.collectionView.collectionViewLayout.invalidateLayout() UIView.animateWithDuration(duration, animations: { // Adjust page indicator view if let _pageIndicatorFrame = pageIndicatorFrame { self.pageIndicatorView?.frame = _pageIndicatorFrame self.pageIndicatorView?.reloadView(updateShadow: true) } // Adjust scroll scrubber slider if let _scrollScrubberFrame = scrollScrubberFrame { self.scrollScrubber?.slider.frame = _scrollScrubberFrame } // Adjust collectionView self.collectionView.contentSize = isDirection( CGSize(width: pageWidth, height: pageHeight * CGFloat(self.totalPages)), CGSize(width: pageWidth * CGFloat(self.totalPages), height: pageHeight), CGSize(width: pageWidth * CGFloat(self.totalPages), height: pageHeight) ) self.collectionView.setContentOffset(self.frameForPage(currentPageNumber).origin, animated: false) self.collectionView.collectionViewLayout.invalidateLayout() // Adjust internal page offset guard let currentPage = self.currentPage else { return } let pageScrollView = currentPage.webView.scrollView self.pageOffsetRate = pageScrollView.contentOffset.forDirection() / pageScrollView.contentSize.forDirection() }) } self.currentOrientation = toInterfaceOrientation } override public func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { guard FolioReader.isReaderReady else { return } guard let currentPage = currentPage else { return } // Update pages pagesForCurrentPage(currentPage) currentPage.refreshPageMode() scrollScrubber?.setSliderVal() // After rotation fix internal page offset var pageOffset = currentPage.webView.scrollView.contentSize.forDirection() * pageOffsetRate // Fix the offset for paged scroll if readerConfig.scrollDirection == .horizontal { let page = round(pageOffset / pageWidth) pageOffset = page * pageWidth } let pageOffsetPoint = isDirection(CGPoint(x: 0, y: pageOffset), CGPoint(x: pageOffset, y: 0)) currentPage.webView.scrollView.setContentOffset(pageOffsetPoint, animated: true) } override public func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { guard FolioReader.isReaderReady else { return } self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: currentPageNumber - 1, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.None, animated: false) if currentPageNumber+1 >= totalPages { UIView.animateWithDuration(duration, animations: { self.collectionView.setContentOffset(self.frameForPage(currentPageNumber).origin, animated: false) }) } } // MARK: - Page func setPageSize(orientation: UIInterfaceOrientation) { if orientation.isPortrait { if screenBounds.size.width < screenBounds.size.height { pageWidth = self.view.frame.width pageHeight = self.view.frame.height } else { pageWidth = self.view.frame.height pageHeight = self.view.frame.width } } else { if screenBounds.size.width > screenBounds.size.height { pageWidth = self.view.frame.width pageHeight = self.view.frame.height } else { pageWidth = self.view.frame.height pageHeight = self.view.frame.width } } } func updateCurrentPage(completion: (() -> Void)? = nil) { updateCurrentPage(nil) { () -> Void in completion?() } } func updateCurrentPage(page: FolioReaderPage!, completion: (() -> Void)? = nil) { if let page = page { currentPage = page previousPageNumber = page.pageNumber-1 currentPageNumber = page.pageNumber } else { let currentIndexPath = getCurrentIndexPath() if currentIndexPath != NSIndexPath(forRow: 0, inSection: 0) { currentPage = collectionView.cellForItemAtIndexPath(currentIndexPath) as? FolioReaderPage } previousPageNumber = currentIndexPath.row currentPageNumber = currentIndexPath.row+1 } nextPageNumber = currentPageNumber+1 <= totalPages ? currentPageNumber+1 : currentPageNumber // // Set navigation title // if let chapterName = getCurrentChapterName() { // title = chapterName // } else { title = ""} // Set pages if let page = currentPage { page.webView.becomeFirstResponder() scrollScrubber?.setSliderVal() if let readingTime = page.webView.js("getReadingTime()") { pageIndicatorView?.totalMinutes = Int(readingTime)! } else { pageIndicatorView?.totalMinutes = 0 } pagesForCurrentPage(page) } completion?() } func pagesForCurrentPage(page: FolioReaderPage?) { guard let page = page else { return } let pageSize = isDirection(pageHeight, pageWidth) pageIndicatorView?.totalPages = Int(ceil(page.webView.scrollView.contentSize.forDirection()/pageSize)) let pageOffSet = isDirection(page.webView.scrollView.contentOffset.x, page.webView.scrollView.contentOffset.x, page.webView.scrollView.contentOffset.y) let webViewPage = pageForOffset(pageOffSet, pageHeight: pageSize) pageIndicatorView?.currentPage = webViewPage } func pageForOffset(offset: CGFloat, pageHeight height: CGFloat) -> Int { let page = Int(ceil(offset / height))+1 return page } func getCurrentIndexPath() -> NSIndexPath { let indexPaths = collectionView.indexPathsForVisibleItems() var indexPath = NSIndexPath() if indexPaths.count > 1 { let first = indexPaths.first! as NSIndexPath let last = indexPaths.last! as NSIndexPath switch pageScrollDirection { case .Up: if first.compare(last) == .OrderedAscending { indexPath = last } else { indexPath = first } default: if first.compare(last) == .OrderedAscending { indexPath = first } else { indexPath = last } } } else { indexPath = indexPaths.first ?? NSIndexPath(forRow: 0, inSection: 0) } return indexPath } func frameForPage(page: Int) -> CGRect { return isDirection( CGRectMake(0, pageHeight * CGFloat(page-1), pageWidth, pageHeight), CGRectMake(pageWidth * CGFloat(page-1), 0, pageWidth, pageHeight) ) } func changePageWith(page page: Int, animated: Bool = false, completion: (() -> Void)? = nil) { if page > 0 && page-1 < totalPages { let indexPath = NSIndexPath(forRow: page-1, inSection: 0) changePageWith(indexPath: indexPath, animated: animated, completion: { () -> Void in self.updateCurrentPage({ () -> Void in completion?() }) }) } } func changePageWith(page page: Int, andFragment fragment: String, animated: Bool = false, completion: (() -> Void)? = nil) { if currentPageNumber == page { if let currentPage = currentPage where fragment != "" { currentPage.handleAnchor(fragment, avoidBeginningAnchors: true, animated: animated) } completion?() } else { tempFragment = fragment changePageWith(page: page, animated: animated, completion: { () -> Void in self.updateCurrentPage({ () -> Void in completion?() }) }) } } func changePageWith(href href: String, animated: Bool = false, completion: (() -> Void)? = nil) { let item = findPageByHref(href) let indexPath = NSIndexPath(forRow: item, inSection: 0) changePageWith(indexPath: indexPath, animated: animated, completion: { () -> Void in self.updateCurrentPage({ () -> Void in completion?() }) }) } func changePageWith(href href: String, andAudioMarkID markID: String) { if recentlyScrolled { return } // if user recently scrolled, do not change pages or scroll the webview guard let currentPage = currentPage else { return } let item = findPageByHref(href) let pageUpdateNeeded = item+1 != currentPage.pageNumber let indexPath = NSIndexPath(forRow: item, inSection: 0) changePageWith(indexPath: indexPath, animated: true) { () -> Void in if pageUpdateNeeded { self.updateCurrentPage({ () -> Void in currentPage.audioMarkID(markID) }) } else { currentPage.audioMarkID(markID) } } } func changePageWith(indexPath indexPath: NSIndexPath, animated: Bool = false, completion: (() -> Void)? = nil) { guard indexPathIsValid(indexPath) else { print("ERROR: Attempt to scroll to invalid index path") completion?() return } UIView.animateWithDuration(animated ? 0.3 : 0, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .direction(), animated: false) }) { (finished: Bool) -> Void in completion?() } } func indexPathIsValid(indexPath: NSIndexPath) -> Bool { let section = indexPath.section let row = indexPath.row let lastSectionIndex = numberOfSectionsInCollectionView(collectionView) - 1 //Make sure the specified section exists if section > lastSectionIndex { return false } let rowCount = self.collectionView(collectionView, numberOfItemsInSection: indexPath.section) - 1 return row <= rowCount } func isLastPage() -> Bool{ return currentPageNumber == nextPageNumber } func changePageToNext(completion: (() -> Void)? = nil) { changePageWith(page: nextPageNumber, animated: true) { () -> Void in completion?() } } func changePageToPrevious(completion: (() -> Void)? = nil) { changePageWith(page: previousPageNumber, animated: true) { () -> Void in completion?() } } /** Find a page by FRTocReference. */ func findPageByResource(reference: FRTocReference) -> Int { var count = 0 for item in book.spine.spineReferences { if let resource = reference.resource where item.resource == resource { return count } count += 1 } return count } /** Find a page by href. */ func findPageByHref(href: String) -> Int { var count = 0 for item in book.spine.spineReferences { if item.resource.href == href { return count } count += 1 } return count } /** Find and return the current chapter resource. */ func getCurrentChapter() -> FRResource? { if let currentPageNumber = currentPageNumber { for item in book.flatTableOfContents { if let reference = book.spine.spineReferences[safe: currentPageNumber-1], resource = item.resource where resource == reference.resource { return item.resource } } } return nil } /** Find and return the current chapter name. */ func getCurrentChapterName() -> String? { if let currentPageNumber = currentPageNumber { for item in book.flatTableOfContents { if let reference = book.spine.spineReferences[safe: currentPageNumber-1], resource = item.resource where resource == reference.resource { if let title = item.title { return title } return nil } } } return nil } // MARK: - Audio Playing func audioMark(href href: String, fragmentID: String) { changePageWith(href: href, andAudioMarkID: fragmentID) } // MARK: - Sharing /** Sharing chapter method. */ func shareChapter(sender: UIBarButtonItem) { guard let currentPage = currentPage else { return } if let chapterText = currentPage.webView.js("getBodyText()") { let htmlText = chapterText.stringByReplacingOccurrencesOfString("[\\n\\r]+", withString: "<br />", options: .RegularExpressionSearch) var subject = readerConfig.localizedShareChapterSubject var html = "" var text = "" var bookTitle = "" var chapterName = "" var authorName = "" var shareItems = [AnyObject]() // Get book title if let title = book.title() { bookTitle = title subject += " “\(title)”" } // Get chapter name if let chapter = getCurrentChapterName() { chapterName = chapter } // Get author name if let author = book.metadata.creators.first { authorName = author.name } // Sharing html and text html = "<html><body>" html += "<br /><hr> <p>\(htmlText)</p> <hr><br />" html += "<center><p style=\"color:gray\">"+readerConfig.localizedShareAllExcerptsFrom+"</p>" html += "<b>\(bookTitle)</b><br />" html += readerConfig.localizedShareBy+" <i>\(authorName)</i><br />" if let bookShareLink = readerConfig.localizedShareWebLink { html += "<a href=\"\(bookShareLink.absoluteString)\">\(bookShareLink.absoluteString)</a>" shareItems.append(bookShareLink) } html += "</center></body></html>" text = "\(chapterName)\n\n“\(chapterText)” \n\n\(bookTitle) \n\(readerConfig.localizedShareBy) \(authorName)" let act = FolioReaderSharingProvider(subject: subject, text: text, html: html) shareItems.insertContentsOf([act, ""], at: 0) let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypePostToVimeo] // Pop style on iPad if let actv = activityViewController.popoverPresentationController { actv.barButtonItem = sender } presentViewController(activityViewController, animated: true, completion: nil) } } /** Sharing highlight method. */ func shareHighlight(string: String, rect: CGRect) { var subject = readerConfig.localizedShareHighlightSubject var html = "" var text = "" var bookTitle = "" var chapterName = "" var authorName = "" var shareItems = [AnyObject]() // Get book title if let title = book.title() { bookTitle = title subject += " “\(title)”" } // Get chapter name if let chapter = getCurrentChapterName() { chapterName = chapter } // Get author name if let author = book.metadata.creators.first { authorName = author.name } // Sharing html and text html = "<html><body>" html += "<br /><hr> <p>\(chapterName)</p>" html += "<p>\(string)</p> <hr><br />" html += "<center><p style=\"color:gray\">"+readerConfig.localizedShareAllExcerptsFrom+"</p>" html += "<b>\(bookTitle)</b><br />" html += readerConfig.localizedShareBy+" <i>\(authorName)</i><br />" if let bookShareLink = readerConfig.localizedShareWebLink { html += "<a href=\"\(bookShareLink.absoluteString)\">\(bookShareLink.absoluteString)</a>" shareItems.append(bookShareLink) } html += "</center></body></html>" text = "\(chapterName)\n\n“\(string)” \n\n\(bookTitle) \n\(readerConfig.localizedShareBy) \(authorName)" let act = FolioReaderSharingProvider(subject: subject, text: text, html: html) shareItems.insertContentsOf([act, ""], at: 0) let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypePostToVimeo] // Pop style on iPad if let actv = activityViewController.popoverPresentationController { actv.sourceView = currentPage actv.sourceRect = rect } presentViewController(activityViewController, animated: true, completion: nil) } // MARK: - ScrollView Delegate public func scrollViewWillBeginDragging(scrollView: UIScrollView) { isScrolling = true clearRecentlyScrolled() recentlyScrolled = true pointNow = scrollView.contentOffset if let currentPage = currentPage { currentPage.webView.createMenu(options: true) currentPage.webView.setMenuVisible(false) } scrollScrubber?.scrollViewWillBeginDragging(scrollView) } public func scrollViewDidScroll(scrollView: UIScrollView) { if !navigationController!.navigationBarHidden { toggleBars() } scrollScrubber?.scrollViewDidScroll(scrollView) // Update current reading page if scrollView is UICollectionView {} else { let pageSize = isDirection(pageHeight, pageWidth) if let page = currentPage where page.webView.scrollView.contentOffset.forDirection()+pageSize <= page.webView.scrollView.contentSize.forDirection() { let webViewPage = pageForOffset(page.webView.scrollView.contentOffset.forDirection(), pageHeight: pageSize) if (readerConfig.scrollDirection == .horizontalWithVerticalContent), let cell = ((scrollView.superview as? UIWebView)?.delegate as? FolioReaderPage) { let currentIndexPathRow = cell.pageNumber - 1 // if the cell reload don't save the top position offset if let oldOffSet = self.currentWebViewScrollPositions[currentIndexPathRow] where (abs(oldOffSet.y - scrollView.contentOffset.y) > 100) {} else { self.currentWebViewScrollPositions[currentIndexPathRow] = scrollView.contentOffset } } if pageIndicatorView?.currentPage != webViewPage { pageIndicatorView?.currentPage = webViewPage } } } pageScrollDirection = scrollView.contentOffset.forDirection() < pointNow.forDirection() ? .negative() : .positive() } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { isScrolling = false if (readerConfig.scrollDirection == .horizontalWithVerticalContent), let cell = ((scrollView.superview as? UIWebView)?.delegate as? FolioReaderPage) { let currentIndexPathRow = cell.pageNumber - 1 self.currentWebViewScrollPositions[currentIndexPathRow] = scrollView.contentOffset } if scrollView is UICollectionView { if totalPages > 0 { updateCurrentPage() } } scrollScrubber?.scrollViewDidEndDecelerating(scrollView) } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { recentlyScrolledTimer = NSTimer(timeInterval:recentlyScrolledDelay, target: self, selector: #selector(FolioReaderCenter.clearRecentlyScrolled), userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(recentlyScrolledTimer, forMode: NSRunLoopCommonModes) } func clearRecentlyScrolled() { if(recentlyScrolledTimer != nil) { recentlyScrolledTimer.invalidate() recentlyScrolledTimer = nil } recentlyScrolled = false } public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) { scrollScrubber?.scrollViewDidEndScrollingAnimation(scrollView) } // MARK: NavigationBar Actions func closeReader(sender: UIBarButtonItem) { dismiss() FolioReader.close() } /** Present chapter list */ func presentChapterList(sender: UIBarButtonItem) { FolioReader.saveReaderState() let chapter = FolioReaderChapterList() chapter.delegate = self let highlight = FolioReaderHighlightList() let pageController = PageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options:nil) pageController.viewControllerOne = chapter pageController.viewControllerTwo = highlight pageController.segmentedControlItems = [readerConfig.localizedContentsTitle, readerConfig.localizedHighlightsTitle] let nav = UINavigationController(rootViewController: pageController) presentViewController(nav, animated: true, completion: nil) } /** Present fonts and settings menu */ func presentFontsMenu() { FolioReader.saveReaderState() hideBars() let menu = FolioReaderFontsMenu() menu.modalPresentationStyle = .Custom animator = ZFModalTransitionAnimator(modalViewController: menu) animator.dragable = false animator.bounces = false animator.behindViewAlpha = 0.4 animator.behindViewScale = 1 animator.transitionDuration = 0.6 animator.direction = ZFModalTransitonDirection.Bottom menu.transitioningDelegate = animator presentViewController(menu, animated: true, completion: nil) } /** Present audio player menu */ func presentPlayerMenu(sender: UIBarButtonItem) { FolioReader.saveReaderState() hideBars() let menu = FolioReaderPlayerMenu() menu.modalPresentationStyle = .Custom animator = ZFModalTransitionAnimator(modalViewController: menu) animator.dragable = true animator.bounces = false animator.behindViewAlpha = 0.4 animator.behindViewScale = 1 animator.transitionDuration = 0.6 animator.direction = ZFModalTransitonDirection.Bottom menu.transitioningDelegate = animator presentViewController(menu, animated: true, completion: nil) } /** Present Quote Share */ func presentQuoteShare(string: String) { let quoteShare = FolioReaderQuoteShare(initWithText: string) let nav = UINavigationController(rootViewController: quoteShare) presentViewController(nav, animated: true, completion: nil) } } // MARK: FolioPageDelegate extension FolioReaderCenter: FolioReaderPageDelegate { func pageDidLoad(page: FolioReaderPage) { if let position = FolioReader.defaults.valueForKey(kBookId) as? NSDictionary { let pageNumber = position["pageNumber"]! as! Int let offset = isDirection(position["pageOffsetY"], position["pageOffsetX"]) as? CGFloat let pageOffset = offset if isFirstLoad { updateCurrentPage(page) isFirstLoad = false if currentPageNumber == pageNumber && pageOffset > 0 { page.scrollPageToOffset(pageOffset!, animated: false) } } else if !isScrolling && FolioReader.needsRTLChange { page.scrollPageToBottom() } } else if isFirstLoad { updateCurrentPage(page) isFirstLoad = false } // Go to fragment if needed if let fragmentID = tempFragment, let currentPage = currentPage where fragmentID != "" { currentPage.handleAnchor(fragmentID, avoidBeginningAnchors: true, animated: true) tempFragment = nil } if (readerConfig.scrollDirection == .horizontalWithVerticalContent), let offsetPoint = self.currentWebViewScrollPositions[page.pageNumber - 1] { page.webView.scrollView.setContentOffset(offsetPoint, animated: false) } } } // MARK: FolioReaderChapterListDelegate extension FolioReaderCenter: FolioReaderChapterListDelegate { func chapterList(chapterList: FolioReaderChapterList, didSelectRowAtIndexPath indexPath: NSIndexPath, withTocReference reference: FRTocReference) { let item = findPageByResource(reference) if item < totalPages { let indexPath = NSIndexPath(forRow: item, inSection: 0) changePageWith(indexPath: indexPath, animated: false, completion: { () -> Void in self.updateCurrentPage() }) tempReference = reference } else { print("Failed to load book because the requested resource is missing.") } } func chapterList(didDismissedChapterList chapterList: FolioReaderChapterList) { updateCurrentPage() // Move to #fragment if let reference = tempReference { if let fragmentID = reference.fragmentID, let currentPage = currentPage where fragmentID != "" { currentPage.handleAnchor(reference.fragmentID!, avoidBeginningAnchors: true, animated: true) } tempReference = nil } } }
bsd-3-clause
0f50373a91dd9bf1d466d23244da9757
36.924628
205
0.633735
5.651299
false
false
false
false
negherbon/crosswalk-ios
XWalkView/XWalkView/XWalkChannel.swift
5
6066
// Copyright (c) 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation import WebKit public class XWalkChannel : NSObject, WKScriptMessageHandler { public let name: String public var mirror: XWalkReflection! private(set) public var namespace: String = "" private(set) public weak var webView: XWalkView? private(set) public weak var thread: NSThread? private var instances: [Int: AnyObject] = [:] private var userScript: WKUserScript? public init(webView: XWalkView) { struct seq{ static var num: UInt32 = 0 } self.webView = webView self.name = "\(++seq.num)" super.init() webView.configuration.userContentController.addScriptMessageHandler(self, name: "\(self.name)") } public func bind(object: AnyObject, namespace: String, thread: NSThread?) { self.namespace = namespace self.thread = thread ?? NSThread.mainThread() mirror = XWalkReflection(cls: object.dynamicType) var script = XWalkStubGenerator(reflection: mirror).generate(name, namespace: namespace, object: object) let delegate = object as? XWalkDelegate script = delegate?.didGenerateStub?(script) ?? script userScript = webView?.injectScript(script) delegate?.didBindExtension?(self, instance: 0) instances[0] = object } public func destroyExtension() { if webView?.URL != nil { evaluateJavaScript("delete \(namespace);", completionHandler:nil) } webView?.configuration.userContentController.removeScriptMessageHandlerForName("\(name)") if userScript != nil { webView?.configuration.userContentController.removeUserScript(userScript!) } for (_, object) in instances { (object as? XWalkDelegate)?.didUnbindExtension?() } instances.removeAll(keepCapacity: false) } public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage: WKScriptMessage) { let body = didReceiveScriptMessage.body as! [String: AnyObject] let instid = (body["instance"] as? NSNumber)?.integerValue ?? 0 let callid = body["callid"] as? NSNumber ?? NSNumber(integer: 0) let args = [callid] + (body["arguments"] as? [AnyObject] ?? []) if let method = body["method"] as? String { // Invoke method if let object: AnyObject = instances[instid] { let delegate = object as? XWalkDelegate if delegate?.invokeNativeMethod != nil { let selector = Selector("invokeNativeMethod:arguments:") XWalkInvocation.asyncCallOnThread(thread, target: object, selector: selector, arguments: [method, args]) } else if mirror.hasMethod(method) { XWalkInvocation.asyncCallOnThread(thread, target: object, selector: mirror.getMethod(method), arguments: args) } else { println("ERROR: Method '\(method)' is not defined in class '\(object.dynamicType.description())'.") } } else { println("ERROR: Instance \(instid) does not exist.") } } else if let prop = body["property"] as? String { // Update property if let object: AnyObject = instances[instid] { let value: AnyObject = body["value"] ?? NSNull() let delegate = object as? XWalkDelegate if delegate?.setNativeProperty != nil { let selector = Selector("setNativeProperty:value:") XWalkInvocation.asyncCallOnThread(thread, target: object, selector: selector, arguments: [prop, value]) } else if mirror.hasProperty(prop) { let selector = mirror.getSetter(prop) if selector != Selector() { XWalkInvocation.asyncCallOnThread(thread, target: object, selector: selector, arguments: [value]) } else { println("ERROR: Property '\(prop)' is readonly.") } } else { println("ERROR: Property '\(prop)' is not defined in class '\(object.dynamicType.description())'.") } } else { println("ERROR: Instance \(instid) does not exist.") } } else if instid > 0 && instances[instid] == nil { // Create instance let ctor: AnyObject = instances[0]! let object: AnyObject = XWalkInvocation.constructOnThread(thread, `class`: ctor.dynamicType, initializer: mirror.constructor, arguments: args) instances[instid] = object (object as? XWalkDelegate)?.didBindExtension?(self, instance: instid) // TODO: shoud call releaseArguments } else if let object: AnyObject = instances[-instid] { // Destroy instance instances.removeValueForKey(-instid) (object as? XWalkDelegate)?.didUnbindExtension?() } else if body["destroy"] != nil { destroyExtension() } else { // TODO: support user defined message? println("ERROR: Unknown message: \(body)") } } public func evaluateJavaScript(string: String, completionHandler: ((AnyObject!, NSError!)->Void)?) { // TODO: Should call completionHandler with an NSError object when webView is nil if NSThread.isMainThread() { webView?.evaluateJavaScript(string, completionHandler: completionHandler) } else { weak var weakSelf = self dispatch_async(dispatch_get_main_queue()) { if let strongSelf = weakSelf { strongSelf.webView?.evaluateJavaScript(string, completionHandler: completionHandler) } } } } }
bsd-3-clause
5df7233897a879fec798be81f11d2e92
45.305344
154
0.603198
5.042394
false
false
false
false
mspegagne/ToDoReminder-iOS
ToDoReminder/ToDoReminder/AppDelegate.swift
1
6145
// // AppDelegate.swift // ToDoReminder // // Created by Mathieu Spegagne on 24/03/2015. // Copyright (c) 2015 Mathieu Spegagne. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.Ms.ToDoReminder" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("ToDoReminder", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ToDoReminder.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
ce5fe596702b9930f0bad0d92c68297a
54.36036
290
0.716517
5.748363
false
false
false
false