repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
collinhundley/MySQL
|
refs/heads/master
|
Sources/MySQL/PreparedStatement.swift
|
mit
|
1
|
//
// PreparedStatement.swift
// MySQL
//
// Created by Collin Hundley on 6/24/17.
//
import Foundation
#if os(Linux)
import CMySQLLinux
#else
import CMySQLMac
#endif
/// MySQL implementation for prepared statements.
public class PreparedStatement {
enum Error: Swift.Error, LocalizedError {
case initialize(String)
case execute(String)
var errorDescription: String? {
switch self {
case .execute(let msg):
return msg
case .initialize(let msg):
return msg
}
}
}
/// Reference to native MySQL statement.
private(set) var statement: UnsafeMutablePointer<MYSQL_STMT>?
private var binds = [MYSQL_BIND]()
private var bindsCapacity = 0
private var bindPtr: UnsafeMutablePointer<MYSQL_BIND>? = nil
/// Static date formatter for converting MySQL fetch results to Swift types.
private static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
/// Initializes a prepared statement.
///
/// - Parameters:
/// - stmt: The statement to execute.
/// - mysql: A reference to a MySQL connection.
/// - Throws: `PreparedStatement.Error` if an error is encountered.
init(_ stmt: String, mysql: UnsafeMutablePointer<MYSQL>?) throws {
// Make sure database connection has already been established
guard let mysql = mysql else {
throw Error.initialize("MySQL not connected. Call connect() before execute().")
}
// Initialize MySQL statement
guard let statement = mysql_stmt_init(mysql) else {
throw Error.initialize(Connection.getError(from: mysql))
}
// Prepare statement
guard mysql_stmt_prepare(statement, stmt, UInt(stmt.utf8.count)) == 0 else {
defer {
mysql_stmt_close(statement)
}
throw Error.initialize(Connection.getError(from: statement))
}
self.statement = statement
}
/// Ensure that statement and binds become deallocated.
deinit {
release()
}
/// Execute the statement, optionally with parameters.
///
/// - Parameter parameters: An array of parameters to use for execution, if any.
/// - Returns: The result of the execution.
/// - Throws: `PreparedStatement.Error` if an error occurs.
func execute(parameters: [Any?]? = nil) throws -> MySQL.Result {
guard let statement = self.statement else {
throw Error.execute("The prepared statement has already been released.")
}
if let parameters = parameters {
if let bindPtr = bindPtr {
guard bindsCapacity == parameters.count else {
throw Error.execute("Each call to execute() must pass the same number of parameters.")
}
} else { // true only for the first time execute() is called for this PreparedStatement
bindsCapacity = parameters.count
bindPtr = UnsafeMutablePointer<MYSQL_BIND>.allocate(capacity: bindsCapacity)
}
do {
try allocateBinds(parameters: parameters)
} catch {
// Catch error so we can close the statement before throwing
self.statement = nil
mysql_stmt_close(statement)
throw error
}
}
guard let resultMetadata = mysql_stmt_result_metadata(statement) else {
// Non-query statement (insert, update, delete)
guard mysql_stmt_execute(statement) == 0 else {
guard let statement = self.statement else {
throw Error.execute("Statement is nil after execution.")
}
let error = Connection.getError(from: statement)
self.statement = nil
mysql_stmt_close(statement)
throw Error.execute(error)
}
// TODO: Potentially return number of affected rows here
// let affectedRows = mysql_stmt_affected_rows(statement) as UInt64
return [[:]]
}
defer {
mysql_free_result(resultMetadata)
}
let resultFetcher = try ResultFetcher(preparedStatement: self, resultMetadata: resultMetadata)
return resultFetcher.rows()
}
/// Deallocate statement and binds.
func release() {
deallocateBinds()
if let statement = self.statement {
self.statement = nil
mysql_stmt_close(statement)
}
}
private func allocateBinds(parameters: [Any?]) throws {
if binds.isEmpty { // first parameter set, create new bind and bind it to the parameter
for (index, parameter) in parameters.enumerated() {
var bind = MYSQL_BIND()
setBind(&bind, parameter)
binds.append(bind)
bindPtr![index] = bind
}
} else { // bind was previously created, re-initialize value
for (index, parameter) in parameters.enumerated() {
var bind = binds[index]
setBind(&bind, parameter)
binds[index] = bind
bindPtr![index] = bind
}
}
guard mysql_stmt_bind_param(statement, bindPtr) == 0 else {
throw Error.execute(Connection.getError(from: statement!)) // THis is guaranteed to be safe
}
}
private func deallocateBinds() {
guard let bindPtr = self.bindPtr else {
return
}
self.bindPtr = nil
for bind in binds {
if bind.buffer != nil {
bind.buffer.deallocate(bytes: Int(bind.buffer_length), alignedTo: 1)
}
if bind.length != nil {
bind.length.deallocate(capacity: 1)
}
if bind.is_null != nil {
bind.is_null.deallocate(capacity: 1)
}
}
bindPtr.deallocate(capacity: bindsCapacity)
binds.removeAll()
}
private func setBind(_ bind: inout MYSQL_BIND, _ parameter: Any?) {
if bind.is_null == nil {
bind.is_null = UnsafeMutablePointer<Int8>.allocate(capacity: 1)
}
guard let parameter = parameter else {
bind.buffer_type = MYSQL_TYPE_NULL
bind.is_null.initialize(to: 1)
return
}
bind.buffer_type = getType(parameter: parameter)
bind.is_null.initialize(to: 0)
bind.is_unsigned = 0
switch parameter {
case let string as String:
initialize(string: string, &bind)
case let date as Date:
// Note: Here we assume this is DateTime type - does not handle Date or Time types
let formattedDate = PreparedStatement.dateFormatter.string(from: date)
initialize(string: formattedDate, &bind)
case let byteArray as [UInt8]:
let typedBuffer = allocate(type: UInt8.self, capacity: byteArray.count, bind: &bind)
#if swift(>=3.1)
let _ = UnsafeMutableBufferPointer(start: typedBuffer, count: byteArray.count).initialize(from: byteArray)
#else
typedBuffer.initialize(from: byteArray)
#endif
case let data as Data:
let typedBuffer = allocate(type: UInt8.self, capacity: data.count, bind: &bind)
data.copyBytes(to: typedBuffer, count: data.count)
case let dateTime as MYSQL_TIME:
initialize(dateTime, &bind)
case let float as Float:
initialize(float, &bind)
case let double as Double:
initialize(double, &bind)
case let bool as Bool:
initialize(bool, &bind)
case let int as Int:
initialize(int, &bind)
case let int as Int8:
initialize(int, &bind)
case let int as Int16:
initialize(int, &bind)
case let int as Int32:
initialize(int, &bind)
case let int as Int64:
initialize(int, &bind)
case let uint as UInt:
initialize(uint, &bind)
bind.is_unsigned = 1
case let uint as UInt8:
initialize(uint, &bind)
bind.is_unsigned = 1
case let uint as UInt16:
initialize(uint, &bind)
bind.is_unsigned = 1
case let uint as UInt32:
initialize(uint, &bind)
bind.is_unsigned = 1
case let uint as UInt64:
initialize(uint, &bind)
bind.is_unsigned = 1
case let unicodeScalar as UnicodeScalar:
initialize(unicodeScalar, &bind)
bind.is_unsigned = 1
default:
print("WARNING: Unhandled parameter \(parameter) (type: \(type(of: parameter))). Will attempt to convert it to a String")
initialize(string: String(describing: parameter), &bind)
}
}
private func allocate<T>(type: T.Type, capacity: Int, bind: inout MYSQL_BIND) -> UnsafeMutablePointer<T> {
let length = UInt(capacity * MemoryLayout<T>.size)
if bind.length == nil {
bind.length = UnsafeMutablePointer<UInt>.allocate(capacity: 1)
}
bind.length.initialize(to: length)
let typedBuffer: UnsafeMutablePointer<T>
if let buffer = bind.buffer, bind.buffer_length >= length {
typedBuffer = buffer.assumingMemoryBound(to: type)
} else {
if bind.buffer != nil {
// deallocate existing smaller buffer
bind.buffer.deallocate(bytes: Int(bind.buffer_length), alignedTo: 1)
}
typedBuffer = UnsafeMutablePointer<T>.allocate(capacity: capacity)
bind.buffer = UnsafeMutableRawPointer(typedBuffer)
bind.buffer_length = length
}
return typedBuffer
}
private func initialize<T>(_ parameter: T, _ bind: inout MYSQL_BIND) {
let typedBuffer = allocate(type: type(of: parameter), capacity: 1, bind: &bind)
typedBuffer.initialize(to: parameter)
}
private func initialize(string: String, _ bind: inout MYSQL_BIND) {
let utf8 = string.utf8
let typedBuffer = allocate(type: UInt8.self, capacity: utf8.count, bind: &bind)
#if swift(>=3.1)
let _ = UnsafeMutableBufferPointer(start: typedBuffer, count: utf8.count).initialize(from: utf8)
#else
typedBuffer.initialize(from: utf8)
#endif
}
private func getType(parameter: Any) -> enum_field_types {
switch parameter {
case is String,
is Date:
return MYSQL_TYPE_STRING
case is Data,
is [UInt8]:
return MYSQL_TYPE_BLOB
case is Int8,
is UInt8,
is Bool:
return MYSQL_TYPE_TINY
case is Int16,
is UInt16:
return MYSQL_TYPE_SHORT
case is Int32,
is UInt32,
is UnicodeScalar:
return MYSQL_TYPE_LONG
case is Int,
is UInt,
is Int64,
is UInt64:
return MYSQL_TYPE_LONGLONG
case is Float:
return MYSQL_TYPE_FLOAT
case is Double:
return MYSQL_TYPE_DOUBLE
case is MYSQL_TIME:
return MYSQL_TYPE_DATETIME
default:
return MYSQL_TYPE_STRING
}
}
}
|
2333ee2037e1e4166b4c9e92be497d09
| 33.420749 | 133 | 0.55777 | false | false | false | false |
crazypoo/PTools
|
refs/heads/master
|
PooToolsSource/Base/PTFloatingPanelFuction.swift
|
mit
|
1
|
//
// PTFloatingPanelFuction.swift
// PooTools_Example
//
// Created by jax on 2022/10/11.
// Copyright © 2022 crazypoo. All rights reserved.
//
import UIKit
import FloatingPanel
public typealias FloatingBlock = () -> Void
public class PTFloatingPanelFuction: NSObject {
class open func floatPanel_VC(vc:PTBaseViewController,panGesDelegate:(UIViewController & UIGestureRecognizerDelegate)? = PTUtils.getCurrentVC() as! PTBaseViewController,floatingDismiss:FloatingBlock? = nil)
{
let fpc = FloatingPanelController()
fpc.set(contentViewController: vc)
fpc.contentMode = .fitToBounds
fpc.contentInsetAdjustmentBehavior = .never
fpc.isRemovalInteractionEnabled = true
fpc.panGestureRecognizer.isEnabled = true
fpc.panGestureRecognizer.delegateProxy = panGesDelegate
fpc.surfaceView.backgroundColor = .randomColor
let backDropDismiss = UITapGestureRecognizer.init { action in
vc.dismiss(animated: true)
if floatingDismiss != nil
{
floatingDismiss!()
}
}
fpc.backdropView.addGestureRecognizer(backDropDismiss)
// Create a new appearance.
let appearance = SurfaceAppearance()
// Define shadows
let shadow = SurfaceAppearance.Shadow()
shadow.color = UIColor.black
shadow.offset = CGSize(width: 0, height: 16)
shadow.radius = 16
shadow.spread = 8
appearance.shadows = [shadow]
// Define corner radius and background color
appearance.cornerRadius = 8.0
appearance.backgroundColor = .white
// Set the new appearance
fpc.surfaceView.appearance = appearance
fpc.delegate = vc
(PTUtils.getCurrentVC() as? PTBaseViewController)?.present(fpc, animated: true) {
if floatingDismiss != nil
{
floatingDismiss!()
}
}
}
}
|
7d4d8343a733da6df699dedfe76a852f
| 31.622951 | 210 | 0.640201 | false | false | false | false |
bsmith11/ScoreReporter
|
refs/heads/master
|
ScoreReporterCore/ScoreReporterCore/Models/Standing.swift
|
mit
|
1
|
//
// Standing.swift
// ScoreReporter
//
// Created by Bradley Smith on 7/18/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
import CoreData
public class Standing: NSManagedObject {
}
// MARK: - Public
public extension Standing {
static func fetchedStandingsFor(pool: Pool) -> NSFetchedResultsController<Standing> {
let predicate = NSPredicate(format: "%K == %@", #keyPath(Standing.pool), pool)
let sortDescriptors = [
NSSortDescriptor(key: #keyPath(Standing.sortOrder), ascending: true)
]
return fetchedResultsController(predicate: predicate, sortDescriptors: sortDescriptors)
}
}
// MARK: - Fetchable
extension Standing: Fetchable {
public static var primaryKey: String {
return ""
}
}
// MARK: - CoreDataImportable
extension Standing: CoreDataImportable {
public static func object(from dictionary: [String: Any], context: NSManagedObjectContext) -> Standing? {
guard let standing = createObject(in: context) else {
return nil
}
standing.wins = dictionary[APIConstants.Response.Keys.wins] as? NSNumber
standing.losses = dictionary[APIConstants.Response.Keys.losses] as? NSNumber
standing.sortOrder = dictionary[APIConstants.Response.Keys.sortOrder] as? NSNumber
let teamName = dictionary <~ APIConstants.Response.Keys.teamName
let seed = self.seed(from: teamName)
standing.seed = seed as NSNumber
let seedString = "(\(seed))"
standing.teamName = teamName?.replacingOccurrences(of: seedString, with: "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if !standing.hasPersistentChangedValues {
context.refresh(standing, mergeChanges: false)
}
return standing
}
static func seed(from teamName: String?) -> Int {
let pattern = "([0-9]+)"
if let seed = teamName?.matching(regexPattern: pattern), !seed.isEmpty {
return Int(seed) ?? 0
}
else {
return 0
}
}
}
|
0141d54ebf6b12bb4dfd9cad58085a04
| 27.337838 | 144 | 0.657129 | false | false | false | false |
roehrdor/diagnoseit-ios-mobile-agent
|
refs/heads/master
|
Constants.swift
|
mit
|
1
|
/*
Copyright (c) 2017 Oliver Roehrdanz
Copyright (c) 2017 Matteo Sassano
Copyright (c) 2017 Christopher Voelker
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 UIKit
struct Constants {
static let INVALID = "INVALID".data(using: .utf8)
static var HOST : String = ""
static let submitResultUrl : String = "/rest/mobile/newinvocation"
static var spanServicetUrl : String = ""
static let UNKNOWN : String = "unknown"
static func getTimestamp() -> UInt64 {
return UInt64(NSDate().timeIntervalSince1970 * 1000000.0)
}
static func decimalToHex(decimal: UInt64) -> String {
return String(decimal, radix: 16)
}
static func alert(windowTitle : String, message : String, confirmButtonName : String) -> UIAlertController {
let alert = UIAlertController(title: windowTitle, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: confirmButtonName, style: UIAlertActionStyle.default, handler: nil))
return alert;
}
static func addLabel(text : String, x : CGFloat, y : CGFloat, width : CGFloat, height : CGFloat) -> UILabel {
let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
label.text = text
return label
}
}
|
40dca6c24f07c2084652ca19f9ba19a1
| 42.203704 | 121 | 0.727818 | false | false | false | false |
phimage/Alamofire-YamlSwift
|
refs/heads/master
|
Alamofire-YamlSwift/Alamofire+YamlSwift.swift
|
mit
|
1
|
//
// Alamofire+YamlSwift.swift
// Alamofire-YamlSwift
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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 YamlSwift
import Alamofire
extension Request {
public static func YamlResponseSerializer() -> ResponseSerializer<Yaml, NSError> {
return ResponseSerializer { request, response, data, error in
guard error == nil else { return .Failure(error!) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
guard let string = String(data: validData, encoding: NSUTF8StringEncoding) else {
let failureReason = "Data could not be deserialized. Input data was not convertible to String."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
let result: YamlSwift.Result<Yaml> = Yaml.load(string)
switch result {
case .Error(let failureReason):
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
case .Value:
return .Success(result.value!)
}
}
}
public func responseYaml(completionHandler: Response<Yaml, NSError> -> Void) -> Self {
return response(responseSerializer: Request.YamlResponseSerializer(), completionHandler: completionHandler)
}
}
|
8e6fe05241c6b9c140a382bf4ca93383
| 45.389831 | 115 | 0.695541 | false | false | false | false |
insidegui/WWDC
|
refs/heads/master
|
WWDC/ClipComposition.swift
|
bsd-2-clause
|
1
|
//
// ClipComposition.swift
// WWDC
//
// Created by Guilherme Rambo on 02/06/20.
// Copyright © 2020 Guilherme Rambo. All rights reserved.
//
import Cocoa
import AVFoundation
import CoreMedia
import CoreImage.CIFilterBuiltins
final class ClipComposition: AVMutableComposition {
private struct Constants {
static let minBoxWidth: CGFloat = 325
static let maxBoxWidth: CGFloat = 600
static let boxPadding: CGFloat = 42
}
let title: String
let subtitle: String
let video: AVAsset
let includeBanner: Bool
var videoComposition: AVMutableVideoComposition?
init(video: AVAsset, title: String, subtitle: String, includeBanner: Bool) throws {
self.video = video
self.title = title
self.subtitle = subtitle
self.includeBanner = includeBanner
super.init()
guard let newVideoTrack = addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) else {
// Should this ever fail in real life? Who knows...
preconditionFailure("Failed to add video track to composition")
}
if let videoTrack = video.tracks(withMediaType: .video).first {
try newVideoTrack.insertTimeRange(CMTimeRange(start: .zero, duration: video.duration), of: videoTrack, at: .zero)
}
if let newAudioTrack = addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) {
if let audioTrack = video.tracks(withMediaType: .audio).first {
try newAudioTrack.insertTimeRange(CMTimeRange(start: .zero, duration: video.duration), of: audioTrack, at: .zero)
}
}
configureCompositionIfNeeded(videoTrack: newVideoTrack)
}
private func configureCompositionIfNeeded(videoTrack: AVMutableCompositionTrack) {
guard includeBanner else { return }
let mainInstruction = AVMutableVideoCompositionInstruction()
mainInstruction.timeRange = CMTimeRange(start: .zero, duration: video.duration)
let videolayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
mainInstruction.layerInstructions = [videolayerInstruction]
videoComposition = AVMutableVideoComposition(propertiesOf: video)
videoComposition?.instructions = [mainInstruction]
composeTemplate(with: videoTrack.naturalSize)
}
private func composeTemplate(with renderSize: CGSize) {
guard let asset = CALayer.load(assetNamed: "ClipTemplate") else {
fatalError("Missing ClipTemplate asset")
}
guard let assetContainer = asset.sublayer(named: "container", of: CALayer.self) else {
fatalError("Missing container layer")
}
guard let box = assetContainer.sublayer(named: "box", of: CALayer.self) else {
fatalError("Missing box layer")
}
guard let titleLayer = box.sublayer(named: "sessionTitle", of: CATextLayer.self) else {
fatalError("Missing sessionTitle layer")
}
guard let subtitleLayer = box.sublayer(named: "eventName", of: CATextLayer.self) else {
fatalError("Missing sessionTitle layer")
}
guard let videoLayer = assetContainer.sublayer(named: "video", of: CALayer.self) else {
fatalError("Missing video layer")
}
if let iconLayer = box.sublayer(named: "appicon", of: CALayer.self) {
iconLayer.contents = NSApp.applicationIconImage
}
// Add a NSVisualEffectView-like blur to the box.
let blur = CIFilter.gaussianBlur()
blur.radius = 22
let saturate = CIFilter.colorControls()
saturate.setDefaults()
saturate.saturation = 1.5
box.backgroundFilters = [saturate, blur]
box.masksToBounds = true
// Set text on layers.
titleLayer.string = attributedTitle
subtitleLayer.string = attributedSubtitle
// Compute final box/title layer widths based on title.
let titleSize = attributedTitle.size()
if titleSize.width > titleLayer.bounds.width {
var boxFrame = box.frame
boxFrame.size.width = titleSize.width + Constants.boxPadding * 3
box.frame = boxFrame
var titleFrame = titleLayer.frame
titleFrame.size.width = titleSize.width
titleLayer.frame = titleFrame
}
let container = CALayer()
container.frame = CGRect(origin: .zero, size: renderSize)
container.addSublayer(assetContainer)
container.resizeLayer(assetContainer)
assetContainer.isGeometryFlipped = true
videoComposition?.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: container)
box.sublayers?.compactMap({ $0 as? CATextLayer }).forEach { layer in
layer.minificationFilter = .trilinear
// Workaround rdar://32718905
layer.display()
}
}
private lazy var attributedTitle: NSAttributedString = {
NSAttributedString.create(
with: title,
font: .wwdcRoundedSystemFont(ofSize: 16, weight: .medium),
color: .white
)
}()
private lazy var attributedSubtitle: NSAttributedString = {
NSAttributedString.create(
with: subtitle,
font: .systemFont(ofSize: 13, weight: .medium),
color: .white
)
}()
}
|
210f12be8983fc4dbfcad98f1f877500
| 34.11465 | 132 | 0.657537 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Localization/Sources/Localization/LocalizationConstants+Account.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
// swiftlint:disable all
import Foundation
extension LocalizationConstants {
public enum Account {
public static let myWallet = NSLocalizedString(
"Private Key Wallet",
comment: "Used for naming non custodial wallets."
)
public static let myInterestWallet = NSLocalizedString(
"Rewards Account",
comment: "Used for naming rewards accounts."
)
public static let myTradingAccount = NSLocalizedString(
"Trading Account",
comment: "Used for naming trading accounts."
)
public static let myExchangeAccount = NSLocalizedString(
"Exchange Account",
comment: "Used for naming exchange accounts."
)
public static let lowFees = NSLocalizedString(
"Low Fees",
comment: "Low Fees"
)
public static let faster = NSLocalizedString(
"Faster",
comment: "Faster"
)
public static let legacyMyBitcoinWallet = NSLocalizedString(
"My Bitcoin Wallet",
comment: "My Bitcoin Wallet"
)
public static let noFees = NSLocalizedString(
"No Fees",
comment: "No Fees"
)
public static let wireFee = NSLocalizedString(
"Wire Fee",
comment: "Wire Fee"
)
public static let minWithdraw = NSLocalizedString(
"Min Withdraw",
comment: "Min Withdraw"
)
}
public enum AccountGroup {
public static let allWallets = NSLocalizedString(
"All Wallets",
comment: "All Wallets"
)
public static let myWallets = NSLocalizedString(
"%@ Wallets",
comment: "Must contain %@. Used for naming account groups e.g. Ethereum Wallets"
)
public static let myCustodialWallets = NSLocalizedString(
"%@ Custodial Accounts",
comment: "Must contain %@. Used for naming trading account groups e.g. Ethereum Custodial Wallets"
)
}
}
|
a4b4ca331e764049a4ba863fd7b98836
| 27.671053 | 110 | 0.577788 | false | false | false | false |
JGiola/swift-corelibs-foundation
|
refs/heads/master
|
Foundation/NSPredicate.swift
|
apache-2.0
|
13
|
// 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
//
// Predicates wrap some combination of expressions and operators and when evaluated return a BOOL.
open class NSPredicate : NSObject, NSSecureCoding, NSCopying {
private enum PredicateKind {
case boolean(Bool)
case block((Any?, [String : Any]?) -> Bool)
case format(String)
case metadataQuery(String)
}
private let kind: PredicateKind
public static var supportsSecureCoding: Bool {
return true
}
public required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let encodedBool = aDecoder.decodeBool(forKey: "NS.boolean.value")
self.kind = .boolean(encodedBool)
super.init()
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
//TODO: store kind key for .boolean, .format, .metadataQuery
switch self.kind {
case .boolean(let value):
aCoder.encode(value, forKey: "NS.boolean.value")
case .block:
preconditionFailure("NSBlockPredicate cannot be encoded or decoded.")
case .format:
NSUnimplemented()
case .metadataQuery:
NSUnimplemented()
}
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
switch self.kind {
case .boolean(let value):
return NSPredicate(value: value)
case .block(let block):
return NSPredicate(block: block)
case .format:
NSUnimplemented()
case .metadataQuery:
NSUnimplemented()
}
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSPredicate else { return false }
if other === self {
return true
} else {
switch (other.kind, self.kind) {
case (.boolean(let otherBool), .boolean(let selfBool)):
return otherBool == selfBool
case (.format, .format):
NSUnimplemented()
case (.metadataQuery, .metadataQuery):
NSUnimplemented()
default:
// NSBlockPredicate returns false even for copy
return false
}
}
}
// Parse predicateFormat and return an appropriate predicate
public init(format predicateFormat: String, argumentArray arguments: [Any]?) { NSUnimplemented() }
public init(format predicateFormat: String, arguments argList: CVaListPointer) { NSUnimplemented() }
public init?(fromMetadataQueryString queryString: String) { NSUnimplemented() }
public init(value: Bool) {
kind = .boolean(value)
super.init()
} // return predicates that always evaluate to true/false
public init(block: @escaping (Any?, [String : Any]?) -> Bool) {
kind = .block(block)
super.init()
}
open var predicateFormat: String {
switch self.kind {
case .boolean(let value):
return value ? "TRUEPREDICATE" : "FALSEPREDICATE"
case .block:
// TODO: Bring NSBlockPredicate's predicateFormat to macOS's Foundation version
// let address = unsafeBitCast(block, to: Int.self)
// return String(format:"BLOCKPREDICATE(%2X)", address)
return "BLOCKPREDICATE"
case .format:
NSUnimplemented()
case .metadataQuery:
NSUnimplemented()
}
}
open func withSubstitutionVariables(_ variables: [String : Any]) -> Self { NSUnimplemented() } // substitute constant values for variables
open func evaluate(with object: Any?) -> Bool {
return evaluate(with: object, substitutionVariables: nil)
} // evaluate a predicate against a single object
open func evaluate(with object: Any?, substitutionVariables bindings: [String : Any]?) -> Bool {
if bindings != nil {
NSUnimplemented()
}
switch kind {
case let .boolean(value):
return value
case let .block(block):
return block(object, bindings)
case .format:
NSUnimplemented()
case .metadataQuery:
NSUnimplemented()
}
} // single pass evaluation substituting variables from the bindings dictionary for any variable expressions encountered
open func allowEvaluation() { NSUnimplemented() } // Force a predicate which was securely decoded to allow evaluation
}
extension NSPredicate {
public convenience init(format predicateFormat: String, _ args: CVarArg...) { NSUnimplemented() }
}
extension NSArray {
open func filtered(using predicate: NSPredicate) -> [Any] {
return allObjects.filter({ object in
return predicate.evaluate(with: object)
})
}
}
extension NSMutableArray {
open func filter(using predicate: NSPredicate) {
var indexesToRemove = IndexSet()
for (index, object) in self.enumerated() {
if !predicate.evaluate(with: object) {
indexesToRemove.insert(index)
}
}
self.removeObjects(at: indexesToRemove)
}
}
extension NSSet {
open func filtered(using predicate: NSPredicate) -> Set<AnyHashable> {
let objs = allObjects.filter { (object) -> Bool in
return predicate.evaluate(with: object)
}
return Set(objs.map { $0 as! AnyHashable })
}
}
extension NSMutableSet {
open func filter(using predicate: NSPredicate) {
for object in self {
if !predicate.evaluate(with: object) {
self.remove(object)
}
}
}
}
extension NSOrderedSet {
open func filtered(using predicate: NSPredicate) -> NSOrderedSet {
return NSOrderedSet(array: self.allObjects.filter({ object in
return predicate.evaluate(with: object)
}))
}
}
extension NSMutableOrderedSet {
open func filter(using predicate: NSPredicate) {
var indexesToRemove = IndexSet()
for (index, object) in self.enumerated() {
if !predicate.evaluate(with: object) {
indexesToRemove.insert(index)
}
}
self.removeObjects(at: indexesToRemove)
}
}
|
d39c94973b4d6dc355d28e9a34f530fc
| 31.153488 | 142 | 0.604947 | false | false | false | false |
alfredcc/SwiftPlayground
|
refs/heads/master
|
Functions/Functions.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
func treble(i: Int) -> Int {
return i * 3
}
let nums = [1,2,3,4].map(treble)
// closure expression
let treble1 = { (i: Int) in return i * 3}
let newNums = [1,2,3,4].map(treble1)
let isEven = { $0%2 == 0} as Int8 -> Bool
isEven(4)
// IntegerLiteralConvertible
//protocol IntegerLiteralConvertible {
// typealias IntegerLiteralType
//
// init(IntegerLiteral value: Self.IntegerLiteralType)
//}
func isEven<T: IntegerType>(i: T) -> Bool {
return i%2 == 0
}
// 将一个generic funtion 赋值给一个变量必须指定 Type
let int8isEven: Int8 -> Bool = isEven
// Tips: 闭包是一种特殊的方法(匿名方法),闭包与方法主要的不同点是`闭包`能够捕获变量
// 一个粒子
// 利用 Objective-C 的 runtime
let last = "lastName", first = "firstName"
let people = [
[first: "Neil", last: "Chao"],
[first: "Yu",last: "Yu"],
[first: "Chao", last: "Race"]
]
//
//let lastDescriptor = NSSortDescriptor(key: last, ascending: true, selector: "localizedCaseInsensitiveCompare:")
//let firstDescriptor = NSSortDescriptor(key: first, ascending: true, selector: "localizedCaseInsensitiveCompare:")
//
//let descriptor = [lastDescriptor, firstDescriptor]
//let sortedArray = (people as NSArray).sortedArrayUsingDescriptors(descriptor)
var strings = ["Hello", "hallo", "Hallo","hello"]
strings.sortInPlace {
return $0.localizedCaseInsensitiveCompare($1) == .OrderedAscending
}
let sortedArrays = people.sort { $0[last] < $1[last] }
sortedArrays
let sortedArray = people.sort { (lhs, rhs) -> Bool in
return rhs[first].flatMap{
lhs[first]?.localizedCaseInsensitiveCompare($0)
} == .OrderedAscending
}
|
b3b1e492c31b5ad9d64b5294bd2ce18c
| 22.926471 | 115 | 0.687154 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
refs/heads/master
|
Swift/LeetCode/Array/80_Remove Duplicates from Sorted Array II.swift
|
mit
|
1
|
//
// 80. Remove Duplicates from Sorted Array II.swift
// LeetCode
//
// Created by Honghao Zhang on 2016-10-20.
// Copyright © 2016 Honghaoz. All rights reserved.
//
import Foundation
//Follow up for "Remove Duplicates":
//What if duplicates are allowed at most twice?
//
//For example,
//Given sorted array nums = [1,1,1,2,2,3],
//
//Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
class Num80_RemoveDuplicatesFromSortedArrayII: Solution {
func removeDuplicates(_ nums: inout [Int]) -> Int {
guard nums.count > 2 else {
return nums.count
}
var lastIndex1: Int = 0
var lastIndex2: Int = 1
for i in 2 ..< nums.count {
let num = nums[i]
if num != nums[lastIndex2] || (num == nums[lastIndex2] && num != nums[lastIndex1]) {
lastIndex1 += 1
lastIndex2 += 1
nums[lastIndex2] = num
continue
}
}
return lastIndex2 + 1
}
func removeDuplicates2(_ nums: inout [Int]) -> Int {
guard nums.count > 0 else { return 0 }
if nums.count == 1 {
return 1
}
var last = 1
for i in 2..<nums.count {
let n = nums[i]
if n != nums[last] {
last += 1
nums[last] = n
} else if nums[last - 1] != nums[last] {
last += 1
nums[last] = n
}
}
return last + 1
}
func test() {
// [] -> []
var nums: [Int] = []
var expected: [Int] = []
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1] -> [1]
nums = [1]
expected = [1]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 1] -> [1, 1]
nums = [1, 1]
expected = [1, 1]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 2] -> [1, 2]
nums = [1, 2]
expected = [1, 2]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 1, 1] -> [1, 1]
nums = [1, 1, 1]
expected = [1, 1]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 1, 2] -> [1, 1, 2]
nums = [1, 1, 2]
expected = [1, 1, 2]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 2, 2] -> [1, 2, 2]
nums = [1, 2, 2]
expected = [1, 2, 2]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 1, 1, 1] -> [1, 1]
nums = [1, 1, 1, 1]
expected = [1, 1]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 1, 1, 2] -> [1, 1, 2]
nums = [1, 1, 1, 2]
expected = [1, 1, 2]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 1, 2, 2] -> [1, 1, 2, 2]
nums = [1, 1, 2, 2]
expected = [1, 1, 2, 2]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
// [1, 2, 2, 2] -> [1, 2, 2]
nums = [1, 2, 2, 2]
expected = [1, 2, 2]
assert(removeDuplicates(&nums) == expected.count)
assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count))
}
func checkEqual(nums1: [Int], nums2: [Int], firstCount: Int) -> Bool {
guard nums1.count >= firstCount && nums2.count >= firstCount else { return false }
for i in 0..<firstCount {
if nums1[i] != nums2[i] {
return false
}
}
return true
}
}
|
7cee29c610f4e85ea53c14aec6889cc0
| 28.166667 | 158 | 0.58559 | false | false | false | false |
muccy/Ferrara
|
refs/heads/master
|
Source/Match.swift
|
mit
|
1
|
import Foundation
/// How two objects match
///
/// - none: No match
/// - change: Partial match (same object has changed)
/// - equal: Complete match
public enum Match: String, CustomDebugStringConvertible {
case none = "❌"
case change = "🔄"
case equal = "✅"
public var debugDescription: String {
return self.rawValue
}
}
/// The way two objects are compared to spot no match, partial match or complete match
public protocol Matchable {
func match(with object: Any) -> Match
}
public extension Matchable where Self: Equatable {
public func match(with object: Any) -> Match {
if let object = object as? Self {
return self == object ? .equal : .none
}
return .none
}
}
public extension Equatable where Self: Matchable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.match(with: rhs) == .equal
}
}
|
5a62bd6d0c446bbfa84a638df9f4411d
| 24 | 86 | 0.624865 | false | false | false | false |
nicolastinkl/swift
|
refs/heads/master
|
AdventureBuildingaSpriteKitgameusingSwift/Adventure/Adventure Shared/Sprites/HeroCharacter.swift
|
mit
|
1
|
/*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Defines the common class for hero characters
*/
import SpriteKit
let kCharacterCollisionRadius: CGFloat = 40.0
let kHeroProjectileSpeed: CGFloat = 480.0
let kHeroProjectileLifetime: NSTimeInterval = 1.0
let kHeroProjectileFadeOutTime: NSTimeInterval = 0.6
class HeroCharacter: Character {
var player: Player
init(atPosition position: CGPoint, withTexture texture: SKTexture? = nil, player: Player) {
self.player = player
super.init(texture: texture, atPosition: position)
zRotation = CGFloat(M_PI)
zPosition = -0.25
name = "Hero"
}
override func configurePhysicsBody() {
physicsBody = SKPhysicsBody(circleOfRadius: kCharacterCollisionRadius)
physicsBody.categoryBitMask = ColliderType.Hero.toRaw()
physicsBody.collisionBitMask = ColliderType.GoblinOrBoss.toRaw() | ColliderType.Hero.toRaw() | ColliderType.Wall.toRaw() | ColliderType.Cave.toRaw()
physicsBody.contactTestBitMask = ColliderType.GoblinOrBoss.toRaw()
}
override func collidedWith(other: SKPhysicsBody) {
if other.categoryBitMask & ColliderType.GoblinOrBoss.toRaw() == 0 {
return
}
if let enemy = other.node as? Character {
if !enemy.dying {
applyDamage(5.0)
requestedAnimation = .GetHit
}
}
}
override func animationDidComplete(animation: AnimationState) {
super.animationDidComplete(animation)
switch animation {
case .Death:
let actions = [SKAction.waitForDuration(4.0),
SKAction.runBlock {
self.characterScene.heroWasKilled(self)
},
SKAction.removeFromParent()]
runAction(SKAction.sequence(actions))
case .Attack:
fireProjectile()
default:
() // Do nothing
}
}
// PROJECTILES
func fireProjectile() {
let projectile = self.projectile()!.copy() as SKSpriteNode
projectile.position = position
projectile.zRotation = zRotation
let emitter = projectileEmitter()!.copy() as SKEmitterNode
emitter.targetNode = scene.childNodeWithName("world")
projectile.addChild(emitter)
characterScene.addNode(projectile, atWorldLayer: .Character)
let rot = zRotation
let x = -sin(rot) * kHeroProjectileSpeed * CGFloat(kHeroProjectileLifetime)
let y = cos(rot) * kHeroProjectileSpeed * CGFloat(kHeroProjectileLifetime)
projectile.runAction(SKAction.moveByX(x, y: y, duration: kHeroProjectileLifetime))
let waitAction = SKAction.waitForDuration(kHeroProjectileFadeOutTime)
let fadeAction = SKAction.fadeOutWithDuration(kHeroProjectileLifetime - kHeroProjectileFadeOutTime)
let removeAction = SKAction.removeFromParent()
let sequence = [waitAction, fadeAction, removeAction]
projectile.runAction(SKAction.sequence(sequence))
projectile.runAction(projectileSoundAction())
let data: NSMutableDictionary = ["kPlayer" : self.player]
projectile.userData = data
}
func projectile() -> SKSpriteNode? {
return nil
}
func projectileEmitter() -> SKEmitterNode? {
return nil
}
func projectileSoundAction() -> SKAction {
return sSharedProjectileSoundAction
}
class func loadSharedHeroAssets() {
sSharedProjectileSoundAction = SKAction.playSoundFileNamed("magicmissile.caf", waitForCompletion: false)
}
}
var sSharedProjectileSoundAction = SKAction()
let kPlayer = "kPlayer"
|
d558ff9b2efe8f4927d1ecd095c838d1
| 31.711864 | 156 | 0.649741 | false | false | false | false |
prebid/prebid-mobile-ios
|
refs/heads/master
|
InternalTestApp/PrebidMobileDemoRendering/Model/TestCasesManager.swift
|
apache-2.0
|
1
|
/* 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
import UIKit
import GoogleMobileAds
import PrebidMobileGAMEventHandlers
import PrebidMobile
let nativeStylesCreative = """
<html><body>
<style type='text/css'>.sponsored-post {
background-color: #fffdeb;
font-family: sans-serif;
}
.content {
overflow: hidden;
}
.thumbnail {
width: 50px;
height: 50px;
float: left;
margin: 0 20px 10px 0;
background-size: cover;
}
h1 {
font-size: 18px;
margin: 0;
}
a {
color: #0086b3;
text-decoration: none;
}
p {
font-size: 16px;
color: #000;
margin: 10px 0 10px 0;
}
.attribution {
color: #000;
font-size: 9px;
font-weight: bold;
display: inline-block;
letter-spacing: 2px;
background-color: #ffd724;
border-radius: 2px;
padding: 4px;
}</style>
<div class="sponsored-post">
<div class="thumbnail">
<img src="hb_native_icon" alt="hb_native_icon" width="50" height="50"></div>
<div class="content">
<h1><p>hb_native_title</p></h1>
<p>hb_native_body</p>
<a target="_blank" href="hb_native_linkurl" class="pb-click">hb_native_cta</a>
<div class="attribution">hb_native_brand</div>
</div>
<img src="hb_native_image" alt="hb_native_image" width="320" height="50">
</div>
<script src="https://cdn.jsdelivr.net/npm/prebid-universal-creative@latest/dist/native-trk.js"></script>
<script>
let pbNativeTagData = {};
pbNativeTagData.pubUrl = "%%PATTERN:url%%";
pbNativeTagData.targetingMap = %%PATTERN:TARGETINGMAP%%;
// if not DFP, use these params
pbNativeTagData.adId = "%%PATTERN:hb_adid%%";
pbNativeTagData.cacheHost = "%%PATTERN:hb_cache_host%%";
pbNativeTagData.cachePath = "%%PATTERN:hb_cache_path%%";
pbNativeTagData.uuid = "%%PATTERN:hb_cache_id%%";
pbNativeTagData.env = "%%PATTERN:hb_env%%";
pbNativeTagData.hbPb = "%%PATTERN:hb_pb%%";
window.pbNativeTag.startTrackers(pbNativeTagData);
</script>
</body>
</html>
""";
//NOTE: there is no pbNativeTagData.targetingMap = %%PATTERN:TARGETINGMAP%%; in this creative
let nativeStylesCreativeKeys = """
<html><body>
<style type='text/css'>.sponsored-post {
background-color: #fffdeb;
font-family: sans-serif;
}
.content {
overflow: hidden;
}
.thumbnail {
width: 50px;
height: 50px;
float: left;
margin: 0 20px 10px 0;
background-size: cover;
}
h1 {
font-size: 18px;
margin: 0;
}
a {
color: #0086b3;
text-decoration: none;
}
p {
font-size: 16px;
color: #000;
margin: 10px 0 10px 0;
}
.attribution {
color: #000;
font-size: 9px;
font-weight: bold;
display: inline-block;
letter-spacing: 2px;
background-color: #ffd724;
border-radius: 2px;
padding: 4px;
}</style>
<div class="sponsored-post">
<div class="thumbnail">
<img src="hb_native_icon" alt="hb_native_icon" width="50" height="50"></div>
<div class="content">
<h1><p>hb_native_title</p></h1>
<p>hb_native_body</p>
<a target="_blank" href="hb_native_linkurl" class="pb-click">hb_native_cta</a>
<div class="attribution">hb_native_brand</div>
</div>
<img src="hb_native_image" alt="hb_native_image" width="320" height="50">
</div>
<script src="https://cdn.jsdelivr.net/npm/prebid-universal-creative@latest/dist/native-trk.js"></script>
<script>
let pbNativeTagData = {};
pbNativeTagData.pubUrl = "%%PATTERN:url%%";
// if not DFP, use these params
pbNativeTagData.adId = "%%PATTERN:hb_adid%%";
pbNativeTagData.cacheHost = "%%PATTERN:hb_cache_host%%";
pbNativeTagData.cachePath = "%%PATTERN:hb_cache_path%%";
pbNativeTagData.uuid = "%%PATTERN:hb_cache_id%%";
pbNativeTagData.env = "%%PATTERN:hb_env%%";
pbNativeTagData.hbPb = "%%PATTERN:hb_pb%%";
window.pbNativeTag.startTrackers(pbNativeTagData);
</script>
</body>
</html>
""";
struct TestCaseManager {
// {"configId": ["7e2c753a-2aad-49fb-b3b3-9b18018feb67": params1, "0e04335b-c39a-41f8-8f91-24ff13767dcc": params2]}
private static var customORTBParams: [String: [String: [String: Any]]] = [:]
// MARK: - Public Methods
let testCases = TestCaseManager.prebidExamples
mutating func parseCustomOpenRTB(openRTBString: String) {
guard let data = openRTBString.data(using: .utf8) else { return }
guard let jsonArray = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [Any] else { return }
for param in jsonArray {
guard let dictParam = param as? [String:Any],
let openRtb = dictParam["openRtb"] as? [String: Any] else { continue }
if let configId = dictParam["configId"] as? String {
TestCaseManager.customORTBParams["configId", default: [:]][configId] = openRtb
}
}
}
/*
EXTRA_OPEN_RTB "[ { "auid":"537454411","openRtb":{ "auid":"537454411", "age":23, "url":"https://url.com", "crr":"carrier", "ip":"127.0.0.1", "xid":"007", "gen":"MALE", "buyerid":"buyerid", "publisherName": "publisherName", "customdata":"customdata", "keywords":"keyword1,keyword2", "geo":{ "lat":1.0, "lon":2.0 }, "ext":{ "key1":"string", "key2":1, "object":{ "inner":"value" } } } } ]"
*/
static func updateUserData(_ openRtb: [String: Any]) {
let targeting = Targeting.shared
if let age = openRtb["age"] as? Int {
targeting.yearOfBirth = age
}
if let value = openRtb["url"] as? String {
targeting.storeURL = value
}
if let value = openRtb["gen"] as? String {
targeting.userGender = TestCaseManager.strToGender(value)
}
if let value = openRtb["buyerid"] as? String {
targeting.buyerUID = value
}
if let value = openRtb["xid"] as? String {
targeting.userID = value
}
if let value = openRtb["publisherName"] as? String {
targeting.publisherName = value
}
if let value = openRtb["keywords"] as? String {
targeting.keywords = value
}
if let value = openRtb["customdata"] as? String {
targeting.userCustomData = value
}
if let geo = openRtb["geo"] as? [String: Double] {
if let lat = geo["lat"], let lon = geo["lon"] {
targeting.setLatitude(lat, longitude: lon)
}
}
if let dictExt = openRtb["ext"] as? [String : AnyHashable] {
targeting.userExt = dictExt
}
}
// MARK: - Private Methods
// MARK: - --== PREBID ==--
private static let prebidExamples: [TestCase] = {
return [
// MARK: ---- Banner (In-App) ----
TestCase(title: "Banner 320x50 (In-App)",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.adSizes = [CGSize(width: 320, height: 50)]
bannerController.prebidConfigId = "imp-prebid-banner-320-50";
bannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner Events 320x50 (In-App)",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.adSizes = [CGSize(width: 320, height: 50)]
bannerController.prebidConfigId = "imp-prebid-banner-320-50";
bannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [noBids]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.adSizes = [CGSize(width: 320, height: 50)]
bannerController.prebidConfigId = "imp-prebid-no-bids"
bannerController.storedAuctionResponse = "response-prebid-no-bids"
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [Items]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-items"
bannerController.storedAuctionResponse = "response-prebid-banner-items"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [New Tab]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-newtab"
bannerController.storedAuctionResponse = "response-prebid-banner-newtab"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [Incorrect VAST]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-incorrect-vast"
bannerController.storedAuctionResponse = "response-prebid-banner-incorrect-vast"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [DeepLink+]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-deeplink"
bannerController.storedAuctionResponse = "response-prebid-banner-deeplink"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [Scrollable]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "ScrollableAdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-320-50"
bannerController.storedAuctionResponse = "response-prebid-banner-320-50"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 300x250 (In-App)",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-300-250"
bannerController.storedAuctionResponse = "response-prebid-banner-300-250"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 728x90 (In-App)",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-728-90"
bannerController.storedAuctionResponse = "response-prebid-banner-728-90"
bannerController.adSizes = [CGSize(width: 728, height: 90)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner Multisize (In-App)",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-multisize"
bannerController.storedAuctionResponse = "response-prebid-banner-multisize"
bannerController.adSizes = [CGSize(width: 320, height: 50), CGSize(width: 728, height: 90)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) ATS",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Targeting.shared.eids = [
[
"source" : "liveramp.com",
"uids" : [
[
"id": "XY1000bIVBVah9ium-sZ3ykhPiXQbEcUpn4GjCtxrrw2BRDGM"
]
]
]
]
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-320-50"
bannerController.storedAuctionResponse = "response-prebid-banner-320-50"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [SKAdN]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-320-50-skadn"
bannerController.storedAuctionResponse = "response-prebid-banner-320-50-skadn"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (In-App) [SKAdN 2.2]",
tags: [.banner, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-banner-320-50-skadn-v22"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
bannerController.storedAuctionResponse = "response-prebid-banner-320-50-skadn-v22"
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
// MARK: ---- Banner (GAM) ----
TestCase(title: "Banner 320x50 (GAM) [OK, AppEvent]",
tags: [.banner, .gam, .server, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner"
gamBannerController.validAdSizes = [GADAdSizeBanner]
gamBannerController.prebidConfigId = "imp-prebid-banner-320-50"
gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 Events (GAM) [OK, AppEvent]",
tags: [.banner, .gam, .server, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner"
gamBannerController.validAdSizes = [GADAdSizeBanner]
gamBannerController.prebidConfigId = "imp-prebid-banner-320-50"
gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (GAM) [OK, GAM Ad]",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-banner-320-50"
gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner_static"
gamBannerController.validAdSizes = [GADAdSizeBanner]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (GAM) [noBids, GAM Ad]",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-no-bids"
gamBannerController.storedAuctionResponse = "response-prebid-no-bids"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner_static"
gamBannerController.validAdSizes = [GADAdSizeBanner]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (GAM) [OK, Random]",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-banner-320-50"
gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner_random"
gamBannerController.validAdSizes = [GADAdSizeBanner]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (GAM) [Random, Respective]",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-banner-320-50"
gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner"
gamBannerController.validAdSizes = [GADAdSizeBanner]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 300x250 (GAM)",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-banner-300-250"
gamBannerController.storedAuctionResponse = "response-prebid-banner-300-250"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_300x250_banner"
gamBannerController.validAdSizes = [GADAdSizeMediumRectangle]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 728x90 (GAM)",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-banner-728-90"
gamBannerController.storedAuctionResponse = "response-prebid-banner-728-90"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_728x90_banner"
gamBannerController.validAdSizes = [GADAdSizeLeaderboard]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner Multisize (GAM)",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-banner-multisize"
gamBannerController.storedAuctionResponse = "response-prebid-banner-multisize"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_multisize_banner"
gamBannerController.validAdSizes = [GADAdSizeBanner, GADAdSizeLeaderboard]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (GAM) [Vanilla Prebid Order]",
tags: [.banner, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-banner-320-50"
gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
gamBannerController.gamAdUnitId = "/21808260008/prebid_android_300x250_banner"
gamBannerController.validAdSizes = [GADAdSizeMediumRectangle]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
// MARK: ---- Interstitial (In-App) ----
TestCase(title: "Display Interstitial 320x480 (In-App)",
tags: [.interstitial, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.adFormats = [.display]
interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
interstitialController.storedAuctionResponse="response-prebid-display-interstitial-320-480"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (In-App) [noBids]",
tags: [.interstitial, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.adFormats = [.display]
interstitialController.prebidConfigId = "imp-prebid-no-bids"
interstitialController.storedAuctionResponse="response-prebid-no-bids"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (In-App) [Presentation]",
tags: [.interstitial, .inapp, .server],
exampleVCStoryboardID: "PrebidPresentationViewController",
configurationClosure: { vc in
guard let presentationVC = vc as? PrebidPresentationViewController else {
return
}
presentationVC.adFormats = [.display]
presentationVC.prebidConfigId = "imp-prebid-display-interstitial-320-480"
presentationVC.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
setupCustomParams(for: presentationVC.prebidConfigId)
}),
TestCase(title: "Display Interstitial Multisize (In-App)",
tags: [.interstitial, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.adFormats = [.display]
interstitialController.prebidConfigId = "imp-prebid-display-interstitial-multisize"
interstitialController.storedAuctionResponse = "response-prebid-display-interstitial-multisize"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (In-App) [SKAdN]",
tags: [.interstitial, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.adFormats = [.display]
interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480-skadn"
interstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480-skadn"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (In-App) [SKAdN 2.2]",
tags: [.interstitial, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.adFormats = [.display]
interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480-skadn"
interstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480-skadn-v22"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
// MARK: ---- Multiformat Interstitial (In-App)
TestCase(title: "MultiBid Video Interstitial 320x480 (In-App)",
tags: [.interstitial, .video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-interstitial-multiformat"
interstitialController.storedAuctionResponse = "response-prebid-interstitial-multiformat"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Multiformat Interstitial 320x480 (In-App)",
tags: [.interstitial, .video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"]
interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
interstitialController.storedAuctionResponse = prebidStoredAuctionResponses.randomElement() ?? prebidStoredAuctionResponses[0]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
// MARK: ---- Interstitial (GAM) ----
TestCase(title: "Display Interstitial 320x480 (GAM) [OK, AppEvent]",
tags: [.interstitial, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.adFormats = [.display]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial"
gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (GAM) [OK, Random]",
tags: [.interstitial, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.adFormats = [.display]
gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial_random"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (GAM) [noBids, GAM Ad]",
tags: [.interstitial, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.adFormats = [.display]
gamInterstitialController.prebidConfigId = "imp-prebid-no-bids"
gamInterstitialController.storedAuctionResponse = "response-prebid-no-bids"
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_320x480_html_interstitial_static"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial Multisize (GAM) [OK, AppEvent]",
tags: [.interstitial, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.adFormats = [.display]
gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-multisize"
gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-multisize"
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (GAM) [Vanilla Prebid Order]",
tags: [.interstitial, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.adFormats = [.display]
gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_html_interstitial"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
// MARK: ---- Multiformat Interstitial (GAM)
TestCase(title: "Multiformat Interstitial 320x480 (GAM)",
tags: [.interstitial, .video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let randomId = [0, 1].randomElement() ?? 0
let interstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
let gamAdUnitIds = ["/21808260008/prebid_html_interstitial", "/21808260008/prebid_oxb_interstitial_video"]
let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"]
interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
interstitialController.storedAuctionResponse = prebidStoredAuctionResponses[randomId]
interstitialController.gamAdUnitId = gamAdUnitIds[randomId]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
// MARK: ---- Video Interstitial (In-App) ----
TestCase(title: "Video Interstitial 320x480 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration API 320x480 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration"
interstitialController.adFormats = [.video]
// Custom video configuration
interstitialController.maxDuration = 30
interstitialController.closeButtonArea = 0.15
interstitialController.closeButtonPosition = .topLeft
interstitialController.skipDelay = 5
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card API 320x480 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card"
interstitialController.adFormats = [.video]
// Custom video configuration
interstitialController.maxDuration = 30
interstitialController.closeButtonArea = 0.15
interstitialController.closeButtonPosition = .topLeft
interstitialController.skipButtonArea = 0.15
interstitialController.skipButtonPosition = .topRight
interstitialController.skipDelay = 5
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration Server 320x480 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card Server 320x480 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (In-App) [noBids]",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-no-bids"
interstitialController.storedAuctionResponse = "response-prebid-no-bids"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 with End Card (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial Vertical (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-vertical"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-vertical"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial Vertical With End Card (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-vertical"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-vertical-with-end-card"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial Landscape With End Card (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-vertical"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-landscape-with-end-card"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 DeepLink+ (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-deeplink"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-deeplink"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 SkipOffset (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-skip-offset"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-skip-offset"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 .mp4 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-mp4"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-mp4"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 .m4v (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-m4v"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-m4v"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 .mov (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-mov"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-mov"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 with MRAID End Card (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-mraid-end-card"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-mraid-end-card"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (In-App) [SKAdN]",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-skadn"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-skadn"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (In-App) [SKAdN 2.2]",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-skadn"
interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-skadn-v22"
interstitialController.adFormats = [.video]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
// MARK: ---- Video Interstitial (GAM) ----
TestCase(title: "Video Interstitial 320x480 (GAM) [OK, AppEvent]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (GAM) [OK, Random]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_320x480_interstitial_video_random"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (GAM) [noBids, GAM Ad]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-no-bids"
gamInterstitialController.storedAuctionResponse = "response-prebid-no-bids"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_320x480_interstitial_video_static"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 With Ad Configuration API (GAM) [OK, AppEvent]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video"
// Custom video configuration
gamInterstitialController.maxDuration = 30
gamInterstitialController.closeButtonArea = 0.15
gamInterstitialController.closeButtonPosition = .topLeft
gamInterstitialController.skipDelay = 5
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card API 320x480 (GAM) [OK, AppEvent]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video"
// Custom video configuration
gamInterstitialController.maxDuration = 30
gamInterstitialController.closeButtonArea = 0.15
gamInterstitialController.closeButtonPosition = .topLeft
gamInterstitialController.skipButtonArea = 0.15
gamInterstitialController.skipButtonPosition = .topRight
gamInterstitialController.skipDelay = 5
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration Server 320x480 (GAM) [OK, AppEvent]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card Server 320x480 (GAM) [OK, AppEvent]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (GAM) [Vanilla Prebid Order]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
gamInterstitialController.adFormats = [.video]
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_interstitial_video"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
// MARK: ---- Video (In-App) ----
TestCase(title: "Video Outstream (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-video-outstream"
bannerController.storedAuctionResponse = "response-prebid-video-outstream"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
bannerController.adFormat = .video
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream (In-App) [noBids]",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-no-bids"
bannerController.storedAuctionResponse = "response-prebid-no-bids"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
bannerController.adFormat = .video
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream with End Card (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.adSizes = [CGSize(width: 300, height: 250)]
bannerController.adFormat = .video
bannerController.prebidConfigId = "imp-prebid-video-outstream-with-end-card"
bannerController.storedAuctionResponse = "response-prebid-video-outstream-with-end-card"
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream Feed (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "PrebidFeedTableViewController",
configurationClosure: { vc in
guard let feedVC = vc as? PrebidFeedTableViewController,
let tableView = feedVC.tableView else {
return
}
feedVC.testCases = [
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseForTableCell(configurationClosureForTableCell: { [weak feedVC, weak tableView] cell in
guard let videoViewCell = tableView?.dequeueReusableCell(withIdentifier: "FeedAdTableViewCell") as? FeedAdTableViewCell else {
return
}
cell = videoViewCell
guard videoViewCell.adView == nil else {
return
}
var prebidConfigId = "imp-prebid-video-outstream"
var storedAuctionResponse = "response-prebid-video-outstream"
let adSize = CGSize(width: 300, height: 250)
let adBannerView = BannerView(frame: CGRect(origin: .zero, size: adSize),configID: prebidConfigId,adSize: adSize)
adBannerView.adFormat = .video
adBannerView.videoParameters.placement = .InFeed
adBannerView.delegate = feedVC
adBannerView.accessibilityIdentifier = "PrebidBannerView"
if let adUnitContext = AppConfiguration.shared.adUnitContext {
for dataPair in adUnitContext {
adBannerView.addContextData(dataPair.value, forKey: dataPair.key)
}
}
setupCustomParams(for: prebidConfigId)
adBannerView.setStoredAuctionResponse(storedAuction: storedAuctionResponse)
adBannerView.loadAd()
videoViewCell.bannerView.addSubview(adBannerView)
videoViewCell.adView = adBannerView
}),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
];
}),
TestCase(title: "Video Outstream (In-App) [SKAdN]",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-video-outstream-skadn"
bannerController.storedAuctionResponse = "response-prebid-video-outstream-skadn"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
bannerController.adFormat = .video
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream (In-App) [SKAdN 2.2]",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-video-outstream-skadn"
bannerController.storedAuctionResponse = "response-prebid-video-outstream-skadn-v22"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
bannerController.adFormat = .video
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
// MARK: ---- Video (GAM) ----
TestCase(title: "Video Outstream (GAM) [OK, AppEvent]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_300x250_banner"
gamBannerController.validAdSizes = [GADAdSizeMediumRectangle]
gamBannerController.adFormat = .video
gamBannerController.prebidConfigId = "imp-prebid-video-outstream"
gamBannerController.storedAuctionResponse = "response-prebid-video-outstream"
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream with End Card (GAM) [OK, AppEvent]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_300x250_banner"
gamBannerController.validAdSizes = [GADAdSizeMediumRectangle]
gamBannerController.adFormat = .video
gamBannerController.prebidConfigId = "imp-prebid-video-outstream-with-end-card"
gamBannerController.storedAuctionResponse = "response-prebid-video-outstream-with-end-card"
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream (GAM) [OK, Random]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-video-outstream"
gamBannerController.storedAuctionResponse = "response-prebid-video-outstream-with-end-card"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_outstream_video_reandom"
gamBannerController.validAdSizes = [GADAdSizeMediumRectangle]
gamBannerController.adFormat = .video
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream (GAM) [noBids, GAM Ad]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-no-bids"
gamBannerController.storedAuctionResponse = "response-prebid-no-bids"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_outsream_video"
gamBannerController.validAdSizes = [GADAdSizeMediumRectangle]
gamBannerController.adFormat = .video
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "Video Outstream Feed (GAM)",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "PrebidFeedTableViewController",
configurationClosure: { vc in
guard let feedVC = vc as? PrebidFeedTableViewController,
let tableView = feedVC.tableView else {
return
}
feedVC.testCases = [
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseForTableCell(configurationClosureForTableCell: { [weak feedVC, weak tableView] cell in
guard let videoViewCell = tableView?.dequeueReusableCell(withIdentifier: "FeedAdTableViewCell") as? FeedAdTableViewCell else {
return
}
cell = videoViewCell
guard videoViewCell.adView == nil else {
return
}
var prebidConfigId = "imp-prebid-video-outstream"
var storedAuctionResponse = "response-prebid-video-outstream"
let gamAdUnitId = "/21808260008/prebid_oxb_outstream_video_reandom"
let validAdSize = GADAdSizeMediumRectangle
let adSize = validAdSize.size
let adEventHandler = GAMBannerEventHandler(adUnitID: gamAdUnitId, validGADAdSizes: [NSValueFromGADAdSize(validAdSize)])
let adBannerView = BannerView(configID: prebidConfigId,eventHandler: adEventHandler)
adBannerView.adFormat = .video
adBannerView.videoParameters.placement = .InFeed
adBannerView.delegate = feedVC
adBannerView.accessibilityIdentifier = "PrebidBannerView"
if let adUnitContext = AppConfiguration.shared.adUnitContext {
for dataPair in adUnitContext {
adBannerView.addContextData(dataPair.value, forKey: dataPair.key)
}
}
setupCustomParams(for: prebidConfigId)
adBannerView.setStoredAuctionResponse(storedAuction: storedAuctionResponse)
adBannerView.loadAd()
videoViewCell.bannerView.addSubview(adBannerView)
videoViewCell.adView = adBannerView
}),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
TestCaseManager.createDummyTableCell(for: tableView),
];
}),
// MARK: ---- Video Rewarded (In-App) ----
TestCase(title: "Video Rewarded 320x480 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let rewardedAdController = PrebidRewardedController(rootController: adapterVC)
rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
adapterVC.setup(adapter: rewardedAdController)
setupCustomParams(for: rewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 (In-App) [noBids]",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let rewardedAdController = PrebidRewardedController(rootController: adapterVC)
rewardedAdController.prebidConfigId = "imp-prebid-no-bids"
rewardedAdController.storedAuctionResponse = "response-prebid-no-bids"
adapterVC.setup(adapter: rewardedAdController)
setupCustomParams(for: rewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 without End Card (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let rewardedAdController = PrebidRewardedController(rootController: adapterVC)
rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card"
rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card"
adapterVC.setup(adapter: rewardedAdController)
setupCustomParams(for: rewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 480x320 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let rewardedAdController = PrebidRewardedController(rootController: adapterVC)
rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
adapterVC.setup(adapter: rewardedAdController)
setupCustomParams(for: rewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded With Ad Configuration Server 320x480 (In-App)",
tags: [.video, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let rewardedAdController = PrebidRewardedController(rootController: adapterVC)
rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration"
adapterVC.setup(adapter: rewardedAdController)
setupCustomParams(for: rewardedAdController.prebidConfigId)
}),
// MARK: ---- Video Rewarded (GAM) ----
TestCase(title: "Video Rewarded 320x480 (GAM) [OK, Metadata]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC)
gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_test"
gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
adapterVC.setup(adapter: gamRewardedAdController)
setupCustomParams(for: gamRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 With Ad Configuration Server (GAM) [OK, Metadata]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC)
gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_test"
gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration"
adapterVC.setup(adapter: gamRewardedAdController)
setupCustomParams(for: gamRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 (GAM) [OK, Random]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC)
gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_random"
adapterVC.setup(adapter: gamRewardedAdController)
setupCustomParams(for: gamRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 (GAM) [noBids, GAM Ad]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC)
gamRewardedAdController.prebidConfigId = "imp-prebid-no-bids"
gamRewardedAdController.storedAuctionResponse = "response-prebid-no-bids"
gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_static"
adapterVC.setup(adapter: gamRewardedAdController)
setupCustomParams(for: gamRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 without End Card (GAM) [OK, Metadata]",
tags: [.video, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC)
gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card"
gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card"
gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_test"
adapterVC.setup(adapter: gamRewardedAdController)
setupCustomParams(for: gamRewardedAdController.prebidConfigId)
}),
// MARK: ---- MRAID (In-App) ----
TestCase(title: "MRAID 2.0: Expand - 1 Part (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-expand-1-part"
bannerController.storedAuctionResponse = "response-prebid-mraid-expand-1-part"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID 2.0: Expand - 2 Part (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-expand-2-part"
bannerController.storedAuctionResponse = "response-prebid-mraid-expand-2-part"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID 2.0: Resize (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.adSizes = [CGSize(width: 320, height: 50)]
bannerController.prebidConfigId = "imp-prebid-mraid-resize"
bannerController.storedAuctionResponse = "response-prebid-mraid-resize"
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID 2.0: Resize with Errors (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-resize-with-errors"
bannerController.storedAuctionResponse = "response-prebid-mraid-resize-with-errors"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID 2.0: Fullscreen (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "ScrollableAdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-fullscreen"
bannerController.storedAuctionResponse = "response-prebid-mraid-fullscreen"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID 2.0: Video Interstitial (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let interstitialController = PrebidInterstitialController(rootController: adapterVC)
interstitialController.prebidConfigId = "imp-prebid-mraid-video-interstitial"
interstitialController.storedAuctionResponse = "response-prebid-mraid-video-interstitial"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
TestCase(title: "MRAID 3.0: Viewability Compliance (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "ScrollableAdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-viewability-compliance"
bannerController.storedAuctionResponse = "response-prebid-mraid-viewability-compliance"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID 3.0: Resize Negative Test (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-resize-negative-test"
bannerController.storedAuctionResponse = "response-prebid-mraid-resize-negative-test"
bannerController.adSizes = [CGSize(width: 300, height: 250)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID 3.0: Load And Events (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-load-and-events"
bannerController.storedAuctionResponse = "response-prebid-mraid-load-and-events"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID OX: Test Properties 3.0 (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-test-properties-3"
bannerController.storedAuctionResponse = "response-prebid-mraid-test-properties-3"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID OX: Test Methods 3.0 (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-test-methods-3"
bannerController.storedAuctionResponse = "response-prebid-mraid-test-methods-3"
bannerController.adSizes = [CGSize(width: 320, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID OX: Resize (Expandable) (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-resize-expandable"
bannerController.storedAuctionResponse = "response-prebid-mraid-resize-expandable"
bannerController.adSizes = [CGSize(width: 300, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
TestCase(title: "MRAID OX: Resize (With Scroll) (In-App)",
tags: [.mraid, .inapp, .server],
exampleVCStoryboardID: "ScrollableAdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let bannerController = PrebidBannerController(rootController: adapterVC)
bannerController.prebidConfigId = "imp-prebid-mraid-resize"
bannerController.storedAuctionResponse = "response-prebid-mraid-resize"
bannerController.adSizes = [CGSize(width: 300, height: 50)]
adapterVC.setup(adapter: bannerController)
setupCustomParams(for: bannerController.prebidConfigId)
}),
// MARK: ---- MRAID (GAM) ----
TestCase(title: "MRAID 2.0: Expand - 1 Part (GAM)",
tags: [.mraid, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-mraid-expand-1-part"
gamBannerController.storedAuctionResponse = "response-prebid-mraid-expand-1-part"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner"
gamBannerController.validAdSizes = [GADAdSizeBanner]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "MRAID 2.0: Resize (GAM)",
tags: [.mraid, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamBannerController = PrebidGAMBannerController(rootController: adapterVC)
gamBannerController.prebidConfigId = "imp-prebid-mraid-resize"
gamBannerController.storedAuctionResponse = "response-prebid-mraid-resize"
gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner"
gamBannerController.validAdSizes = [GADAdSizeBanner]
adapterVC.setup(adapter: gamBannerController)
setupCustomParams(for: gamBannerController.prebidConfigId)
}),
TestCase(title: "MRAID 2.0: Video Interstitial (GAM)",
tags: [.mraid, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC)
gamInterstitialController.prebidConfigId = "imp-prebid-mraid-video-interstitial"
gamInterstitialController.storedAuctionResponse = "response-prebid-mraid-video-interstitial"
gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial"
adapterVC.setup(adapter: gamInterstitialController)
setupCustomParams(for: gamInterstitialController.prebidConfigId)
}),
// MARK: ---- Banner (AdMob) ----
TestCase(title: "Banner 320x50 (AdMob) [OK, OXB Adapter]",
tags: [.banner, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC)
admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409"
admobBannerController.adUnitSize = CGSize(width: 320, height: 50);
admobBannerController.prebidConfigId = "imp-prebid-banner-320-50"
admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: admobBannerController)
setupCustomParams(for: admobBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 Events (AdMob) [OK, OXB Adapter]",
tags: [.banner, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC)
admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409"
admobBannerController.adUnitSize = CGSize(width: 320, height: 50);
admobBannerController.prebidConfigId = "imp-prebid-banner-320-50"
admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: admobBannerController)
setupCustomParams(for: admobBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (AdMob) [OK, Random]",
tags: [.banner, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC)
admobBannerController.prebidConfigId = "imp-prebid-banner-320-50"
admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409"
admobBannerController.adUnitSize = CGSize(width: 320, height: 50);
adapterVC.setup(adapter: admobBannerController)
setupCustomParams(for: admobBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (AdMob) [noBids, AdMob Ad]",
tags: [.banner, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC)
admobBannerController.prebidConfigId = "imp-prebid-no-bids"
admobBannerController.storedAuctionResponse = "response-prebid-no-bids"
admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409"
admobBannerController.adUnitSize = CGSize(width: 320, height: 50);
adapterVC.setup(adapter: admobBannerController)
setupCustomParams(for: admobBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (AdMob) [Random, Respective]",
tags: [.banner, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC)
admobBannerController.prebidConfigId = "imp-prebid-banner-320-50"
admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409"
admobBannerController.adUnitSize = CGSize(width: 320, height: 50);
adapterVC.setup(adapter: admobBannerController)
setupCustomParams(for: admobBannerController.prebidConfigId)
}),
TestCase(title: "Banner 300x250 (AdMob)",
tags: [.banner, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC)
admobBannerController.prebidConfigId = "imp-prebid-banner-300-250"
admobBannerController.storedAuctionResponse = "response-prebid-banner-300-250"
admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409"
admobBannerController.adUnitSize = CGSize(width: 300, height: 250);
adapterVC.setup(adapter: admobBannerController)
setupCustomParams(for: admobBannerController.prebidConfigId)
}),
TestCase(title: "Banner Adaptive (AdMob)",
tags: [.banner, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC)
admobBannerController.prebidConfigId = "imp-prebid-banner-multisize"
admobBannerController.storedAuctionResponse = "response-prebid-banner-multisize"
admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409"
admobBannerController.adUnitSize = CGSize(width: 320, height: 50);
admobBannerController.additionalAdSizes = [CGSize(width: 728, height: 90)]
admobBannerController.gadAdSizeType = .adaptiveAnchored
adapterVC.setup(adapter: admobBannerController)
setupCustomParams(for: admobBannerController.prebidConfigId)
}),
// MARK: ---- Interstitial (AdMob) ----
TestCase(title: "Display Interstitial 320x480 (AdMob) [OK, OXB Adapter]",
tags: [.interstitial, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/3383099861"
admobInterstitialController.adFormats = [.display]
admobInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
admobInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (AdMob) [noBids, AdMob Ad]",
tags: [.interstitial, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.adFormats = [.display]
admobInterstitialController.prebidConfigId = "imp-prebid-no-bids"
admobInterstitialController.storedAuctionResponse = "response-prebid-no-bids"
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/3383099861"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (AdMob) [OK, Random]",
tags: [.interstitial, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.adFormats = [.display]
admobInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
admobInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/3383099861"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
// MARK: ---- Video Interstitial (AdMob) ----
TestCase(title: "Video Interstitial 320x480 (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
admobInterstitialController.adFormats = [.video]
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration 320x480 API (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
admobInterstitialController.adFormats = [.video]
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002"
// Custom video configuration
admobInterstitialController.maxDuration = 30
admobInterstitialController.closeButtonArea = 0.15
admobInterstitialController.closeButtonPosition = .topLeft
admobInterstitialController.skipDelay = 5
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 API (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card"
admobInterstitialController.adFormats = [.video]
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002"
// Custom video configuration
admobInterstitialController.maxDuration = 30
admobInterstitialController.closeButtonArea = 0.15
admobInterstitialController.closeButtonPosition = .topLeft
admobInterstitialController.skipButtonArea = 0.15
admobInterstitialController.skipButtonPosition = .topRight
admobInterstitialController.skipDelay = 5
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration 320x480 Server (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration"
admobInterstitialController.adFormats = [.video]
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 Server (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration"
admobInterstitialController.adFormats = [.video]
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (AdMob) [OK, Random]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
admobInterstitialController.adFormats = [.video]
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (AdMob) [noBids, AdMob Ad]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
admobInterstitialController.prebidConfigId = "imp-prebid-no-bids"
admobInterstitialController.storedAuctionResponse = "response-prebid-no-bids"
admobInterstitialController.adFormats = [.video]
admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002"
adapterVC.setup(adapter: admobInterstitialController)
setupCustomParams(for: admobInterstitialController.prebidConfigId)
}),
// MARK: ---- Multiformat Interstitial (AdMob) ----
TestCase(title: "Multiformat Interstitial 320x480 (AdMob)",
tags: [.interstitial, .video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let randomId = [0, 1].randomElement() ?? 0
let interstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC)
let admobAdUnitIds = ["ca-app-pub-5922967660082475/3383099861", "ca-app-pub-5922967660082475/4527792002"]
let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"]
interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
interstitialController.storedAuctionResponse = prebidStoredAuctionResponses[randomId]
interstitialController.adMobAdUnitId = admobAdUnitIds[randomId]
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
// MARK: ---- Video Rewarded (AdMob) ----
TestCase(title: "Video Rewarded 320x480 (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC)
admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641"
admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
adapterVC.setup(adapter: admobRewardedAdController)
setupCustomParams(for: admobRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded With Ad Configuration 320x480 Server (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC)
admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641"
admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration"
adapterVC.setup(adapter: admobRewardedAdController)
setupCustomParams(for: admobRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 (AdMob) [noBids, AdMob Ad]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC)
admobRewardedAdController.prebidConfigId = "imp-prebid-no-bids"
admobRewardedAdController.storedAuctionResponse = "response-prebid-no-bids"
admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641"
adapterVC.setup(adapter: admobRewardedAdController)
setupCustomParams(for: admobRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 (AdMob) [OK, Random]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC)
admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641"
adapterVC.setup(adapter: admobRewardedAdController)
setupCustomParams(for: admobRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 without End Card (AdMob) [OK, OXB Adapter]",
tags: [.video, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC)
admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card"
admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card"
admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641"
adapterVC.setup(adapter: admobRewardedAdController)
setupCustomParams(for: admobRewardedAdController.prebidConfigId)
}),
// MARK: ---- Native (AdMob) ----
TestCase(title: "Native Ad (AdMob) [OK, OXB Adapter]",
tags: [.native, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let nativeController = PrebidAdMobNativeViewController(rootController: adapterVC)
nativeController.adMobAdUnitId = "ca-app-pub-5922967660082475/8634069303"
nativeController.prebidConfigId = "imp-prebid-banner-native-styles"
nativeController.storedAuctionResponse = "response-prebid-banner-native-styles"
nativeController.nativeAssets = .defaultNativeRequestAssets
nativeController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeController)
setupCustomParams(for: nativeController.prebidConfigId)
}),
TestCase(title: "Native Ad Events (AdMob) [OK, OXB Adapter]",
tags: [.native, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let nativeController = PrebidAdMobNativeViewController(rootController: adapterVC)
nativeController.adMobAdUnitId = "ca-app-pub-5922967660082475/8634069303"
nativeController.prebidConfigId = "imp-prebid-banner-native-styles"
nativeController.storedAuctionResponse = "response-prebid-banner-native-styles"
nativeController.nativeAssets = .defaultNativeRequestAssets
nativeController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeController)
setupCustomParams(for: nativeController.prebidConfigId)
}),
TestCase(title: "Native Ad (AdMob) [noBids, GADNativeAd]",
tags: [.native, .admob, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let nativeController = PrebidAdMobNativeViewController(rootController: adapterVC)
nativeController.adMobAdUnitId = "ca-app-pub-5922967660082475/8634069303"
nativeController.prebidConfigId = "imp-prebid-no-bids"
nativeController.storedAuctionResponse = "imp-prebid-no-bids"
nativeController.nativeAssets = .defaultNativeRequestAssets
nativeController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeController)
setupCustomParams(for: nativeController.prebidConfigId)
}),
// MARK: ---- Native (In-App) ----
TestCase(title: "Native Ad (In-App)",
tags: [.native, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let nativeAdController = PrebidNativeAdController(rootController: adapterVC)
nativeAdController.setupNativeAdView(NativeAdViewBox())
nativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
nativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
nativeAdController.nativeAssets = .defaultNativeRequestAssets
nativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeAdController)
setupCustomParams(for: nativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad Events (In-App)",
tags: [.native, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let nativeAdController = PrebidNativeAdController(rootController: adapterVC)
nativeAdController.setupNativeAdView(NativeAdViewBox())
nativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
nativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
nativeAdController.nativeAssets = .defaultNativeRequestAssets
nativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeAdController)
setupCustomParams(for: nativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad Links (In-App)",
tags: [.native, .inapp, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let nativeAdController = PrebidNativeAdController(rootController: adapterVC)
nativeAdController.setupNativeAdView(NativeAdViewBoxLinks())
nativeAdController.prebidConfigId = "imp-prebid-native-links"
nativeAdController.storedAuctionResponse = "response-prebid-native-links"
Prebid.shared.shouldAssignNativeAssetID = true
let sponsored = NativeAssetData(type: .sponsored, required: true)
let rating = NativeAssetData(type: .rating, required: true)
let desc = NativeAssetData(type: .description, required: true)
let cta = NativeAssetData(type: .ctatext, required: true)
nativeAdController.nativeAssets = [sponsored, desc, rating, cta]
nativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeAdController)
setupCustomParams(for: nativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad Feed (In-App)",
tags: [.native, .inapp, .server],
exampleVCStoryboardID: "PrebidFeedTableViewController",
configurationClosure: { vc in
guard let feedVC = vc as? PrebidFeedTableViewController else {
return
}
let nativeAdFeedController = PrebidNativeAdFeedController(rootTableViewController: feedVC)
nativeAdFeedController.prebidConfigId = "imp-prebid-banner-native-styles"
nativeAdFeedController.storedAuctionResponse = "response-prebid-banner-native-styles"
nativeAdFeedController.nativeAssets = .defaultNativeRequestAssets
nativeAdFeedController.eventTrackers = .defaultNativeEventTrackers
feedVC.adapter = nativeAdFeedController
feedVC.loadAdClosure = nativeAdFeedController.allowLoadingAd
nativeAdFeedController.createCells()
setupCustomParams(for: nativeAdFeedController.prebidConfigId)
}),
// MARK: ---- Native (GAM, CustomTemplate) ----
TestCase(title: "Native Ad Custom Templates (GAM) [OK, NativeAd]",
tags: [.native, .gam,.server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC)
gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit"
gamNativeAdController.adTypes = [.customNative]
gamNativeAdController.gamCustomTemplateIDs = ["11934135"]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: gamNativeAdController)
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad Custom Templates Events (GAM) [OK, NativeAd]",
tags: [.native, .gam,.server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC)
gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit"
gamNativeAdController.adTypes = [.customNative]
gamNativeAdController.gamCustomTemplateIDs = ["11934135"]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: gamNativeAdController)
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad (GAM) [OK, GADNativeCustomTemplateAd]",
tags: [.native, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC)
gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit"
gamNativeAdController.adTypes = [.customNative]
gamNativeAdController.gamCustomTemplateIDs = ["11982639"]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: gamNativeAdController)
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad (GAM) [noBids, GADNativeCustomTemplateAd]",
tags: [.native, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC)
gamNativeAdController.prebidConfigId = "imp-prebid-native-video-with-end-card--dummy"
gamNativeAdController.storedAuctionResponse = "response-prebid-video-with-end-card"
gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit"
gamNativeAdController.adTypes = [.customNative]
gamNativeAdController.gamCustomTemplateIDs = ["11982639"]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: gamNativeAdController)
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad Feed (GAM) [OK, NativeAd]",
tags: [.native, .gam, .server],
exampleVCStoryboardID: "PrebidFeedTableViewController",
configurationClosure: { vc in
guard let feedVC = vc as? PrebidFeedTableViewController else {
return
}
let gamNativeAdController = PrebidGAMNativeAdFeedController(rootTableViewController: feedVC)
gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit"
gamNativeAdController.adTypes = [.customNative]
gamNativeAdController.gamCustomTemplateIDs = ["11934135"]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
feedVC.adapter = gamNativeAdController
feedVC.loadAdClosure = gamNativeAdController.allowLoadingAd
gamNativeAdController.createCells()
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
// MARK: ---- Native (GAM, Unified) ----
TestCase(title: "Native Ad Unified Ad (GAM) [OK, NativeAd]",
tags: [.native, .gam,.server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC)
gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
gamNativeAdController.gamAdUnitId = "/21808260008/unified_native_ad_unit"
gamNativeAdController.adTypes = [.native]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: gamNativeAdController)
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad (GAM) [OK, GADUnifiedNativeAd]",
tags: [.native, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC)
gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles"
gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles"
gamNativeAdController.gamAdUnitId = "/21808260008/unified_native_ad_unit_static"
gamNativeAdController.adTypes = [.native]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: gamNativeAdController)
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
TestCase(title: "Native Ad (GAM) [noBids, GADUnifiedNativeAd]",
tags: [.native, .gam, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC)
gamNativeAdController.prebidConfigId = "imp-prebid-native-video-with-end-card--dummy"
gamNativeAdController.storedAuctionResponse = "response-prebid-video-with-end-card"
gamNativeAdController.gamAdUnitId = "/21808260008/unified_native_ad_unit_static"
gamNativeAdController.adTypes = [.native]
gamNativeAdController.nativeAssets = .defaultNativeRequestAssets
gamNativeAdController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: gamNativeAdController)
setupCustomParams(for: gamNativeAdController.prebidConfigId)
}),
// MARK: ---- Banner (MAX) ----
TestCase(title: "Banner 320x50 (MAX) [OK, OXB Adapter]",
tags: [.banner, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxBannerController = PrebidMAXBannerController(rootController: adapterVC)
maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca"
maxBannerController.adUnitSize = CGSize(width: 320, height: 50);
maxBannerController.prebidConfigId = "imp-prebid-banner-320-50"
maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: maxBannerController)
setupCustomParams(for: maxBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 Events (MAX) [OK, OXB Adapter]",
tags: [.banner, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let maxBannerController = PrebidMAXBannerController(rootController: adapterVC)
maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca"
maxBannerController.adUnitSize = CGSize(width: 320, height: 50);
maxBannerController.prebidConfigId = "imp-prebid-banner-320-50"
maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
adapterVC.setup(adapter: maxBannerController)
setupCustomParams(for: maxBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (MAX) [noBids, MAX Ad]",
tags: [.banner, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxBannerController = PrebidMAXBannerController(rootController: adapterVC)
maxBannerController.prebidConfigId = "imp-prebid-no-bids"
maxBannerController.storedAuctionResponse = "response-prebid-no-bids"
maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca"
maxBannerController.adUnitSize = CGSize(width: 320, height: 50);
adapterVC.setup(adapter: maxBannerController)
setupCustomParams(for: maxBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (MAX) [OK, Random]",
tags: [.banner, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxBannerController = PrebidMAXBannerController(rootController: adapterVC)
maxBannerController.prebidConfigId = "imp-prebid-banner-320-50"
maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca"
maxBannerController.adUnitSize = CGSize(width: 320, height: 50);
adapterVC.setup(adapter: maxBannerController)
setupCustomParams(for: maxBannerController.prebidConfigId)
}),
TestCase(title: "Banner 320x50 (MAX) [Random, Respective]",
tags: [.banner, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxBannerController = PrebidMAXBannerController(rootController: adapterVC)
maxBannerController.prebidConfigId = "imp-prebid-banner-320-50"
maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50"
maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca"
maxBannerController.adUnitSize = CGSize(width: 320, height: 50);
adapterVC.setup(adapter: maxBannerController)
setupCustomParams(for: maxBannerController.prebidConfigId)
}),
TestCase(title: "Banner 300x250 (MAX)",
tags: [.banner, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxBannerController = PrebidMAXBannerController(rootController: adapterVC)
maxBannerController.prebidConfigId = "imp-prebid-banner-300-250"
maxBannerController.storedAuctionResponse = "response-prebid-banner-300-250"
maxBannerController.maxAdUnitId = "7715f9965a065152"
maxBannerController.adUnitSize = CGSize(width: 300, height: 250);
adapterVC.setup(adapter: maxBannerController)
setupCustomParams(for: maxBannerController.prebidConfigId)
}),
TestCase(title: "Banner Adaptive (MAX)",
tags: [.banner, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxBannerController = PrebidMAXBannerController(rootController: adapterVC)
maxBannerController.prebidConfigId = "imp-prebid-banner-multisize"
maxBannerController.storedAuctionResponse = "response-prebid-banner-multisize"
maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca"
maxBannerController.adUnitSize = CGSize(width: 320, height: 50);
maxBannerController.additionalAdSizes = [CGSize(width: 728, height: 90)]
maxBannerController.isAdaptive = true
adapterVC.setup(adapter: maxBannerController)
setupCustomParams(for: maxBannerController.prebidConfigId)
}),
// MARK: ---- Interstitial (MAX) ----
TestCase(title: "Display Interstitial 320x480 (MAX) [OK, OXB Adapter]",
tags: [.interstitial, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.adFormats = [.display]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
maxInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
maxInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (MAX) [noBids, MAX Ad]",
tags: [.interstitial, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.adFormats = [.display]
maxInterstitialController.prebidConfigId = "imp-prebid-no-bids"
maxInterstitialController.storedAuctionResponse = "response-prebid-no-bids"
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Display Interstitial 320x480 (MAX) [OK, Random]",
tags: [.interstitial, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.adFormats = [.display]
maxInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480"
maxInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480"
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
// MARK: ---- Video Interstitial (MAX) ----
TestCase(title: "Video Interstitial 320x480 (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
maxInterstitialController.adFormats = [.video]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration 320x480 API (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
maxInterstitialController.adFormats = [.video]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
// Custom video configuration
maxInterstitialController.maxDuration = 30
maxInterstitialController.closeButtonArea = 0.15
maxInterstitialController.closeButtonPosition = .topLeft
maxInterstitialController.skipDelay = 5
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 API (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card"
maxInterstitialController.adFormats = [.video]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
// Custom video configuration
maxInterstitialController.maxDuration = 30
maxInterstitialController.closeButtonArea = 0.15
maxInterstitialController.closeButtonPosition = .topLeft
maxInterstitialController.skipButtonArea = 0.15
maxInterstitialController.skipButtonPosition = .topRight
maxInterstitialController.skipDelay = 5
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration 320x480 Server (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration"
maxInterstitialController.adFormats = [.video]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 Server (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card"
maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration"
maxInterstitialController.adFormats = [.video]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (MAX) [OK, Random]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480"
maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480"
maxInterstitialController.adFormats = [.video]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
TestCase(title: "Video Interstitial 320x480 (MAX) [noBids, MAX Ad]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
maxInterstitialController.prebidConfigId = "imp-prebid-no-bids"
maxInterstitialController.storedAuctionResponse = "response-prebid-no-bids"
maxInterstitialController.adFormats = [.video]
maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: maxInterstitialController)
setupCustomParams(for: maxInterstitialController.prebidConfigId)
}),
// MARK: ---- Multiformat Interstitial (MAX) ----
TestCase(title: "Multiformat Interstitial 320x480 (MAX)",
tags: [.interstitial, .video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let randomId = [0, 1].randomElement() ?? 0
let interstitialController = PrebidMAXInterstitialController(rootController: adapterVC)
let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"]
let prebidStoredImps = ["imp-prebid-display-interstitial-320-480", "imp-prebid-video-interstitial-320-480", ]
interstitialController.prebidConfigId = prebidStoredImps[randomId]
interstitialController.storedAuctionResponse = prebidStoredAuctionResponses[randomId]
interstitialController.maxAdUnitId = "78f9d445b8a1add7"
adapterVC.setup(adapter: interstitialController)
setupCustomParams(for: interstitialController.prebidConfigId)
}),
// MARK: ---- Video Rewarded (MAX) ----
TestCase(title: "Video Rewarded 320x480 (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC)
maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af"
maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
adapterVC.setup(adapter: maxRewardedAdController)
setupCustomParams(for: maxRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 With Ad Configuration Server (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC)
maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af"
maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration"
adapterVC.setup(adapter: maxRewardedAdController)
setupCustomParams(for: maxRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 (MAX) [noBids, MAX Ad]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC)
maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af"
maxRewardedAdController.prebidConfigId = "imp-prebid-no-bids"
maxRewardedAdController.storedAuctionResponse = "response-prebid-no-bids"
adapterVC.setup(adapter: maxRewardedAdController)
setupCustomParams(for: maxRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 (MAX) [OK, Random]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC)
maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af"
maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480"
maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480"
adapterVC.setup(adapter: maxRewardedAdController)
setupCustomParams(for: maxRewardedAdController.prebidConfigId)
}),
TestCase(title: "Video Rewarded 320x480 without End Card (MAX) [OK, OXB Adapter]",
tags: [.video, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC)
maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af"
maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card"
maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card"
adapterVC.setup(adapter: maxRewardedAdController)
setupCustomParams(for: maxRewardedAdController.prebidConfigId)
}),
// MARK: ---- Native (MAX) ----
TestCase(title: "Native Ad (MAX) [OK, OXB Adapter]",
tags: [.native, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let nativeController = PrebidMAXNativeController(rootController: adapterVC)
nativeController.maxAdUnitId = "f4c3d8281ebf3c39"
nativeController.prebidConfigId = "imp-prebid-banner-native-styles"
nativeController.storedAuctionResponse = "response-prebid-banner-native-styles"
nativeController.nativeAssets = .defaultNativeRequestAssets
nativeController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeController)
setupCustomParams(for: nativeController.prebidConfigId)
}),
TestCase(title: "Native Ad Events (MAX) [OK, OXB Adapter]",
tags: [.native, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events"
let nativeController = PrebidMAXNativeController(rootController: adapterVC)
nativeController.maxAdUnitId = "f4c3d8281ebf3c39"
nativeController.prebidConfigId = "imp-prebid-banner-native-styles"
nativeController.storedAuctionResponse = "response-prebid-banner-native-styles"
nativeController.nativeAssets = .defaultNativeRequestAssets
nativeController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeController)
setupCustomParams(for: nativeController.prebidConfigId)
}),
TestCase(title: "Native Ad (MAX) [noBids, MAX Ad]",
tags: [.native, .max, .server],
exampleVCStoryboardID: "AdapterViewController",
configurationClosure: { vc in
guard let adapterVC = vc as? AdapterViewController else {
return
}
let nativeController = PrebidMAXNativeController(rootController: adapterVC)
nativeController.maxAdUnitId = "f4c3d8281ebf3c39"
nativeController.prebidConfigId = "imp-prebid-no-bids"
nativeController.storedAuctionResponse = "imp-prebid-no-bids"
nativeController.nativeAssets = .defaultNativeRequestAssets
nativeController.eventTrackers = .defaultNativeEventTrackers
adapterVC.setup(adapter: nativeController)
setupCustomParams(for: nativeController.prebidConfigId)
}),
]
}()
// MARK: - Helper Methods
private static func setupCustomParams(for prebidConfigId: String) {
if let customParams = TestCaseManager.customORTBParams["configId"]?[prebidConfigId] {
TestCaseManager.updateUserData(customParams)
}
}
static func createDummyTableCell(for tableView: UITableView) -> TestCaseForTableCell {
return TestCaseForTableCell(configurationClosureForTableCell: { cell in
cell = tableView.dequeueReusableCell(withIdentifier: "DummyTableViewCell")
});
}
// MALE, FEMALE, OTHER to PBMGender {
private static func strToGender(_ gender: String) -> Gender {
switch gender {
case "MALE":
return .male
case "FEMALE":
return .female
case "OTHER":
return .female
default:
return .unknown
}
}
}
|
4d757dd17bb344fced716f3a238a7178
| 53.490638 | 391 | 0.578693 | false | true | false | false |
AnRanScheme/magiGlobe
|
refs/heads/master
|
magi/magiGlobe/magiGlobe/Classes/View/Home/View/ARALabel.swift
|
mit
|
1
|
//
// ARALabel.swift
// swift-magic
//
// Created by 安然 on 17/2/22.
// Copyright © 2017年 安然. All rights reserved.
//
import UIKit
import CoreText
let kRegexHighlightViewTypeURL = "url"
let kRegexHighlightViewTypeAccount = "account"
let kRegexHighlightViewTypeTopic = "topic"
let kRegexHighlightViewTypeEmoji = "emoji"
let URLRegular = "(http|https)://(t.cn/|weibo.com/)+(([a-zA-Z0-9/])*)"
let EmojiRegular = "(\\[\\w+\\])"
//let AccountRegular = "@[\u4e00-\u9fa5a-zA-Z0-9_-]{2,30}"
let TopicRegular = "#[^#]+#"
class ARALabel: UIView {
var text: String?
var textColor: UIColor?
var font: UIFont?
var lineSpace: NSInteger?
var textAlignment: NSTextAlignment?
/*
UIImageView *labelImageView;
UIImageView *highlightImageView;
BOOL highlighting;
BOOL btnLoaded;
BOOL emojiLoaded;
NSRange currentRange;
NSMutableDictionary *highlightColors;
NSMutableDictionary *framesDict;
NSInteger drawFlag;
*/
private var labelImageView: UIImageView?
private var highlightImageView: UIImageView?
private var highlighting: Bool?
private var btnLoaded: Bool?
private var emojiLoaded: Bool?
private var currentRange: NSRange?
private var highlightColors: NSMutableDictionary?
private var framesDict: NSMutableDictionary?
private var drawFlag: UInt32?
override init(frame: CGRect) {
super.init(frame: frame)
drawFlag = arc4random()
framesDict = NSMutableDictionary()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
caa14e5e8413ba98605029f547ab5111
| 21.881579 | 75 | 0.636573 | false | false | false | false |
hagmas/APNsKit
|
refs/heads/master
|
APNsKit/APNsRequest.swift
|
mit
|
1
|
import Foundation
public struct APNsRequest {
public struct Header {
public enum Priority: String {
case p5 = "5", p10 = "10"
}
public let id: String
public let expiration: Date
public let priority: Priority
public let topic: String?
public let collapseId: String?
public init(id: String = UUID().uuidString,
expiration: Date = Date(timeIntervalSince1970: 0),
priority: Priority = .p10,
topic: String? = nil,
collapseId: String? = nil) {
self.id = id
self.expiration = expiration
self.priority = .p10
self.topic = topic
self.collapseId = collapseId
}
}
public var port: APNsPort
public var server: APNsServer
public var deviceToken: String
public var header: Header
public var payload: APNsPayload
public static let method = "POST"
public init(port: APNsPort, server: APNsServer, deviceToken: String, header: Header = Header(), payload: APNsPayload) {
self.port = port
self.server = server
self.deviceToken = deviceToken
self.header = header
self.payload = payload
}
public var url: URL? {
let urlString = "https://" + server.rawValue + ":\(port.rawValue)" + "/3/device/" + deviceToken
return URL(string: urlString)
}
public var urlRequest: URLRequest? {
guard let url = url else {
return nil
}
var request = URLRequest(url: url)
request.setValue(for: header)
request.httpMethod = APNsRequest.method
request.httpBody = payload.data
return request
}
}
private extension URLRequest {
mutating func setValue(for header: APNsRequest.Header) {
self.addValue(header.id, forHTTPHeaderField: "apns-id")
self.addValue("\(Int(header.expiration.timeIntervalSince1970))", forHTTPHeaderField: "apns-expiration")
self.addValue(header.priority.rawValue, forHTTPHeaderField: "apns-priority")
if let topic = header.topic {
self.addValue(topic, forHTTPHeaderField: "apns-topic")
}
if let collapseId = header.collapseId {
self.addValue(collapseId, forHTTPHeaderField: "apns-collapse-id")
}
}
}
|
101117372169cede68a2fe9c2b85cc90
| 31.092105 | 123 | 0.585896 | false | false | false | false |
dymx101/Gamers
|
refs/heads/master
|
Gamers/Service/SliderBL.swift
|
apache-2.0
|
1
|
//
// SliderBL.swift
// Gamers
//
// Created by 虚空之翼 on 15/7/15.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import Foundation
import Alamofire
import Bolts
import SwiftyJSON
class SliderBL: NSObject {
// 单例模式
static let sharedSingleton = SliderBL()
/**
获取首页顶部的轮播信息
:returns: 成功轮播列表,失败错误信息
*/
func getHomeSlider() -> BFTask {
var fetchTask = BFTask(result: nil)
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return SliderDao.getHomeSlider()
})
fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in
if let sliders = task.result as? [Slider] {
return BFTask(result: sliders)
}
if let response = task.result as? Response {
return BFTask(result: response)
}
return task
})
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return task
})
return fetchTask
}
/**
获取频道的轮播信息
:param: channelId 频道ID
:returns: 成功轮播列表,失败错误信息
*/
func getChannelSlider(#channelId: String) -> BFTask {
var fetchTask = BFTask(result: nil)
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return SliderDao.getChannelSlider(channelId: channelId)
})
fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in
if let sliders = task.result as? [Slider] {
return BFTask(result: sliders)
}
if let response = task.result as? Response {
return BFTask(result: response)
}
return task
})
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return task
})
return fetchTask
}
}
|
5b46a7e5abfbda71f4a031f66944362f
| 24.1375 | 80 | 0.535323 | false | false | false | false |
LukaszLiberda/Swift-Design-Patterns
|
refs/heads/master
|
PatternProj/Creational/PrototypePattern.swift
|
gpl-2.0
|
1
|
//
// PrototypePattern.swift
// PatternProj
//
// Created by lukaszliberda on 06.07.2015.
// Copyright (c) 2015 lukasz. All rights reserved.
//
import Foundation
/*
The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation.
The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern.
The mitotic division of a cell — resulting in two identical cells — is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.[1]
*/
class ChungasRevengeDisplay {
var name: String?
let font: String
init(font: String) {
self.font = font
}
func clone() -> ChungasRevengeDisplay {
return ChungasRevengeDisplay(font: self.font)
}
}
/*
usage
*/
class TestPrototype {
func test() {
let prototype = ChungasRevengeDisplay(font: "Project")
let philippe = prototype.clone()
philippe.name = "Philippe"
let christoph = prototype.clone()
christoph.name = "Christoph"
let eduardo = prototype.clone()
eduardo.name = "Eduardo"
println()
}
func test2() {
var pBin:BinPrototypesModule = BinPrototypesModule()
pBin.addBinPrototype(Bin())
pBin.addBinPrototype(Bin())
pBin.addBinPrototype(TheOther())
var binObject: [BinPrototype] = []
var total: Int = 0
var sty: [String] = ["The other", "Bin", "The", "Bin", "The other", "Bin", "other", "Bin", "The other", "The other"]
for i in 0...9 {
if let binObj = pBin.findAndClone(sty[i]) {
binObject.append(binObj)
total++
}
}
for obj in binObject {
println("obj \(obj)")
if let bObj = obj as? BinCommand {
println("\(bObj)--> ")
bObj.binExecute()
}
}
println()
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protocol BinPrototype {
func clone() -> BinPrototype
func name() -> String
}
protocol BinCommand {
func binExecute()
}
class BinPrototypesModule {
private var prototypes: [BinPrototype] = []
private var total: Int = 0
func addBinPrototype(obj: BinPrototype) {
prototypes.append(obj)
total++
}
func findAndClone(name: String) -> BinPrototype? {
for binProtot in prototypes {
if binProtot.name() == name {
return binProtot
}
}
return nil
}
}
class Bin: BinPrototype, BinCommand {
func clone() -> BinPrototype {
return Bin()
}
func name() -> String {
return "Bin"
}
func binExecute() {
println("Bin execute")
}
}
class TheOther: BinPrototype, BinCommand {
func clone() -> BinPrototype {
return TheOther()
}
func name() -> String {
return "The other"
}
func binExecute() {
println("The other execute")
}
}
|
0edbd70c483e5751c5aa8b48bb7b1a59
| 24.959064 | 326 | 0.612976 | false | false | false | false |
mikezone/EffectiveSwift
|
refs/heads/master
|
EffectiveSwift/Extension/Foundation/Data+SE.swift
|
gpl-3.0
|
1
|
//
// Data+MKAdd.swift
// SwiftExtension
//
// Created by Mike on 17/1/20.
// Copyright © 2017年 Mike. All rights reserved.
//
import Foundation
import CommonCrypto
// MARK: - Hash
public extension Data {
public var md2String: String? {
return String(data: self, encoding: .utf8)?.md2String
}
public var md4String: String? {
return String(data: self, encoding: .utf8)?.md4String
}
public var md5String: String? {
return String(data: self, encoding: .utf8)?.md5String
}
public var sha1String: String? {
return String(data: self, encoding: .utf8)?.sha1String
}
public var sha224String: String? {
return String(data: self, encoding: .utf8)?.sha224String
}
public var sha256String: String? {
return String(data: self, encoding: .utf8)?.sha256String
}
public var sha384String: String? {
return String(data: self, encoding: .utf8)?.sha384String
}
public var sha512String: String? {
return String(data: self, encoding: .utf8)?.sha512String
}
public func hmacString(_ algorithm: CCHmacAlgorithm, _ key: String) -> String? {
return String(data: self, encoding: .utf8)?.hmacString(algorithm, key)
}
public func hmacMD5String(_ key: String) -> String? {
return hmacString(CCHmacAlgorithm(kCCHmacAlgMD5), key)
}
public func hmacSHA1String(_ key: String) -> String? {
return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA1), key)
}
public func hmacSHA224String(_ key: String) -> String? {
return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA224), key)
}
public func hmacSHA256String(_ key: String) -> String? {
return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA256), key)
}
public func hmacSHA384String(_ key: String) -> String? {
return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA384), key)
}
public func hmacSHA512String(_ key: String) -> String? {
return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA512), key)
}
public var crc32String: String? {
guard let crc32Value = self.crc32Value else { return nil }
return String(format: "%08x", crc32Value)
}
public var crc32Value: UInt? {
return String(data: self, encoding: .utf8)?.crc32Value
}
}
// MARK: - Encrypt and Decrypt
public extension Data {
public func aes256Encrypt(_ key: Data, _ iv: Data) -> Data? {
if key.count != 16 && key.count != 24 && key.count != 32 {
return nil
}
if iv.count != 16 && key.count != 0 {
return nil
}
let bufferSize = self.count + kCCBlockSizeAES128
let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: bufferSize)
var encryptedSize: Int = 0;
let cryptStatus = CCCrypt(CCOperation(kCCEncrypt),
CCAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
String(data: key, encoding: .utf8)?.cString(using: .utf8),
key.count,
String(data: iv, encoding: .utf8)?.cString(using: .utf8),
String(data: self, encoding: .utf8)?.cString(using: .utf8),
self.count,
buffer,
bufferSize,
&encryptedSize);
if cryptStatus == CCCryptorStatus(kCCSuccess) {
let result = Data(bytes: buffer, count: encryptedSize)
free(buffer);
return result;
} else {
free(buffer);
return nil;
}
}
public func aes256Decrypt(_ key: Data, _ iv: Data) -> Data? {
if key.count != 16 && key.count != 24 && key.count != 32 {
return nil
}
if iv.count != 16 && key.count != 0 {
return nil
}
let bufferSize = self.count + kCCBlockSizeAES128
let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: bufferSize)
var encryptedSize: Int = 0;
let cryptStatus = CCCrypt(CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
String(data: key, encoding: .utf8)?.cString(using: .utf8),
key.count,
String(data: iv, encoding: .utf8)?.cString(using: .utf8),
String(data: self, encoding: .utf8)?.cString(using: .utf8),
self.count,
buffer,
bufferSize,
&encryptedSize);
if cryptStatus == CCCryptorStatus(kCCSuccess) {
let result = Data(bytes: buffer, count: encryptedSize)
free(buffer);
return result;
} else {
free(buffer);
return nil;
}
}
}
|
49b612d6deb5244b373eac21dc357037
| 32.647436 | 93 | 0.532673 | false | false | false | false |
KhunLam/Swift_weibo
|
refs/heads/master
|
LKSwift_weibo/LKSwift_weibo/Classes/Library/Emoticon/UITextView+Emoticon.swift
|
apache-2.0
|
1
|
//
// UITextView+Emoticon.swift
// 表情键盘
//
// Created by lamkhun on 15/11/8.
// Copyright © 2015年 lamKhun. All rights reserved.
//
import UIKit
/// 扩展 UITextView 分类
extension UITextView {
/**
获取带表情图片的字符串
- returns: 带表情图片的字符串
*/
func emoticonText() -> String {
// 将所有遍历的文本拼接起来
var text = ""
// enumerationRange: 遍历的范围 --0开始 文本长度
attributedText.enumerateAttributesInRange(NSRange(location: 0, length:attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
// print("dict\(dict)") ///---打印驱动 key -- “NSAttachment”
// print("range\(range)")
// 如果dict有 "NSAttachment" key 并且拿出来有值(NSTextAttachment) 表情图片, 没有就是普通的文本NSFont
if let attachment = dict["NSAttachment"] as? LKTextAttachment {
// 需要获取到表情图片对应的名称
// 需要一个属性记录下表情图片的名称,现有的类不能满足要求,创建一个类继承NSTextAttachment 的自定义类
text += attachment.name!
}else {
// 普通文本,截取
let str = (self.attributedText.string as NSString).substringWithRange(range)
text += str
}
}
// 遍历完后输出
return text
}
/**
添加表情到textView
- parameter emoticon: 要添加的表情
*/
func insertEmoticon(emoticon: LKEmoticon) {
// 判断如果是删除按钮
if emoticon.removeEmoticon {
// 删除文字或表情
deleteBackward()
}
// 添加emoji表情--系统自带
if let emoji = emoticon.emoji{
//插入文本
insertText(emoji)
}
// 添加图片表情 --判断是否 有表情 --用文本附件的形式 显示表情
if let pngPath = emoticon.pngPath {
//一① 创建附件 --
let attachment = LKTextAttachment()
//② 创建 image
let image = UIImage(contentsOfFile: pngPath)
//③ 将 image 添加到附件
attachment.image = image
// 将表情图片的名称赋值 ---自定义属性 记录
attachment.name = emoticon.chs
// 获取文本font的线高度 --文字高度
let height = font?.lineHeight ?? 10
// 设置附件大小
attachment.bounds = CGRect(x: 0, y: -(height * 0.25), width: height, height: height)
//二① 创建属性文本 可变的
let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
// 发现在表情图片后面在添加表情会很小.原因是前面的这个表请缺少font属性
// 给属性文本(附件) 添加 font属性 --附件 Range 0开始 长度1
attrString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
// 获取到已有的文本,将表情添加到已有的可变文本后面
let oldAttrString = NSMutableAttributedString(attributedString: attributedText)
// 记录选中的范围
let oldSelectedRange = selectedRange
// range: 替换的文本范围
oldAttrString.replaceCharactersInRange(oldSelectedRange, withAttributedString: attrString)
//三① 赋值给textView的 attributedText 显示
attributedText = oldAttrString
//② 设置输入光标位置,在表情后面
selectedRange = NSRange(location: oldSelectedRange.location + 1, length: 0)
// 让表情图片 也能 发出 extViewDidChange 给条用者 知道
// 重新设置textView的attributedText没有触发textDidChanged
// 主动调用代理的textViewDidChange
delegate?.textViewDidChange?(self)
// 主动发送 UITextViewTextDidChangeNotification
NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
}
}
}
|
a0fb7a6be8a6ad8e8494ec9846bc5d06
| 31.299145 | 191 | 0.550026 | false | false | false | false |
xdliu002/TongjiAppleClubDeviceManagement
|
refs/heads/master
|
TAC-DM/BookViewController.swift
|
mit
|
1
|
//
// BookViewController.swift
// TAC-DM
//
// Created by Harold Liu on 8/18/15.
// Copyright (c) 2015 TAC. All rights reserved.
//
import UIKit
class BookViewController:UITableViewController, DMDelegate {
var dmModel: DatabaseModel!
var bookList:[String]? = nil
var bookNameArray:[String] = []
//MARK:- Custom Nav
@IBOutlet weak var navView: UIView!
@IBAction func back() {
SVProgressHUD.dismiss()
(tabBarController as! TabBarController).sidebar.showInViewController(self, animated: true)
}
// MARK:- Configure UI
override func viewDidLoad() {
super.viewDidLoad()
configureNavBar()
self.navigationController?.navigationBarHidden = true
//self.navView.backgroundColor = UIColor(patternImage:UIImage(named: "book background")!)
self.navView.backgroundColor = UIColor.clearColor()
dmModel = DatabaseModel.getInstance()
dmModel.delegate = self
self.refreshControl = UIRefreshControl()
self.refreshControl!.addTarget(self, action: Selector("refresh"), forControlEvents: .ValueChanged)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = true
updateUI()
tableView.reloadData()
SVProgressHUD.show()
}
func refresh() {
SVProgressHUD.show()
updateUI()
print("data is refresh")
tableView.reloadData()
refreshControl?.endRefreshing()
}
//更新所有书籍
func updateUI() {
bookList = nil
bookNameArray = []
dmModel.getDeviceList("book")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// this api mush better than what i am use before remember it.
self.tableView.backgroundView = UIImageView(image: UIImage(named: "book background"))
}
func configureNavBar()
{
self.navigationController?.navigationBar.barTintColor = UIColor(patternImage: UIImage(named: "book background")!)
self.navigationController?.navigationBar.titleTextAttributes =
[NSForegroundColorAttributeName : UIColor.whiteColor(),NSFontAttributeName:UIFont(name: "Hiragino Kaku Gothic ProN", size: 30)!]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TextCell", forIndexPath: indexPath)
let row = indexPath.row
if 0 == row % 2
{
cell.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.65)
cell.textLabel?.text = bookNameArray[row/2]
cell.textLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0)
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
else
{
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.text = ""
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if 0 == indexPath.row % 2
{
return 75
}
else
{
return 5
}
}
// MARK:- UITableViewDelegate Methods
// TODO: should return count *2 Here attention
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bookNameArray.count * 2
}
@IBAction func backButton(sender: UIBarButtonItem) {
// self.navigationController?.navigationBarHidden = true
SVProgressHUD.dismiss()
(tabBarController as! TabBarController).sidebar.showInViewController(self, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let selectedIndex = self.tableView.indexPathForCell(sender as! UITableViewCell)
if segue.identifier == "showDetial" {
if let destinationVC = segue.destinationViewController as? BookDetail
{
let book = bookList![selectedIndex!.row/2].componentsSeparatedByString(",")
destinationVC.borrowBookId = book[0]
destinationVC.borrowBookName = book[1]
destinationVC.borrowBookDescription = book[2]
}
}
}
func getRequiredInfo(Info: String) {
//put book list in tableView
print("图书列表:\(Info)")
bookList = Info.componentsSeparatedByString("|")
for book in bookList! {
let bookName = book.componentsSeparatedByString(",")
//check Info is empty
if bookName.count > 1 {
let tmpName = "\(bookName[0]),\(bookName[1])"
bookNameArray.append(tmpName)
} else {
print("there is no book")
tableView.reloadData()
//tableView为空,给用户提示
SVProgressHUD.showErrorWithStatus("Sorry,there is no book for borrowing")
return
}
}
self.tableView.reloadData()
SVProgressHUD.dismiss()
}
}
|
86bc52b89f67ed334b211350e23561f0
| 32.796178 | 140 | 0.62288 | false | false | false | false |
DazzlingDevelopment/MathKit
|
refs/heads/master
|
MKProbability.swift
|
mit
|
1
|
//
// MKProbability.swift
// MathKit
//
// Created by Dazzling Development on 5/25/15.
// Copyright (c) 2015 DAZ. All rights reserved.
//
import Foundation
class MKProbability {
var MathKitBasics = MKBasics()
// Permutation Basic
func permutation(totalObj: Double, objToHandle: Double) -> Double {
var numerator = MathKitBasics.factorial(totalObj)
var denominator = MathKitBasics.factorial(totalObj - objToHandle)
var final: Double = Double(numerator) / Double(denominator)
return final
}
// PermutationRepitition
func permutationWithRepitition(totalObj: Double, similarObjects: [Double]) -> Double {
var numerator = MathKitBasics.factorial(totalObj)
var denominator: Double = 1
var iterator = 0
while iterator < similarObjects.count {
denominator *= MathKitBasics.factorial(similarObjects[iterator])
iterator++
}
var final = Double(numerator) / Double(denominator)
return final
}
// PermutationCircular
func permutationCircular(totalObj: Double) -> Double {
var numerator = MathKitBasics.factorial(totalObj)
var denominator = totalObj
var final = Double(numerator) / Double(denominator)
return final
}
// Combination Basic
func combination(totalObj: Double, objToHandle: Double) -> Double {
var numerator = MathKitBasics.factorial(totalObj)
var denominator = ((MathKitBasics.factorial(totalObj - objToHandle)) * (MathKitBasics.factorial(objToHandle)))
var final: Double = Double(numerator) / Double(denominator)
return final
}
// Odds For
func oddsFor(probSuccess: Double, probFailure: Double) -> Double {
return probSuccess / probFailure
}
// Odds Against
func oddsAgainst(probSuccess: Double, probFailure: Double) -> Double {
return probFailure / probSuccess
}
}
|
b773d4b6c44e81e52b7dfba9e10b15d5
| 29.753846 | 118 | 0.648824 | false | false | false | false |
CatchChat/Yep
|
refs/heads/master
|
Yep/Extensions/ASImageNode+Yep.swift
|
mit
|
1
|
//
// ASImageNode+Yep.swift
// Yep
//
// Created by NIX on 16/7/5.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import YepKit
import Navi
import AsyncDisplayKit
private var avatarKeyAssociatedObject: Void?
extension ASImageNode {
private var navi_avatarKey: String? {
return objc_getAssociatedObject(self, &avatarKeyAssociatedObject) as? String
}
private func navi_setAvatarKey(avatarKey: String) {
objc_setAssociatedObject(self, &avatarKeyAssociatedObject, avatarKey, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func navi_setAvatar(avatar: Navi.Avatar, withFadeTransitionDuration fadeTransitionDuration: NSTimeInterval = 0) {
navi_setAvatarKey(avatar.key)
AvatarPod.wakeAvatar(avatar) { [weak self] finished, image, cacheType in
guard let strongSelf = self, avatarKey = strongSelf.navi_avatarKey where avatarKey == avatar.key else {
return
}
if finished && cacheType != .Memory {
UIView.transitionWithView(strongSelf.view, duration: fadeTransitionDuration, options: .TransitionCrossDissolve, animations: {
self?.image = image
}, completion: nil)
} else {
self?.image = image
}
}
}
}
private var messageKey: Void?
extension ASImageNode {
private var yep_messageImageKey: String? {
return objc_getAssociatedObject(self, &messageKey) as? String
}
private func yep_setMessageImageKey(messageImageKey: String) {
objc_setAssociatedObject(self, &messageKey, messageImageKey, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func yep_setImageOfMessage(message: Message, withSize size: CGSize, tailDirection: MessageImageTailDirection, completion: (loadingProgress: Double, image: UIImage?) -> Void) {
let imageKey = message.imageKey
yep_setMessageImageKey(imageKey)
ImageCache.sharedInstance.imageOfMessage(message, withSize: size, tailDirection: tailDirection, completion: { [weak self] progress, image in
guard let strongSelf = self, _imageKey = strongSelf.yep_messageImageKey where _imageKey == imageKey else {
return
}
completion(loadingProgress: progress, image: image)
})
}
}
|
e79e071efaefb164c78b4478363eaf4b
| 30.432432 | 179 | 0.670679 | false | false | false | false |
Bijiabo/F-Client-iOS
|
refs/heads/master
|
F/F/Controllers/ActionSelectTableViewController.swift
|
gpl-2.0
|
1
|
//
// ActionSelectTableViewController.swift
// CKM
//
// Created by huchunbo on 15/10/27.
// Copyright © 2015年 TIDELAB. All rights reserved.
//
import UIKit
class ActionSelectTableViewController: UITableViewController {
let actions = [
[
"text": "New RecordType",
"action": "NewRecord"
],
[
"text": "Delete RecordType",
"action": "DeleteRecord"
],
[
"text": "Add Record",
"action": "AddRecord"
],
[
"text": "Edit Record",
"action": "EditRecord"
],
[
"text": "Delete Record",
"action": "DeleteRecord"
],
[
"text": "Query",
"action": "Query"
]
]
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = true
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
a7c50f1401c865585fecff32c398e604
| 29.440678 | 157 | 0.630568 | false | false | false | false |
ddki/my_study_project
|
refs/heads/master
|
language/swift/MyPlayground.playground/Contents.swift
|
mit
|
1
|
print("hello world!")
// let - constant, var - variable
var myVariable = 42
myVariable = 50
let myConstant = 42
// type
let explicitDouble: Double = 70
// Values are never implicitly converted to another type.
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
// /()
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples";
let fruitSummary = "I have \(apples + oranges) pieces of fruit";
// array
var shoppingList = ["catfish", "water", "tulips", "blue paint"];
shoppingList[1] = "bottle of water";
print(shoppingList)
// dictionary
var occupations = [
"Malcolm": "Captain",
"Keylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
print(occupations)
// empty
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
//
shoppingList = [];
occupations = [:];
// for if
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
// ?
var optionalString: String? = "option"
print(optionalString == nil)
var optionalName: String? = nil
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
} else {
greeting = "just hello."
}
// ??
let nickName: String? = nil
let fullName: String = "ddchen"
let informalGreeting = "Hi \(nickName ?? fullName)"
// switch case
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("celery")
case "cucumber", "watercress":
print("cucumber, watercress")
case let x where x.hasSuffix("pepper"):
print("pepper \(x)?")
default:
print("Everything tastes good in soup.")
}
// for dictionary
let interestingNumber = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25]
]
var largest = 0
var largestKind:String? = nil
for (kind, numbers) in interestingNumber {
for number in numbers {
if number > largest {
largest = number
largestKind = kind
}
}
}
print(largest)
print(largestKind)
// while repeat-while
var n = 2
while n < 100 {
n = n * 2
}
print(n)
var m = 2
repeat {
m = m * 2
} while m < 100
print(m)
// ..<
var firstForLoop = 0
let loopTimes:Int = 4
for i in 0 ..< loopTimes {
firstForLoop += i
}
print(firstForLoop)
var secondForLoop = 0
for var i=0;i < 4;i++ {
secondForLoop += i
}
print(secondForLoop)
// ...
var thirdForLoop = 0
for i in 0...4 {
thirdForLoop += i
}
print(thirdForLoop)
// function
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", day: "Tuesday")
// tuples
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0];
var max = scores[0];
var sum = 0;
for score in scores {
if score > max {
max = score
} else {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
// inner functions
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
// closure
func makeIncrementer () -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
//
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
// closure
var clsr = [1, 2, 3, 4].map({
(number: Int) -> Int in
if number % 2 == 1 {
return 0
}
return 1
})
print(clsr);
var mapNum = [3, 4].map({ number in 3 * number });
print(mapNum)
let sortedNumbers = [5, 6].sort {$0 > $1}
print(sortedNumbers)
// class
class Shape {
var numberOfSides = 0
func simpleDescription () -> String {
return "A shape with \(numberOfSides) sides."
}
}
var shape = Shape()
shape.numberOfSides = 7
var shapeDesc = shape.simpleDescription()
print(shapeDesc)
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func test () -> () {
print("\(self.numberOfSides)")
}
}
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name:name)
numberOfSides = 4
}
override func test () -> () {
print("\(self.sideLength)");
}
}
var square = Square(sideLength: 4.0, name: "square")
square.test()
class EquilateralTriangle: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name);
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func test() -> () {
print("\(self.sideLength)")
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
// willSet run before setting a new value
// didSet run after setting a new value
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name:name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
// ?
var optionalValue:Dictionary? = [
"good": [1, 2, 3, 5]
];
let okGetIt = (optionalValue?["good"]![2])! + 1
print(okGetIt)
optionalValue = nil
let okGetIt2 = optionalValue?["good"]
print(optionalValue)
//
enum Rank: Int {
case Ace = 100
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
default:
return String(self.rawValue)
}
}
func compare (other: Rank) -> Bool {
return self.rawValue > other.rawValue
}
}
let ace = Rank.Ace
let aceRawValue = ace.rawValue
ace.simpleDescription()
let queen = Rank.Queen
let queenRawValue = queen.rawValue
queen.compare(ace)
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
}
enum Suit: String {
case Spades, Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts
print(hearts.rawValue)
let heartsDescription = hearts.simpleDescription()
// struct
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let card = Card(rank:.Three, suit:.Hearts)
card.simpleDescription()
//
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
switch success {
case let .Result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .Error(error):
print("Failure... \(error)")
}
// protocol
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 78932
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var simpleInst = SimpleClass()
simpleInst.adjust()
let aDesc = simpleInst.simpleDescription;
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A very simple structure."
mutating func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var b = SimpleStructure()
b.adjust()
let bDesc = b.simpleDescription
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
let protocolValue: ExampleProtocol = simpleInst
print(protocolValue.simpleDescription)
// generic <>
func repeatItem<Item>(item: Item, numberOfTimes: Int)
-> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
repeatItem("knock", numberOfTimes: 4)
enum OptionalValue<Wrapped> {
case None
case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .some(100)
func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) ->
Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
// import
import UIKit
let redSquare = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
redSquare.backgroundColor = UIColor.redColor()
|
aa8a842c912ee1c67f1ea227e918623a
| 15.415797 | 160 | 0.548357 | false | false | false | false |
victor-pavlychko/SwiftyTasks
|
refs/heads/master
|
SwiftyTasks/Tasks/TaskProtocol.swift
|
mit
|
1
|
//
// TaskProtocol.swift
// SwiftyTasks
//
// Created by Victor Pavlychko on 9/15/16.
// Copyright © 2016 address.wtf. All rights reserved.
//
import Foundation
/// Abstract task
public protocol AnyTask {
/// List of backing operations
var backingOperations: [Operation] { get }
}
/// Abstract task with result
public protocol TaskProtocol: AnyTask {
associatedtype ResultType
/// Retrieves tast execution result or error
///
/// - Throws: captured error if any
/// - Returns: execution result
func getResult() throws -> ResultType
}
extension Operation: AnyTask {
/// List of backing operations which is equal to `[self]` in case of Operation
public var backingOperations: [Operation] {
return [self]
}
}
public extension AnyTask {
/// Starts execution of all backing operation and fires completion block when ready.
/// Async operations will run concurrently in background, sync ones will execute one by one
/// in current thread.
///
/// - Parameter completionBlock: Completion block to be fired when everyhting is done
public func start(_ completionBlock: @escaping () -> Void) {
guard !backingOperations.isEmpty else {
completionBlock()
return
}
var counter: Int32 = Int32(backingOperations.count)
let countdownBlock = {
if (OSAtomicDecrement32Barrier(&counter) == 0) {
completionBlock()
}
}
for operation in backingOperations {
operation.completionBlock = countdownBlock
operation.start()
}
}
}
public extension TaskProtocol {
/// Starts execution of all backing operation and fires completion block when ready.
/// Async operations will run concurrently in background, sync ones will execute one by one
/// in current thread.
///
/// - Parameters:
/// - completionBlock: Completion block to be fired when everyhting is done
/// - resultBlock: Result block wrapping task outcome
public func start(_ completionBlock: @escaping (_ resultBlock: () throws -> ResultType) -> Void) {
start { completionBlock(self.getResult) }
}
}
|
a9e8bee83be68c583d3a3aeb3c54e471
| 27.935065 | 102 | 0.650808 | false | false | false | false |
sgr-ksmt/i18nSwift
|
refs/heads/master
|
Sources/Language.swift
|
mit
|
1
|
//
// Language.swift
// i18nSwift
//
// Created by Suguru Kishimoto on 3/28/17.
// Copyright © 2017 Suguru Kishimoto. All rights reserved.
//
import Foundation
extension i18n {
public final class Language {
public struct Constant {
internal init() {}
public static let currentLanguageKey = "i18n.current_language"
fileprivate static let defaultLanguage = "en"
fileprivate static let stringsFileSuffix = "lproj"
fileprivate static let baseStringsFileName = "Base"
fileprivate static let notificationKey = "i18n.current_language.didupdate"
}
static var dataStore: LanguageDataStore = DefaultLanguageDataStore()
static var languageBundle: Bundle = .main
static func localizableBundle(in bundle: Bundle, language: String) -> Bundle? {
return localizableBundlePath(in: bundle, language: language).flatMap { Bundle(path: $0) }
}
private static func localizableBundlePath(in bundle: Bundle, language: String = current) -> String? {
for l in [language, Constant.baseStringsFileName] {
if let path = bundle.path(forResource: l, ofType: Constant.stringsFileSuffix) {
return path
}
}
return nil
}
// MARK: - Language
public static func availableLanguages(includeBase: Bool = true) -> [String] {
return languageBundle.localizations.filter { $0 != Constant.baseStringsFileName || includeBase }
}
public static var current: String {
get {
return dataStore.language(forKey: Constant.currentLanguageKey) ?? self.default
}
set {
let language = availableLanguages().contains(newValue) ? newValue : Constant.defaultLanguage
dataStore.set(language, forKey: Constant.currentLanguageKey)
NotificationCenter.default.post(name: .CurrentLanguageDidUpdate, object: nil)
}
}
public static func reset() {
dataStore.reset(forKey: Constant.currentLanguageKey)
NotificationCenter.default.post(name: .CurrentLanguageDidUpdate, object: nil)
}
public static var `default`: String {
return languageBundle.preferredLocalizations.first!
}
public static func displayName(for language: String = current) -> String? {
return NSLocale(localeIdentifier: current).displayName(forKey: .identifier, value: language)
}
}
}
public extension Notification.Name {
public static let CurrentLanguageDidUpdate = Notification.Name(i18n.Language.Constant.notificationKey)
}
|
c37d34ea1d35e75a86ad5f78bfc5994d
| 36.84 | 109 | 0.616279 | false | false | false | false |
natecook1000/WWDC
|
refs/heads/master
|
WWDC/SlidesDownloader.swift
|
bsd-2-clause
|
1
|
//
// SlidesDownloader.swift
// WWDC
//
// Created by Guilherme Rambo on 10/3/15.
// Copyright © 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
import Alamofire
class SlidesDownloader {
typealias ProgressHandler = (downloaded: Double, total: Double) -> Void
typealias CompletionHandler = (success: Bool, data: NSData?) -> Void
var session: Session
init(session: Session) {
self.session = session
}
func downloadSlides(completionHandler: CompletionHandler, progressHandler: ProgressHandler?) {
guard session.slidesURL != "" else { return completionHandler(success: false, data: nil) }
guard let slidesURL = NSURL(string: session.slidesURL) else { return completionHandler(success: false, data: nil) }
Alamofire.download(Method.GET, slidesURL.absoluteString) { tempURL, response in
if let data = NSData(contentsOfURL: tempURL) {
mainQ {
WWDCDatabase.sharedDatabase.doChanges { self.session.slidesPDFData = data }
completionHandler(success: true, data: data)
}
} else {
completionHandler(success: false, data: nil)
}
do {
try NSFileManager.defaultManager().removeItemAtURL(tempURL)
} catch {
print("Error removing temporary PDF file")
}
return tempURL
}.progress { _, totalBytesRead, totalBytesExpected in
mainQ { progressHandler?(downloaded: Double(totalBytesRead), total: Double(totalBytesExpected)) }
}
}
}
|
b66503e9738a0d6c1a7772d71d8c8501
| 32.897959 | 123 | 0.612048 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS
|
refs/heads/master
|
ResearchUXFactory/SBAPermissionsStep.swift
|
bsd-3-clause
|
1
|
//
// SBAPermissionsStep.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
open class SBAPermissionsSkipRule: ORKSkipStepNavigationRule {
/**
Manager for handling requesting permissions
*/
open var permissionsManager: SBAPermissionsManager {
return SBAPermissionsManager.shared
}
/**
Permission types to request for this step of the task.
*/
public let permissionTypes: [SBAPermissionObjectType]
/**
Whether or not the rule should be applied
@param taskResult Ignored.
@return `YES` if all permissions are granted
*/
open override func stepShouldSkip(with taskResult: ORKTaskResult) -> Bool {
return self.permissionsManager.allPermissionsAuthorized(for: self.permissionTypes)
}
public required init(permissionTypes: [SBAPermissionObjectType]) {
self.permissionTypes = permissionTypes
super.init()
}
public required init(coder aDecoder: NSCoder) {
self.permissionTypes = aDecoder.decodeObject(forKey: "permissionTypes") as! [SBAPermissionObjectType]
super.init(coder: aDecoder)
}
open override func encode(with aCoder: NSCoder) {
aCoder.encode(self.permissionTypes, forKey: "permissionTypes")
super.encode(with: aCoder)
}
override open func copy(with zone: NSZone? = nil) -> Any {
return type(of: self).init(permissionTypes: self.permissionTypes)
}
}
open class SBAPermissionsStep: ORKTableStep, SBANavigationSkipRule {
/**
Manager for handling requesting permissions
*/
open var permissionsManager: SBAPermissionsManager {
return SBAPermissionsManager.shared
}
/**
Permission types to request for this step of the task.
*/
open var permissionTypes: [SBAPermissionObjectType] {
get {
return self.items as? [SBAPermissionObjectType] ?? []
}
set {
self.items = newValue
}
}
@available(*, deprecated, message: "use `permissionTypes` instead")
open var permissions: SBAPermissionsType {
get {
return permissionsManager.permissionsType(for: self.permissionTypes)
}
set {
self.items = permissionsManager.typeObjectsFor(for: newValue)
}
}
override public init(identifier: String) {
super.init(identifier: identifier)
commonInit()
}
public init(identifier: String, permissions: [SBAPermissionTypeIdentifier]) {
super.init(identifier: identifier)
self.items = self.permissionsManager.permissionsTypeFactory.permissionTypes(for: permissions)
commonInit()
}
public convenience init?(inputItem: SBASurveyItem) {
guard let survey = inputItem as? SBAFormStepSurveyItem else { return nil }
self.init(identifier: inputItem.identifier)
survey.mapStepValues(with: self)
self.items = self.permissionsManager.permissionsTypeFactory.permissionTypes(for: survey.items)
commonInit()
}
fileprivate func commonInit() {
if self.title == nil {
self.title = Localization.localizedString("SBA_PERMISSIONS_TITLE")
}
if self.items == nil {
self.items = self.permissionsManager.defaultPermissionTypes
}
else if let healthKitPermission = self.permissionTypes.find({ $0.permissionType == .healthKit }) as? SBAHealthKitPermissionObjectType,
(healthKitPermission.healthKitTypes == nil) || healthKitPermission.healthKitTypes!.count == 0,
let replacement = permissionsManager.defaultPermissionTypes.find({ $0.permissionType == .healthKit }) as? SBAHealthKitPermissionObjectType {
// If this is a healthkit step and the permission types are not defined,
// then look in the default permission types for the default types to include.
healthKitPermission.healthKitTypes = replacement.healthKitTypes
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func stepViewControllerClass() -> AnyClass {
return SBAPermissionsStepViewController.classForCoder()
}
override open func isInstructionStep() -> Bool {
return true
}
// MARK: SBANavigationSkipRule
open func shouldSkipStep(with result: ORKTaskResult, and additionalTaskResults: [ORKTaskResult]?) -> Bool {
return self.permissionsManager.allPermissionsAuthorized(for: self.permissionTypes)
}
// MARK: Cell overrides
let cellIdentifier = "PermissionsCell"
override open func reuseIdentifierForRow(at indexPath: IndexPath) -> String {
return cellIdentifier
}
override open func registerCells(for tableView: UITableView) {
tableView.register(SBAMultipleLineTableViewCell.classForCoder(), forCellReuseIdentifier: cellIdentifier)
}
override open func configureCell(_ cell: UITableViewCell, indexPath: IndexPath, tableView: UITableView) {
guard let item = self.objectForRow(at: indexPath) as? SBAPermissionObjectType,
let multipleLineCell = cell as? SBAMultipleLineTableViewCell
else {
return
}
multipleLineCell.titleLabel?.text = item.title
multipleLineCell.subtitleLabel?.text = item.detail
}
}
open class SBAPermissionsStepViewController: ORKTableStepViewController {
var permissionsGranted: Bool = false
override open var result: ORKStepResult? {
guard let result = super.result else { return nil }
// Add a result for whether or not the permissions were granted
let grantedResult = ORKBooleanQuestionResult(identifier: result.identifier)
grantedResult.booleanAnswer = NSNumber(value: permissionsGranted)
result.results = [grantedResult]
return result
}
override open func goForward() {
guard let permissionsStep = self.step as? SBAPermissionsStep else {
assertionFailure("Step is not of expected type")
super.goForward()
return
}
// Show a loading view to indicate that something is happening
self.showLoadingView()
let permissionsManager = permissionsStep.permissionsManager
let permissions = permissionsStep.permissionTypes
permissionsManager.requestPermissions(for: permissions, alertPresenter: self) { [weak self] (granted) in
if granted || permissionsStep.isOptional {
self?.permissionsGranted = granted
self?.goNext()
}
else if let strongSelf = self, let strongDelegate = strongSelf.delegate {
let error = NSError(domain: "SBAPermissionsStepDomain", code: 1, userInfo: nil)
strongDelegate.stepViewControllerDidFail(strongSelf, withError: error)
}
}
}
override open func skipForward() {
goNext()
}
fileprivate func goNext() {
super.goForward()
}
open override var cancelButtonItem: UIBarButtonItem? {
// Override the cancel button to *not* display. User must tap the "Continue" button.
get { return nil }
set {}
}
}
|
31a5e0dd50cd18d4c808f4910dd84c41
| 37.227848 | 152 | 0.681788 | false | false | false | false |
Kesoyuh/Codebrew2017
|
refs/heads/master
|
Codebrew2017/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Codebrew2017
//
// Created by Changchang on 18/3/17.
// Copyright © 2017 University of Melbourne. All rights reserved.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Initialize Firebase
FIRApp.configure()
//customize UINavigationBar appearance
UINavigationBar.appearance().barStyle = UIBarStyle.default
//UINavigationBar.appearance().barTintColor = UIColor.blackColor() //UIColor(red: 242.0/255.0, green: 116.0/255.0, blue: 119.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor(red: 0.0/255.0, green: 51.0/255.0, blue: 102.0/255.0, alpha: 1.0)
if let barFont = UIFont(name: "Avenir-Light", size: 24.0) {
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor(red: 0.0/255.0, green: 51.0/255.0, blue: 102.0/255.0, alpha: 1.0), NSFontAttributeName:barFont]
}
//customize UITabBar appearance
UITabBar.appearance().tintColor = UIColor(red: 0.0/255.0, green: 51.0/255.0, blue: 102.0/255.0, alpha: 1.0)
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:.
}
}
|
f22744379ee998d1014494c411f35e6c
| 51.559322 | 285 | 0.726217 | false | false | false | false |
OatmealCode/Oatmeal
|
refs/heads/master
|
Carlos/FetcherValueTransformation.swift
|
mit
|
2
|
import Foundation
import PiedPiper
extension Fetcher {
/**
Applies a transformation to the fetcher
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter transformer: The transformation you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
public func transformValues<A: OneWayTransformer where OutputType == A.TypeIn>(transformer: A) -> BasicFetcher<KeyType, A.TypeOut> {
return BasicFetcher(
getClosure: { key in
return self.get(key).mutate(transformer)
}
)
}
/**
Applies a transformation to the fetcher
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter transformerClosure: The transformation closure you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.7)
public func transformValues<A>(transformerClosure: OutputType -> Future<A>) -> BasicFetcher<KeyType, A> {
return self.transformValues(wrapClosureIntoOneWayTransformer(transformerClosure))
}
}
/**
Applies a transformation to a fetch closure
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetchClosure: The fetcher closure you want to transform
- parameter transformer: The transformation you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.5)
public func transformValues<A, B: OneWayTransformer>(fetchClosure: (key: A) -> Future<B.TypeIn>, transformer: B) -> BasicFetcher<A, B.TypeOut> {
return transformValues(wrapClosureIntoFetcher(fetchClosure), transformer: transformer)
}
/**
Applies a transformation to a fetcher
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetcher: The fetcher you want to transform
- parameter transformer: The transformation you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.5)
public func transformValues<A: Fetcher, B: OneWayTransformer where A.OutputType == B.TypeIn>(fetcher: A, transformer: B) -> BasicFetcher<A.KeyType, B.TypeOut> {
return fetcher.transformValues(transformer)
}
/**
Applies a transformation to a fetch closure
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetchClosure: The fetcher closure you want to transform
- parameter transformerClosure: The transformation closure you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.5)
public func transformValues<A, B, C>(fetchClosure: (key: A) -> Future<B>, transformerClosure: B -> Future<C>) -> BasicFetcher<A, C> {
return transformValues(wrapClosureIntoFetcher(fetchClosure), transformer: wrapClosureIntoOneWayTransformer(transformerClosure))
}
/**
Applies a transformation to a fetcher
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetcher: The fetcher you want to transform
- parameter transformerClosure: The transformation closure you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.5)
public func transformValues<A: Fetcher, B>(fetcher: A, transformerClosure: A.OutputType -> Future<B>) -> BasicFetcher<A.KeyType, B> {
return fetcher.transformValues(transformerClosure)
}
/**
Applies a transformation to a fetch closure
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetchClosure: The fetch closure you want to transform
- parameter transformer: The transformation you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.7)
public func =>><A, B: OneWayTransformer>(fetchClosure: (key: A) -> Future<B.TypeIn>, transformer: B) -> BasicFetcher<A, B.TypeOut> {
return wrapClosureIntoFetcher(fetchClosure).transformValues(transformer)
}
/**
Applies a transformation to a fetcher
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetcher: The fetcher you want to transform
- parameter transformer: The transformation you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
public func =>><A: Fetcher, B: OneWayTransformer where A.OutputType == B.TypeIn>(fetcher: A, transformer: B) -> BasicFetcher<A.KeyType, B.TypeOut> {
return fetcher.transformValues(transformer)
}
/**
Applies a transformation to a fetch closure
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetchClosure: The fetch closure you want to transform
- parameter transformerClosure: The transformation closure you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.7)
public func =>><A, B, C>(fetchClosure: (key: A) -> Future<B>, transformerClosure: B -> Future<C>) -> BasicFetcher<A, C> {
return wrapClosureIntoFetcher(fetchClosure).transformValues(wrapClosureIntoOneWayTransformer(transformerClosure))
}
/**
Applies a transformation to a fetcher
The transformation works by changing the type of the value the fetcher returns when succeeding
Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types
- parameter fetcher: The fetcher you want to transform
- parameter transformerClosure: The transformation closure you want to apply
- returns: A new fetcher result of the transformation of the original fetcher
*/
@available(*, deprecated=0.7)
public func =>><A: Fetcher, B>(fetcher: A, transformerClosure: A.OutputType -> Future<B>) -> BasicFetcher<A.KeyType, B> {
return fetcher.transformValues(wrapClosureIntoOneWayTransformer(transformerClosure))
}
|
0e94e80a38bb0d1aa0ca7c1508b7dc43
| 46.477419 | 160 | 0.773716 | false | false | false | false |
mono0926/LicensePlist
|
refs/heads/main
|
Tests/LicensePlistTests/Entity/FileReader/SwiftPackageFileReaderTests.swift
|
mit
|
1
|
//
// SwiftPackageFileReaderTests.swift
// LicensePlistTests
//
// Created by yosshi4486 on 2021/04/06.
//
import XCTest
@testable import LicensePlistCore
class SwiftPackageFileReaderTests: XCTestCase {
var fileURL: URL!
var packageResolvedText: String {
return #"""
{
"object": {
"pins": [
{
"package": "APIKit",
"repositoryURL": "https://github.com/ishkawa/APIKit.git",
"state": {
"branch": null,
"revision": "4e7f42d93afb787b0bc502171f9b5c12cf49d0ca",
"version": "5.3.0"
}
},
{
"package": "Flatten",
"repositoryURL": "https://github.com/YusukeHosonuma/Flatten.git",
"state": {
"branch": null,
"revision": "5286148aa255f57863e0d7e2b827ca6b91677051",
"version": "0.1.0"
}
},
{
"package": "HeliumLogger",
"repositoryURL": "https://github.com/Kitura/HeliumLogger.git",
"state": {
"branch": null,
"revision": "fc2a71597ae974da5282d751bcc11965964bccce",
"version": "2.0.0"
}
},
{
"package": "LoggerAPI",
"repositoryURL": "https://github.com/Kitura/LoggerAPI.git",
"state": {
"branch": null,
"revision": "4e6b45e850ffa275e8e26a24c6454fd709d5b6ac",
"version": "2.0.0"
}
},
{
"package": "SHList",
"repositoryURL": "https://github.com/YusukeHosonuma/SHList.git",
"state": {
"branch": null,
"revision": "6c61f5382dd07a64d76bc8b7fad8cec0d8a4ff7a",
"version": "0.1.0"
}
},
{
"package": "swift-argument-parser",
"repositoryURL": "https://github.com/apple/swift-argument-parser.git",
"state": {
"branch": null,
"revision": "9f39744e025c7d377987f30b03770805dcb0bcd1",
"version": "1.1.4"
}
},
{
"package": "HTMLEntities",
"repositoryURL": "https://github.com/Kitura/swift-html-entities.git",
"state": {
"branch": null,
"revision": "d8ca73197f59ce260c71bd6d7f6eb8bbdccf508b",
"version": "4.0.1"
}
},
{
"package": "swift-log",
"repositoryURL": "https://github.com/apple/swift-log.git",
"state": {
"branch": null,
"revision": "5d66f7ba25daf4f94100e7022febf3c75e37a6c7",
"version": "1.4.2"
}
},
{
"package": "SwiftParamTest",
"repositoryURL": "https://github.com/YusukeHosonuma/SwiftParamTest",
"state": {
"branch": null,
"revision": "f513e1dbbdd86e2ca2b672537f4bcb4417f94c27",
"version": "2.2.1"
}
},
{
"package": "Yaml",
"repositoryURL": "https://github.com/behrang/YamlSwift.git",
"state": {
"branch": null,
"revision": "287f5cab7da0d92eb947b5fd8151b203ae04a9a3",
"version": "3.4.4"
}
}
]
},
"version": 1
}
"""#
}
override func setUpWithError() throws {
fileURL = URL(fileURLWithPath: "\(TestUtil.testProjectsPath)/SwiftPackageManagerTestProject/SwiftPackageManagerTestProject.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved")
}
override func tearDownWithError() throws {
fileURL = nil
}
func testInvalidPath() throws {
let invalidFilePath = fileURL.deletingLastPathComponent().appendingPathComponent("Podfile.lock")
let reader = SwiftPackageFileReader(path: invalidFilePath)
XCTAssertThrowsError(try reader.read())
}
func testPackageSwift() throws {
// Path for this package's Package.swift.
let packageSwiftPath = TestUtil.sourceDir.appendingPathComponent("Package.swift").lp.fileURL
let reader = SwiftPackageFileReader(path: packageSwiftPath)
XCTAssertEqual(
try reader.read()?.trimmingCharacters(in: .whitespacesAndNewlines),
packageResolvedText.trimmingCharacters(in: .whitespacesAndNewlines)
)
}
func testPackageResolved() throws {
// Path for this package's Package.resolved.
let packageResolvedPath = TestUtil.sourceDir.appendingPathComponent("Package.resolved").lp.fileURL
let reader = SwiftPackageFileReader(path: packageResolvedPath)
XCTAssertEqual(
try reader.read()?.trimmingCharacters(in: .whitespacesAndNewlines),
packageResolvedText.trimmingCharacters(in: .whitespacesAndNewlines)
)
}
}
|
6030245b16d3d6814c41ea5cf7327df3
| 34.675497 | 200 | 0.501021 | false | true | false | false |
fangspeen/swift-linear-algebra
|
refs/heads/master
|
LinearAlgebra/main.swift
|
bsd-2-clause
|
1
|
//
// main.swift
// LinearAlgebra
//
// Created by Jean Blignaut on 2015/03/21.
// Copyright (c) 2015 Jean Blignaut. All rights reserved.
//
import Foundation
import Accelerate
let a: Array<Double> = [1,2,3,4]
let b: Array<Double> = [1,2,3]
var A = la_object_t()
var B = la_object_t()
a.withUnsafeBufferPointer{ (buffer: UnsafeBufferPointer<Double>) -> Void in
//should have been short hand for below but some how doesn't work in swift
//A = la_vector_from_double_buffer(buffer.baseAddress, la_count_t(4), la_count_t(1), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
A = la_matrix_from_double_buffer(buffer.baseAddress, la_count_t(a.count), la_count_t(1), la_count_t(1), la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
}
b.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<Double>) -> Void in
//should have been short hand for below but some how doesn't work in swift
//B = la_vector_from_double_buffer(buffer.baseAddress, la_count_t(4), la_count_t(1), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
//I would have expected that the transpose would be required but seems oiptional
B = //la_transpose(
la_matrix_from_double_buffer(buffer.baseAddress, la_count_t(b.count), la_count_t(1), la_count_t(1), la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES))//)
}
let res = la_solve(A,B)
let mult = la_outer_product(A, B)
var buf: Array<Double> = [0,0,0
,0,0,0
,0,0,0
,0,0,0]
buf.withUnsafeMutableBufferPointer {
(inout buffer: UnsafeMutableBufferPointer<Double>) -> Void in
la_matrix_to_double_buffer(buffer.baseAddress, la_count_t(3), mult)
}
//contents of a
println(a)
//contents of b
println(b)
//seems to be the dimensions of the vector in A
print(A)
//seems to be the dimensions of the vector in B
print(B)
//seems to be the dimensions of the resultant matrix
print(mult)
//result
println(buf)
|
b363bdfd1c7bf21129b07f2ea69ef607
| 32.482759 | 172 | 0.678682 | false | false | false | false |
IcyButterfly/JSONFactory
|
refs/heads/master
|
JSONConverter/JSON/JSONAssembler.swift
|
mit
|
1
|
//
// JSONAssembler.swift
// JSONConverter
//
// Created by ET|冰琳 on 2017/3/2.
// Copyright © 2017年 IB. All rights reserved.
//
import Foundation
protocol JSONAssembler {
static func assemble(jsonInfo: JSONInfo) -> String
}
extension JSONAssembler {
static func assemble(jsonInfos: [JSONInfo]) -> String {
let count = jsonInfos.count
let last = jsonInfos[count - 1]
var code = MappingAceAssembler.assemble(jsonInfo: last)
for index in 0..<(count - 1) {
code += "\n\n"
let jsonInfo = jsonInfos[index]
code += MappingAceAssembler.assemble(jsonInfo: jsonInfo)
}
return code
}
static func assemble(jsonInfos: [JSONInfo], to filePath: String) {
let txt = assemble(jsonInfos: jsonInfos)
do {
try txt.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
print("write to file suceed\n[Path]: \(filePath)")
}catch (let e) {
print("write to file failed\n[Path]: \(filePath)\n[Error]: \(e)")
}
}
static func assemble(jsonInfos: [JSONInfo], toDocument: String){
let date = Date()
let dateFormate = DateFormatter()
dateFormate.dateFormat = "yyyy/M/d"
let time = dateFormate.string(from: date)
for item in jsonInfos {
let title = "//\n" +
"// \(item.name!).swift\n" +
"//\n" +
"// created by JSONConverter on \(time)" +
"\n\n\n"
let txt = title + assemble(jsonInfo: item)
let filePath = toDocument + "/\(item.name!).swift"
do {
try txt.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
print("write to file suceed\n[Path]: \(filePath)")
}catch (let e) {
print("write to file failed\n[Path]: \(filePath)\n[Error]: \(e)")
}
}
}
}
struct MappingAceAssembler: JSONAssembler {
static func assemble(jsonInfo: JSONInfo) -> String {
let name = jsonInfo.name!
var code = "public struct \(name): Mapping {\n"
for property in jsonInfo.properties.sorted(by: { (a, b) -> Bool in a.name < b.name }) {
let name = property.name
let type = property.isRequired ? property.type : "\(property.type)?"
let defaultValue: String
if let defaultV = property.defaultValue {
defaultValue = " = \(defaultV)"
code = "public struct \(name): InitMapping {\n"
}
else {
defaultValue = ""
}
let desc: String
if let description = property.description {
desc = "//\(description)"
}else {
desc = ""
}
code += " public var \(name): \(type)\(defaultValue)? \(desc)\n"
}
code += "}\n"
return code
}
}
|
6350ba9994a8417b57af94d08d5e8ff0
| 26.429752 | 97 | 0.480265 | false | false | false | false |
Brightify/DataMapper
|
refs/heads/master
|
Tests/TestUtils/TestData.swift
|
mit
|
1
|
//
// TestData.swift
// DataMapper
//
// Created by Filip Dolnik on 01.01.17.
// Copyright © 2017 Brightify. All rights reserved.
//
import DataMapper
import Nimble
struct TestData {
static let deserializableStruct = DeserializableStruct(number: 1, text: "a", points: [2], children: [])
static let mappableStruct = MappableStruct(number: 1, text: "a", points: [2], children: [])
static let mappableClass = MappableClass(number: 1, text: "a", points: [2], children: [])
static let serializableStruct = SerializableStruct(number: 1, text: "a", points: [2], children: [])
static let type = SupportedType.dictionary(["number": .int(1), "text": .string("a"), "points": .array([.double(2)]), "children": .array([])])
static let invalidType = SupportedType.dictionary(["number": .int(1)])
// Returned elements == Floor[ x! * e ]
static func generate(x: Int) -> PerformanceStruct {
var object = PerformanceStruct(number: 0, text: "0", points: [], children: [], dictionary: ["A": false, "B": true])
for i in 1...x {
object = PerformanceStruct(number: i, text: "\(i)", points: (1...i).map { Double($0) },
children: (1...i).map { _ in object }, dictionary: ["A": false, "B": true])
}
return object
}
struct PerformanceStruct: Mappable, Codable {
private(set) var number: Int?
private(set) var text: String = ""
private(set) var points: [Double] = []
private(set) var children: [PerformanceStruct] = []
let dictionary: [String: Bool]
init(number: Int?, text: String, points: [Double], children: [PerformanceStruct], dictionary: [String: Bool]) {
self.number = number
self.text = text
self.points = points
self.children = children
self.dictionary = dictionary
}
init(_ data: DeserializableData) throws {
dictionary = try data["dictionary"].get()
try mapping(data)
}
func serialize(to data: inout SerializableData) {
data["dictionary"].set(dictionary)
mapping(&data)
}
mutating func mapping(_ data: inout MappableData) throws {
data["number"].map(&number)
try data["text"].map(&text)
data["points"].map(&points, or: [])
data["children"].map(&children, or: [])
}
}
struct DeserializableStruct: Deserializable {
let number: Int?
let text: String
let points: [Double]
let children: [MappableStruct]
init(number: Int?, text: String, points: [Double], children: [MappableStruct]) {
self.number = number
self.text = text
self.points = points
self.children = children
}
init(_ data: DeserializableData) throws {
number = data["number"].get()
text = try data["text"].get()
points = data["points"].get(or: [])
children = data["children"].get(or: [])
}
}
struct MappableStruct: Mappable {
private(set) var number: Int?
private(set) var text: String = ""
private(set) var points: [Double] = []
private(set) var children: [MappableStruct] = []
init(number: Int?, text: String, points: [Double], children: [MappableStruct]) {
self.number = number
self.text = text
self.points = points
self.children = children
}
init(_ data: DeserializableData) throws {
try mapping(data)
}
mutating func mapping(_ data: inout MappableData) throws {
data["number"].map(&number)
try data["text"].map(&text)
data["points"].map(&points, or: [])
data["children"].map(&children, or: [])
}
}
class MappableClass: Mappable {
let number: Int?
private(set) var text: String = ""
private(set) var points: [Double] = []
private(set) var children: [MappableStruct] = []
init(number: Int?, text: String, points: [Double], children: [MappableStruct]) {
self.number = number
self.text = text
self.points = points
self.children = children
}
required init(_ data: DeserializableData) throws {
number = data["number"].get()
try mapping(data)
}
func serialize(to data: inout SerializableData) {
mapping(&data)
data["number"].set(number)
}
func mapping(_ data: inout MappableData) throws {
try data["text"].map(&text)
data["points"].map(&points, or: [])
data["children"].map(&children, or: [])
}
}
struct SerializableStruct: Serializable {
let number: Int?
let text: String
let points: [Double]
let children: [MappableStruct]
init(number: Int?, text: String, points: [Double], children: [MappableStruct]) {
self.number = number
self.text = text
self.points = points
self.children = children
}
func serialize(to data: inout SerializableData) {
data["number"].set(number)
data["text"].set(text)
data["points"].set(points)
data["children"].set(children)
}
}
struct Map {
static let validType = SupportedType.dictionary([
"value": .int(1),
"array": .array([.int(1), .int(2)]),
"dictionary": .dictionary(["a": .int(1), "b": .int(2)]),
"optionalArray": .array([.int(1), .null]),
"optionalDictionary": .dictionary(["a": .int(1), "b": .null]),
])
static let invalidType = SupportedType.dictionary([
"value": .double(1),
"array": .array([.double(1), .int(2)]),
"dictionary": .dictionary(["a": .double(1), "b": .int(2)]),
"optionalArray": .double(1),
"optionalDictionary": .null
])
static let nullType = SupportedType.dictionary([
"value": .null,
"array": .null,
"dictionary": .null,
"optionalArray": .null,
"optionalDictionary": .null,
])
static let pathType = SupportedType.dictionary(["a": .dictionary(["b": .int(1)])])
static func assertValidType(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?,
_ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) {
expect(value, file: file, line: line) == 1
expect(array, file: file, line: line) == [1, 2]
expect(dictionary, file: file, line: line) == ["a": 1, "b": 2]
expect(areEqual(optionalArray, [1, nil]), file: file, line: line).to(beTrue())
expect(areEqual(optionalDictionary, ["a": 1, "b": nil]), file: file, line: line).to(beTrue())
}
static func assertValidTypeUsingTransformation(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?,
_ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) {
expect(value, file: file, line: line) == 2
expect(array, file: file, line: line) == [2, 4]
expect(dictionary, file: file, line: line) == ["a": 2, "b": 4]
expect(areEqual(optionalArray, [2, nil]), file: file, line: line).to(beTrue())
expect(areEqual(optionalDictionary, ["a": 2, "b": nil]), file: file, line: line).to(beTrue())
}
static func assertInvalidTypeOr(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?,
_ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) {
expect(value, file: file, line: line) == 0
expect(array, file: file, line: line) == [0]
expect(dictionary, file: file, line: line) == ["a": 0]
expect(areEqual(optionalArray, [0]), file: file, line: line).to(beTrue())
expect(areEqual(optionalDictionary, ["a": 0]), file: file, line: line).to(beTrue())
}
static func assertInvalidType(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?,
_ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) {
expect(value, file: file, line: line).to(beNil())
expect(array, file: file, line: line).to(beNil())
expect(dictionary, file: file, line: line).to(beNil())
expect(optionalArray, file: file, line: line).to(beNil())
expect(optionalDictionary, file: file, line: line).to(beNil())
}
}
struct StaticPolymorph {
class A: Polymorphic {
class var polymorphicKey: String {
return "K"
}
class var polymorphicInfo: PolymorphicInfo {
return createPolymorphicInfo().with(subtype: B.self)
}
}
class B: A {
override class var polymorphicInfo: PolymorphicInfo {
// D is intentionally registered here.
return createPolymorphicInfo().with(subtypes: C.self, D.self)
}
}
class C: B {
override class var polymorphicKey: String {
return "C"
}
}
class D: C {
override class var polymorphicInfo: PolymorphicInfo {
return createPolymorphicInfo(name: "D2")
}
}
// Intentionally not registered.
class E: D {
}
class X {
}
}
struct PolymorphicTypes {
static let a = A(id: 1)
static let b = B(id: 2, name: "name")
static let c = C(id: 3, number: 0)
static let aType = SupportedType.dictionary(["id": .int(1), "type": .string("A")])
static let bType = SupportedType.dictionary(["id": .int(2), "name": .string("name"), "type": .string("B")])
static let cType = SupportedType.dictionary(["id": .int(3), "number": .int(0), "type": .string("C")])
static let aTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(1)])
static let bTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(2), "name": .string("name")])
static let cTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(3), "number": .int(0)])
class A: PolymorphicMappable {
static var polymorphicKey = "type"
static var polymorphicInfo: PolymorphicInfo {
return createPolymorphicInfo().with(subtypes: B.self, C.self)
}
let id: Int
init(id: Int) {
self.id = id
}
required init(_ data: DeserializableData) throws {
id = try data["id"].get()
try mapping(data)
}
func serialize(to data: inout SerializableData) {
data["id"].set(id)
mapping(&data)
}
func mapping(_ data: inout MappableData) throws {
}
}
class B: A {
var name: String?
init(id: Int, name: String?) {
super.init(id: id)
self.name = name
}
required init(_ data: DeserializableData) throws {
try super.init(data)
}
override func mapping(_ data: inout MappableData) throws {
try super.mapping(&data)
data["name"].map(&name)
}
}
class C: A {
var number: Int?
init(id: Int, number: Int?) {
super.init(id: id)
self.number = number
}
required init(_ data: DeserializableData) throws {
try super.init(data)
}
override func mapping(_ data: inout MappableData) throws {
try super.mapping(&data)
data["number"].map(&number)
}
}
}
struct CustomIntTransformation: Transformation {
typealias Object = Int
func transform(from value: SupportedType) -> Int? {
return value.int.map { $0 * 2 } ?? nil
}
func transform(object: Int?) -> SupportedType {
return object.map { .int($0 / 2) } ?? .null
}
}
}
extension TestData.PerformanceStruct: Equatable {
}
func ==(lhs: TestData.PerformanceStruct, rhs: TestData.PerformanceStruct) -> Bool {
return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children && lhs.dictionary == rhs.dictionary
}
extension TestData.DeserializableStruct: Equatable {
}
func ==(lhs: TestData.DeserializableStruct, rhs: TestData.DeserializableStruct) -> Bool {
return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children
}
extension TestData.MappableStruct: Equatable {
}
func ==(lhs: TestData.MappableStruct, rhs: TestData.MappableStruct) -> Bool {
return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children
}
extension TestData.MappableClass: Equatable {
}
func ==(lhs: TestData.MappableClass, rhs: TestData.MappableClass) -> Bool {
return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children
}
extension TestData.SerializableStruct: Equatable {
}
func ==(lhs: TestData.SerializableStruct, rhs: TestData.SerializableStruct) -> Bool {
return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children
}
func areEqual(_ lhs: [Int?]?, _ rhs: [Int?]?) -> Bool {
if let lhs = lhs, let rhs = rhs {
if lhs.count == rhs.count {
for i in lhs.indices {
if lhs[i] != rhs[i] {
return false
}
}
return true
}
}
return lhs == nil && rhs == nil
}
func areEqual(_ lhs: [String: Int?]?, _ rhs: [String: Int?]?) -> Bool {
if let lhs = lhs, let rhs = rhs {
if lhs.count == rhs.count {
for i in lhs.keys {
if let lValue = lhs[i], let rValue = rhs[i], lValue == rValue {
continue
} else {
return false
}
}
return true
}
}
return lhs == nil && rhs == nil
}
|
d72f718979429f4133a356f31d7ca1e3
| 34.43018 | 155 | 0.508105 | false | false | false | false |
lyimin/EyepetizerApp
|
refs/heads/master
|
EyepetizerApp/EyepetizerApp/Views/VideoDetailView/EYEVideoDetailView.swift
|
mit
|
1
|
//
// EYEVideoDetailView.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/23.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
protocol EYEVideoDetailViewDelegate {
// 点击播放按钮
func playImageViewDidClick()
// 点击返回按钮
func backBtnDidClick()
}
class EYEVideoDetailView: UIView {
//MARK: --------------------------- Life Cycle --------------------------
override init(frame: CGRect) {
super.init(frame: frame)
self.clipsToBounds = true
self.addSubview(albumImageView)
self.addSubview(blurImageView)
self.addSubview(blurView)
self.addSubview(backBtn)
self.addSubview(playImageView)
self.addSubview(videoTitleLabel)
self.addSubview(lineView)
self.addSubview(classifyLabel)
self.addSubview(describeLabel)
self.addSubview(bottomToolView)
// 添加底部item
let itemSize: CGFloat = 80
for i in 0..<bottomImgArray.count {
let btn = BottomItemBtn(frame: CGRect(x: UIConstant.UI_MARGIN_15+CGFloat(i)*itemSize, y: 0, width: itemSize, height: bottomToolView.height), title: "0", image: bottomImgArray[i]!)
itemArray.append(btn)
bottomToolView.addSubview(btn)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var model : ItemModel! {
didSet {
// self.albumImageView.yy_setImageWithURL(NSURL(string: model.feed), placeholder: UIImage.colorImage(UIColor.lightGrayColor(), size: albumImageView.size))
// self.albumImageView.yy_setImageWithURL(NSURL(string: model.feed), options: .ProgressiveBlur)
self.blurImageView.yy_setImageWithURL(NSURL(string:model.feed), placeholder: UIImage(named: "7e42a62065ef37cfa233009fb364fd1e_0_0"))
videoTitleLabel.animationString = model.title
self.classifyLabel.text = model.subTitle
// 显示底部数据
self.itemArray.first?.setTitle("\(model.collectionCount)", forState: .Normal)
self.itemArray[1].setTitle("\(model.shareCount)", forState: .Normal)
self.itemArray[2].setTitle("\(model.replyCount)", forState: .Normal)
self.itemArray.last?.setTitle("缓存", forState: .Normal)
// 计算宽度
self.describeLabel.text = model.description
let size = self.describeLabel.boundingRectWithSize(describeLabel.size)
self.describeLabel.frame = CGRectMake(describeLabel.x, describeLabel.y, size.width, size.height)
}
}
//MARK: --------------------------- Event response --------------------------
/**
点击播放按钮
*/
@objc private func playImageViewDidClick() {
delegate.playImageViewDidClick()
}
/**
点击返回按钮
*/
@objc private func backBtnDidClick() {
delegate.backBtnDidClick()
}
//MARK: --------------------------- Getter or Setter --------------------------
// 代理
var delegate: EYEVideoDetailViewDelegate!
// 图片
lazy var albumImageView : UIImageView = {
// 图片大小 1242 x 777
// 6 621*388.5
// 5 621*388.5
let photoW : CGFloat = 1222.0
let photoH : CGFloat = 777.0
let albumImageViewH = self.height*0.6
let albumImageViewW = photoW*albumImageViewH/photoH
let albumImageViewX = (albumImageViewW-self.width)*0.5
// let imageViewH = self.width*photoH / UIConstant.IPHONE6_WIDTH
var albumImageView = UIImageView(frame: CGRect(x: -albumImageViewX, y: 0, width: albumImageViewW, height: albumImageViewH))
albumImageView.clipsToBounds = true
albumImageView.contentMode = .ScaleAspectFill
albumImageView.userInteractionEnabled = true
return albumImageView
}()
// 模糊背景
lazy var blurImageView : UIImageView = {
var blurImageView = UIImageView(frame: CGRect(x: 0, y: self.albumImageView.height, width: self.width, height: self.height-self.albumImageView.height))
return blurImageView
}()
lazy var blurView : UIVisualEffectView = {
let blurEffect : UIBlurEffect = UIBlurEffect(style: .Light)
var blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = self.blurImageView.frame
return blurView
}()
// 返回按钮
lazy var backBtn : UIButton = {
var backBtn = UIButton(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: UIConstant.UI_MARGIN_20, width: 40, height: 40))
backBtn.setImage(UIImage(named: "play_back_full"), forState: .Normal)
backBtn.addTarget(self, action: #selector(EYEVideoDetailView.backBtnDidClick), forControlEvents: .TouchUpInside)
return backBtn
}()
// 播放按钮
lazy var playImageView : UIImageView = {
var playImageView = UIImageView(image: UIImage(named: "ic_action_play"))
playImageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
playImageView.center = self.albumImageView.center
playImageView.contentMode = .ScaleAspectFit
playImageView.viewAddTarget(self, action: #selector(EYEVideoDetailView.playImageViewDidClick))
return playImageView
}()
// 标题
lazy var videoTitleLabel : EYEShapeView = {
let rect = CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.albumImageView.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 20)
let font = UIFont.customFont_FZLTZCHJW(fontSize: UIConstant.UI_FONT_16)
var videoTitleLabel = EYEShapeView(frame: rect)
videoTitleLabel.font = font
videoTitleLabel.fontSize = UIConstant.UI_FONT_16
return videoTitleLabel
}()
// 分割线
private lazy var lineView : UIView = {
var lineView = UIView(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.videoTitleLabel.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 0.5))
lineView.backgroundColor = UIColor.whiteColor()
return lineView
}()
// 分类/时间
lazy var classifyLabel : UILabel = {
var classifyLabel = UILabel(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.lineView.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 20))
classifyLabel.textColor = UIColor.whiteColor()
classifyLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: UIConstant.UI_FONT_13)
return classifyLabel
}()
// 描述
lazy var describeLabel : UILabel = {
var describeLabel = UILabel(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.classifyLabel.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 200))
describeLabel.numberOfLines = 0
describeLabel.textColor = UIColor.whiteColor()
describeLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: UIConstant.UI_FONT_13)
return describeLabel
}()
// 底部 喜欢 分享 评论 缓存
lazy var bottomToolView : UIView = {
var bottomToolView = UIView(frame: CGRect(x: 0, y: self.height-50, width: self.width, height: 30))
bottomToolView.backgroundColor = UIColor.clearColor()
return bottomToolView
}()
private var itemArray: [BottomItemBtn] = [BottomItemBtn]()
// 底部图片数组
private var bottomImgArray = [UIImage(named: "ic_action_favorites_without_padding"), UIImage(named: "ic_action_share_without_padding"), UIImage(named: "ic_action_reply_nopadding"), UIImage(named: "action_download_cut")]
/// 底部item
private class BottomItemBtn : UIButton {
// 标题
private var title: String!
// 图片
private var image: UIImage!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.titleLabel?.font = UIFont.customFont_FZLTXIHJW()
self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
}
convenience init(frame: CGRect, title: String, image: UIImage) {
self.init(frame: frame)
self.title = title
self.image = image
self.setImage(image, forState: .Normal)
self.setTitle(title, forState: .Normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
文字的frame
*/
private override func titleRectForContentRect(contentRect: CGRect) -> CGRect {
return CGRect(x: self.height-8, y: 0, width: self.width-self.height+8, height: self.height)
}
/**
图片的frame
*/
private override func imageRectForContentRect(contentRect: CGRect) -> CGRect {
return CGRect(x: 0, y: 8, width: self.height-16, height: self.height-16)
}
}
}
|
625a0e3fe855545fb9307e09a0e2adad
| 39.728507 | 223 | 0.63093 | false | false | false | false |
Lickability/PinpointKit
|
refs/heads/master
|
Examples/Pippin/Pods/PinpointKit/PinpointKit/PinpointKit/Sources/Core/BasicLogViewController.swift
|
mit
|
2
|
//
// BasicLogViewController.swift
// PinpointKit
//
// Created by Brian Capps on 2/5/16.
// Copyright © 2016 Lickability. All rights reserved.
//
import UIKit
/// The default view controller for the text log.
open class BasicLogViewController: UIViewController, LogViewer {
// MARK: - InterfaceCustomizable
open var interfaceCustomization: InterfaceCustomization? {
didSet {
title = interfaceCustomization?.interfaceText.logCollectorTitle
textView.font = interfaceCustomization?.appearance.logFont
}
}
// MARK: - BasicLogViewController
private let textView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.isEditable = false
textView.dataDetectorTypes = UIDataDetectorTypes()
return textView
}()
// MARK: - UIViewController
override open func viewDidLoad() {
super.viewDidLoad()
func setUpTextView() {
view.addSubview(textView)
textView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
textView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
textView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 0).isActive = true
textView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 0).isActive = true
}
setUpTextView()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.scrollRangeToVisible(NSRange(location: (textView.text as NSString).length, length: 0))
}
// MARK: - LogViewer
open func viewLog(in collector: LogCollector, from viewController: UIViewController) {
let logText = collector.retrieveLogs().joined(separator: "\n")
textView.text = logText
viewController.show(self, sender: viewController)
}
}
|
3fed6ea5d7e61b29dc439c94cc7be4bf
| 30.923077 | 103 | 0.655904 | false | false | false | false |
ello/ello-ios
|
refs/heads/master
|
Sources/Networking/UserService.swift
|
mit
|
1
|
////
/// UserService.swift
//
import Moya
import SwiftyJSON
import PromiseKit
struct UserService {
func join(
email: String,
username: String,
password: String,
invitationCode: String? = nil
) -> Promise<User> {
return ElloProvider.shared.request(
.join(
email: email,
username: username,
password: password,
invitationCode: invitationCode
)
)
.then { data, _ -> Promise<User> in
guard let user = data as? User else {
throw NSError.uncastableModel()
}
let promise: Promise<User> = CredentialsAuthService().authenticate(
email: email,
password: password
)
.map { _ -> User in
return user
}
return promise
}
}
func requestPasswordReset(email: String) -> Promise<()> {
return ElloProvider.shared.request(.requestPasswordReset(email: email))
.asVoid()
}
func resetPassword(password: String, authToken: String) -> Promise<User> {
return ElloProvider.shared.request(.resetPassword(password: password, authToken: authToken))
.map { user, _ -> User in
guard let user = user as? User else {
throw NSError.uncastableModel()
}
return user
}
}
func loadUser(_ endpoint: ElloAPI) -> Promise<User> {
return ElloProvider.shared.request(endpoint)
.map { data, responseConfig -> User in
guard let user = data as? User else {
throw NSError.uncastableModel()
}
Preloader().preloadImages([user])
return user
}
}
func loadUserPosts(_ userId: String) -> Promise<([Post], ResponseConfig)> {
return ElloProvider.shared.request(.userStreamPosts(userId: userId))
.map { data, responseConfig -> ([Post], ResponseConfig) in
let posts: [Post]?
if data as? String == "" {
posts = []
}
else if let foundPosts = data as? [Post] {
posts = foundPosts
}
else {
posts = nil
}
if let posts = posts {
Preloader().preloadImages(posts)
return (posts, responseConfig)
}
else {
throw NSError.uncastableModel()
}
}
}
}
|
d701576b235c2cece8ea6d7e51b09bf7
| 29.318681 | 100 | 0.470823 | false | true | false | false |
zhenghao58/On-the-road
|
refs/heads/master
|
OnTheRoadB/LocationPickerViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// OnTheRoadB
//
// Created by Cunqi.X on 14/10/24.
// Copyright (c) 2014年 CS9033. All rights reserved.
//
import UIKit
import MapKit
class LocationPickerViewController: UITableViewController, CLLocationManagerDelegate {
var locationDelegate: LocationInformationDelegate!
var locationManager:CLLocationManager!
var sections = ["Restaurants","Parks","Museums","Hotels","Attractions"]
var locationCategories = [
"Restaurants":[],
"Parks":[],
"Museums":[],
"Hotels":[],
"Attractions":[]
]
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() == false {
println("Can't get location")
}
self.locationManager = CLLocationManager();
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
let location = locations.last as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
var requests = [String:MKLocalSearchRequest]()
var searches = [String:MKLocalSearch]()
for (category, closestPlaces)in self.locationCategories{
requests[category] = MKLocalSearchRequest()
requests[category]!.region = region
requests[category]!.naturalLanguageQuery = category
searches[category] = MKLocalSearch(request: requests[category])
searches[category]!.startWithCompletionHandler { (response, error) in
self.locationCategories[category] = response.mapItems as [MKMapItem]
}
}
self.tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return self.locationCategories.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var category = self.locationCategories[self.sections[section]] as [MKMapItem]
return category.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let cell = self.tableView.dequeueReusableCellWithIdentifier("location", forIndexPath: indexPath) as UITableViewCell
let category = self.sections[indexPath.section]
let rows = self.locationCategories[category] as [MKMapItem]
cell.textLabel!.text = rows[row].name
let partOfAddress = rows[row].placemark.addressDictionary["FormattedAddressLines"] as? NSArray
cell.detailTextLabel!.text = mergeToAddress(partOfAddress!)
return cell
}
private func mergeToAddress(partOfAddress: NSArray)-> String {
let result = NSMutableString()
for element in partOfAddress {
result.appendString(element as String)
}
return result.description
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row
let category = self.sections[indexPath.section]
let rows = self.locationCategories[category] as [MKMapItem]
let placemark = rows[row].placemark as MKPlacemark
var location = [String: AnyObject]()
location["name"] = placemark.name
location["address"] = placemark.addressDictionary["FormattedAddressLines"]
location["location"] = placemark.location
locationDelegate.setCurrentLocation(location)
self.navigationController?.popViewControllerAnimated(true)
}
}
|
86e8b79b6fdd50d99e5c87fa25b0f354
| 34.353448 | 125 | 0.701536 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/CryptoAssets/Sources/EthereumKit/Services/Activity/EthereumActivityItemEventDetails.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import PlatformKit
public struct EthereumActivityItemEventDetails: Equatable {
public struct Confirmation: Equatable {
public let needConfirmation: Bool
public let confirmations: Int
public let requiredConfirmations: Int
public let factor: Float
public let status: EthereumTransactionState
}
public let amount: CryptoValue
public let confirmation: Confirmation
public let createdAt: Date
public let data: String?
public let fee: CryptoValue
public let from: EthereumAddress
public let identifier: String
public let to: EthereumAddress
init(transaction: EthereumHistoricalTransaction) {
amount = transaction.amount
createdAt = transaction.createdAt
data = transaction.data
fee = transaction.fee ?? .zero(currency: .ethereum)
from = transaction.fromAddress
identifier = transaction.transactionHash
to = transaction.toAddress
confirmation = Confirmation(
needConfirmation: transaction.state == .pending,
confirmations: transaction.confirmations,
requiredConfirmations: EthereumHistoricalTransaction.requiredConfirmations,
factor: Float(transaction.confirmations) / Float(EthereumHistoricalTransaction.requiredConfirmations),
status: transaction.state
)
}
}
|
08044ca8e99fb187c463d3ce2b29e2fe
| 34.560976 | 114 | 0.707819 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/Lumia/Lumia/Component/Parade/Sources/ParadeExtensions/UIScrollView+Parade.swift
|
mit
|
1
|
//
// UIScrollView+PDAnimation.swift
// PDAnimator-Demo
//
// Created by Anton Doudarev on 4/2/18.
// Copyright © 2018 ELEPHANT. All rights reserved.
//
import Foundation
import UIKit
/// This swizzles methods on a specific class.
/// Note: Don't got get the call the swizzled method
/// to ensure the original selector gets called
///
/// - Parameters:
/// - cls: slass to swizzle methods in
/// - originalSelector: the original method
/// - swizzledSelector: the swizzled method
func swizzleSelector(_ cls: AnyClass!, originalSelector : Selector, swizzledSelector : Selector)
{
let originalMethod = class_getInstanceMethod(cls, originalSelector)
let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector)
method_exchangeImplementations(originalMethod!, swizzledMethod!);
}
// MARK: - UIScrollViewv - ContentOffset Swizzle
extension UIScrollView {
/// Call this method to initialize the contentOffset highjacking
final public class func initializeParade()
{
swizzleSelector(self,
originalSelector: #selector(UIScrollView.setContentOffset(_:animated:)),
swizzledSelector: #selector(UIScrollView.swizzledSetContentOffset(_:animated:)))
swizzleSelector(self,
originalSelector: #selector(getter : UIScrollView.contentOffset),
swizzledSelector: #selector(getter : UIScrollView.swizzledContentOffset))
swizzleSelector(self,
originalSelector: #selector(setter: UIScrollView.contentOffset),
swizzledSelector: #selector(UIScrollView.swizzledSetContentOffset(_:)))
}
/// The swizzled contentOffset property
@objc public var swizzledContentOffset: CGPoint
{
get {
return self.swizzledContentOffset // not recursive, false warning
}
}
/// The swizzed ContentOffset method (2 input parameters)
@objc public func swizzledSetContentOffset(_ contentOffset : CGPoint, animated: Bool)
{
swizzledSetContentOffset(contentOffset, animated: animated)
updateViews()
}
/// The swizzed ContentOffset method (1 input setter)
@objc public func swizzledSetContentOffset(_ contentOffset: CGPoint)
{
swizzledSetContentOffset(contentOffset) // not recursive
updateViews()
}
}
extension UIScrollView {
/// This is called by the swizzled method
func updateViews()
{
var views : [UIView] = [UIView]()
if let collectionSelf = self as? UICollectionView
{
views = collectionSelf.visibleCells
}
else if let collectionSelf = self as? UITableView
{
views = collectionSelf.visibleCells
}
else {
views = subviews
}
for view in views {
guard let animatableObject = view as? PDAnimatableType else {
continue
}
var progressAnimator : PDAnimator? = view.cachedProgressAnimator
if progressAnimator == nil {
view.cachedProgressAnimator = animatableObject.configuredAnimator()
progressAnimator = view.cachedProgressAnimator!
}
let relativeCenter = self.convert(view.center, to: UIScreen.main.coordinateSpace)
switch progressAnimator!.animationDirection {
case .vertical:
if let progress = verticalProgress(at: relativeCenter,
to : self.bounds.height) {
progressAnimator!.interpolateViewAnimation(forProgress: progress)
}
case .horizontal:
if let progress = horizontalProgress(at: relativeCenter,
to : self.bounds.width) {
progressAnimator!.interpolateViewAnimation(forProgress: progress)
}
}
}
}
}
let centerThreshHold : CGFloat = 0.0005
extension UIScrollView {
internal func verticalProgress(at relativeCenter : CGPoint,
to viewportHeight: CGFloat) -> PDScrollProgressType?
{
let relativePercent : CGFloat = relativeProgress(at: relativeCenter.y, to: viewportHeight)!
if relativePercent < -centerThreshHold
{
return .verticalAboveCenter(progress : (1.0 + relativePercent))
}
else if relativePercent > centerThreshHold
{
return .verticalBelowCenter(progress : (1.0 - relativePercent))
}
return .verticalCenter
}
internal func horizontalProgress(at relativeCenter : CGPoint,
to viewportWidth: CGFloat) -> PDScrollProgressType?
{
let relativePercent : CGFloat = relativeProgress(at: relativeCenter.x, to: viewportWidth)!
if relativePercent < -centerThreshHold
{
return .horizontalLeftCenter(progress : (1.0 + relativePercent))
}
else if relativePercent > centerThreshHold
{
return .horizontalRightCenter(progress : (1.0 - relativePercent))
}
return .horizontalCenter
}
internal func relativeProgress(at progressValue : CGFloat,
to relativeValue: CGFloat) -> CGFloat? {
let relativePercent = (progressValue - (relativeValue / 2.0)) / relativeValue
if relativePercent == 0.0 { return 0.0 }
if relativePercent <= -1.0 { return -1.0 }
if relativePercent >= 1.0 { return 1.0 }
return relativePercent
}
}
|
92b3766ba8a7ad86f4fe6831c464a483
| 32.568182 | 104 | 0.595802 | false | false | false | false |
grpc/grpc-swift
|
refs/heads/main
|
Sources/protoc-gen-grpc-swift/Generator-Client+AsyncAwait.swift
|
apache-2.0
|
1
|
/*
* Copyright 2021, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import SwiftProtobuf
import SwiftProtobufPluginLibrary
// MARK: - Client protocol
extension Generator {
internal func printAsyncServiceClientProtocol() {
let comments = self.service.protoSourceComments()
if !comments.isEmpty {
// Source comments already have the leading '///'
self.println(comments, newline: false)
}
self.printAvailabilityForAsyncAwait()
self.println("\(self.access) protocol \(self.asyncClientProtocolName): GRPCClient {")
self.withIndentation {
self.println("static var serviceDescriptor: GRPCServiceDescriptor { get }")
self.println("var interceptors: \(self.clientInterceptorProtocolName)? { get }")
for method in service.methods {
self.println()
self.method = method
let rpcType = streamingType(self.method)
let callType = Types.call(for: rpcType)
let arguments: [String]
switch rpcType {
case .unary, .serverStreaming:
arguments = [
"_ request: \(self.methodInputName)",
"callOptions: \(Types.clientCallOptions)?",
]
case .clientStreaming, .bidirectionalStreaming:
arguments = [
"callOptions: \(Types.clientCallOptions)?",
]
}
self.printFunction(
name: self.methodMakeFunctionCallName,
arguments: arguments,
returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
bodyBuilder: nil
)
}
}
self.println("}") // protocol
}
}
// MARK: - Client protocol default implementation: Calls
extension Generator {
internal func printAsyncClientProtocolExtension() {
self.printAvailabilityForAsyncAwait()
self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) {
// Service descriptor.
self.withIndentation(
"\(self.access) static var serviceDescriptor: GRPCServiceDescriptor",
braces: .curly
) {
self.println("return \(self.serviceClientMetadata).serviceDescriptor")
}
self.println()
// Interceptor factory.
self.withIndentation(
"\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?",
braces: .curly
) {
self.println("return nil")
}
// 'Unsafe' calls.
for method in self.service.methods {
self.println()
self.method = method
let rpcType = streamingType(self.method)
let callType = Types.call(for: rpcType)
let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false)
switch rpcType {
case .unary, .serverStreaming:
self.printFunction(
name: self.methodMakeFunctionCallName,
arguments: [
"_ request: \(self.methodInputName)",
"callOptions: \(Types.clientCallOptions)? = nil",
],
returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
access: self.access
) {
self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) {
self.println("path: \(self.methodPathUsingClientMetadata),")
self.println("request: request,")
self.println("callOptions: callOptions ?? self.defaultCallOptions,")
self.println(
"interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
)
}
}
case .clientStreaming, .bidirectionalStreaming:
self.printFunction(
name: self.methodMakeFunctionCallName,
arguments: ["callOptions: \(Types.clientCallOptions)? = nil"],
returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
access: self.access
) {
self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) {
self.println("path: \(self.methodPathUsingClientMetadata),")
self.println("callOptions: callOptions ?? self.defaultCallOptions,")
self.println(
"interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
)
}
}
}
}
}
}
}
// MARK: - Client protocol extension: "Simple, but safe" call wrappers.
extension Generator {
internal func printAsyncClientProtocolSafeWrappersExtension() {
self.printAvailabilityForAsyncAwait()
self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) {
for (i, method) in self.service.methods.enumerated() {
self.method = method
let rpcType = streamingType(self.method)
let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false)
let streamsResponses = [.serverStreaming, .bidirectionalStreaming].contains(rpcType)
let streamsRequests = [.clientStreaming, .bidirectionalStreaming].contains(rpcType)
// (protocol, requires sendable)
let sequenceProtocols: [(String, Bool)?] = streamsRequests
? [("Sequence", false), ("AsyncSequence", true)]
: [nil]
for (j, sequenceProtocol) in sequenceProtocols.enumerated() {
// Print a new line if this is not the first function in the extension.
if i > 0 || j > 0 {
self.println()
}
let functionName = streamsRequests
? "\(self.methodFunctionName)<RequestStream>"
: self.methodFunctionName
let requestParamName = streamsRequests ? "requests" : "request"
let requestParamType = streamsRequests ? "RequestStream" : self.methodInputName
let returnType = streamsResponses
? Types.responseStream(of: self.methodOutputName)
: self.methodOutputName
let maybeWhereClause = sequenceProtocol.map { protocolName, mustBeSendable -> String in
let constraints = [
"RequestStream: \(protocolName)" + (mustBeSendable ? " & Sendable" : ""),
"RequestStream.Element == \(self.methodInputName)",
]
return "where " + constraints.joined(separator: ", ")
}
self.printFunction(
name: functionName,
arguments: [
"_ \(requestParamName): \(requestParamType)",
"callOptions: \(Types.clientCallOptions)? = nil",
],
returnType: returnType,
access: self.access,
async: !streamsResponses,
throws: !streamsResponses,
genericWhereClause: maybeWhereClause
) {
self.withIndentation(
"return\(!streamsResponses ? " try await" : "") self.perform\(callTypeWithoutPrefix)",
braces: .round
) {
self.println("path: \(self.methodPathUsingClientMetadata),")
self.println("\(requestParamName): \(requestParamName),")
self.println("callOptions: callOptions ?? self.defaultCallOptions,")
self.println(
"interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
)
}
}
}
}
}
}
}
// MARK: - Client protocol implementation
extension Generator {
internal func printAsyncServiceClientImplementation() {
self.printAvailabilityForAsyncAwait()
self.withIndentation(
"\(self.access) struct \(self.asyncClientStructName): \(self.asyncClientProtocolName)",
braces: .curly
) {
self.println("\(self.access) var channel: GRPCChannel")
self.println("\(self.access) var defaultCallOptions: CallOptions")
self.println("\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?")
self.println()
self.println("\(self.access) init(")
self.withIndentation {
self.println("channel: GRPCChannel,")
self.println("defaultCallOptions: CallOptions = CallOptions(),")
self.println("interceptors: \(self.clientInterceptorProtocolName)? = nil")
}
self.println(") {")
self.withIndentation {
self.println("self.channel = channel")
self.println("self.defaultCallOptions = defaultCallOptions")
self.println("self.interceptors = interceptors")
}
self.println("}")
}
}
}
|
d960790c41730ec2a3345dcb7d07af96
| 36.160494 | 100 | 0.620155 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
stdlib/public/core/CString.swift
|
apache-2.0
|
14
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// String interop with C
//===----------------------------------------------------------------------===//
import SwiftShims
extension String {
/// Creates a new string by copying the null-terminated UTF-8 data referenced
/// by the given pointer.
///
/// If `cString` contains ill-formed UTF-8 code unit sequences, this
/// initializer replaces them with the Unicode replacement character
/// (`"\u{FFFD}"`).
///
/// The following example calls this initializer with pointers to the
/// contents of two different `CChar` arrays---the first with well-formed
/// UTF-8 code unit sequences and the second with an ill-formed sequence at
/// the end.
///
/// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(cString: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Café"
///
/// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(cString: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Caf�"
///
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
public init(cString: UnsafePointer<CChar>) {
let len = UTF8._nullCodeUnitOffset(in: cString)
self = String._fromUTF8Repairing(
UnsafeBufferPointer(start: cString._asUInt8, count: len)).0
}
/// Creates a new string by copying the null-terminated UTF-8 data referenced
/// by the given pointer.
///
/// This is identical to `init(cString: UnsafePointer<CChar>)` but operates on
/// an unsigned sequence of bytes.
public init(cString: UnsafePointer<UInt8>) {
let len = UTF8._nullCodeUnitOffset(in: cString)
self = String._fromUTF8Repairing(
UnsafeBufferPointer(start: cString, count: len)).0
}
/// Creates a new string by copying and validating the null-terminated UTF-8
/// data referenced by the given pointer.
///
/// This initializer does not try to repair ill-formed UTF-8 code unit
/// sequences. If any are found, the result of the initializer is `nil`.
///
/// The following example calls this initializer with pointers to the
/// contents of two different `CChar` arrays---the first with well-formed
/// UTF-8 code unit sequences and the second with an ill-formed sequence at
/// the end.
///
/// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(validatingUTF8: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Optional("Café")"
///
/// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(validatingUTF8: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "nil"
///
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
public init?(validatingUTF8 cString: UnsafePointer<CChar>) {
let len = UTF8._nullCodeUnitOffset(in: cString)
guard let str = String._tryFromUTF8(
UnsafeBufferPointer(start: cString._asUInt8, count: len))
else { return nil }
self = str
}
/// Creates a new string by copying the null-terminated data referenced by
/// the given pointer using the specified encoding.
///
/// When you pass `true` as `isRepairing`, this method replaces ill-formed
/// sequences with the Unicode replacement character (`"\u{FFFD}"`);
/// otherwise, an ill-formed sequence causes this method to stop decoding
/// and return `nil`.
///
/// The following example calls this method with pointers to the contents of
/// two different `CChar` arrays---the first with well-formed UTF-8 code
/// unit sequences and the second with an ill-formed sequence at the end.
///
/// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String.decodeCString(ptr.baseAddress,
/// as: UTF8.self,
/// repairingInvalidCodeUnits: true)
/// print(s)
/// }
/// // Prints "Optional((result: "Café", repairsMade: false))"
///
/// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String.decodeCString(ptr.baseAddress,
/// as: UTF8.self,
/// repairingInvalidCodeUnits: true)
/// print(s)
/// }
/// // Prints "Optional((result: "Caf�", repairsMade: true))"
///
/// - Parameters:
/// - cString: A pointer to a null-terminated code sequence encoded in
/// `encoding`.
/// - encoding: The Unicode encoding of the data referenced by `cString`.
/// - isRepairing: Pass `true` to create a new string, even when the data
/// referenced by `cString` contains ill-formed sequences. Ill-formed
/// sequences are replaced with the Unicode replacement character
/// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new
/// string if an ill-formed sequence is detected.
/// - Returns: A tuple with the new string and a Boolean value that indicates
/// whether any repairs were made. If `isRepairing` is `false` and an
/// ill-formed sequence is detected, this method returns `nil`.
@_specialize(where Encoding == Unicode.UTF8)
@_specialize(where Encoding == Unicode.UTF16)
@inlinable // Fold away specializations
public static func decodeCString<Encoding: _UnicodeEncoding>(
_ cString: UnsafePointer<Encoding.CodeUnit>?,
as encoding: Encoding.Type,
repairingInvalidCodeUnits isRepairing: Bool = true
) -> (result: String, repairsMade: Bool)? {
guard let cPtr = cString else { return nil }
if _fastPath(encoding == Unicode.UTF8.self) {
let ptr = UnsafeRawPointer(cPtr).assumingMemoryBound(to: UInt8.self)
let len = UTF8._nullCodeUnitOffset(in: ptr)
let codeUnits = UnsafeBufferPointer(start: ptr, count: len)
if isRepairing {
return String._fromUTF8Repairing(codeUnits)
} else {
guard let str = String._tryFromUTF8(codeUnits) else { return nil }
return (str, false)
}
}
var end = cPtr
while end.pointee != 0 { end += 1 }
let len = end - cPtr
let codeUnits = UnsafeBufferPointer(start: cPtr, count: len)
return String._fromCodeUnits(
codeUnits, encoding: encoding, repair: isRepairing)
}
/// Creates a string from the null-terminated sequence of bytes at the given
/// pointer.
///
/// - Parameters:
/// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code
/// units in the encoding specified in `sourceEncoding`, ending just
/// before the first zero code unit.
/// - sourceEncoding: The encoding in which the code units should be
/// interpreted.
@_specialize(where Encoding == Unicode.UTF8)
@_specialize(where Encoding == Unicode.UTF16)
@inlinable // Fold away specializations
public init<Encoding: Unicode.Encoding>(
decodingCString ptr: UnsafePointer<Encoding.CodeUnit>,
as sourceEncoding: Encoding.Type
) {
self = String.decodeCString(ptr, as: sourceEncoding)!.0
}
}
extension UnsafePointer where Pointee == UInt8 {
@inlinable
internal var _asCChar: UnsafePointer<CChar> {
@inline(__always) get {
return UnsafeRawPointer(self).assumingMemoryBound(to: CChar.self)
}
}
}
extension UnsafePointer where Pointee == CChar {
@inlinable
internal var _asUInt8: UnsafePointer<UInt8> {
@inline(__always) get {
return UnsafeRawPointer(self).assumingMemoryBound(to: UInt8.self)
}
}
}
|
0724c9a28f98e179b30406edd13041e4
| 39.678049 | 80 | 0.624895 | false | false | false | false |
arvedviehweger/swift
|
refs/heads/master
|
test/SILGen/keypaths.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -enable-experimental-keypaths -emit-silgen %s | %FileCheck %s
// REQUIRES: PTRSIZE=64
struct S<T> {
var x: T
let y: String
var z: C<T>
var computed: C<T> { fatalError() }
var observed: C<T> { didSet { fatalError() } }
var reabstracted: () -> ()
}
class C<T> {
final var x: T
final let y: String
final var z: S<T>
var nonfinal: S<T>
var computed: S<T> { fatalError() }
var observed: S<T> { didSet { fatalError() } }
final var reabstracted: () -> ()
init() { fatalError() }
}
protocol P {
var x: Int { get }
var y: String { get set }
}
// CHECK-LABEL: sil hidden @{{.*}}storedProperties
func storedProperties<T>(_: T) {
// CHECK: keypath $WritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = #keyPath2(S<T>, .x)
// CHECK: keypath $KeyPath<S<T>, String>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.y : $String) <T>
_ = #keyPath2(S<T>, .y)
// CHECK: keypath $ReferenceWritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = #keyPath2(S<T>, .z.x)
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T>
_ = #keyPath2(C<T>, .x)
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = #keyPath2(C<T>, .y)
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T>
_ = #keyPath2(C<T>, .z.x)
// CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.y : $String) <T>
_ = #keyPath2(C<T>, .z.z.y)
}
// CHECK-LABEL: sil hidden @{{.*}}computedProperties
func computedProperties<T: P>(_: T) {
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.nonfinal!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @_T08keypaths1CC8nonfinalAA1SVyxGvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out S<τ_0_0>,
// CHECK-SAME: setter @_T08keypaths1CC8nonfinalAA1SVyxGvTk : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @in C<τ_0_0>, @thick C<τ_0_0>.Type) -> ()
// CHECK-SAME: ) <T>
_ = #keyPath2(C<T>, .nonfinal)
// CHECK: keypath $KeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: gettable_property $S<τ_0_0>,
// CHECK-SAME: id #C.computed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @_T08keypaths1CC8computedAA1SVyxGvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out S<τ_0_0>
// CHECK-SAME: ) <T>
_ = #keyPath2(C<T>, .computed)
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $S<τ_0_0>,
// CHECK-SAME: id #C.observed!getter.1 : <T> (C<T>) -> () -> S<T>,
// CHECK-SAME: getter @_T08keypaths1CC8observedAA1SVyxGvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out S<τ_0_0>,
// CHECK-SAME: setter @_T08keypaths1CC8observedAA1SVyxGvTk : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @in C<τ_0_0>, @thick C<τ_0_0>.Type) -> ()
// CHECK-SAME: ) <T>
_ = #keyPath2(C<T>, .observed)
_ = #keyPath2(C<T>, .nonfinal.x)
_ = #keyPath2(C<T>, .computed.x)
_ = #keyPath2(C<T>, .observed.x)
_ = #keyPath2(C<T>, .z.computed)
_ = #keyPath2(C<T>, .z.observed)
_ = #keyPath2(C<T>, .observed.x)
// CHECK: keypath $ReferenceWritableKeyPath<C<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $C<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##C.reabstracted,
// CHECK-SAME: getter @_T08keypaths1CC12reabstractedyycvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out @callee_owned (@in ()) -> @out (),
// CHECK-SAME: setter @_T08keypaths1CC12reabstractedyycvTk : $@convention(thin) <τ_0_0> (@in @callee_owned (@in ()) -> @out (), @in C<τ_0_0>, @thick C<τ_0_0>.Type) -> ()
// CHECK-SAME: ) <T>
_ = #keyPath2(C<T>, .reabstracted)
// CHECK: keypath $KeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>; gettable_property $C<τ_0_0>,
// CHECK-SAME: id @_T08keypaths1SV8computedAA1CCyxGfg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @_T08keypaths1SV8computedAA1CCyxGvTK : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @thick S<τ_0_0>.Type) -> @out C<τ_0_0>
// CHECK-SAME: ) <T>
_ = #keyPath2(S<T>, .computed)
// CHECK: keypath $WritableKeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $C<τ_0_0>,
// CHECK-SAME: id @_T08keypaths1SV8observedAA1CCyxGfg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>,
// CHECK-SAME: getter @_T08keypaths1SV8observedAA1CCyxGvTK : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @thick S<τ_0_0>.Type) -> @out C<τ_0_0>,
// CHECK-SAME: setter @_T08keypaths1SV8observedAA1CCyxGvTk : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @inout S<τ_0_0>, @thick S<τ_0_0>.Type) -> ()
// CHECK-SAME: ) <T>
_ = #keyPath2(S<T>, .observed)
_ = #keyPath2(S<T>, .z.nonfinal)
_ = #keyPath2(S<T>, .z.computed)
_ = #keyPath2(S<T>, .z.observed)
_ = #keyPath2(S<T>, .computed.x)
_ = #keyPath2(S<T>, .computed.y)
// CHECK: keypath $WritableKeyPath<S<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $S<τ_0_0>;
// CHECK-SAME: settable_property $() -> (),
// CHECK-SAME: id ##S.reabstracted,
// CHECK-SAME: getter @_T08keypaths1SV12reabstractedyycvTK : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @thick S<τ_0_0>.Type) -> @out @callee_owned (@in ()) -> @out (),
// CHECK-SAME: setter @_T08keypaths1SV12reabstractedyycvTk : $@convention(thin) <τ_0_0> (@in @callee_owned (@in ()) -> @out (), @inout S<τ_0_0>, @thick S<τ_0_0>.Type) -> ()
// CHECK-SAME: ) <T>
_ = #keyPath2(S<T>, .reabstracted)
// CHECK: keypath $KeyPath<T, Int>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: gettable_property $Int,
// CHECK-SAME: id #P.x!getter.1 : <Self where Self : P> (Self) -> () -> Int,
// CHECK-SAME: getter @_T08keypaths1PP1xSivTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out Int
// CHECK-SAME: ) <T>
_ = #keyPath2(T, .x)
// CHECK: keypath $WritableKeyPath<T, String>, <τ_0_0 where τ_0_0 : P> (
// CHECK-SAME: root $τ_0_0;
// CHECK-SAME: settable_property $String,
// CHECK-SAME: id #P.y!getter.1 : <Self where Self : P> (Self) -> () -> String,
// CHECK-SAME: getter @_T08keypaths1PP1ySSvTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out String,
// CHECK-SAME: setter @_T08keypaths1PP1ySSvTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in String, @inout τ_0_0) -> ()
// CHECK-SAME: ) <T>
_ = #keyPath2(T, .y)
}
|
3a898a86ad4caf7b2fef664eaa03fa6f
| 50.948905 | 177 | 0.578334 | false | false | false | false |
mohssenfathi/MTLImage
|
refs/heads/master
|
Example-iOS/Example-iOS/ViewControllers/Settings/SettingsViewController.swift
|
mit
|
1
|
//
// SettingsViewController.swift
// MTLImage
//
// Created by Mohssen Fathi on 3/31/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import MTLImage
class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,
SettingsCellDelegate, PickerCellDelegate, ToggleCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var emptyLabel: UILabel!
var filter: Filter!
var touchProperty: Property?
var mainViewController: MainViewController!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = filter.title
tableView.estimatedRowHeight = 80
mainViewController = self.navigationController?.parent as! MainViewController
for property: Property in filter.properties {
if property.propertyType == .point {
touchProperty = property
break;
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.isHidden = (filter.properties.count == 0)
emptyLabel.isHidden = (filter.properties.count != 0)
}
func handleTouchAtLocation(_ location: CGPoint) {
if filter is Smudge { return } // Temp
if touchProperty != nil {
let viewSize = mainViewController.mtlView.frame.size
let point = CGPoint(x: location.x / viewSize.width, y: location.y / viewSize.height)
filter.setValue(NSValue(cgPoint: point), forKey: touchProperty!.key)
}
}
func handlePan(_ sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: sender.view)
let location = sender.location(in: sender.view)
// let velocity = sender.velocityInView(sender.view)
if let smudgeFilter = filter as? Smudge {
smudgeFilter.location = location
smudgeFilter.direction = translation
// smudgeFilter.force = Float(max(velocity.x, velocity.y))
}
}
// MARK: - UITableView
// MARK: DataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filter.properties.count + 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == filter.properties.count { return 80.0 }
if cellIdentifier(filter.properties[indexPath.row].propertyType) == "pickerCell" {
return 200.0
}
return 80.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var identifier: String!
if indexPath.row == filter.properties.count {
identifier = "resetCell"
} else {
identifier = cellIdentifier(filter.properties[indexPath.row].propertyType)
}
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
return cell
}
func cellIdentifier(_ propertyType: Property.PropertyType) -> String {
if propertyType == .selection { return "pickerCell" }
else if propertyType == .image { return "imageCell" }
else if propertyType == .bool { return "toggleCell" }
return "settingsCell"
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.reuseIdentifier == "settingsCell" {
let settingsCell: SettingsCell = cell as! SettingsCell
let property: Property = filter.properties[indexPath.row]
settingsCell.delegate = self
settingsCell.titleLabel.text = property.title
if property.propertyType == .value {
let value = filter.value(forKey: property.key!) as! Float
settingsCell.spectrum = false
settingsCell.valueLabel.text = String(format: "%.2f", value)
settingsCell.slider.value = value
}
else if property.propertyType == .color {
settingsCell.spectrum = true
settingsCell.valueLabel.text = "-"
}
else if property.propertyType == .point {
settingsCell.message = "Touch preview image to adjust."
}
}
else if cell.reuseIdentifier == "toggleCell" {
let toggleCell: ToggleCell = cell as! ToggleCell
toggleCell.titleLabel.text = filter.properties[indexPath.row].title
toggleCell.delegate = self
if let key = filter.properties[indexPath.row].key {
if let isOn = filter.value(forKey: key) as? Bool {
toggleCell.toggleSwitch.isOn = isOn
}
}
}
else if cell.reuseIdentifier == "pickerCell" {
let pickerCell: PickerCell = cell as! PickerCell
pickerCell.titleLabel.text = filter.properties[indexPath.row].title
pickerCell.selectionItems = filter.properties[indexPath.row].selectionItems!
pickerCell.delegate = self
}
}
// MARK: Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if cell?.reuseIdentifier == "resetCell" {
filter.reset()
}
else if cell?.reuseIdentifier == "imageCell" {
let navigationController = parent as! UINavigationController
// let mainViewController = navigationController?.parentViewController as? MainViewController
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
navigationController.present(imagePicker, animated: true, completion: nil)
}
}
// MARK: SettingsCell Delegate
func settingsCellSliderValueChanged(_ sender: SettingsCell, value: Float) {
let indexPath = tableView.indexPath(for: sender)
let property: Property = filter.properties[(indexPath?.row)!]
if property.propertyType == .value {
sender.valueLabel.text = String(format: "%.2f", value)
filter.setValue(value, forKey: property.key)
}
else if property.propertyType == .color {
sender.valueLabel.text = "-"
filter.setValue(sender.currentColor(), forKey: property.key)
}
}
// MARK: PickerCell Delegate
func pickerCellDidSelectItem(_ sender: PickerCell, index: Int) {
let indexPath = tableView.indexPath(for: sender)
let property: Property = filter.properties[(indexPath?.row)!]
filter.setValue(index, forKey: property.key)
}
// MARK: ToggleCell Delegate
func toggleValueChanged(sender: ToggleCell, isOn: Bool) {
let indexPath = tableView.indexPath(for: sender)
let property: Property = filter.properties[(indexPath?.row)!]
filter.setValue(isOn, forKey: property.key)
}
// MARK: ImagePickerController Delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
for property in filter.properties {
if property.propertyType == .image {
if let image: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
filter.setValue(image, forKey: property.key)
dismiss(animated: true, completion: nil)
return
}
}
}
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
1361e50d31c5b1dfc376dca4d608a50d
| 35.516949 | 127 | 0.613367 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Account/Sources/Account/LocalAccount/LocalAccountDelegate.swift
|
mit
|
1
|
//
// LocalAccountDelegate.swift
// NetNewsWire
//
// Created by Brent Simmons on 9/16/17.
// Copyright © 2017 Ranchero Software, LLC. All rights reserved.
//
import Foundation
import os.log
import RSCore
import RSParser
import Articles
import ArticlesDatabase
import RSWeb
import Secrets
public enum LocalAccountDelegateError: String, Error {
case invalidParameter = "An invalid parameter was used."
}
final class LocalAccountDelegate: AccountDelegate {
private var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "LocalAccount")
weak var account: Account?
private lazy var refresher: LocalAccountRefresher? = {
let refresher = LocalAccountRefresher()
refresher.delegate = self
return refresher
}()
let behaviors: AccountBehaviors = []
let isOPMLImportInProgress = false
let server: String? = nil
var credentials: Credentials?
var accountMetadata: AccountMetadata?
let refreshProgress = DownloadProgress(numberOfTasks: 0)
func receiveRemoteNotification(for account: Account, userInfo: [AnyHashable : Any], completion: @escaping () -> Void) {
completion()
}
func refreshAll(for account: Account, completion: @escaping (Result<Void, Error>) -> Void) {
guard refreshProgress.isComplete else {
completion(.success(()))
return
}
var refresherWebFeeds = Set<WebFeed>()
let webFeeds = account.flattenedWebFeeds()
refreshProgress.addToNumberOfTasksAndRemaining(webFeeds.count)
let group = DispatchGroup()
var feedProviderError: Error? = nil
for webFeed in webFeeds {
if let components = URLComponents(string: webFeed.url), let feedProvider = FeedProviderManager.shared.best(for: components) {
group.enter()
feedProvider.refresh(webFeed) { result in
switch result {
case .success(let parsedItems):
account.update(webFeed.webFeedID, with: parsedItems) { _ in
self.refreshProgress.completeTask()
group.leave()
}
case .failure(let error):
os_log(.error, log: self.log, "Feed Provider refresh error: %@.", error.localizedDescription)
feedProviderError = error
self.refreshProgress.completeTask()
group.leave()
}
}
} else {
refresherWebFeeds.insert(webFeed)
}
}
group.enter()
refresher?.refreshFeeds(refresherWebFeeds) {
group.leave()
}
group.notify(queue: DispatchQueue.main) {
self.refreshProgress.clear()
account.metadata.lastArticleFetchEndTime = Date()
if let error = feedProviderError {
completion(.failure(error))
} else {
completion(.success(()))
}
}
}
func syncArticleStatus(for account: Account, completion: ((Result<Void, Error>) -> Void)? = nil) {
completion?(.success(()))
}
func sendArticleStatus(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) {
completion(.success(()))
}
func refreshArticleStatus(for account: Account, completion: @escaping ((Result<Void, Error>) -> Void)) {
completion(.success(()))
}
func importOPML(for account:Account, opmlFile: URL, completion: @escaping (Result<Void, Error>) -> Void) {
var fileData: Data?
do {
fileData = try Data(contentsOf: opmlFile)
} catch {
completion(.failure(error))
return
}
guard let opmlData = fileData else {
completion(.success(()))
return
}
let parserData = ParserData(url: opmlFile.absoluteString, data: opmlData)
var opmlDocument: RSOPMLDocument?
do {
opmlDocument = try RSOPMLParser.parseOPML(with: parserData)
} catch {
completion(.failure(error))
return
}
guard let loadDocument = opmlDocument else {
completion(.success(()))
return
}
guard let children = loadDocument.children else {
return
}
BatchUpdate.shared.perform {
account.loadOPMLItems(children)
}
completion(.success(()))
}
func createWebFeed(for account: Account, url urlString: String, name: String?, container: Container, validateFeed: Bool, completion: @escaping (Result<WebFeed, Error>) -> Void) {
guard let url = URL(string: urlString), let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
completion(.failure(LocalAccountDelegateError.invalidParameter))
return
}
// Username should be part of the URL on new feed adds
if let feedProvider = FeedProviderManager.shared.best(for: urlComponents) {
createProviderWebFeed(for: account, urlComponents: urlComponents, editedName: name, container: container, feedProvider: feedProvider, completion: completion)
} else {
createRSSWebFeed(for: account, url: url, editedName: name, container: container, completion: completion)
}
}
func renameWebFeed(for account: Account, with feed: WebFeed, to name: String, completion: @escaping (Result<Void, Error>) -> Void) {
feed.editedName = name
completion(.success(()))
}
func removeWebFeed(for account: Account, with feed: WebFeed, from container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
container.removeWebFeed(feed)
completion(.success(()))
}
func moveWebFeed(for account: Account, with feed: WebFeed, from: Container, to: Container, completion: @escaping (Result<Void, Error>) -> Void) {
from.removeWebFeed(feed)
to.addWebFeed(feed)
completion(.success(()))
}
func addWebFeed(for account: Account, with feed: WebFeed, to container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
container.addWebFeed(feed)
completion(.success(()))
}
func restoreWebFeed(for account: Account, feed: WebFeed, container: Container, completion: @escaping (Result<Void, Error>) -> Void) {
container.addWebFeed(feed)
completion(.success(()))
}
func createFolder(for account: Account, name: String, completion: @escaping (Result<Folder, Error>) -> Void) {
if let folder = account.ensureFolder(with: name) {
completion(.success(folder))
} else {
completion(.failure(FeedbinAccountDelegateError.invalidParameter))
}
}
func renameFolder(for account: Account, with folder: Folder, to name: String, completion: @escaping (Result<Void, Error>) -> Void) {
folder.name = name
completion(.success(()))
}
func removeFolder(for account: Account, with folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
account.removeFolder(folder)
completion(.success(()))
}
func restoreFolder(for account: Account, folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) {
account.addFolder(folder)
completion(.success(()))
}
func markArticles(for account: Account, articles: Set<Article>, statusKey: ArticleStatus.Key, flag: Bool, completion: @escaping (Result<Void, Error>) -> Void) {
account.update(articles, statusKey: statusKey, flag: flag) { result in
if case .failure(let error) = result {
completion(.failure(error))
} else {
completion(.success(()))
}
}
}
func accountDidInitialize(_ account: Account) {
self.account = account
}
func accountWillBeDeleted(_ account: Account) {
}
static func validateCredentials(transport: Transport, credentials: Credentials, endpoint: URL? = nil, completion: (Result<Credentials?, Error>) -> Void) {
return completion(.success(nil))
}
// MARK: Suspend and Resume (for iOS)
func suspendNetwork() {
refresher?.suspend()
}
func suspendDatabase() {
// Nothing to do
}
func resume() {
refresher?.resume()
}
}
extension LocalAccountDelegate: LocalAccountRefresherDelegate {
func localAccountRefresher(_ refresher: LocalAccountRefresher, requestCompletedFor: WebFeed) {
refreshProgress.completeTask()
}
func localAccountRefresher(_ refresher: LocalAccountRefresher, articleChanges: ArticleChanges, completion: @escaping () -> Void) {
completion()
}
}
private extension LocalAccountDelegate {
func createProviderWebFeed(for account: Account, urlComponents: URLComponents, editedName: String?, container: Container, feedProvider: FeedProvider, completion: @escaping (Result<WebFeed, Error>) -> Void) {
refreshProgress.addToNumberOfTasksAndRemaining(2)
feedProvider.metaData(urlComponents) { result in
self.refreshProgress.completeTask()
switch result {
case .success(let metaData):
guard let urlString = urlComponents.url?.absoluteString else {
completion(.failure(AccountError.createErrorNotFound))
return
}
let feed = account.createWebFeed(with: metaData.name, url: urlString, webFeedID: urlString, homePageURL: metaData.homePageURL)
feed.editedName = editedName
container.addWebFeed(feed)
feedProvider.refresh(feed) { result in
self.refreshProgress.completeTask()
switch result {
case .success(let parsedItems):
account.update(urlString, with: parsedItems) { _ in
completion(.success(feed))
}
case .failure(let error):
self.refreshProgress.clear()
completion(.failure(error))
}
}
case .failure:
self.refreshProgress.clear()
completion(.failure(AccountError.createErrorNotFound))
}
}
}
func createRSSWebFeed(for account: Account, url: URL, editedName: String?, container: Container, completion: @escaping (Result<WebFeed, Error>) -> Void) {
// We need to use a batch update here because we need to assign add the feed to the
// container before the name has been downloaded. This will put it in the sidebar
// with an Untitled name if we don't delay it being added to the sidebar.
BatchUpdate.shared.start()
refreshProgress.addToNumberOfTasksAndRemaining(1)
FeedFinder.find(url: url) { result in
switch result {
case .success(let feedSpecifiers):
guard let bestFeedSpecifier = FeedSpecifier.bestFeed(in: feedSpecifiers),
let url = URL(string: bestFeedSpecifier.urlString) else {
self.refreshProgress.completeTask()
BatchUpdate.shared.end()
completion(.failure(AccountError.createErrorNotFound))
return
}
if account.hasWebFeed(withURL: bestFeedSpecifier.urlString) {
self.refreshProgress.completeTask()
BatchUpdate.shared.end()
completion(.failure(AccountError.createErrorAlreadySubscribed))
return
}
InitialFeedDownloader.download(url) { parsedFeed in
self.refreshProgress.completeTask()
if let parsedFeed = parsedFeed {
let feed = account.createWebFeed(with: nil, url: url.absoluteString, webFeedID: url.absoluteString, homePageURL: nil)
feed.editedName = editedName
container.addWebFeed(feed)
account.update(feed, with: parsedFeed, {_ in
BatchUpdate.shared.end()
completion(.success(feed))
})
} else {
BatchUpdate.shared.end()
completion(.failure(AccountError.createErrorNotFound))
}
}
case .failure:
BatchUpdate.shared.end()
self.refreshProgress.completeTask()
completion(.failure(AccountError.createErrorNotFound))
}
}
}
}
|
945f971969666d81a764be92d40922cf
| 29.172222 | 208 | 0.711379 | false | false | false | false |
louisdh/panelkit
|
refs/heads/master
|
PanelKit/PanelManager/PanelManager+Floating.swift
|
mit
|
1
|
//
// PanelManager+Floating.swift
// PanelKit
//
// Created by Louis D'hauwe on 07/03/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import UIKit
public extension PanelManager where Self: UIViewController {
var managerViewController: UIViewController {
return self
}
}
public extension PanelManager {
func toggleFloatStatus(for panel: PanelViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
let panelNavCon = panel.panelNavigationController
if (panel.isFloating || panel.isPinned) && !panelNavCon.isPresentedAsPopover {
close(panel)
completion?()
} else if panelNavCon.isPresentedAsPopover {
let rect = panel.view.convert(panel.view.frame, to: panelContentWrapperView)
panel.dismiss(animated: false, completion: {
self.floatPanel(panel, toRect: rect, animated: animated)
completion?()
})
} else {
let rect = CGRect(origin: .zero, size: panel.preferredContentSize)
floatPanel(panel, toRect: rect, animated: animated)
}
}
internal func floatPanel(_ panel: PanelViewController, toRect rect: CGRect, animated: Bool) {
self.panelContentWrapperView.addSubview(panel.resizeCornerHandle)
self.panelContentWrapperView.addSubview(panel.view)
panel.resizeCornerHandle.bottomAnchor.constraint(equalTo: panel.view.bottomAnchor, constant: 16).isActive = true
panel.resizeCornerHandle.trailingAnchor.constraint(equalTo: panel.view.trailingAnchor, constant: 16).isActive = true
panel.didUpdateFloatingState()
self.updateFrame(for: panel, to: rect)
self.panelContentWrapperView.layoutIfNeeded()
let x = rect.origin.x
let y = rect.origin.y + panelPopYOffset
let width = panel.view.frame.size.width
let height = panel.view.frame.size.height
var newFrame = CGRect(x: x, y: y, width: width, height: height)
newFrame.center = panel.allowedCenter(for: newFrame.center)
self.updateFrame(for: panel, to: newFrame)
if animated {
UIView.animate(withDuration: panelPopDuration, delay: 0.0, options: [.allowUserInteraction, .curveEaseOut], animations: {
self.panelContentWrapperView.layoutIfNeeded()
}, completion: nil)
} else {
self.panelContentWrapperView.layoutIfNeeded()
}
if panel.view.superview == self.panelContentWrapperView {
panel.contentDelegate?.didUpdateFloatingState()
}
}
}
public extension PanelManager {
func float(_ panel: PanelViewController, at frame: CGRect) {
guard !panel.isFloating else {
return
}
guard panel.canFloat else {
return
}
toggleFloatStatus(for: panel, animated: false)
updateFrame(for: panel, to: frame)
self.panelContentWrapperView.layoutIfNeeded()
panel.viewWillAppear(false)
panel.viewDidAppear(false)
}
}
|
24f60448660578d91a49c77e3f6c4164
| 22.115702 | 124 | 0.72113 | false | false | false | false |
huynguyencong/DataCache
|
refs/heads/master
|
Sources/DataCache.swift
|
mit
|
1
|
//
// Cache.swift
// CacheDemo
//
// Created by Nguyen Cong Huy on 7/4/16.
// Copyright © 2016 Nguyen Cong Huy. All rights reserved.
//
import UIKit
public enum ImageFormat {
case unknown, png, jpeg
}
open class DataCache {
static let cacheDirectoryPrefix = "com.nch.cache."
static let ioQueuePrefix = "com.nch.queue."
static let defaultMaxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 // a week
public static let instance = DataCache(name: "default")
let cachePath: String
let memCache = NSCache<AnyObject, AnyObject>()
let ioQueue: DispatchQueue
let fileManager: FileManager
/// Name of cache
open var name: String = ""
/// Life time of disk cache, in second. Default is a week
open var maxCachePeriodInSecond = DataCache.defaultMaxCachePeriodInSecond
/// Size is allocated for disk cache, in byte. 0 mean no limit. Default is 0
open var maxDiskCacheSize: UInt = 0
/// Specify distinc name param, it represents folder name for disk cache
public init(name: String, path: String? = nil) {
self.name = name
var cachePath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
cachePath = (cachePath as NSString).appendingPathComponent(DataCache.cacheDirectoryPrefix + name)
self.cachePath = cachePath
ioQueue = DispatchQueue(label: DataCache.ioQueuePrefix + name)
self.fileManager = FileManager()
#if !os(OSX) && !os(watchOS)
NotificationCenter.default.addObserver(self, selector: #selector(cleanExpiredDiskCache), name: UIApplication.willTerminateNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(cleanExpiredDiskCache), name: UIApplication.didEnterBackgroundNotification, object: nil)
#endif
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Store data
extension DataCache {
/// Write data for key. This is an async operation.
public func write(data: Data, forKey key: String) {
memCache.setObject(data as AnyObject, forKey: key as AnyObject)
writeDataToDisk(data: data, key: key)
}
private func writeDataToDisk(data: Data, key: String) {
ioQueue.async {
if self.fileManager.fileExists(atPath: self.cachePath) == false {
do {
try self.fileManager.createDirectory(atPath: self.cachePath, withIntermediateDirectories: true, attributes: nil)
} catch {
print("DataCache: Error while creating cache folder: \(error.localizedDescription)")
}
}
self.fileManager.createFile(atPath: self.cachePath(forKey: key), contents: data, attributes: nil)
}
}
/// Read data for key
public func readData(forKey key:String) -> Data? {
var data = memCache.object(forKey: key as AnyObject) as? Data
if data == nil {
if let dataFromDisk = readDataFromDisk(forKey: key) {
data = dataFromDisk
memCache.setObject(dataFromDisk as AnyObject, forKey: key as AnyObject)
}
}
return data
}
/// Read data from disk for key
public func readDataFromDisk(forKey key: String) -> Data? {
return self.fileManager.contents(atPath: cachePath(forKey: key))
}
// MARK: - Read & write Codable types
public func write<T: Encodable>(codable: T, forKey key: String) throws {
let data = try JSONEncoder().encode(codable)
write(data: data, forKey: key)
}
public func readCodable<T: Decodable>(forKey key: String) throws -> T? {
guard let data = readData(forKey: key) else { return nil }
return try JSONDecoder().decode(T.self, from: data)
}
// MARK: - Read & write primitive types
/// Write an object for key. This object must inherit from `NSObject` and implement `NSCoding` protocol. `String`, `Array`, `Dictionary` conform to this method.
///
/// NOTE: Can't write `UIImage` with this method. Please use `writeImage(_:forKey:)` to write an image
public func write(object: NSCoding, forKey key: String) {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
write(data: data, forKey: key)
}
/// Write a string for key
public func write(string: String, forKey key: String) {
write(object: string as NSCoding, forKey: key)
}
/// Write a dictionary for key
public func write(dictionary: Dictionary<AnyHashable, Any>, forKey key: String) {
write(object: dictionary as NSCoding, forKey: key)
}
/// Write an array for key
public func write(array: Array<Any>, forKey key: String) {
write(object: array as NSCoding, forKey: key)
}
/// Read an object for key. This object must inherit from `NSObject` and implement NSCoding protocol. `String`, `Array`, `Dictionary` conform to this method
public func readObject(forKey key: String) -> NSObject? {
let data = readData(forKey: key)
if let data = data {
return NSKeyedUnarchiver.unarchiveObject(with: data) as? NSObject
}
return nil
}
/// Read a string for key
public func readString(forKey key: String) -> String? {
return readObject(forKey: key) as? String
}
/// Read an array for key
public func readArray(forKey key: String) -> Array<Any>? {
return readObject(forKey: key) as? Array<Any>
}
/// Read a dictionary for key
public func readDictionary(forKey key: String) -> Dictionary<AnyHashable, Any>? {
return readObject(forKey: key) as? Dictionary<AnyHashable, Any>
}
// MARK: - Read & write image
/// Write image for key. Please use this method to write an image instead of `writeObject(_:forKey:)`
public func write(image: UIImage, forKey key: String, format: ImageFormat? = nil) {
var data: Data? = nil
if let format = format, format == .png {
data = image.pngData()
}
else {
data = image.jpegData(compressionQuality: 0.9)
}
if let data = data {
write(data: data, forKey: key)
}
}
/// Read image for key. Please use this method to write an image instead of `readObject(forKey:)`
public func readImage(forKey key: String) -> UIImage? {
let data = readData(forKey: key)
if let data = data {
return UIImage(data: data, scale: 1.0)
}
return nil
}
@available(*, deprecated, message: "Please use `readImage(forKey:)` instead. This will be removed in the future.")
public func readImageForKey(key: String) -> UIImage? {
return readImage(forKey: key)
}
}
// MARK: - Utils
extension DataCache {
/// Check if has data for key
public func hasData(forKey key: String) -> Bool {
return hasDataOnDisk(forKey: key) || hasDataOnMem(forKey: key)
}
/// Check if has data on disk
public func hasDataOnDisk(forKey key: String) -> Bool {
return self.fileManager.fileExists(atPath: self.cachePath(forKey: key))
}
/// Check if has data on mem
public func hasDataOnMem(forKey key: String) -> Bool {
return (memCache.object(forKey: key as AnyObject) != nil)
}
}
// MARK: - Clean
extension DataCache {
/// Clean all mem cache and disk cache. This is an async operation.
public func cleanAll() {
cleanMemCache()
cleanDiskCache()
}
/// Clean cache by key. This is an async operation.
public func clean(byKey key: String) {
memCache.removeObject(forKey: key as AnyObject)
ioQueue.async {
do {
try self.fileManager.removeItem(atPath: self.cachePath(forKey: key))
} catch {
print("DataCache: Error while remove file: \(error.localizedDescription)")
}
}
}
public func cleanMemCache() {
memCache.removeAllObjects()
}
public func cleanDiskCache() {
ioQueue.async {
do {
try self.fileManager.removeItem(atPath: self.cachePath)
} catch {
print("DataCache: Error when clean disk: \(error.localizedDescription)")
}
}
}
/// Clean expired disk cache. This is an async operation.
@objc public func cleanExpiredDiskCache() {
cleanExpiredDiskCache(completion: nil)
}
// This method is from Kingfisher
/**
Clean expired disk cache. This is an async operation.
- parameter completionHandler: Called after the operation completes.
*/
open func cleanExpiredDiskCache(completion handler: (()->())? = nil) {
// Do things in cocurrent io queue
ioQueue.async {
var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false)
for fileURL in URLsToDelete {
do {
try self.fileManager.removeItem(at: fileURL)
} catch {
print("DataCache: Error while removing files \(error.localizedDescription)")
}
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
if let date1 = resourceValue1.contentAccessDate,
let date2 = resourceValue2.contentAccessDate
{
return date1.compare(date2) == .orderedAscending
}
// Not valid date information. This should not happen. Just in case.
return true
}
for fileURL in sortedFiles {
do {
try self.fileManager.removeItem(at: fileURL)
} catch {
print("DataCache: Error while removing files \(error.localizedDescription)")
}
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize {
diskCacheSize -= UInt(fileSize)
}
if diskCacheSize < targetSize {
break
}
}
}
DispatchQueue.main.async(execute: { () -> Void in
handler?()
})
}
}
}
// MARK: - Helpers
extension DataCache {
// This method is from Kingfisher
fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) {
let diskCacheURL = URL(fileURLWithPath: cachePath)
let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
let expiredDate: Date? = (maxCachePeriodInSecond < 0) ? nil : Date(timeIntervalSinceNow: -maxCachePeriodInSecond)
var cachedFiles = [URL: URLResourceValues]()
var urlsToDelete = [URL]()
var diskCacheSize: UInt = 0
for fileUrl in (try? fileManager.contentsOfDirectory(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)) ?? [] {
do {
let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys)
// If it is a Directory. Continue to next file URL.
if resourceValues.isDirectory == true {
continue
}
// If this file is expired, add it to URLsToDelete
if !onlyForCacheSize,
let expiredDate = expiredDate,
let lastAccessData = resourceValues.contentAccessDate,
(lastAccessData as NSDate).laterDate(expiredDate) == expiredDate
{
urlsToDelete.append(fileUrl)
continue
}
if let fileSize = resourceValues.totalFileAllocatedSize {
diskCacheSize += UInt(fileSize)
if !onlyForCacheSize {
cachedFiles[fileUrl] = resourceValues
}
}
} catch {
print("DataCache: Error while iterating files \(error.localizedDescription)")
}
}
return (urlsToDelete, diskCacheSize, cachedFiles)
}
func cachePath(forKey key: String) -> String {
let fileName = key.md5
return (cachePath as NSString).appendingPathComponent(fileName)
}
}
|
74907b38d68ecc74137d2adde988da6f
| 34.873016 | 165 | 0.580015 | false | false | false | false |
miktap/pepe-p06
|
refs/heads/master
|
PePeP06/PePeP06/AWS/S3Client.swift
|
mit
|
1
|
//
// S3Client.swift
// PePeP06
//
// Created by Mikko Tapaninen on 14/01/2018.
//
import Foundation
import AWSCore
import AWSS3
protocol S3ClientDelegate {
/**
* S3 client has downloaded Taso API key.
*
* - Parameter api_key: Taso API key
*/
func apiKeyReceived(api_key: String)
}
class S3Client {
// MARK: - Properties
var delegate: S3ClientDelegate?
// MARK: - Methods
func getTasoAPIKey() {
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
completionHandler = { (task, URL, data, error) -> Void in
if let error = error {
log.error(error.localizedDescription)
}
if let data = data, let message = String(data: data, encoding: .utf8) {
log.debug("S3 client successfully downloaded Taso API key")
self.delegate?.apiKeyReceived(api_key: message)
}
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.downloadData(
fromBucket: "pepep06",
key: "taso_api_key.txt",
expression: nil,
completionHandler: completionHandler
)
}
}
|
548e73cea33ebc0be23ac644161274ec
| 24.08 | 83 | 0.582137 | false | false | false | false |
vigneshuvi/SwiftLoggly
|
refs/heads/master
|
SwiftLogglyOSXTests/SwiftLogglyOSXTests.swift
|
mit
|
1
|
//
// SwiftLogglyOSXTests.swift
// SwiftLogglyOSXTests
//
// Created by Vignesh on 30/01/17.
// Copyright © 2017 vigneshuvi. All rights reserved.
//
import XCTest
@testable import SwiftLogglyOSX
class SwiftLogglyOSXTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let logsDirectory = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("vignesh", isDirectory: true)
Loggly.logger.directory = logsDirectory.path
Loggly.logger.enableEmojis = true
Loggly.logger.logFormatType = LogFormatType.Normal
Loggly.logger.logEncodingType = String.Encoding.utf8;
loggly(LogType.Info, text: "Welcome to Swift Loggly")
loggly(LogType.Verbose, text: "Fun")
loggly(LogType.Debug, text: "is")
loggly(LogType.Warnings, text: "Matter")
loggly(LogType.Error, text: "here!!")
print(getLogglyReportsOutput());
loggly(LogType.Debug, text: "is")
loggly(LogType.Warnings, text: "Matter")
loggly(LogType.Error, text: "here!!")
print(getLogglyReportsOutput());
loggly(LogType.Debug, text: "is")
loggly(LogType.Warnings, text: "Matter")
loggly(LogType.Error, text: "here!!")
print(getLogCountBasedonType(LogType.Warnings));
let dict:NSMutableDictionary = NSMutableDictionary();
dict.setValue("Vignesh", forKey: "name") ;
dict.setValue("Senior Engineer",forKey: "Position");
loggly(LogType.Info, dictionary: dict)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
d21d5d466d736cdd40d4de7035fc974a
| 32.424658 | 121 | 0.627869 | false | true | false | false |
coodly/SlimTimerAPI
|
refs/heads/master
|
Sources/Entry.swift
|
apache-2.0
|
1
|
/*
* Copyright 2017 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import SWXMLHash
public struct Entry {
public let id: Int?
public let startTime: Date
public let endTime: Date?
public let taskId: Int
public let tags: [String]?
public let comments: String?
public let durationInSeconds: Int
public let inProgress: Bool
public let task: Task?
public let updatedAt: Date?
public let createdAt: Date?
}
extension Entry {
public init(id: Int?, startTime: Date, endTime: Date?, taskId: Int, tags: [String]?, comments: String?) {
self.id = id
self.startTime = startTime
self.endTime = endTime
self.taskId = taskId
self.tags = tags
self.comments = comments
self.inProgress = endTime == nil
task = nil
updatedAt = nil
createdAt = nil
let end = endTime ?? Date()
durationInSeconds = max(Int(end.timeIntervalSince(startTime)), 60)
}
}
extension Entry: RequestBody {
}
extension Entry: RemoteModel {
init?(xml: XMLIndexer) {
//TODO jaanus: figure this out
let entry: XMLIndexer
switch xml["time-entry"] {
case .xmlError(_):
entry = xml
default:
entry = xml["time-entry"]
}
guard let idString = entry["id"].element?.text, let id = Int(idString) else {
return nil
}
guard let start = entry["start-time"].element?.date else {
return nil
}
let taskData = entry["task"]
guard let task = Task(xml: taskData) else {
return nil
}
self.id = id
self.startTime = start
self.task = task
self.taskId = task.id!
tags = (entry["tags"].element?.text ?? "").components(separatedBy: ",")
comments = entry["comments"].element?.text ?? ""
inProgress = entry["in-progress"].element?.bool ?? false
endTime = entry["end-time"].element?.date ?? Date.distantPast
durationInSeconds = entry["duration-in-seconds"].element?.int ?? -1
updatedAt = entry["updated-at"].element?.date
createdAt = entry["created-at"].element?.date
}
}
|
ce82ee3cb306fe33bcc1451513b68da9
| 28.041237 | 109 | 0.604189 | false | false | false | false |
elationfoundation/Reporta-iOS
|
refs/heads/master
|
IWMF/Helper/CoreDataHelper.swift
|
gpl-3.0
|
1
|
//
// CoreDataHelper.swift
//
//
import CoreData
import UIKit
class CoreDataHelper: NSObject{
let store: CoreDataStore!
override init(){
self.store = Structures.Constant.appDelegate.cdstore
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSaveContext:", name: NSManagedObjectContextDidSaveNotification, object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.store.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
lazy var backgroundContext: NSManagedObjectContext? = {
let coordinator = self.store.persistentStoreCoordinator
var backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
backgroundContext.persistentStoreCoordinator = coordinator
return backgroundContext
}()
func saveContext (context: NSManagedObjectContext) {
if context.hasChanges {
do {
try context.save()
} catch _ as NSError {
abort()
}
}
}
func saveContext () {
self.saveContext( self.backgroundContext! )
}
func contextDidSaveContext(notification: NSNotification) {
let sender = notification.object as! NSManagedObjectContext
if sender === self.managedObjectContext {
self.backgroundContext!.performBlock {
self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
}
} else if sender === self.backgroundContext {
self.managedObjectContext.performBlock {
self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
}
} else {
self.backgroundContext!.performBlock {
self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
}
self.managedObjectContext.performBlock {
self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
}
}
}
}
|
d4af9f0402b88926ee352c954fd4f15a
| 32.04 | 160 | 0.658192 | false | false | false | false |
seungprk/PenguinJump
|
refs/heads/master
|
PenguinJump/PenguinJump/Coin.swift
|
bsd-2-clause
|
1
|
//
// Coin.swift
//
// Created by Matthew Tso on 6/6/16.
// Copyright © 2016 De Anza. All rights reserved.
//
import SpriteKit
/**
A collectable coin in the stage.
- parameter value: An integer value of the coin towards the persistent coin total. The default is 1.
*/
class Coin: SKSpriteNode {
let value = 1
var shadow: SKSpriteNode!
var body: SKSpriteNode!
var particles = [SKSpriteNode]()
var collected = false
init() {
/// Array of the coin's textures. The last texture is the coin image without the shine.
var coinTextures = [SKTexture]()
for i in 1...7 {
coinTextures.append(SKTexture(image: UIImage(named: "coin\(i)")!))
}
// Designated initializer for SKSpriteNode.
super.init(texture: nil, color: SKColor.clearColor(), size: coinTextures.last!.size())
name = "coin"
let coinShine = SKAction.animateWithTextures(coinTextures, timePerFrame: 1/30)
let wait = SKAction.waitForDuration(2.5)
let coinAnimation = SKAction.sequence([coinShine, wait])
body = SKSpriteNode(texture: coinTextures.last)
body.runAction(SKAction.repeatActionForever(coinAnimation))
body.zPosition = 200
body.name = "body"
shadow = SKSpriteNode(texture: SKTexture(image: UIImage(named: "coin_shadow")!))
shadow.alpha = 0.1
shadow.position.y -= size.height // 3
shadow.zPosition = -100
shadow.physicsBody = shadowPhysicsBody(shadow.texture!, category: CoinCategory)
addChild(body)
addChild(shadow)
bob()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bob() {
let bobDepth = 6.0
let bobDuration = 1.5
let down = SKAction.moveBy(CGVector(dx: 0.0, dy: -bobDepth), duration: bobDuration)
let up = SKAction.moveBy(CGVector(dx: 0.0, dy: bobDepth), duration: bobDuration)
down.timingMode = .EaseInEaseOut
up.timingMode = .EaseInEaseOut
let bobSequence = SKAction.sequence([down, up])
let bob = SKAction.repeatActionForever(bobSequence)
removeAllActions()
body.runAction(bob)
}
/**
Creates coin particles used to increment the charge bar.
- parameter camera: The target `SKCameraNode`. The particles are added as children of the camera because the particles need to move to the charge bar, which is a child of the camera.
*/
func generateCoinParticles(camera: SKCameraNode) {
let numberOfParticles = random() % 2 + 3
for _ in 1...numberOfParticles {
let particle = SKSpriteNode(color: SKColor.yellowColor(), size: CGSize(width: size.width / 5, height: size.width / 5))
// let randomX = random() % Int(size.width) - Int(size.width / 2)
let randomX = Int( arc4random_uniform( UInt32(size.width) ) ) - Int(size.width / 2)
let randomY = Int( arc4random_uniform( UInt32(size.height) ) ) - Int(size.height / 2)
let bodyPositionInScene = convertPoint(body.position, toNode: scene!)
let bodyPositionInCam = camera.convertPoint(bodyPositionInScene, fromNode: scene!)
particle.position = CGPoint(x: bodyPositionInCam.x + CGFloat(randomX), y: bodyPositionInCam.y + CGFloat(randomY))
particle.zPosition = 200000
particles.append(particle)
}
for particle in particles {
camera.addChild(particle)
}
}
}
|
87e87e7f08089f16591c90b0bf6e2d48
| 34.216981 | 187 | 0.607822 | false | false | false | false |
AlexeyTyurenkov/NBUStats
|
refs/heads/develop
|
NBUStatProject/NBUStat/ViewControllers/CurrencyViewController.swift
|
mit
|
1
|
//
// CurrencyViewController.swift
// NBUStat
//
// Created by Oleksii Tiurenkov on 7/14/17.
// Copyright © 2017 Oleksii Tiurenkov. All rights reserved.
//
import UIKit
class CurrencyViewController: UIViewController {
var presenter: DateDependedPresenterProtocol & TablePresenterProtocol = NBUCurrencyRatesManager(date: Date())
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var tomorrowButton: UIButton!
@IBOutlet weak var yesterdayButton: UIButton!
@IBOutlet weak var yesterdayLabel: UILabel!
@IBOutlet weak var tomorrowLabel: UILabel!
@IBOutlet weak var dateTextField: UITextField!
@IBOutlet weak var dropdownMarker: UIImageView!
lazy var picker: UIDatePicker = {
return self.presenter.picker
}()
lazy var toolBar: UIToolbar = {
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = ThemeManager.shared.positiveColor
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: NSLocalizedString("Готово", comment: ""), style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let todayButton = UIBarButtonItem(title: "Сьогодні", style: UIBarButtonItemStyle.plain, target: self, action: #selector(todayPicker))
let cancelButton = UIBarButtonItem(title: "Відміна", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelPicker))
toolBar.setItems([cancelButton, spaceButton, todayButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
return toolBar
}()
private(set) var detailedCurrency: String = ""
override func viewDidLoad() {
super.viewDidLoad()
updateDate(label: dateLabel)
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(self.handleDynamicTypeChange(notification:)), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
dateTextField.inputView = picker
dateTextField.inputAccessoryView = toolBar
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
navigationItem.leftItemsSupplementBackButton = true
}
//MARK: - date picker handling
@objc func donePicker()
{
closePicker(with: picker.date)
}
@objc func todayPicker()
{
closePicker(with: Date())
}
private func closePicker(with date: Date? = nil)
{
dropdownMarker.transform = CGAffineTransform(rotationAngle: 0)
dateTextField.resignFirstResponder()
guard let date = date else { return }
presenter.date = date
updateDate(label: dateLabel)
}
@objc func cancelPicker()
{
closePicker()
}
@objc func handleDynamicTypeChange(notification: Notification)
{
presenter.updateView()
dateLabel.font = UIFont.preferredFont(forTextStyle: .body)
yesterdayLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
tomorrowLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func changeDateButtonPressed(_ sender: Any) {
dropdownMarker.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
dateTextField.becomeFirstResponder()
}
@IBAction func previousButtonPressed(_ sender: Any) {
presenter.movePreviousDate()
updateDate(label: dateLabel)
}
@IBAction func nextButtonPressed(_ sender: Any) {
presenter.moveNextDate()
updateDate(label: dateLabel)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? NBURatesTableViewController
{
viewController.presenter = presenter
viewController.presenter.delegate = viewController
viewController.openDetail = { [weak self](cc) in
self?.detailedCurrency = cc
if cc != ""
{
self?.performSegue(withIdentifier: "ShowCurrency", sender: nil)
}
}
}
else if let viewController = segue.destination as? CurrencyDetailContainerViewController
{
viewController.currency = detailedCurrency
}
else if let viewController = segue.destination as? DataProviderInfoViewController
{
viewController.info = presenter.dataProviderInfo
}
}
func updateDate(label: UILabel)
{
label.text = presenter.currentDate
yesterdayLabel.text = presenter.prevDate
tomorrowLabel.text = presenter.nextDate
}
}
|
910302aa47b4ad8889a2b4e1ef937c43
| 33.401316 | 189 | 0.669153 | false | false | false | false |
braintree/braintree-ios-drop-in
|
refs/heads/master
|
UnitTests/FakeApplication.swift
|
mit
|
1
|
import UIKit
@objcMembers
class FakeApplication: NSObject {
var lastOpenURL: URL? = nil
var openURLWasCalled: Bool = false
var cannedOpenURLSuccess: Bool = true
var cannedCanOpenURL: Bool = true
var canOpenURLWhitelist: [URL] = []
func openURL(_ url: URL, options: [UIApplication.OpenExternalURLOptionsKey : Any], completionHandler completion: ((Bool) -> Void)?) {
lastOpenURL = url
openURLWasCalled = true
completion?(cannedOpenURLSuccess)
}
func canOpenURL(_ url: URL) -> Bool {
for whitelistURL in canOpenURLWhitelist {
if whitelistURL.scheme == url.scheme {
return true
}
}
return cannedCanOpenURL
}
}
|
e841527c778b4e1b853908bee8272eaf
| 28.32 | 137 | 0.635744 | false | false | false | false |
MrWhoami/programmer_calc_ios
|
refs/heads/master
|
ProgrammerCalc/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ProgrammerCalc
//
// Created by LiuJiyuan on 5/24/16.
// Copyright © 2016 Joel Liu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var numberScreen: UILabel!
@IBOutlet weak var characterScreen: UILabel!
@IBOutlet weak var button8: UIButton!
@IBOutlet weak var button9: UIButton!
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
@IBOutlet weak var buttonC: UIButton!
@IBOutlet weak var buttonD: UIButton!
@IBOutlet weak var buttonE: UIButton!
@IBOutlet weak var buttonF: UIButton!
@IBOutlet weak var buttonFF: UIButton!
var printMode = 10
var characterMode = "None"
var expression = CalculationStack()
var justTouchedOperator = false
let disabledColor = UIColor.lightGrayColor()
let enabledColor = UIColor.blackColor()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
// Change the status bar color
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
button8.setTitleColor(enabledColor, forState: UIControlState.Normal)
button9.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonA.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonB.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonC.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonD.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonE.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonF.setTitleColor(enabledColor, forState: UIControlState.Normal)
buttonFF.setTitleColor(enabledColor, forState: UIControlState.Normal)
button8.setTitleColor(disabledColor, forState: UIControlState.Disabled)
button9.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonA.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonB.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonC.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonD.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonE.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonF.setTitleColor(disabledColor, forState: UIControlState.Disabled)
buttonFF.setTitleColor(disabledColor, forState: UIControlState.Disabled)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
// Number pad has been touched.
@IBAction func numberPadTouched(sender: UIButton) {
if justTouchedOperator {
// If just finish one calculation, then the screen must be cleared for new input.
if sender.currentTitle! == "00" {
// Of course, in this situation, 00 will be accepted as 0.
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
} else {
// Other situations, just replace the printing number.
if printMode == 16 {
numberScreen.text = "0x" + sender.currentTitle!
} else {
numberScreen.text = sender.currentTitle!
}
}
justTouchedOperator = false
refreshCharacterScreen()
return
}
// If the screen do dot need to refresh.
if numberScreen.text! == "0" {
// If the screen is printing out 0, we need to replace the number.
if sender.currentTitle! != "00" {
// Of course, in this situation, 00 is not accepted.
numberScreen.text = sender.currentTitle!
}
}
else if numberScreen.text! == "0x0" {
// If the screen is printing out 0x0, we need to replace the number.
if sender.currentTitle! != "00" {
// Of course, in this situation, 00 is not accepted.
numberScreen.text = "0x" + sender.currentTitle!
}
}
else {
// If the screen already has something to print out, just append the new number.
var printingStr:String
if printMode == 16 {
printingStr = numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2))
} else {
printingStr = numberScreen.text!
}
printingStr += sender.currentTitle!
if UInt64(printingStr, radix: printMode) == nil {
printingStr = String(UInt64.max, radix: printMode).uppercaseString
}
if printMode == 16 {
numberScreen.text = "0x" + printingStr
} else {
numberScreen.text = printingStr
}
}
refreshCharacterScreen()
}
// C button at left-top.
@IBAction func clearTouched(sender: UIButton) {
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
justTouchedOperator = false
refreshCharacterScreen()
}
// AC button
@IBAction func allClearTouched(sender: UIButton) {
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
expression.clearStack()
justTouchedOperator = false
refreshCharacterScreen()
}
// "<<", ">>", "1's", "2's", "byte flip", "word flip", "RoL", "RoR"
@IBAction func instantActions(sender: UIButton) {
var printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
switch sender.currentTitle! {
case "<<":
printingNumber = printingNumber << 1;
case ">>":
printingNumber = printingNumber >> 1;
case "1's":
printingNumber = ~printingNumber;
case "2's":
printingNumber = ~printingNumber &+ 1;
case "byte flip":
// Get bytes
var buffer = [UInt8]()
var highest = 0
for i in 0...7 {
buffer.append(UInt8(printingNumber >> UInt64(i * 8) & 0xff))
highest = buffer[i] == 0 ? highest : i
}
// Flip bytes
for i in 0...(highest / 2) {
let tmp = buffer[i]
buffer[i] = buffer[highest - i]
buffer[highest - i] = tmp
}
// Get the result
printingNumber = 0
for i in 0...7 {
printingNumber |= UInt64(buffer[i]) << UInt64(i * 8)
}
case "word flip":
// Get words
var buffer = [UInt16]()
var highest = 0
for i in 0...3 {
buffer.append(UInt16(printingNumber >> UInt64(i * 16) & 0xffff))
highest = buffer[i] == 0 ? highest : i
}
// Flip words
for i in 0...(highest / 2) {
let tmp = buffer[i]
buffer[i] = buffer[highest - i]
buffer[highest - i] = tmp
}
// Get the result
printingNumber = 0
for i in 0...3 {
printingNumber |= UInt64(buffer[i]) << UInt64(i * 16)
}
case "RoL":
let tmp = printingNumber & (UInt64.max - UInt64.max >> 1)
printingNumber <<= 1
if tmp != 0 {
printingNumber |= 1
}
case "RoR":
let tmp = printingNumber & 1
printingNumber >>= 1
if tmp != 0 {
printingNumber |= (UInt64.max - UInt64.max >> 1)
}
default:
print("Unknown operator in instantAction: \(sender.currentTitle!).\n")
}
if printMode == 16 {
numberScreen.text = "0x" + String(printingNumber, radix: printMode)
} else {
numberScreen.text = String(printingNumber, radix: printMode)
}
justTouchedOperator = true
refreshCharacterScreen()
}
// "+", "-", "*", "/", "=", "X<<Y", "X>>Y", "AND", "OR", "NOR", "XOR"
@IBAction func normalCalculationTouched(sender: UIButton) {
var printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
do {
try printingNumber = expression.pushOperator(printingNumber, symbol: sender.currentTitle!)
if printMode == 16 {
numberScreen.text = "0x" + String(printingNumber, radix: printMode)
} else {
numberScreen.text = String(printingNumber, radix: printMode)
}
justTouchedOperator = true
} catch {
if printMode == 16 {
numberScreen.text = "0x0"
} else {
numberScreen.text = "0"
}
}
refreshCharacterScreen()
}
@IBAction func printingModeControl(sender: UISegmentedControl) {
let printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
switch sender.selectedSegmentIndex {
case 0:
printMode = 8
numberScreen.text = String(printingNumber, radix: 8)
changeNumberPadStatus(8)
case 1:
printMode = 10
numberScreen.text = String(printingNumber, radix: 10)
changeNumberPadStatus(10)
case 2:
printMode = 16
numberScreen.text = "0x" + String(printingNumber, radix: 16)
changeNumberPadStatus(16)
default:
print("Unknown mode in printingModeControl: \(sender.selectedSegmentIndex)\n")
}
}
@IBAction func characterModeControl(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
characterMode = "ascii"
default:
characterMode = "unicode"
}
refreshCharacterScreen()
}
// MARK: tools
// Change number pad status while the printing mode changed.
private func changeNumberPadStatus(radix: Int) {
switch radix {
case 8:
button8.enabled = false
button9.enabled = false
buttonA.enabled = false
buttonB.enabled = false
buttonC.enabled = false
buttonD.enabled = false
buttonE.enabled = false
buttonF.enabled = false
buttonFF.enabled = false
case 10:
button8.enabled = true
button9.enabled = true
buttonA.enabled = false
buttonB.enabled = false
buttonC.enabled = false
buttonD.enabled = false
buttonE.enabled = false
buttonF.enabled = false
buttonFF.enabled = false
case 16:
button8.enabled = true
button9.enabled = true
buttonA.enabled = true
buttonB.enabled = true
buttonC.enabled = true
buttonD.enabled = true
buttonE.enabled = true
buttonF.enabled = true
buttonFF.enabled = true
default:
print("Error while changing number pad statusn")
}
}
// Determine what the character screen prints.
private func refreshCharacterScreen() {
let printingNumber = UInt64(printMode == 16 ? numberScreen.text!.substringFromIndex(numberScreen.text!.startIndex.advancedBy(2)) : numberScreen.text!, radix: printMode)!
switch characterMode {
case "ascii":
var array = [Character]()
for i in 0...7 {
let tmp = UInt8(printingNumber >> UInt64(8 * (7 - i)) & 0xff)
if (tmp >= 0x20 && tmp < 0x80) {
array.append(Character(UnicodeScalar(tmp)))
}
}
characterScreen.text = String(array)
case "unicode":
var array = [Character]()
for i in 0...3 {
let tmp = UInt16(printingNumber >> UInt64(16 * (3 - i)) & 0xffff)
if (tmp != 0) {
array.append(Character(UnicodeScalar(tmp)))
}
}
characterScreen.text = String(array)
default:
characterScreen.text = ""
}
}
}
|
eb2c7f94f339362702bfc0c3d7a21016
| 37.394118 | 177 | 0.563505 | false | false | false | false |
iAugux/Zoom-Contacts
|
refs/heads/master
|
Phonetic/AppDelegate+3DTouch.swift
|
mit
|
1
|
//
// AppDelegate+3DTouch.swift
// Phonetic
//
// Created by Augus on 4/2/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import UIKit
extension AppDelegate {
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
// react to shortcut item selections
debugPrint("A shortcut item was pressed. It was ", shortcutItem.localizedTitle)
switch shortcutItem.type {
case Type.Excute.rawValue: execute()
case Type.Rollback.rawValue: rollback()
default: return
}
}
private enum Type: String {
case Excute
case Rollback
}
// MARK: Springboard Shortcut Items (dynamic)
func createShortcutItemsWithIcons() {
let executeIcon = UIApplicationShortcutIcon(type: .Add)
let rollbackIcon = UIApplicationShortcutIcon(templateImageName: "rollback_3d")
let executeItemTitle = NSLocalizedString("Add Phonetic Keys", comment: "")
let rollbackItemTitle = NSLocalizedString("Clean Contacts Keys", comment: "")
// create dynamic shortcut items
let executeItem = UIMutableApplicationShortcutItem(type: Type.Excute.rawValue, localizedTitle: executeItemTitle, localizedSubtitle: nil, icon: executeIcon, userInfo: nil)
let rollbackItem = UIMutableApplicationShortcutItem(type: Type.Rollback.rawValue, localizedTitle: rollbackItemTitle, localizedSubtitle: nil, icon: rollbackIcon, userInfo: nil)
// add all items to an array
let items = [executeItem, rollbackItem]
UIApplication.sharedApplication().shortcutItems = items
}
// MARK: - Actions
private func execute() {
viewController?.execute()
}
private func rollback() {
viewController?.clean()
}
private var viewController: ViewController? {
// ensure root vc is presenting.
window?.rootViewController?.presentedViewController?.dismissViewControllerWithoutAnimation()
return window?.rootViewController as? ViewController
}
}
|
f641efd8eab4ab5ad0309acfe37cdc8b
| 29.972603 | 183 | 0.653097 | false | false | false | false |
mckaskle/FlintKit
|
refs/heads/master
|
FlintKit/UIKit/UIColor+FlintKit.swift
|
mit
|
1
|
//
// MIT License
//
// UIColor+FlintKit.swift
//
// Copyright (c) 2017 Devin McKaskle
//
// 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 UIKit
fileprivate enum UIColorError: Error {
case couldNotGenerateImage
}
extension UIColor {
// MARK: - Object Lifecycle
/// Supported formats are: #abc, #abcf, #aabbcc, #aabbccff where:
/// - a: red
/// - b: blue
/// - c: green
/// - f: alpha
public convenience init?(hexadecimal: String) {
var normalized = hexadecimal
if normalized.hasPrefix("#") {
normalized = String(normalized.dropFirst())
}
var characterCount = normalized.count
if characterCount == 3 || characterCount == 4 {
// Double each character.
normalized = normalized.lazy.map { "\($0)\($0)" }.joined()
// Character count has doubled.
characterCount *= 2
}
if characterCount == 6 {
// If alpha was not included, add it.
normalized.append("ff")
characterCount += 2
}
// If the string is not 8 characters at this point, it could not be normalized.
guard characterCount == 8 else { return nil }
let scanner = Scanner(string: normalized)
var value: UInt32 = 0
guard scanner.scanHexInt32(&value) else { return nil }
let red = CGFloat((value & 0xFF000000) >> 24) / 255
let green = CGFloat((value & 0xFF0000) >> 16) / 255
let blue = CGFloat((value & 0xFF00) >> 8) / 255
let alpha = CGFloat(value & 0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
// MARK: - Public Methods
public func image(withSize size: CGSize) throws -> UIImage {
var alpha: CGFloat = 1
if !getRed(nil, green: nil, blue: nil, alpha: &alpha) {
alpha = 1
}
UIGraphicsBeginImageContextWithOptions(size, alpha == 1, 0)
defer { UIGraphicsEndImageContext() }
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(cgColor)
context?.fill(CGRect(origin: .zero, size: size))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
throw UIColorError.couldNotGenerateImage
}
return image
}
}
|
6003d75b972015c02a9d4225b831877b
| 30.735294 | 83 | 0.670683 | false | false | false | false |
seandavidmcgee/HumanKontactBeta
|
refs/heads/master
|
src/keyboardTest/KeyboardViewController.swift
|
mit
|
1
|
//
// KeyboardView.swift
// keyboardTest
//
// Created by Sean McGee on 5/26/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import UIKit
import Foundation
import RealmSwift
import SwiftyUserDefaults
var entrySoFar : String? = nil
var nameSearch = UITextField()
class KeyboardViewController: UIViewController, UITextFieldDelegate {
var buttonsArray: Array<UIButton> = []
var buttonsBlurArray = [AnyObject]()
var keyPresses: Int = 1
var deleteInput: UIButton!
var clearSearch: UIButton!
var moreOptionsForward = UIButton()
var moreOptionsBack = UIButton()
var altKeyboard = UIButton()
var optionsControl: Bool = false
var moreKeyPresses: Int = 0
var firstRowKeyStrings = ""
var secondRowKeyStrings = ""
var lastRowKeyStrings = ""
var buttonXFirst: CGFloat!
var buttonXSecond: CGFloat!
var buttonXThird: CGFloat!
var fieldXSearch: CGFloat!
var altXKeyboard: CGFloat!
var deleteX: CGFloat!
var dismissX: CGFloat!
var clearX: CGFloat!
var paddingW: CGFloat!
var moreOptionsX: CGFloat!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if GlobalVariables.sharedManager.keyboardFirst && !GlobalVariables.sharedManager.keyboardOrientChanged {
GlobalVariables.sharedManager.keyboardFirst = false
populateKeys()
} else if GlobalVariables.sharedManager.keyboardOrientChanged {
keyboardOrient()
for view in self.view.subviews {
if view.accessibilityLabel == "keyButton" || view.accessibilityLabel == "altKeys" {
view.removeFromSuperview()
} else if view.accessibilityLabel == "keyBlur" || view.accessibilityLabel == "searchBlur" {
view.removeFromSuperview()
} else if view.accessibilityLabel == "searchField" {
view.removeFromSuperview()
}
}
createKeyboard("changed")
populateKeys()
GlobalVariables.sharedManager.keyboardFirst = false
GlobalVariables.sharedManager.keyboardOrientChanged = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
keyboardOrient()
createKeyboard("default")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func keyboardOrient() {
if Defaults[.orient] == "right" {
buttonXFirst = 260
buttonXSecond = buttonXFirst
buttonXThird = buttonXSecond
fieldXSearch = 10
altXKeyboard = 0
dismissX = self.view.frame.width - 40
deleteX = dismissX - 54
paddingW = 15
moreOptionsX = self.view.frame.width - 260
} else if Defaults[.orient] == "left" {
buttonXFirst = self.view.frame.width - 10
buttonXSecond = buttonXFirst
buttonXThird = buttonXSecond
fieldXSearch = 111
altXKeyboard = self.view.frame.width - 50
dismissX = 10
deleteX = 64
paddingW = 41
moreOptionsX = 10
}
}
private class var indexFile : String {
print("index file path")
let directory: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.kannuu.humankontact")!
let hkIndexPath = directory.path!.stringByAppendingPathComponent("HKIndex")
return hkIndexPath
}
func refreshData() {
dispatch_async(dispatch_get_main_queue()) {
self.optionsControl = false
if let indexController = Lookup.lookupController {
GlobalVariables.sharedManager.objectKeys.removeAll(keepCapacity: false)
GlobalVariables.sharedManager.objectKeys = indexController.options!
entrySoFar = indexController.entrySoFar!
nameSearch.text = entrySoFar?.capitalizedString
contactsSearchController.searchBar.text = entrySoFar?.capitalizedString
self.optionsControl = indexController.moreOptions
if (People.people.count <= 8 && indexController.branchSelectionCount != 0 && self.keyPresses > 1) {
self.view.hidden = true
}
if (self.optionsControl == true) {
if (indexController.atTop == true) {
self.moreOptionsBack.hidden = true
}
if (self.keyPresses > 1 && indexController.optionCount == 9) {
self.moreOptionsBack.hidden = true
}
if self.moreKeyPresses == 1 {
self.moreOptionsBack.hidden = false
}
self.moreOptionsForward.hidden = false
}
else if (self.optionsControl == false && indexController.complete == true) {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = true
}
else if (self.optionsControl == false && self.moreKeyPresses != 2) {
if self.keyPresses > 1 && self.moreKeyPresses == 1 {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = false
} else {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = true
}
}
else if (self.optionsControl == false && self.moreKeyPresses == 2) {
if self.keyPresses > 1 {
self.moreOptionsForward.hidden = true
self.moreOptionsBack.hidden = true
} else {
self.moreOptionsForward.hidden = true
}
}
}
}
}
func backToInitialView() {
self.view.hidden = true
if contactsSearchController.searchBar.text != nil {
contactsSearchController.searchBar.text = ""
}
contactsSearchController.active = false
if nameSearch.text != nil {
nameSearch.text = ""
}
keyPresses = 1
if (Lookup.lookupController?.atTop == false) {
Lookup.lookupController?.restart()
self.refreshData()
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("singleReset"), userInfo: nil, repeats: false)
}
GlobalVariables.sharedManager.keyboardFirst = true
}
func createKeyboard(orient: String) {
if orient == "default" {
let BlurredKeyBG = UIImage(named: "BlurredKeyBG")
let BlurredKeyBGView = UIImageView(image: BlurredKeyBG)
BlurredKeyBGView.frame = self.view.frame
BlurredKeyBGView.contentMode = UIViewContentMode.ScaleAspectFill
BlurredKeyBGView.clipsToBounds = true
self.view.addSubview(BlurredKeyBGView)
}
nameSearch = UITextField(frame: CGRectMake(fieldXSearch, 10.0, self.view.frame.width - 122, 40.0))
nameSearch.backgroundColor = UIColor.clearColor()
nameSearch.borderStyle = UITextBorderStyle.None
nameSearch.textColor = UIColor(white: 1.0, alpha: 1.0)
nameSearch.layer.cornerRadius = 12
if Defaults[.orient] == "right" {
clearX = nameSearch.frame.maxX - 36
} else if Defaults[.orient] == "left" {
clearX = nameSearch.frame.minX
}
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView = UIVisualEffectView(effect: blur)
blurView.frame = nameSearch.frame
blurView.layer.cornerRadius = 12
blurView.clipsToBounds = true
blurView.accessibilityLabel = "searchBlur"
let paddingView = UIView(frame: CGRectMake(0, 0, paddingW, 40))
nameSearch.leftView = paddingView
nameSearch.leftViewMode = UITextFieldViewMode.Always
nameSearch.enabled = false
nameSearch.font = UIFont(name: "HelveticaNeue-Regular", size: 19)
nameSearch.accessibilityLabel = "searchField"
clearSearch = UIButton(frame: CGRect(x: clearX, y: 12, width: 36, height: 36))
clearSearch.setImage(UIImage(named: "Clear"), forState: UIControlState.Disabled)
clearSearch.setImage(UIImage(named: "Clear"), forState: UIControlState.Normal)
clearSearch.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
clearSearch.enabled = false
clearSearch.addTarget(self, action: "clearNameSearch", forControlEvents: UIControlEvents.TouchUpInside)
clearSearch.accessibilityLabel = "altKeys"
self.view.addSubview(blurView)
self.view.addSubview(nameSearch)
self.view.addSubview(clearSearch)
altKeyboard.frame = CGRect(x: altXKeyboard, y: 262, width: 50, height: 50)
altKeyboard.setImage(UIImage(named: "keyAlt"), forState: UIControlState.Normal)
altKeyboard.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
altKeyboard.addTarget(self, action: "useNormalKeyboard", forControlEvents: UIControlEvents.TouchUpInside)
altKeyboard.accessibilityLabel = "altKeys"
self.view.addSubview(altKeyboard)
self.dismissKeyboard(orient)
}
func dismissKeyboard(orient: String) {
let dismissKeyboard = UIButton(frame: CGRect(x: dismissX, y: 20, width: 30, height: 30))
dismissKeyboard.setImage(UIImage(named: "KeyboardReverse"), forState: UIControlState.Normal)
dismissKeyboard.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
dismissKeyboard.addTarget(self, action: "backToInitialView", forControlEvents: UIControlEvents.TouchUpInside)
dismissKeyboard.accessibilityLabel = "altKeys"
self.view.addSubview(dismissKeyboard)
self.deleteBtn(orient)
}
func useNormalKeyboard() {
self.view.hidden = true
contactsSearchController.active = false
self.view.window?.rootViewController!.presentViewController(normalSearchController, animated: true, completion: nil)
normalSearchController.active = true
}
func deleteBtn(orient: String) {
deleteInput = UIButton(frame: CGRect(x: deleteX, y: 18, width: 26, height: 26))
if Defaults[.orient] == "right" {
deleteInput.setImage(UIImage(named: "Delete"), forState: UIControlState.Disabled)
deleteInput.setImage(UIImage(named: "Delete"), forState: UIControlState.Normal)
} else {
deleteInput.setImage(UIImage(named: "DeleteAlt"), forState: UIControlState.Disabled)
deleteInput.setImage(UIImage(named: "DeleteAlt"), forState: UIControlState.Normal)
}
deleteInput.imageEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -10)
deleteInput.enabled = false
deleteInput.addTarget(self, action: "deleteSearchInput:", forControlEvents: .TouchUpInside)
deleteInput.accessibilityLabel = "altKeys"
self.view.addSubview(deleteInput)
self.navKeys()
}
func populateKeys() {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
if (index < 3) {
let keyButton1 = UIButton(frame: CGRect(x: self.view.frame.width - buttonXFirst, y: 75, width: 77, height: 52))
buttonXFirst = buttonXFirst - 87
keyButton1.layer.cornerRadius = keyButton1.frame.width / 6.0
keyButton1.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
keyButton1.backgroundColor = UIColor.clearColor()
keyButton1.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 17.0)
firstRowKeyStrings = "\(GlobalVariables.sharedManager.objectKeys[index])"
keyButton1.setTitle(firstRowKeyStrings.capitalizedString, forState: UIControlState.Normal)
keyButton1.setTitleColor(UIColor(white: 0.0, alpha: 1.0 ), forState: UIControlState.Highlighted)
keyButton1.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5)
keyButton1.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
keyButton1.titleLabel!.numberOfLines = 2
keyButton1.titleLabel!.text = firstRowKeyStrings.capitalizedString
keyButton1.tag = index
keyButton1.accessibilityLabel = "keyButton"
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView1 = UIVisualEffectView(effect: blur)
blurView1.frame = keyButton1.frame
blurView1.layer.cornerRadius = keyButton1.frame.width / 6.0
blurView1.clipsToBounds = true
blurView1.accessibilityLabel = "keyBlur"
buttonsArray.append(keyButton1)
buttonsBlurArray.append(blurView1)
keyButton1.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchDown);
keyButton1.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(blurView1)
self.view.addSubview(keyButton1)
}
if (index < 6 && index >= 3) {
let keyButton2 = UIButton(frame: CGRect(x: self.view.frame.width - buttonXSecond, y: 137, width: 77, height: 52))
buttonXSecond = buttonXSecond - 87
keyButton2.layer.cornerRadius = keyButton2.frame.width / 6.0
keyButton2.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
keyButton2.backgroundColor = UIColor.clearColor()
keyButton2.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 17.0)
secondRowKeyStrings = "\(GlobalVariables.sharedManager.objectKeys[index])"
keyButton2.setTitle(secondRowKeyStrings.capitalizedString, forState: UIControlState.Normal)
keyButton2.setTitleColor(UIColor(white: 0.0, alpha: 1.000 ), forState: UIControlState.Highlighted)
keyButton2.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5)
keyButton2.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
keyButton2.titleLabel!.numberOfLines = 2
keyButton2.titleLabel!.text = secondRowKeyStrings.capitalizedString
keyButton2.tag = index
keyButton2.accessibilityLabel = "keyButton"
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView2 = UIVisualEffectView(effect: blur)
blurView2.frame = keyButton2.frame
blurView2.layer.cornerRadius = keyButton2.frame.width / 6.0
blurView2.clipsToBounds = true
blurView2.accessibilityLabel = "keyBlur"
buttonsArray.append(keyButton2)
buttonsBlurArray.append(blurView2)
keyButton2.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchDown);
keyButton2.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(blurView2)
self.view.addSubview(keyButton2)
}
if (index < 9 && index >= 6) {
let keyButton3 = UIButton(frame: CGRect(x: self.view.frame.width - buttonXThird, y: 199, width: 77, height: 52))
buttonXThird = buttonXThird - 87
keyButton3.layer.cornerRadius = keyButton3.frame.width / 6.0
keyButton3.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
keyButton3.backgroundColor = UIColor.clearColor()
keyButton3.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 17.0)
lastRowKeyStrings = "\(GlobalVariables.sharedManager.objectKeys[index])"
keyButton3.setTitle(lastRowKeyStrings.capitalizedString, forState: UIControlState.Normal)
keyButton3.setTitleColor(UIColor(white: 0.0, alpha: 1.000 ), forState: UIControlState.Highlighted)
keyButton3.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5)
keyButton3.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
keyButton3.titleLabel!.numberOfLines = 2
keyButton3.titleLabel!.text = lastRowKeyStrings.capitalizedString
keyButton3.tag = index
keyButton3.accessibilityLabel = "keyButton"
let blur = UIBlurEffect(style: UIBlurEffectStyle.Light)
_ = UIVibrancyEffect(forBlurEffect: blur)
let blurView3 = UIVisualEffectView(effect: blur)
blurView3.frame = keyButton3.frame
blurView3.layer.cornerRadius = keyButton3.frame.width / 6.0
blurView3.clipsToBounds = true
blurView3.accessibilityLabel = "keyBlur"
buttonsArray.append(keyButton3)
buttonsBlurArray.append(blurView3)
keyButton3.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchDown);
keyButton3.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(blurView3)
self.view.addSubview(keyButton3)
}
}
}
func navKeys() {
let backTitle = NSAttributedString(string: "Back", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size: 17.0)!])
let moreTitle = NSAttributedString(string: "More", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size: 17.0)!])
moreOptionsBack.frame = CGRect(x: moreOptionsX, y: 273, width: 50, height: 26)
moreOptionsBack.setAttributedTitle(backTitle, forState: .Normal)
moreOptionsBack.tag = 998
moreOptionsBack.hidden = true
moreOptionsBack.addTarget(self, action: "respondToMore:", forControlEvents: UIControlEvents.TouchUpInside)
moreOptionsBack.accessibilityLabel = "altKeys"
self.view.addSubview(moreOptionsBack)
moreOptionsForward.frame = CGRect(x: moreOptionsX + 196, y: 273, width: 50, height: 26)
moreOptionsForward.setAttributedTitle(moreTitle, forState: .Normal)
moreOptionsForward.tag = 999
moreOptionsForward.hidden = true
moreOptionsForward.addTarget(self, action: "respondToMore:", forControlEvents: UIControlEvents.TouchUpInside)
moreOptionsForward.accessibilityLabel = "altKeys"
self.view.addSubview(moreOptionsForward)
}
func keyPressed(sender: UIButton!) {
Lookup.lookupController?.selectOption(sender.tag)
self.refreshData()
keyPresses++
moreKeyPresses = 0
}
func clearNameSearch() {
if contactsSearchController.searchBar.text != nil {
contactsSearchController.searchBar.text = ""
}
if nameSearch.text != nil {
nameSearch.text = ""
}
keyPresses = 1
optionsControl = false
moreKeyPresses = 0
Lookup.lookupController?.restart()
self.refreshData()
clearSearch.enabled = false
deleteInput.enabled = false
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("singleReset"), userInfo: nil, repeats: false)
}
func deleteSearchInput(sender: UIButton!) {
keyPresses--
if (keyPresses > 1) {
Lookup.lookupController?.back()
self.refreshData()
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("combinedReset"), userInfo: nil, repeats: false)
}
else {
Lookup.lookupController?.restart()
self.refreshData()
clearSearch.enabled = false
deleteInput.enabled = false
optionsControl = false
moreKeyPresses = 0
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("singleReset"), userInfo: nil, repeats: false)
}
}
func respondToMore(sender: UIButton!) {
if (sender.tag == 998) {
moreKeyPresses--
Lookup.lookupController?.back()
self.refreshData()
moreOptionsForward.hidden = false
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("respondToBackRefresh"), userInfo: nil, repeats: false)
}
if (sender.tag == 999) {
moreKeyPresses++
Lookup.lookupController?.more()
self.refreshData()
moreOptionsBack.hidden = false
_ = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("respondToForwardRefresh"), userInfo: nil, repeats: false)
}
}
func respondToBackRefresh() {
let baseKey : String = nameSearch.text!.capitalizedString
if (keyPresses == 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
buttonsArray[index].setTitle("\(keyInput.capitalizedString)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(keyInput.capitalizedString)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
}
if (keyPresses > 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(baseKey)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
}
func respondToForwardRefresh() {
let baseKey : String = nameSearch.text!.capitalizedString
if (keyPresses == 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
buttonsArray[index].setTitle("\(keyInput.capitalizedString)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(keyInput.capitalizedString)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
if (keyPresses > 1) {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(baseKey)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
}
func buttonNormal(sender: UIButton!) {
sender.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
sender.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let baseKey = sender.titleLabel!.text!
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(baseKey)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
clearSearch.enabled = true
deleteInput.enabled = true
sender.backgroundColor = UIColor.clearColor()
sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}
func combinedReset() {
let base = nameSearch.text!.capitalizedString
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
let combinedKeys = "\(base)" + "\(keyInput)"
buttonsArray[index].setTitle("\(combinedKeys)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(combinedKeys)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
if (GlobalVariables.sharedManager.objectKeys.count != self.buttonsArray.count) {
for key in GlobalVariables.sharedManager.objectKeys.count..<self.buttonsArray.count {
buttonsArray[key].hidden = true
buttonsBlurArray[key].layer.hidden = true
}
}
}
func singleReset() {
for index in 0..<GlobalVariables.sharedManager.objectKeys.count {
let keyInput = GlobalVariables.sharedManager.objectKeys[index] as! String
buttonsArray[index].setTitle("\(keyInput.capitalizedString)", forState: UIControlState.Normal)
buttonsArray[index].titleLabel!.text = "\(keyInput.capitalizedString)"
buttonsArray[index].hidden = false
buttonsBlurArray[index].layer.hidden = false
}
}
}
|
1caa94ee21e411bd0c9187c32487d4f9
| 48.012281 | 196 | 0.620002 | false | false | false | false |
viWiD/Persist
|
refs/heads/master
|
Pods/Evergreen/Sources/Evergreen/Formatter.swift
|
mit
|
1
|
//
// Formatter.swift
// Evergreen
//
// Created by Nils Fischer on 12.10.14.
// Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved.
//
import Foundation
public class Formatter {
public let components: [Component]
public init(components: [Component]) {
self.components = components
}
public enum Style {
case Default, Simple, Full
}
/// Creates a formatter from any of the predefined styles.
public convenience init(style: Style) {
let components: [Component]
switch style {
case .Default:
components = [ .Text("["), .Logger, .Text("|"), .LogLevel, .Text("] "), .Message ]
case .Simple:
components = [ .Message ]
case .Full:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
components = [ .Date(formatter: dateFormatter), .Text(" ["), .Logger, .Text("|"), .LogLevel, .Text("] "), .Message ]
}
self.init(components: components)
}
public enum Component {
case Text(String), Date(formatter: NSDateFormatter), Logger, LogLevel, Message, Function, File, Line//, Any(stringForEvent: (event: Event<M>) -> String)
public func stringForEvent<M>(event: Event<M>) -> String {
switch self {
case .Text(let text):
return text
case .Date(let formatter):
return formatter.stringFromDate(event.date)
case .Logger:
return event.logger.description
case .LogLevel:
return (event.logLevel?.description ?? "Unspecified").uppercaseString
case .Message:
switch event.message() {
case let error as NSError:
return error.localizedDescription
case let message:
return String(message)
}
case .Function:
return event.function
case .File:
return event.file
case .Line:
return String(event.line)
}
}
}
/// Produces a record from a given event. The record can be subsequently emitted by a handler.
public final func recordFromEvent<M>(event: Event<M>) -> Record {
return Record(date: event.date, description: self.stringFromEvent(event))
}
public func stringFromEvent<M>(event: Event<M>) -> String
{
var string = components.map({ $0.stringForEvent(event) }).joinWithSeparator("")
if let elapsedTime = event.elapsedTime {
string += " [ELAPSED TIME: \(elapsedTime)s]"
}
if let error = event.error {
let errorMessage: String
switch error {
case let error as CustomDebugStringConvertible:
errorMessage = error.debugDescription
case let error as CustomStringConvertible:
errorMessage = error.description
default:
errorMessage = String(error)
}
string += " [ERROR: \(errorMessage)]"
}
if event.once {
string += " [ONLY LOGGED ONCE]"
}
return string
}
}
|
2370b6af118e7d10ceabe485176a926a
| 31.592233 | 160 | 0.545427 | false | false | false | false |
leexiaosi/swift
|
refs/heads/master
|
L06Enum.playground/section-1.swift
|
mit
|
1
|
// Playground - noun: a place where people can play
import UIKit
enum Rank : Int{
case Ace = 1
case Two, Three, Four, Five, Six, Sevem, Eight, Night, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace :
return "ace"
case .Jack :
return "jack"
case .Queen :
return "queen"
default :
return String(self.toRaw())
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()
if let convertedRank = Rank.fromRaw(3){
let threeDescription = convertedRank.simpleDescription()
}
enum ServerResponse{
case Result(String, String)
case Error(String)
}
|
9f16822cb2c4d7ee4ac8d2d2a017b52d
| 18.184211 | 62 | 0.567901 | false | false | false | false |
WeHUD/app
|
refs/heads/master
|
weHub-ios/Gzone_App/Gzone_App/WBComment.swift
|
bsd-3-clause
|
1
|
//
// WBComment.swift
// Gzone_App
//
// Created by Lyes Atek on 19/06/2017.
// Copyright © 2017 Tracy Sablon. All rights reserved.
//
import Foundation
class WBComment: NSObject {
func addComment(userId : String,postId : String,text : String,accessToken : String,_ completion: @escaping (_ result: Bool) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments?access_token="+accessToken
let url: NSURL = NSURL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
request.setValue("application/json", forHTTPHeaderField: "Content-type")
let params = ["userId":userId,"postId" : postId,"text" : text]
let options : JSONSerialization.WritingOptions = JSONSerialization.WritingOptions();
do{
let requestBody = try JSONSerialization.data(withJSONObject: params, options: options)
request.httpBody = requestBody
let session = URLSession.shared
_ = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
completion( false)
}
completion(true)
}).resume()
}
catch{
print("error")
completion(false)
}
}
func deleteComment(commentId : String,accessToken : String, _ completion: @escaping (_ result: Void) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "DELETE"
let session = URLSession.shared
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
})
task.resume()
}
func getCommentByUserId(userId : String,accessToken : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/user/"+userId+"?access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentByPostId(postId : String,accessToken : String ,offset : String,_ completion: @escaping (_ result: [Comment]) -> Void){
var comments : [Comment] = []
let urlPath :String = "https://g-zone.herokuapp.com/comments/post/"+postId+"?access_token="+accessToken+"&offset="+offset
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray
print(jsonResult)
comments = self.JSONToCommentArray(jsonResult)
completion(comments)
}
catch{
print("error")
}
})
task.resume()
}
func getCommentById(commentId : String,accessToken : String,_ completion: @escaping (_ result: Comment) -> Void){
let urlPath :String = "https://g-zone.herokuapp.com/comments/"+commentId+"&access_token="+accessToken
let url: URL = URL(string: urlPath)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
print(error!.localizedDescription)
}
do{
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let comment : Comment = self.JSONToComment(json: jsonResult)!
completion(comment)
}
catch{
print("error")
}
})
task.resume()
}
func JSONToCommentArray(_ jsonEvents : NSArray) -> [Comment]{
print (jsonEvents)
var commentsTab : [Comment] = []
for object in jsonEvents{
let _id = (object as AnyObject).object(forKey: "_id") as! String
let userId = (object as AnyObject).object(forKey: "userId") as! String
let text = (object as AnyObject).object(forKey: "text") as! String
var video : String
if((object as AnyObject).object(forKey: "videos") != nil){
video = (object as AnyObject).object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = (object as AnyObject).object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
commentsTab.append(comment);
}
return commentsTab;
}
func JSONToComment(json : NSDictionary) ->Comment?{
let _id = json.object(forKey: "_id") as! String
let userId = json.object(forKey: "userId") as! String
let text = json.object(forKey: "text") as! String
var video : String
if(json.object(forKey: "videos") != nil){
video = json.object(forKey: "video") as! String
}else{
video = ""
}
let datetimeCreated = json.object(forKey: "datetimeCreated") as! String
let comment : Comment = Comment(_id: _id, userId: userId, text: text, video: video, datetimeCreated: datetimeCreated)
return comment
}
}
|
f1976166db4ad8c6cbc54ad1b452fde2
| 37.550505 | 156 | 0.555221 | false | false | false | false |
schrockblock/gtfs-stations-paris
|
refs/heads/master
|
GTFSStationsParis/Classes/PARRouteColorManager.swift
|
mit
|
1
|
//
// PARRouteColorManager.swift
// GTFSStationsParis
//
// Created by Elliot Schrock on 7/1/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import SubwayStations
open class PARRouteColorManager: NSObject, RouteColorManager {
@objc open func colorForRouteId(_ routeId: String!) -> UIColor {
var color: UIColor = UIColor.darkGray
if ["1"].contains(routeId) {color = UIColor(rgba: "#ffcd01")}
if ["2"].contains(routeId) {color = UIColor(rgba: "#006cb8")}
if ["3"].contains(routeId) {color = UIColor(rgba: "#9b993b")}
if ["3bis"].contains(routeId) {color = UIColor(rgba: "#6dc5e0")}
if ["4"].contains(routeId) {color = UIColor(rgba: "#bb4b9c")}
if ["5"].contains(routeId) {color = UIColor(rgba: "#f68f4b")}
if ["6"].contains(routeId) {color = UIColor(rgba: "#77c696")}
if ["7"].contains(routeId) {color = UIColor(rgba: "#f59fb3")}
if ["7bis"].contains(routeId) {color = UIColor(rgba: "#77c696")}
if ["8"].contains(routeId) {color = UIColor(rgba: "#c5a3cd")}
if ["9"].contains(routeId) {color = UIColor(rgba: "#cec92b")}
if ["10"].contains(routeId) {color = UIColor(rgba: "#e0b03b")}
if ["11"].contains(routeId) {color = UIColor(rgba: "#906030")}
if ["12"].contains(routeId) {color = UIColor(rgba: "#008b5a")}
if ["13"].contains(routeId) {color = UIColor(rgba: "#87d3df")}
if ["14"].contains(routeId) {color = UIColor(rgba: "#652c90")}
if ["15"].contains(routeId) {color = UIColor(rgba: "#a90f32")}
if ["16"].contains(routeId) {color = UIColor(rgba: "#ec7cae")}
if ["17"].contains(routeId) {color = UIColor(rgba: "#ec7cae")}
if ["18"].contains(routeId) {color = UIColor(rgba: "#95bf32")}
return color
}
}
extension UIColor {
@objc public convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.characters.index(rgba.startIndex, offsetBy: 1)
let hex = rgba.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix", terminator: "")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
|
6616fdfa2384f798513119222b94f501
| 45.682353 | 125 | 0.519657 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures
|
refs/heads/master
|
Algorithms/AddTwoIntLinkedLists.playground/Contents.swift
|
mit
|
1
|
//Add two
class Node{
var value:Int
init(_ value:Int){
self.value = value
}
var next:Node?
var prev:Node?
}
func addTwoNumbers(_ h1: inout Node, h2: inout Node) -> Node{
var h1Val = h1.value
var h2Val = h2.value
var multiplier = 10
while let h1Next = h1.next{
h1Val = h1Val + (h1Next.value * multiplier)
h1 = h1Next
print(h1Val)
multiplier = multiplier * 10
}
multiplier = 10
while let h2Next = h2.next{
h2Val = h2Val + (h2Next.value * multiplier)
h2 = h2Next
print(h2Val)
multiplier = multiplier * 10
}
var finalValue = h1Val + h2Val
let temp = finalValue % 10
finalValue = finalValue/10
let returnNode = Node(temp)
var connector = returnNode
while finalValue > 0{
let val = finalValue%10
finalValue = finalValue/10
let node = Node(val)
connector.next = node
connector = node
}
return returnNode
}
var a = Node(3)
var b = Node(1)
var c = Node(5)
var d = Node(5)
var e = Node(9)
var f = Node(2)
a.next = b
b.next = c
d.next = e
e.next = f
var node = addTwoNumbers(&a, h2: &d)
node.value
node.next?.value
node.next?.next?.value
|
cc00999feefc1cba324aa310d437d280
| 18.029851 | 61 | 0.564706 | false | false | false | false |
a1exb1/ABToolKit-pod
|
refs/heads/master
|
Pod/Classes/ImageLoader/ImageLoader.swift
|
mit
|
1
|
//
// ImageLoader.swift
// Pods
//
// Created by Alex Bechmann on 02/06/2015.
//
//
import UIKit
private let kImageLoaderSharedInstance = ImageLoader()
public class ImageLoader {
var cache = NSCache()
public class func sharedLoader() -> ImageLoader {
return kImageLoaderSharedInstance
}
public func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
var data: NSData? = self.cache.objectForKey(urlString) as? NSData
if let goodData = data {
let image = UIImage(data: goodData)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
var downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error != nil) {
completionHandler(image: nil, url: urlString)
return
}
if data != nil {
let image = UIImage(data: data)
self.cache.setObject(data, forKey: urlString)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
})
downloadTask.resume()
})
}
}
|
90e41c0e49abdb1cf9876209f86f65b4
| 29.492063 | 214 | 0.476563 | false | false | false | false |
delbert06/DYZB
|
refs/heads/master
|
DYZB/DYZB/PageContentView.swift
|
mit
|
1
|
//
// PageContentView.swift
// DYZB
//
// Created by 胡迪 on 2016/10/24.
// Copyright © 2016年 D.Huhu. All rights reserved.
//
import UIKit
protocol PageCollectViewDelegate : class {
func pageContentView(contentView:PageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}
let ContentCellID = "ContentCellID"
class PageContentView: UIView {
//MARK: - 定义属性
var chinldVCs:[UIViewController]
weak var parentVC:UIViewController?
var currentIndex : Int = 0
var startOffsetX : CGFloat = 0
var isForbidScrollDelege : Bool = false
weak var delegate : PageCollectViewDelegate?
//MARK: - 懒加载属性
lazy var collectionView:UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame:CGRect.zero,collectionViewLayout:layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.scrollsToTop = false
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
collectionView.delegate = self
return collectionView
}()
//MARK: - 构造函数
init(frame: CGRect,childVCs:[UIViewController],parentVC:UIViewController?) {
self.chinldVCs = childVCs
self.parentVC = parentVC
super.init(frame:frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 设置UI
extension PageContentView {
func setupUI() {
for childVC in chinldVCs {
parentVC?.addChildViewController(childVC)
}
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- 遵守UICollectionViewDataSource
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return chinldVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = chinldVCs[(indexPath as NSIndexPath).item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: - 对外暴露的方法
extension PageContentView{
func setCurrentIndex(currnetIndex: Int ){
// 记录需要进制需要进行代理方法
isForbidScrollDelege = true
let offsetX = CGFloat(currnetIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x : offsetX, y : 0), animated: true)
}
}
//MARK: - 遵守collectionViewDelegate
extension PageContentView:UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelege = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView:UIScrollView){
// 0. 判断是否是点击事件
if isForbidScrollDelege{return}
// 1. 定义需要获取的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
// 2. 判断向左或者向右滑动
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1. 计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2. 计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3. 计算targeIndex
targetIndex = sourceIndex + 1
if targetIndex >= chinldVCs.count{
targetIndex = chinldVCs.count - 1
}
// 4. 如果完全滑过去
if currentOffsetX - startOffsetX == scrollViewW{
progress = 1
targetIndex = sourceIndex
}
} else { // 右滑
// 1. 计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2. 计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3. 计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= chinldVCs.count {
sourceIndex = chinldVCs.count - 1
}
}
// 3. 把progress sourceIndex targerIndex 传递给titleView
// print("progress:\(progress)","sourceIndex:\(sourceIndex)","targetIndex:\(targetIndex)")
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
|
3d759cb61e3755d6ed253c1b24e885a6
| 30.746988 | 124 | 0.633207 | false | false | false | false |
AlexRamey/mbird-iOS
|
refs/heads/master
|
iOS Client/DevotionsController/DevotionsCoordinator.swift
|
mit
|
1
|
//
// DevotionsCoordinator.swift
// iOS Client
//
// Created by Jonathan Witten on 10/30/17.
// Copyright © 2017 Mockingbird. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
class DevotionsCoordinator: NSObject, Coordinator, UNUserNotificationCenterDelegate, DevotionTableViewDelegate {
var childCoordinators: [Coordinator] = []
var devotionsStore = MBDevotionsStore()
let scheduler: DevotionScheduler = Scheduler()
var rootViewController: UIViewController {
return self.navigationController
}
private lazy var navigationController: UINavigationController = {
return UINavigationController()
}()
func start() {
let devotionsController = MBDevotionsViewController.instantiateFromStoryboard()
devotionsController.delegate = self
navigationController.pushViewController(devotionsController, animated: true)
UNUserNotificationCenter.current().delegate = self
let devotions = devotionsStore.getDevotions()
self.scheduleDevotionsIfNecessary(devotions: devotions)
}
private func scheduleDevotionsIfNecessary(devotions: [LoadedDevotion]) {
guard let min = UserDefaults.standard.value(forKey: MBConstants.DEFAULTS_DAILY_DEVOTION_TIME_KEY) as? Int else {
return // user hasn't set up daily reminders
}
self.scheduler.promptForNotifications(withDevotions: devotions, atHour: min/60, minute: min%60) { permission in
DispatchQueue.main.async {
switch permission {
case .allowed:
print("success!")
default:
print("unable to schedule notifications")
}
}
}
}
private func showDevotionDetail(devotion: LoadedDevotion) {
let detailVC = DevotionDetailViewController.instantiateFromStoryboard(devotion: devotion)
self.navigationController.pushViewController(detailVC, animated: true)
}
// MARK: - DevotionTableViewDelegate
func selectedDevotion(_ devotion: LoadedDevotion) {
self.showDevotionDetail(devotion: devotion)
}
// MARK: - UNNotificationDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
selectTodaysDevotion()
} else {
// user dismissed notification
}
// notify the system that we're done
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(UNNotificationPresentationOptions.alert)
}
private func selectTodaysDevotion() {
let devotions = devotionsStore.getDevotions()
if let devotion = devotions.first(where: {$0.dateAsMMdd == Date().toMMddString()}) {
self.navigationController.tabBarController?.selectedIndex = 2
self.showDevotionDetail(devotion: devotion)
}
}
}
|
4fd9c9dbf467e29440be663515a6d52d
| 38.2 | 207 | 0.684874 | false | false | false | false |
andela-jejezie/FlutterwavePaymentManager
|
refs/heads/master
|
Rave/Rave/FWHelperAndConstant/CreditCardFormatter.swift
|
mit
|
1
|
//
// CreditCardFormatter.swift
// flutterwave
//
// Created by Johnson Ejezie on 23/12/2016.
// Copyright © 2016 johnsonejezie. All rights reserved.
//
import UIKit
var creditCardFormatter : CreditCardFormatter
{
return CreditCardFormatter.sharedInstance
}
internal class CreditCardFormatter : NSObject
{
static let sharedInstance : CreditCardFormatter = CreditCardFormatter()
internal func formatToCreditCardNumber(textField : UITextField, withPreviousTextContent previousTextContent : String?, andPreviousCursorPosition previousCursorSelection : UITextRange?) {
var selectedRangeStart = textField.endOfDocument
if textField.selectedTextRange?.start != nil {
selectedRangeStart = (textField.selectedTextRange?.start)!
}
if let textFieldText = textField.text
{
var targetCursorPosition : UInt = UInt(textField.offset(from:textField.beginningOfDocument, to: selectedRangeStart))
let cardNumberWithoutSpaces : String = removeNonDigitsFromString(string: textFieldText, andPreserveCursorPosition: &targetCursorPosition)
if cardNumberWithoutSpaces.characters.count > 19
{
textField.text = previousTextContent
textField.selectedTextRange = previousCursorSelection
return
}
var cardNumberWithSpaces = ""
cardNumberWithSpaces = insertSpacesIntoEvery4DigitsIntoString(string: cardNumberWithoutSpaces, andPreserveCursorPosition: &targetCursorPosition)
textField.text = cardNumberWithSpaces
if let finalCursorPosition = textField.position(from:textField.beginningOfDocument, offset: Int(targetCursorPosition))
{
textField.selectedTextRange = textField.textRange(from: finalCursorPosition, to: finalCursorPosition)
}
}
}
private func removeNonDigitsFromString(string : String, andPreserveCursorPosition cursorPosition : inout UInt) -> String {
var digitsOnlyString : String = ""
for index in stride(from: 0, to: string.characters.count, by: 1)
{
let charToAdd : Character = Array(string.characters)[index]
if isDigit(character: charToAdd)
{
digitsOnlyString.append(charToAdd)
}
else
{
if index < Int(cursorPosition)
{
cursorPosition -= 1
}
}
}
return digitsOnlyString
}
private func isDigit(character : Character) -> Bool
{
return "\(character)".containsOnlyDigits()
}
private func insertSpacesIntoEvery4DigitsIntoString(string : String, andPreserveCursorPosition cursorPosition : inout UInt) -> String {
var stringWithAddedSpaces : String = ""
for index in stride(from: 0, to: string.characters.count, by: 1)
{
if index != 0 && index % 4 == 0 && index < 16
{
stringWithAddedSpaces += " "
if index < Int(cursorPosition)
{
cursorPosition += 1
}
}
if index < 16 {
let characterToAdd : Character = Array(string.characters)[index]
stringWithAddedSpaces.append(characterToAdd)
}
}
return stringWithAddedSpaces
}
}
|
8f32cb224ccfcb630a52c95e07f758b2
| 36.698925 | 190 | 0.618939 | false | false | false | false |
konstantinpavlikhin/RowsView
|
refs/heads/master
|
Sources/AnyRowsViewDelegate.swift
|
mit
|
1
|
//
// AnyRowsViewDelegate.swift
// RowsView
//
// Created by Konstantin Pavlikhin on 30.09.16.
// Copyright © 2016 Konstantin Pavlikhin. All rights reserved.
//
import Foundation
// MARK: - Box base.
class AnyRowsViewDelegateBoxBase<A: AnyObject>: RowsViewDelegate {
// MARK: RowsViewDelegate Implementation
func cellForItemInRowsView(rowsView: RowsView<A>, atCoordinate coordinate: Coordinate) -> RowsViewCell {
abstract()
}
}
// * * *.
// MARK: - Box.
class AnyRowsViewDelegateBox<A: RowsViewDelegate>: AnyRowsViewDelegateBoxBase<A.A> {
private weak var base: A?
// MARK: Initialization
init(_ base: A) {
self.base = base
}
// MARK: RowsViewDelegate Implementation
override func cellForItemInRowsView(rowsView: RowsView<A.A>, atCoordinate coordinate: Coordinate) -> RowsViewCell {
if let b = base {
return b.cellForItemInRowsView(rowsView: rowsView, atCoordinate: coordinate)
} else {
return RowsViewCell(frame: NSZeroRect)
}
}
}
// * * *.
// MARK: - Type-erased RowsViewDelegate.
public final class AnyRowsViewDelegate<A: AnyObject> : RowsViewDelegate {
private let _box: AnyRowsViewDelegateBoxBase<A>
// MARK: Initialization
// This class can be initialized with any RowsViewDelegate.
init<S: RowsViewDelegate>(_ base: S) where S.A == A {
_box = AnyRowsViewDelegateBox(base)
}
// MARK: RowsViewDelegate Implementation
public func cellForItemInRowsView(rowsView: RowsView<A>, atCoordinate coordinate: Coordinate) -> RowsViewCell {
return _box.cellForItemInRowsView(rowsView: rowsView, atCoordinate: coordinate)
}
}
|
0a7852b50c2ace6244321a80ee63920d
| 24.25 | 117 | 0.719059 | false | false | false | false |
HabitRPG/habitrpg-ios
|
refs/heads/develop
|
HabitRPG/TableviewCells/CustomizationHeaderView.swift
|
gpl-3.0
|
1
|
//
// CustomizationHeaderView.swift
// Habitica
//
// Created by Phillip Thelen on 24.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class CustomizationHeaderView: UICollectionReusableView {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var currencyView: HRPGCurrencyCountView!
@IBOutlet weak var purchaseButton: UIView!
@IBOutlet weak var buyAllLabel: UILabel!
var purchaseButtonTapped: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
currencyView.currency = .gem
purchaseButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buttonTapped)))
buyAllLabel.text = L10n.buyAll
}
func configure(customizationSet: CustomizationSetProtocol, isBackground: Bool) {
if isBackground {
if customizationSet.key?.contains("incentive") == true {
label.text = L10n.plainBackgrounds
} else if customizationSet.key?.contains("timeTravel") == true {
label.text = L10n.timeTravelBackgrounds
} else if let key = customizationSet.key?.replacingOccurrences(of: "backgrounds", with: "") {
let index = key.index(key.startIndex, offsetBy: 2)
let month = Int(key[..<index]) ?? 0
let year = Int(key[index...]) ?? 0
let dateFormatter = DateFormatter()
let monthName = month > 0 ? dateFormatter.monthSymbols[month-1] : ""
label.text = "\(monthName) \(year)"
}
} else {
label.text = customizationSet.text
}
label.textColor = ThemeService.shared.theme.primaryTextColor
currencyView.amount = Int(customizationSet.setPrice)
purchaseButton.backgroundColor = ThemeService.shared.theme.windowBackgroundColor
purchaseButton.borderColor = ThemeService.shared.theme.tintColor
}
@objc
private func buttonTapped() {
if let action = purchaseButtonTapped {
action()
}
}
}
|
8c00afb52d8603b341b2bc4f23cce175
| 34.311475 | 114 | 0.627205 | false | false | false | false |
noremac/Futures
|
refs/heads/master
|
Futures/Deref.swift
|
mit
|
1
|
/*
The MIT License (MIT)
Copyright (c) 2016 Cameron Pulsford
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
/**
An enum representing the current state of the Promise or Future.
- Incomplete: The Deref is still running.
- Complete: The Deref has been delivered a value.
- Invalid: The Deref has been delivered an error.
*/
public enum DerefState {
/// The Deref is still running.
case incomplete
/// The Deref has been delivered a value.
case complete
/// The Deref has been delivered an error.
case invalid
}
public enum DerefValue<T> {
case success(T)
case error(NSError)
public var successValue: T? {
if case .success(let val) = self {
return val
} else {
return nil
}
}
public var error: NSError? {
if case .error(let error) = self {
return error
} else {
return nil
}
}
}
public let FutureErrorDomain = "com.smd.Futures.FuturesErrorDomain"
public enum FutureError: Int {
case canceled = -1
case timeout = -2
}
public class Deref<T> {
public typealias DerefSuccessHandler = (value: T) -> ()
public typealias DerefErrorHandler = (error: NSError) -> ()
/// Returns the delivered value, blocking indefinitely.
public var value: DerefValue<T> {
if stateLock.condition != LockState.complete.rawValue {
valueIsBeingRequested()
stateLock.lock(whenCondition: LockState.complete.rawValue)
stateLock.unlock()
}
return valueStorage!
}
/**
Returns the delivered value, blocking for up to the specified timeout. If the timeout passes without a value deing delivered, `nil` is returned.
- parameter timeout: The maximum amount of time to wait for a value to be delivered.
- returns: The delivered value or `nil` if nothing was delivered in the given timeout.
*/
public func value(withTimeout timeout: TimeInterval) -> DerefValue<T>? {
if stateLock.condition != LockState.complete.rawValue {
valueIsBeingRequested()
if self.stateLock.lock(whenCondition: LockState.complete.rawValue, before: Date(timeIntervalSinceNow: timeout)) {
self.stateLock.unlock()
}
}
return valueStorage
}
/// Returns the delivered successValue, or `nil`.
public var successValue: T? {
return value.successValue
}
/// Returns the delivered error, or `nil`.
public var error: NSError? {
return value.error
}
/// The current state of the Deref.
public var state: DerefState {
lockSync()
let s = stateStorage
unlockSync()
return s
}
/// `false` if the Deref has been invalidated; otherwise, `true`.
public var valid: Bool {
return state != .invalid
}
/* You may not publicly initialize a Deref. */
internal init() {}
/// Specify the queue on which to call the completion handler. Defaults to the main queue.
public var completionQueue: DispatchQueue {
set {
sync {
completionQueueStorage = newValue
}
}
get {
lockSync()
let cq = completionQueueStorage
unlockSync()
return cq
}
}
/**
Associates a success handler with the Deref.
- parameter handler: The success handler.
- returns: The receiver to allow for further chaining.
*/
@discardableResult
public func onSuccess(_ handler: (value: T) -> ()) -> Self {
sync {
successHandler = handler
}
return self
}
/**
Associates an error handler with the Deref.
- parameter handler: The error handler.
- returns: The receiver to allow for further chaining.
*/
@discardableResult
public func onError(_ handler: (error: NSError) -> ()) -> Self {
sync {
errorHandler = handler
}
return self
}
/// Set the desired timeout. If no error or value is delivered within the specified window, a "timeout" error will be delivered. This value may only be set once, and it must be non-nil.
public var timeout: TimeInterval? {
didSet {
precondition(timeout != nil)
sync {
precondition(timeoutTimer == nil)
if stateStorage == .incomplete {
timeoutTimer = TimerThread.sharedInstance.timer(timeInterval: timeout!, target: self, selector: #selector(Deref.deliverTimeoutError))
}
}
}
}
private var timeoutTimer: Timer?
@discardableResult
@objc internal func deliverTimeoutError() {
invalidate(NSError(domain: FutureErrorDomain, code: FutureError.timeout.rawValue, userInfo: nil))
}
// MARK: - Delivering a value
@discardableResult
internal func deliver(derefValue value: DerefValue<T>) -> Bool {
guard stateLock.tryLock(whenCondition: LockState.waiting.rawValue) else {
return false
}
sync {
if let timer = timeoutTimer {
TimerThread.sharedInstance.invalidate(timer: timer)
}
valueStorage = value
if value.successValue == nil {
stateStorage = .invalid
} else {
stateStorage = .complete
}
}
stateLock.unlock(withCondition: LockState.complete.rawValue)
if let v = value.successValue {
sync {
if let sh = successHandler {
completionQueue.async {
sh(value: v)
}
}
}
} else if let error = value.error {
sync {
if let eh = errorHandler {
completionQueue.async {
eh(error: error)
}
}
}
}
return true
}
/**
Delivers a value to the Deref.
- parameter value: The value to deliver.
- returns: true if the value was delivered successfully; otherwise, false if a value has already been delivered or invalidated.
*/
@discardableResult
public func deliver(_ value: T) -> Bool {
return deliver(derefValue: .success(value))
}
/**
Invalidates the Deref with the given error. Fails if the Promise was previously delivered, or invalidated.
- parameter error: The error to invalidate the Promise with.
- returns: true if the Promise was invalidated successfully; otherwise, false if it was previously delivered or invalidated.
*/
@discardableResult
public func invalidate(_ error: NSError) -> Bool {
return deliver(derefValue: .error(error))
}
// MARK: - Internal utils
internal func valueIsBeingRequested() {
}
// MARK: - Managing the internal lock
private func lockSync() {
syncLock.lock()
}
private func unlockSync() {
syncLock.unlock()
}
private func sync(_ work: @noescape () -> ()) {
lockSync()
work()
unlockSync()
}
// MARK: - Privat vars
private let stateLock = ConditionLock(condition: LockState.waiting.rawValue)
private var syncLock = RecursiveLock()
private var valueStorage: DerefValue<T>?
private var successHandler: DerefSuccessHandler?
private var errorHandler: DerefErrorHandler?
private var stateStorage = DerefState.incomplete
private var completionQueueStorage = DispatchQueue.main
}
|
7f9e216a1c6aad6ae2a7cc9a68b41ea7
| 27.788079 | 189 | 0.619623 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Status/Views/RestoreStatusView.swift
|
gpl-2.0
|
2
|
import Foundation
import Gridicons
import WordPressUI
class RestoreStatusView: UIView, NibLoadable {
// MARK: - Properties
@IBOutlet private weak var icon: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private weak var progressTitleLabel: UILabel!
@IBOutlet private weak var progressValueLabel: UILabel!
@IBOutlet private weak var progressView: UIProgressView!
@IBOutlet private weak var progressDescriptionLabel: UILabel!
@IBOutlet private weak var hintLabel: UILabel!
// MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
// MARK: - Styling
private func applyStyles() {
backgroundColor = .basicBackground
icon.tintColor = .success
titleLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold)
titleLabel.textColor = .text
titleLabel.numberOfLines = 0
descriptionLabel.font = WPStyleGuide.fontForTextStyle(.body)
descriptionLabel.textColor = .textSubtle
descriptionLabel.numberOfLines = 0
progressValueLabel.font = WPStyleGuide.fontForTextStyle(.body)
progressValueLabel.textColor = .text
progressTitleLabel.font = WPStyleGuide.fontForTextStyle(.body)
progressTitleLabel.textColor = .text
if effectiveUserInterfaceLayoutDirection == .leftToRight {
// swiftlint:disable:next inverse_text_alignment
progressTitleLabel.textAlignment = .right
} else {
// swiftlint:disable:next natural_text_alignment
progressTitleLabel.textAlignment = .left
}
progressView.layer.cornerRadius = Constants.progressViewCornerRadius
progressView.clipsToBounds = true
progressDescriptionLabel.font = WPStyleGuide.fontForTextStyle(.subheadline)
progressDescriptionLabel.textColor = .textSubtle
hintLabel.font = WPStyleGuide.fontForTextStyle(.subheadline)
hintLabel.textColor = .textSubtle
hintLabel.numberOfLines = 0
}
// MARK: - Configuration
func configure(iconImage: UIImage, title: String, description: String, hint: String) {
icon.image = iconImage
titleLabel.text = title
descriptionLabel.text = description
hintLabel.text = hint
}
func update(progress: Int, progressTitle: String? = nil, progressDescription: String? = nil) {
progressValueLabel.text = "\(progress)%"
progressView.progress = Float(progress) / 100
if let progressTitle = progressTitle {
progressTitleLabel.text = progressTitle
progressTitleLabel.isHidden = false
} else {
progressTitleLabel.isHidden = true
}
if let progressDescription = progressDescription {
progressDescriptionLabel.text = progressDescription
progressDescriptionLabel.isHidden = false
} else {
progressDescriptionLabel.isHidden = true
}
}
// MARK: - IBAction
private enum Constants {
static let progressViewCornerRadius: CGFloat = 4
}
}
|
8ac0bd388d23d2183f02356c7f9a0852
| 32.195876 | 98 | 0.681366 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
UICollectionViewLayout/Blueprints-master/Example-OSX/Scenes/LayoutExampleSceneViewController+CollectionView.swift
|
mit
|
1
|
import Cocoa
extension LayoutExampleSceneViewController: NSCollectionViewDataSource {
func numberOfSections(in collectionView: NSCollectionView) -> Int {
return (exampleDataSource?.count) ?? (0)
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return (exampleDataSource?[section].contents?.count) ?? (0)
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
return layoutExampleItem(itemForRepresentedObjectAt: indexPath)
}
func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView {
switch kind {
case NSCollectionView.elementKindSectionHeader:
return headerTitleCollectionViewElement(forItemAt: indexPath)
case NSCollectionView.elementKindSectionFooter:
return footerTitleCollectionViewElement(forItemAt: indexPath)
default:
return NSView()
}
}
// TODO: - Update this once we have implemented dynamic heights.
/*func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
return headerTitleCollectionReusableView(forItemAt: indexPath)
case UICollectionView.elementKindSectionFooter:
return footerTitleCollectionReusableView(forItemAt: indexPath)
default:
return UICollectionReusableView()
}
}*/
}
extension LayoutExampleSceneViewController: NSCollectionViewDelegateFlowLayout {
// TODO: - Update this value once we have implemented dynamic heights.
/*func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
guard let cachedCellSize = dynamicCellSizeCache[safe: indexPath.section]?[safe: indexPath.item] else {
let insertedCellSize = addCellSizeToCache(forItemAt: indexPath)
return insertedCellSize
}
return cachedCellSize
}*/
}
extension LayoutExampleSceneViewController {
private func headerTitleCollectionViewElement(forItemAt indexPath: IndexPath) -> TitleCollectionViewElement {
let titleViewElementIdentifier = Constants
.CollectionViewItemIdentifiers
.titleViewElement
.rawValue
guard let titleViewElementView = layoutExampleCollectionView.makeSupplementaryView(
ofKind: NSCollectionView.elementKindSectionHeader,
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: titleViewElementIdentifier),
for: indexPath) as? TitleCollectionViewElement else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
let title = "\((exampleDataSource?[indexPath.section].title) ?? ("Section")) Header"
titleViewElementView.configure(withTitle: title)
return titleViewElementView
}
private func footerTitleCollectionViewElement(forItemAt indexPath: IndexPath) -> TitleCollectionViewElement {
let titleViewElementIdentifier = Constants
.CollectionViewItemIdentifiers
.titleViewElement
.rawValue
guard let titleViewElementView = layoutExampleCollectionView.makeSupplementaryView(
ofKind: NSCollectionView.elementKindSectionFooter,
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: titleViewElementIdentifier),
for: indexPath) as? TitleCollectionViewElement else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
let title = "\((exampleDataSource?[indexPath.section].title) ?? ("Section")) Footer"
titleViewElementView.configure(withTitle: title)
return titleViewElementView
}
private func layoutExampleItem(itemForRepresentedObjectAt indexPath: IndexPath) -> LayoutExampleCollectionViewItem {
let layoutExampleCellIdentifier = Constants
.CollectionViewItemIdentifiers
.layoutExampleItem
.rawValue
guard let layoutExampleCollectionViewItem = layoutExampleCollectionView.makeItem(
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: layoutExampleCellIdentifier),
for: indexPath) as? LayoutExampleCollectionViewItem else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
layoutExampleCollectionViewItem.configure(forExampleContent: exampleDataSource?[indexPath.section].contents?[indexPath.item])
return layoutExampleCollectionViewItem
}
// TODO: - Update this value once we have implemented dynamic heights.
/*func addCellSizeToCache(forItemAt indexPath: IndexPath) -> CGSize {
let cellSize = layoutExampleCellCalculatedSize(forItemAt: indexPath)
guard dynamicCellSizeCache[safe: indexPath.section] != nil else {
dynamicCellSizeCache.append([cellSize])
return cellSize
}
dynamicCellSizeCache[indexPath.section].insert(cellSize, at: indexPath.item)
return cellSize
}
// TODO: - Research into how the implementation differs from iOS as we need to load a dummy cell with the content to get the size.
// - Cant use makeItem as the collectionView has not been finalised at this time.
func layoutExampleCellCalculatedSize(forItemAt indexPath: IndexPath) -> CGSize {
let layoutExampleCellIdentifier = Constants
.CollectionViewItemIdentifiers
.layoutExampleItem
.rawValue
guard let layoutExampleCollectionViewItem = layoutExampleCollectionView.makeItem(
withIdentifier: NSUserInterfaceItemIdentifier(rawValue: layoutExampleCellIdentifier),
for: indexPath) as? LayoutExampleCollectionViewItem else {
fatalError("Failed to makeItem at indexPath \(indexPath)")
}
layoutExampleCollectionViewItem.configure(forExampleContent: exampleDataSource?[indexPath.section].contents?[indexPath.item])
return layoutExampleCollectionViewItem.view.fittingSize
}
func widthForCellInCurrentLayout() -> CGFloat {
var cellWidth = layoutExampleCollectionView.frame.size.width - (sectionInsets.left + sectionInsets.right)
if itemsPerRow > 1 {
cellWidth -= minimumInteritemSpacing * (itemsPerRow - 1)
}
return floor(cellWidth / itemsPerRow)
}*/
func scrollLayoutExampleCollectionViewToTopItem() {
let initalIndexPath = IndexPath(item: 0, section: 0)
if let sectionHeader = layoutExampleCollectionView.supplementaryView(
forElementKind: NSCollectionView.elementKindSectionHeader,
at: initalIndexPath) {
layoutExampleCollectionView.scrollToVisible(
NSRect(x: sectionHeader.bounds.origin.x,
y: sectionHeader.bounds.origin.y,
width: sectionHeader.bounds.width,
height: sectionHeader.bounds.height))
} else if layoutExampleCollectionView.item(at: initalIndexPath) != nil {
layoutExampleCollectionView.scrollToItems(
at: [initalIndexPath],
scrollPosition: NSCollectionView.ScrollPosition.top)
}
}
}
|
da8db99402345bb868fabfa67eb8f331
| 48.875 | 179 | 0.711384 | false | false | false | false |
mrdepth/EVEOnlineAPI
|
refs/heads/master
|
EVEAPI/EVEAPI/EVEPlanetaryPins.swift
|
mit
|
1
|
//
// EVEPlanetaryPins.swift
// EVEAPI
//
// Created by Artem Shimanski on 29.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVEPlanetaryPinsItem: EVEObject {
public var pinID: Int64 = 0
public var typeID: Int = 0
public var typeName: String = ""
public var schematicID: Int = 0
public var lastLaunchTime: Date = Date.distantPast
public var cycleTime: Int = 0
public var quantityPerCycle: Int = 0
public var installTime: Date = Date.distantPast
public var expiryTime: Date = Date.distantPast
public var contentTypeID: Int = 0
public var contentTypeName: String = ""
public var contentQuantity: Int = 0
public var longitude: Double = 0
public var latitude: Double = 0
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"pinID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"typeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"typeName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"schematicID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"lastLaunchTime":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"cycleTime":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"quantityPerCycle":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"installTime":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"expiryTime":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"contentTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"contentTypeName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"contentQuantity":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"longitude":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"latitude":EVESchemeElementType.Double(elementName:nil, transformer:nil),
]
}
}
public class EVEPlanetaryPins: EVEResult {
public var pins: [EVEPlanetaryPinsItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"pins":EVESchemeElementType.Rowset(elementName: nil, type: EVEPlanetaryPinsItem.self, transformer: nil),
]
}
}
|
9df08221ee91fee0bf062654ccb5cd78
| 33.821918 | 107 | 0.763965 | false | false | false | false |
Dwarven/ShadowsocksX-NG
|
refs/heads/develop
|
MoyaRefreshToken/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift
|
apache-2.0
|
4
|
//
// AsMaybe.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/12/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
fileprivate final class AsMaybeSink<O: ObserverType> : Sink<O>, ObserverType {
typealias ElementType = O.E
typealias E = ElementType
private var _element: Event<E>?
func on(_ event: Event<E>) {
switch event {
case .next:
if self._element != nil {
self.forwardOn(.error(RxError.moreThanOneElement))
self.dispose()
}
self._element = event
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
if let element = self._element {
self.forwardOn(element)
}
self.forwardOn(.completed)
self.dispose()
}
}
}
final class AsMaybe<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = AsMaybeSink(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
|
88f12286a5c260e55f4c0f5f49287db5
| 27.22449 | 145 | 0.588576 | false | false | false | false |
InkAnimator/SKInkAnimator
|
refs/heads/master
|
SKInkAnimator/Classes/ActionFactory.swift
|
mit
|
1
|
//
// AnimationFactory.swift
// Pods
//
// Created by Rafael Moura on 16/03/17.
//
//
import Foundation
import AEXML
import SpriteKit
class ActionFactory: NSObject {
static func action(for keyframe: Keyframe, previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction {
var group = [SKAction]()
if let moveAction = moveAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(moveAction)
}
if let rotateAction = rotateAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(rotateAction)
}
if let resizeAction = resizeAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(resizeAction)
}
if let scaleAction = scaleAction(with: keyframe, and: previousKeyframe, duration: duration) {
group.append(scaleAction)
}
return group.count > 0 ? SKAction.group(group) : SKAction.wait(forDuration: duration)
}
static private func rotateAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.rotation == previousKeyframe.rotation {
return nil
}
let action: SKAction
action = SKAction.rotate(toAngle: keyframe.rotation, duration: duration, shortestUnitArc: false)
action.timingMode = actionTimingMode(for: keyframe.timingMode)
return action
}
static private func resizeAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.size == previousKeyframe.size {
return nil
}
let action: SKAction
action = SKAction.resize(toWidth: keyframe.size.width, height: keyframe.size.height, duration: duration)
action.timingMode = actionTimingMode(for: keyframe.timingMode)
return action
}
static private func scaleAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.scale == previousKeyframe.scale {
return nil
}
let action: SKAction
action = SKAction.scaleX(to: keyframe.scale.x, y: keyframe.scale.y, duration: duration)
return action
}
static private func moveAction(with keyframe: Keyframe, and previousKeyframe: Keyframe?, duration: TimeInterval) -> SKAction? {
if let previousKeyframe = previousKeyframe, keyframe.position == previousKeyframe.position {
return nil
}
let action: SKAction
action = SKAction.move(to: keyframe.position, duration: duration)
action.timingMode = actionTimingMode(for: keyframe.timingMode)
return action
}
static private func actionTimingMode(for timingMode: Keyframe.TimingMode) -> SKActionTimingMode {
switch timingMode {
case .linear:
return .linear
case .easeIn:
return .easeIn
case .easeOut:
return .easeOut
case .easeInEaseOut:
return .easeInEaseOut
}
}
}
|
bf629e6cc05ef83b367f41194b01c990
| 33.626263 | 133 | 0.635648 | false | false | false | false |
ktmswzw/FeelClient
|
refs/heads/master
|
FeelingClient/common/utils/MapHelper.swift
|
mit
|
1
|
//
// MapHelper.swift
// FeelingClient
//
// Created by Vincent on 16/3/25.
// Copyright © 2016年 xecoder. All rights reserved.
//
import Foundation
import MapKit
let a = 6378245.0
let ee = 0.00669342162296594323
// World Geodetic System ==> Mars Geodetic System
func outOfChina(coordinate: CLLocationCoordinate2D) -> Bool {
if coordinate.longitude < 72.004 || coordinate.longitude > 137.8347 {
return true
}
if coordinate.latitude < 0.8293 || coordinate.latitude > 55.8271 {
return true
}
return false
}
func transformLat(x: Double, y: Double) -> Double {
var ret = -100.0 + 2.0 * x + 3.0 * y
ret += 0.2 * y * y + 0.1 * x * y
ret += 0.2 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0
ret += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0
ret += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0
return ret;
}
func transformLon(x: Double, y: Double) -> Double {
var ret = 300.0 + x + 2.0 * y
ret += 0.1 * x * x + 0.1 * x * y
ret += 0.1 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0
ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0
ret += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0
return ret;
}
// 地球坐标系 (WGS-84) -> 火星坐标系 (GCJ-02)
func wgs2gcj(coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
if outOfChina(coordinate) == true {
return coordinate
}
let wgLat = coordinate.latitude
let wgLon = coordinate.longitude
var dLat = transformLat(wgLon - 105.0, y: wgLat - 35.0)
var dLon = transformLon(wgLon - 105.0, y: wgLat - 35.0)
let radLat = wgLat / 180.0 * M_PI
var magic = sin(radLat)
magic = 1 - ee * magic * magic
let sqrtMagic = sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI)
dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI)
return CLLocationCoordinate2DMake(wgLat + dLat, wgLon + dLon)
}
// 地球坐标系 (WGS-84) <- 火星坐标系 (GCJ-02)
func gcj2wgs(coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D {
if outOfChina(coordinate) == true {
return coordinate
}
let c2 = wgs2gcj(coordinate)
return CLLocationCoordinate2DMake(2 * coordinate.latitude - c2.latitude, 2 * coordinate.longitude - c2.longitude)
}
// 计算两点距离
func getDistinct(currentLocation:CLLocation,targetLocation:CLLocation) -> Double
{
let distance:CLLocationDistance = currentLocation.distanceFromLocation(targetLocation)
return distance
}
extension CLLocationCoordinate2D {
func toMars() -> CLLocationCoordinate2D {
return wgs2gcj(self)
}
}
|
1f4bc455f62a9495f066418d6585ad7f
| 30.873563 | 117 | 0.601154 | false | false | false | false |
IBM-Swift/Kitura
|
refs/heads/master
|
Sources/Kitura/CodableRouter+TypeSafeMiddleware.swift
|
apache-2.0
|
1
|
/*
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import LoggerAPI
import KituraNet
import KituraContracts
// Type-safe middleware Codable router
extension Router {
// MARK: Codable Routing with TypeSafeMiddleware
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and returns a single Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and returns a single Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and returns a single Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET(Single) typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User` array, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user else {
return respondWith(nil, .notFound)
}
respondWith([user], nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, id: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and an Identifier, and returns a single of Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an identifier
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, id: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and an Identifier, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an identifier
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and an Identifier, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerGetRoute(route: route, id: Id.self, outputType: O.self)
get(appendId(path: route)) { request, response, next in
Log.verbose("Received GET (singular with identifier and middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: ([(Int, User)]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, and returns an array of (Identifier, Codable) tuples or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, and returns an array of (Identifier, Codable) tuples or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with an array of (`Identifier`, Codable) tuples or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [(Int, User)] dictionary, where `User` conforms to Codable.
```swift
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: ([(Int, User)]?, RequestError?) -> Void) in
guard let users: [(Int, User)] = session.users else {
return respondWith(nil, .notFound)
}
respondWith(users, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, and returns an array of (Identifier, Codable) tuples or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping IdentifierCodableArrayResultClosure<Id, O>) -> Void
) {
registerGetRoute(route: route, id: Id.self, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET(Array) with identifier typed middleware request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructTupleArrayOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, query: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns a single of Codable object or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rquery: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns a single of Codable object or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping CodableResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (singular) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
// Define result handler
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
respondWith(userArray, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.get("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: ([User]?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a QueryParams instance, and returns an array of Codable objects or a RequestError.
*/
public func get<T: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, middle2: Middle2, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
return respondWith(userArray, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: [User]] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, query: Query, respondWith: ([User]?, RequestError?) -> Void) in
guard let user: [User] = session.user[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: false, outputType: O.self, outputIsArray: true)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a GET request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with an array of Codable objects or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (auth: MyHTTPAuth, middle2: Middle2, middle3: Middle3, query: Query?, respondWith: ([User]?, RequestError?) -> Void) in
if let query = query {
let matchedUsers = userArray.filter { $0.id <= query.id }
return respondWith(matchedUsers, nil)
} else {
return respondWith(userArray, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a QueryParams instance, and returns an array of Codable objects or a RequestError.
:nodoc:
*/
public func get<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Q?, @escaping CodableArrayResultClosure<O>) -> Void
) {
registerGetRoute(route: route, queryParams: Q.self, optionalQParam: true, outputType: O.self)
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructOutResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
*/
public func delete<T: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
handler(typeSafeMiddleware, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T1, T2, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, respondWith: (RequestError?) -> Void) in
session.user: User? = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and returns a RequestError or nil on success.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware>(
_ route: String,
handler: @escaping (T1, T2, T3, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route)
delete(route) { request, response, next in
Log.verbose("Received DELETE (plural with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, id: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, id: Int,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, id: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T1, T2, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, respondWith: (RequestError?) -> Void) in
session.user[id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, @escaping ResultClosure) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerDeleteRoute(route: route, id: Id.self)
delete(appendId(path: route)) { request, response, next in
Log.verbose("Received DELETE (singular with middleware) type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, CodableHelpers.constructResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, query: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.delete("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, query: Query?,
respondWith: (RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
*/
public func delete<T: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, middle2: Middle2, query: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, middle2, Middle2, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rquery: Query, respondWith: (RequestError?) -> Void) in
session.user[query.id] = nil
respondWith(nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, T3, Q, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: false)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a DELETE request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, the parsed query parameters,
and a handler which responds with nil on success, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MyHTTPAuth` is a struct that conforms to the `TypeSafeHTTPBasic` protocol from `Kitura-CredentialsHTTP` to provide basic HTTP authentication.
```swift
struct Query: QueryParams {
let id: Int
}
router.delete("/user") { (auth: MyHTTPAuth, middle2, Middle2, middle3, Middle3, query: Query?, respondWith: (RequestError?) -> Void) in
if let query = query {
userArray = userArray.filter { $0.id != query.id }
return respondWith(nil)
} else {
userArray = []
return respondWith(nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware and Identifier, and returns nil on success, or a `RequestError`.
:nodoc:
*/
public func delete<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Q: QueryParams>(
_ route: String,
handler: @escaping (T1, T2, T3, Q?, @escaping ResultClosure) -> Void
) {
registerDeleteRoute(route: route, queryParams: Q.self, optionalQParam: true)
delete(route) { request, response, next in
Log.verbose("Received DELETE type-safe request with middleware and Query Parameters")
Log.verbose("Query Parameters: \(request.queryParameters)")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
do {
var query: Q? = nil
let queryParameters = request.queryParameters
if queryParameters.count > 0 {
query = try QueryDecoder(dictionary: queryParameters).decode(Q.self)
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, query, CodableHelpers.constructResultHandler(response: response, completion: next))
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, user: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.post("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, user: User,
respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a Codable object, and returns a Codable object or a RequestError.
*/
public func post<T: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, user: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an optional `User`, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, ruser: User, respondWith: (User?, RequestError?) -> Void) in
if session.user == nil {
return respondWith(nil, .badRequest)
} else {
session.user = user
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, I, @escaping CodableResultClosure<O>) -> Void
) {
registerPostRoute(route: route, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
next()
return
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, codableInput, CodableHelpers.constructOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.post("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance and a Codable object, and returns an Identifier and a Codable object or a RequestError.
*/
public func post<T: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, user: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances and a Codable object, and returns an Identifier and a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a POST request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, a Codable object
and a handler which responds with an `Identifier` and a Codable object, or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, ruser: User, respondWith: (Int?, User?, RequestError?) -> Void) in
let newId = session.users.count + 1
session.user[newId] = user
respondWith(newId, user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances and a Codable object, and returns an Identifier and a Codable object or a RequestError.
:nodoc:
*/
public func post<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, I: Codable, Id: Identifier, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, I, @escaping IdentifierCodableResultClosure<Id, O>) -> Void
) {
registerPostRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response) else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, codableInput, CodableHelpers.constructIdentOutResultHandler(successStatus: .created, response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.put("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, an Identifier and a Codable object, and returns a Codable object or a RequestError.
*/
public func put<T: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func put<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PUT request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.post("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, r id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
session.user[id] = user
respondWith(user, nil)
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func put<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPutRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
put(appendId(path: route)) { request, response, next in
Log.verbose("Received PUT type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts a successfully executed instance of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, id: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
#### Multiple Middleware: ####
The closure can process up to three `TypeSafeMiddleware` objects by defining them in the handler:
```swift
router.patch("/user") { (middle1: Middle1, middle2: Middle2, middle3: Middle3,
id: Int, user: User, respondWith: (User?, RequestError?) -> Void) in
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives a TypeSafeMiddleware instance, an Identifier and a Codable object, and returns a Codable object or a RequestError.
*/
public func patch<T: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T.self, request: request, response: response) { typeSafeMiddleware in
guard let typeSafeMiddleware = typeSafeMiddleware else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts two successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, middle2: Middle2, id: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives two TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func patch<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T1.self, T2.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
/**
Sets up a closure that will be invoked when a PATCH request to the provided route is received by the server.
The closure accepts three successfully executed instances of `TypeSafeMiddleware`, an `Identifier`, a Codable object
and a handler which responds with a single Codable object or a `RequestError`.
The handler contains the developer's logic, which determines the server's response.
### Usage Example: ###
In this example, `MySession` is a struct that conforms to the `TypeSafeMiddleware` protocol and specifies an [Int: User] dictionary, where `User` conforms to Codable.
```swift
router.patch("/user") { (session: MySession, middle2: Middle2, middle3: Middle3, rid: Int, inputUser: User, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = session.user[id] else {
return respondWith(nil, .notFound)
}
user.id = inputUser.id ?? user.id
user.name = inputUser.name ?? user.name
respondWith(user, nil)
}
}
```
- Parameter route: A String specifying the URL path that will invoke the handler.
- Parameter handler: A closure that receives three TypeSafeMiddleware instances, an Identifier and a Codable object, and returns a Codable object or a RequestError.
:nodoc:
*/
public func patch<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware, Id: Identifier, I: Codable, O: Codable>(
_ route: String,
handler: @escaping (T1, T2, T3, Id, I, @escaping CodableResultClosure<O>) -> Void
) {
if !pathSyntaxIsValid(route, identifierExpected: true) {
return
}
registerPatchRoute(route: route, id: Id.self, inputType: I.self, outputType: O.self)
patch(appendId(path: route)) { request, response, next in
Log.verbose("Received PATCH type-safe request")
self.handleMiddleware(T1.self, T2.self, T3.self, request: request, response: response) { typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3 in
guard let typeSafeMiddleware1 = typeSafeMiddleware1, let typeSafeMiddleware2 = typeSafeMiddleware2, let typeSafeMiddleware3 = typeSafeMiddleware3 else {
return next()
}
guard let identifier = CodableHelpers.parseIdOrSetResponseStatus(Id.self, from: request, response: response),
let codableInput = CodableHelpers.readCodableOrSetResponseStatus(I.self, from: request, response: response)
else {
return next()
}
handler(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3, identifier, codableInput, CodableHelpers.constructOutResultHandler(response: response, completion: next))
}
}
}
// Function to call the static handle function of a TypeSafeMiddleware and on success return
// an instance of the middleware or on failing set the response error and return nil.
private func handleMiddleware<T: TypeSafeMiddleware>(
_ middlewareType: T.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T?) -> Void
) {
T.handle(request: request, response: response) { (typeSafeMiddleware: T?, error: RequestError?) in
guard let typeSafeMiddleware = typeSafeMiddleware else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil)
}
completion(typeSafeMiddleware)
}
}
// Function to call the static handle function of two TypeSafeMiddleware in sequence and on success return
// both instances of the middlewares or on failing set the response error and return at least one nil.
private func handleMiddleware<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware>(
_ middlewareOneType: T1.Type,
_ middlewareTwoType: T2.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T1?, T2?) -> Void
) {
T1.handle(request: request, response: response) { (typeSafeMiddleware1: T1?, error: RequestError?) in
guard let typeSafeMiddleware1 = typeSafeMiddleware1 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil, nil)
}
T2.handle(request: request, response: response) { (typeSafeMiddleware2: T2?, error: RequestError?) in
guard let typeSafeMiddleware2 = typeSafeMiddleware2 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, nil)
}
completion(typeSafeMiddleware1, typeSafeMiddleware2)
}
}
}
// Function to call the static handle function of three TypeSafeMiddleware in sequence and on success return
// all instances of the middlewares or on failing set the response error and return at least one nil.
private func handleMiddleware<T1: TypeSafeMiddleware, T2: TypeSafeMiddleware, T3: TypeSafeMiddleware>(
_ middlewareOneType: T1.Type,
_ middlewareTwoType: T2.Type,
_ middlewareThreeType: T3.Type,
request: RouterRequest,
response: RouterResponse,
completion: @escaping (T1?, T2?, T3?) -> Void
) {
T1.handle(request: request, response: response) { (typeSafeMiddleware1: T1?, error: RequestError?) in
guard let typeSafeMiddleware1 = typeSafeMiddleware1 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(nil, nil, nil)
}
T2.handle(request: request, response: response) { (typeSafeMiddleware2: T2?, error: RequestError?) in
guard let typeSafeMiddleware2 = typeSafeMiddleware2 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, nil, nil)
}
T3.handle(request: request, response: response) { (typeSafeMiddleware3: T3?, error: RequestError?) in
guard let typeSafeMiddleware3 = typeSafeMiddleware3 else {
response.status(CodableHelpers.httpStatusCode(from: error ?? .internalServerError))
return completion(typeSafeMiddleware1, typeSafeMiddleware2, nil)
}
completion(typeSafeMiddleware1, typeSafeMiddleware2, typeSafeMiddleware3)
}
}
}
}
}
|
a04ffaccf355dd54c34c35b25bb6d866
| 55.379864 | 210 | 0.654494 | false | false | false | false |
noppoMan/aws-sdk-swift
|
refs/heads/main
|
Sources/Soto/Extensions/S3/S3RequestMiddleware.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import NIO
import SotoCore
import SotoCrypto
import SotoXML
public struct S3RequestMiddleware: AWSServiceMiddleware {
public init() {}
/// edit request before sending to S3
public func chain(request: AWSRequest, context: AWSMiddlewareContext) throws -> AWSRequest {
var request = request
self.virtualAddressFixup(request: &request, context: context)
self.createBucketFixup(request: &request)
self.calculateMD5(request: &request)
return request
}
/// Edit responses coming back from S3
public func chain(response: AWSResponse, context: AWSMiddlewareContext) throws -> AWSResponse {
var response = response
self.metadataFixup(response: &response)
self.getLocationResponseFixup(response: &response)
return response
}
func virtualAddressFixup(request: inout AWSRequest, context: AWSMiddlewareContext) {
/// process URL into form ${bucket}.s3.amazon.com
let paths = request.url.path.split(separator: "/", omittingEmptySubsequences: true)
if paths.count > 0 {
guard var host = request.url.host else { return }
if let port = request.url.port {
host = "\(host):\(port)"
}
let bucket = paths[0]
var urlPath: String
var urlHost: String
// if host name contains amazonaws.com and bucket name doesn't contain a period do virtual address look up
if host.contains("amazonaws.com") || context.options.contains(.s3ForceVirtualHost), !bucket.contains(".") {
let pathsWithoutBucket = paths.dropFirst() // bucket
urlPath = pathsWithoutBucket.joined(separator: "/")
if let firstHostComponent = host.split(separator: ".").first, bucket == firstHostComponent {
// Bucket name is part of host. No need to append bucket
urlHost = host
} else {
urlHost = "\(bucket).\(host)"
}
} else {
urlPath = paths.joined(separator: "/")
urlHost = host
}
// add percent encoding back into path as converting from URL to String has removed it
let percentEncodedUrlPath = Self.urlEncodePath(urlPath)
var urlString = "\(request.url.scheme ?? "https")://\(urlHost)/\(percentEncodedUrlPath)"
if let query = request.url.query {
urlString += "?\(query)"
}
request.url = URL(string: urlString)!
}
}
static let pathAllowedCharacters = CharacterSet.urlPathAllowed.subtracting(.init(charactersIn: "+"))
/// percent encode path value.
private static func urlEncodePath(_ value: String) -> String {
return value.addingPercentEncoding(withAllowedCharacters: Self.pathAllowedCharacters) ?? value
}
func createBucketFixup(request: inout AWSRequest) {
switch request.operation {
// fixup CreateBucket to include location
case "CreateBucket":
var xml = ""
if request.region != .useast1 {
xml += "<CreateBucketConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
xml += "<LocationConstraint>"
xml += request.region.rawValue
xml += "</LocationConstraint>"
xml += "</CreateBucketConfiguration>"
}
request.body = .text(xml)
default:
break
}
}
func calculateMD5(request: inout AWSRequest) {
guard let byteBuffer = request.body.asByteBuffer(byteBufferAllocator: ByteBufferAllocator()) else { return }
guard request.httpHeaders["Content-MD5"].first == nil else { return }
// if request has a body, calculate the MD5 for that body
let byteBufferView = byteBuffer.readableBytesView
if let encoded = byteBufferView.withContiguousStorageIfAvailable({ bytes in
return Data(Insecure.MD5.hash(data: bytes)).base64EncodedString()
}) {
request.httpHeaders.replaceOrAdd(name: "Content-MD5", value: encoded)
}
}
func getLocationResponseFixup(response: inout AWSResponse) {
if case .xml(let element) = response.body {
// GetBucketLocation comes back without a containing xml element
if element.name == "LocationConstraint" {
if element.stringValue == "" {
element.addChild(.text(stringValue: "us-east-1"))
}
let parentElement = XML.Element(name: "BucketLocation")
parentElement.addChild(element)
response.body = .xml(parentElement)
}
}
}
func metadataFixup(response: inout AWSResponse) {
// convert x-amz-meta-* header values into a dictionary, which we add as a "x-amz-meta-" header. This is processed by AWSClient to fill metadata values in GetObject and HeadObject
switch response.body {
case .raw(_), .empty:
var metadata: [String: String] = [:]
for (key, value) in response.headers {
if key.hasPrefix("x-amz-meta-"), let value = value as? String {
let keyWithoutPrefix = key.dropFirst("x-amz-meta-".count)
metadata[String(keyWithoutPrefix)] = value
}
}
if !metadata.isEmpty {
response.headers["x-amz-meta-"] = metadata
}
default:
break
}
}
}
|
68e9495cee7d7c165aeef4519e511149
| 39.673333 | 187 | 0.586297 | false | false | false | false |
ming1016/smck
|
refs/heads/master
|
smck/Parser/H5Parser.swift
|
apache-2.0
|
1
|
//
// H5Parser.swift
// smck
//
// Created by DaiMing on 2017/4/17.
// Copyright © 2017年 Starming. All rights reserved.
//
import Foundation
enum H5ParseError: Swift.Error {
case unexpectedToken(String)
case unexpectedEOF
}
class H5Parser {
let tokens: [String]
var index = 0
init(tokens:[String]) {
self.tokens = tokens
}
func parseFile() throws -> H5File {
let file = H5File()
while currentToken != nil {
let tag = try parseTag()
file.addTag(tag)
// consumeToken()
}
return file
}
func parseTag() throws -> H5Tag {
guard currentToken != nil else {
throw H5ParseError.unexpectedEOF
}
var name = ""
var subs = [H5Tag]()
var attributes = [String:String]()
var value = ""
var currentAttribuiteName = ""
var psStep = 0 //0:初始,1:标签名,2:标签名取完,3:获取属性值,4:斜线完结,5:标签完结,6:整个标签完成
while let tk = currentToken {
if psStep == 6 {
break
}
if psStep == 5 {
if tk == "<" {
let nextIndex = index + 1
let nextTk = nextIndex < tokens.count ? tokens[nextIndex] : nil
if nextTk == "/" {
while let tok = currentToken {
if tok == ">" {
consumeToken()
break
}
consumeToken()
}
break
}
}
subs.append(try parseTag())
}
if psStep == 4 {
if tk == ">" {
psStep = 6
consumeToken()
continue
}
}
if psStep == 3 {
if tk == "\"" || tk == "'" {
consumeToken()
var str = ""
while let tok = currentToken {
if tok == "\"" {
consumeToken()
break
}
consumeToken()
str.append(tok)
}
attributes[currentAttribuiteName] = str
psStep = 2
continue
}
}
if psStep == 2 {
if tk == "=" {
psStep = 3
consumeToken()
continue
}
if tk == "/" {
psStep = 4
consumeToken()
continue
}
if tk == ">" {
psStep = 5
consumeToken()
continue
}
currentAttribuiteName = tk
consumeToken()
continue
}
if psStep == 1 {
name = tk
psStep = 2
consumeToken()
continue
}
if psStep == 0 {
//
if tk == "<" {
psStep = 1
consumeToken()
continue
} else {
consumeToken()
value = tk
break
}
}
}
return H5Tag(name: name, subs: subs, attributes: attributes, value: value)
}
/*------------------*/
var currentToken: String? {
return index < tokens.count ? tokens[index] : nil
}
func consumeToken(n: Int = 1) {
index += n
}
}
|
6acea83fea3142383a15cba12e3a8c1c
| 25.051948 | 83 | 0.332752 | false | false | false | false |
Epaus/SimpleParseTimelineAndMenu
|
refs/heads/master
|
SimpleParseTimelineAndMenu/MenuCell.swift
|
gpl-3.0
|
1
|
//
// MenuCell.swift
//
// Created by Estelle Paus on 12/1/14.
// Copyright (c) 2014 Estelle Paus. All rights reserved.
//
import Foundation
import UIKit
class MenuCell: UITableViewCell {
var leftMargin : CGFloat!
var topMargin : CGFloat!
var rightMargin : CGFloat!
var width : CGFloat!
var iconImageView: UIImageView!
var menuDividerView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var countContainer: UIView!
override func awakeFromNib() {
self.leftMargin = self.contentView.layer.frame.width * 0.10
self.topMargin = self.contentView.layer.frame.height * 0.70
self.rightMargin = self.contentView.layer.frame.width * 0.95
self.width = self.contentView.layer.frame.width
titleLabel.font = UIFont(name: "Avenir-Black", size: 18)
titleLabel.textColor = UIColor.whiteColor()
// countLabel.font = UIFont(name: "Avenir-Black", size: 13)
// countLabel.textColor = UIColor.whiteColor()
// countContainer.layer.cornerRadius = 15
setupIconImageView()
}
override func setSelected(selected: Bool, animated: Bool) {
// count of items after query, not yet applicable
// let countNotAvailable = countLabel.text == nil
// countContainer.hidden = countNotAvailable
// countLabel.hidden = countNotAvailable
}
func setupIconImageView()
{
self.iconImageView = UIImageView()
var iconImageViewX = self.leftMargin
var iconImageViewSideLen = self.contentView.frame.width * 0.07
self.iconImageView.frame = CGRectMake(iconImageViewX, self.topMargin, iconImageViewSideLen, iconImageViewSideLen)
self.iconImageView.layer.cornerRadius = 5.0
self.iconImageView.clipsToBounds = true
self.contentView.addSubview(self.iconImageView)
}
}
|
7caf8cafe08c27bee32964511b24bbb5
| 27.257143 | 121 | 0.647118 | false | false | false | false |
aquarchitect/MyKit
|
refs/heads/master
|
Sources/Shared/Extensions/CloudKit/CKDatabase+.swift
|
mit
|
1
|
//
// CKDatabase+.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2015 Hai Nguyen.
//
import CloudKit
public extension CKDatabase {
func fetchCurrentUser() -> Promise<CKRecord> {
return Promise { callback in
let operation = CKFetchRecordsOperation.fetchCurrentUserRecordOperation()
operation.perRecordCompletionBlock = { callback(Result($0, $2)) }
self.add(operation)
}
}
}
public extension CKDatabase {
func save(_ record: CKRecord) -> Promise<CKRecord> {
return Promise { (callback: @escaping Result<CKRecord>.Callback) in
let handler = Result.init >>> callback
self.save(record, completionHandler: handler)
}
}
func delete(withRecordID recordID: CKRecordID) -> Promise<CKRecordID> {
return Promise { (callback: @escaping Result<CKRecordID>.Callback) in
let handler = Result.init >>> callback
self.delete(withRecordID: recordID, completionHandler: handler)
}
}
func fetch(withRecordID recordID: CKRecordID) -> Promise<CKRecord> {
return Promise { (callback: @escaping Result<CKRecord>.Callback) in
let handler = Result.init >>> callback
self.fetch(withRecordID: recordID, completionHandler: handler)
}
}
func perform(_ query: CKQuery, inZoneWith zoneID: CKRecordZoneID? = nil) -> Promise<[CKRecord]> {
return Promise { (callback: @escaping Result<[CKRecord]>.Callback) in
let handler = Result.init >>> callback
self.perform(query, inZoneWith: zoneID, completionHandler: handler)
}
}
}
|
83bcb222e4c781b3b9f33c2c1f27fba5
| 31.607843 | 101 | 0.637402 | false | false | false | false |
soapyigu/Swift30Projects
|
refs/heads/master
|
Project 04 - TodoTDD/ToDo/Models/ToDoItem.swift
|
apache-2.0
|
1
|
//
// ToDOItem.swift
// ToDo
//
// Created by gu, yi on 9/6/18.
// Copyright © 2018 gu, yi. All rights reserved.
//
import Foundation
struct ToDoItem {
let title: String
let itemDescription: String?
let timestamp: Double?
let location: Location?
// plist related
private let titleKey = "titleKey"
private let itemDescriptionKey = "itemDescriptionKey"
private let timestampKey = "timestampKey"
private let locationKey = "locationKey"
var plistDict: [String:Any] {
var dict = [String:Any]()
dict[titleKey] = title
if let itemDescription = itemDescription {
dict[itemDescriptionKey] = itemDescription
}
if let timestamp = timestamp {
dict[timestampKey] = timestamp
}
if let location = location {
let locationDict = location.plistDict
dict[locationKey] = locationDict
}
return dict
}
init(title: String, itemDescription: String? = nil, timeStamp: Double? = nil, location: Location? = nil) {
self.title = title
self.itemDescription = itemDescription
self.timestamp = timeStamp
self.location = location
}
init?(dict: [String: Any]) {
guard let title = dict[titleKey] as? String else {
return nil
}
self.title = title
self.itemDescription = dict[itemDescriptionKey] as? String
self.timestamp = dict[timestampKey] as? Double
if let locationDict = dict[locationKey] as? [String: Any] {
self.location = Location(dict: locationDict)
} else {
self.location = nil
}
}
}
extension ToDoItem: Equatable {
static func ==(lhs: ToDoItem, rhs: ToDoItem) -> Bool {
return lhs.title == rhs.title && lhs.location?.name == rhs.location?.name
}
}
|
82450b0b651b6a1fcce79eeeec2fe3fc
| 24.597015 | 108 | 0.658892 | false | false | false | false |
skarppi/cavok
|
refs/heads/master
|
CAVOK/Extensions/UIColor+Additions.swift
|
mit
|
1
|
//
// UIColor+Additions.swift
// CAV-OK
//
// Created by Juho Kolehmainen on 18.7.2021.
//
import Foundation
import SwiftUI
extension UIColor {
func lighter(by saturation: CGFloat) -> UIColor {
var hue: CGFloat = 0, sat: CGFloat = 0
var brt: CGFloat = 0, alpha: CGFloat = 0
guard getHue(&hue, saturation: &sat, brightness: &brt, alpha: &alpha)
else {return self}
return UIColor(hue: hue,
saturation: max(sat - saturation, 0.0),
brightness: brt,
alpha: alpha)
}
}
extension Color {
public func lighter(by amount: CGFloat = 0.2) -> Self { Self(UIColor(self).lighter(by: amount)) }
}
|
bb8a5ad102795caf4ccd2ec5c8ca27bf
| 23.655172 | 101 | 0.572028 | false | false | false | false |
DenHeadless/DTTableViewManager
|
refs/heads/master
|
Sources/DTTableViewManager/DTTableViewDropDelegate.swift
|
mit
|
1
|
//
// DTTableViewDropDelegate.swift
// DTTableViewManager
//
// Created by Denys Telezhkin on 20.08.17.
// Copyright © 2017 Denys Telezhkin. 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.
import UIKit
#if os(iOS)
/// Object, that implements `UITableViewDropDelegate` for `DTTableViewManager`.
open class DTTableViewDropDelegate: DTTableViewDelegateWrapper, UITableViewDropDelegate {
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
_ = performNonCellReaction(.performDropWithCoordinator, argument: coordinator)
(delegate as? UITableViewDropDelegate)?.tableView(tableView, performDropWith: coordinator)
}
override func delegateWasReset() {
tableView?.dropDelegate = nil
tableView?.dropDelegate = self
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
if let canHandle = performNonCellReaction(.canHandleDropSession, argument: session) as? Bool {
return canHandle
}
return (delegate as? UITableViewDropDelegate)?.tableView?(tableView, canHandle: session) ?? true
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidEnter session: UIDropSession) {
_ = performNonCellReaction(.dropSessionDidEnter, argument: session)
(delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidEnter: session)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
if let proposal = performNonCellReaction(.dropSessionDidUpdateWithDestinationIndexPath,
argumentOne: session,
argumentTwo: destinationIndexPath) as? UITableViewDropProposal {
return proposal
}
return (delegate as? UITableViewDropDelegate)?.tableView?(tableView,
dropSessionDidUpdate: session,
withDestinationIndexPath: destinationIndexPath) ?? UITableViewDropProposal(operation: .cancel)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidExit session: UIDropSession) {
_ = performNonCellReaction(.dropSessionDidExit, argument: session)
(delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidExit: session)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropSessionDidEnd session: UIDropSession) {
_ = performNonCellReaction(.dropSessionDidEnd, argument: session)
(delegate as? UITableViewDropDelegate)?.tableView?(tableView, dropSessionDidEnd: session)
}
/// Implementation for `UITableViewDropDelegate` protocol
open func tableView(_ tableView: UITableView, dropPreviewParametersForRowAt indexPath: IndexPath) -> UIDragPreviewParameters? {
if let reaction = unmappedReactions.first(where: { $0.methodSignature == EventMethodSignature.dropPreviewParametersForRowAtIndexPath.rawValue }) {
return reaction.performWithArguments((indexPath, 0, 0)) as? UIDragPreviewParameters
}
return (delegate as? UITableViewDropDelegate)?.tableView?(tableView,
dropPreviewParametersForRowAt: indexPath)
}
}
#endif
|
43312389f044afdd8e5ae62bd283de7a
| 53.32967 | 182 | 0.707524 | false | false | false | false |
jsonkuan/SMILe
|
refs/heads/master
|
SMILe/ScoreboardTableViewController.swift
|
gpl-3.0
|
1
|
//
// LeaderboardTableViewController.swift
// SMILe
//
// Created by Jason Kuan on 16/03/16.
// Copyright © 2016 jsonkuan. All rights reserved.
//
import UIKit
class ScoreboardTableViewController: UITableViewController {
var people: [Player] = PlayerData().getPlayerFromData()
var gameScore = 0
override func viewDidLoad() {
super.viewDidLoad()
}
// TODO: - Get values for people[i].playerName && people[i].score
// MARK: - TableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return people.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people[section].gameType.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return people[section].playerName
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
cell.gameType.text = people[indexPath.section].gameType[indexPath.row]
cell.scoreButton.tag = indexPath.row
cell.scoreButton.addTarget(self, action: "pressedButton", forControlEvents: .TouchUpInside)
// TODO: - Button Not working (try "isFirstResponder")
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! TableViewCell
cell.scoreTextField.becomeFirstResponder()
}
// MARK: - IBActions
@IBAction func pressedButton(sender: UIButton) {
// TODO: - Increment the scoreLabel when the button is pressed
gameScore++
}
// MARK: - My Functions
func calculateLeader() {
// TODO: - Try using myArray.sort on the scores
}
}
|
40f6e38a0d4908fd5fbc3002748d6335
| 28.842857 | 118 | 0.663475 | false | false | false | false |
ggu/2D-RPG-Boilerplate
|
refs/heads/master
|
Borba/UI/SKButton.swift
|
mit
|
2
|
//
// SKButton.swift
// Borba
//
// Created by Gabriel Uribe on 6/5/15.
// Copyright (c) 2015 Team Five Three. All rights reserved.
//
import SpriteKit
protocol SKButtonDelegate {
func buttonTapped(type: SKButton.Tag)
}
class SKButton : SKSpriteNode {
enum Tag {// need to make MainMenu a type of ButtonType
case mainMenuPlay
case mainMenuSettings
}
static let padding: CGFloat = 50
private var button: SKButtonContents
var tag: Tag
var delegate: SKButtonDelegate?
init(color: UIColor, text: String, tag: SKButton.Tag) {
self.tag = tag
self.button = SKButtonContents(color: color, text: text)
let buttonWidth = self.button.frame.size.width + SKButton.padding
let buttonHeight = self.button.frame.size.height + SKButton.padding
super.init(texture: nil, color: UIColor.clearColor(), size: CGSize(width: buttonWidth, height: buttonHeight))
setup()
}
private func setup() {
userInteractionEnabled = true
addChild(button)
}
private func setMargins(horizontal: Int, vertical: Int) {
}
func changeText(text: String) {
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
delegate?.buttonTapped(tag)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
0c66270e8032278335e904d74e8a37fc
| 22.327586 | 113 | 0.686622 | false | false | false | false |
tlax/GaussSquad
|
refs/heads/master
|
GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemReciprocal.swift
|
mit
|
1
|
import UIKit
class MCalculatorFunctionsItemReciprocal:MCalculatorFunctionsItem
{
private let kExponent:Double = -1
init()
{
let icon:UIImage = #imageLiteral(resourceName: "assetFunctionReciprocal")
let title:String = NSLocalizedString("MCalculatorFunctionsItemReciprocal_title", comment:"")
super.init(
icon:icon,
title:title)
}
override func processFunction(
currentValue:Double,
currentString:String,
modelKeyboard:MKeyboard,
view:UITextView)
{
let inversedValue:Double = pow(currentValue, kExponent)
let inversedString:String = modelKeyboard.numberAsString(scalar:inversedValue)
let descr:String = "reciprocal (\(currentString)) = \(inversedString)"
applyUpdate(
modelKeyboard:modelKeyboard,
view:view,
newEditing:inversedString,
descr:descr)
}
}
|
1b4cbb56f92fadbbcc4c9ecb88acc45c
| 28.30303 | 100 | 0.634953 | false | false | false | false |
SeriousChoice/SCSwift
|
refs/heads/master
|
Example/scswift-example/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// SCSwift
//
// Created by Nicola Innocenti on 08/01/2022.
// Copyright © 2022 Nicola Innocenti. All rights reserved.
//
import UIKit
import SCSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if #available(iOS 15, *) {
let navAppearance = UINavigationBarAppearance()
navAppearance.backgroundColor = .white
UINavigationBar.appearance().standardAppearance = navAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navAppearance
} else {
UINavigationBar.appearance().isTranslucent = false
}
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: ViewController())
window?.makeKeyAndVisible()
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:.
}
}
|
f3faaaadba96599219c37eceb7d79559
| 45.457627 | 285 | 0.729296 | false | false | false | false |
regnerjr/Microfiche
|
refs/heads/master
|
MicroficheTests/MicroficheTests.swift
|
mit
|
1
|
import UIKit
import XCTest
import Microfiche
/// Person Struct will be an example Immutable Data Structure we want to archive
struct Person {
let name: String
let age: Int
}
private struct Archive {
static var path: String? {
let documentsDirectories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String]
let documentDirectory = documentsDirectories?.first
if let dir = documentDirectory {
let documentPath = dir + "/items.archive"
return documentPath
}
return nil
}
}
// Person needs to be equatable in order to be used in a Set
extension Person: Equatable {}
func ==(rhs: Person, lhs: Person) -> Bool{
return (rhs.name == lhs.name) && (rhs.age == lhs.age)
}
// Person Must be hashable to be used in a set
extension Person : Hashable {
var hashValue: Int {
return self.name.hashValue
}
}
class microficheTests: XCTestCase {
func testArrayArchiveAndRestore() {
// Create and Array for archiving
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let people = [me, shelby]
// Archive the Collection, In this case an Array<People>
let arrayArchive = NSKeyedArchiver.archivedDataWithRootObject(convertCollectionToArrayOfData(people))
// Restore the data from the archive, Note the required cast to NSMutableArray
let arayUnarchive = NSKeyedUnarchiver.unarchiveObjectWithData(arrayArchive) as? NSMutableArray
// Finally take the Restored NSMutableArray, and convert it back to our preferred Data type
// NOTE: The cast is required! Without this the Type Inference Engine will not know what type
// of object should be returned to you
let restoredArray = restoreFromArchiveArray(arayUnarchive!) as Array<Person>
XCTAssert(restoredArray == people, "Restored Array is equal to the Source Data")
}
func testDictionaryArchiveAndRestore(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let dictionaryPeeps: Dictionary<NSUUID, Person> = [NSUUID(): me, NSUUID(): shelby]
let dictionaryArchive = NSKeyedArchiver.archivedDataWithRootObject(convertCollectionToArrayOfData(dictionaryPeeps))
let dictionaryUnarchive = NSKeyedUnarchiver.unarchiveObjectWithData(dictionaryArchive) as? NSMutableArray
let restoredDictionary = restoreFromArchiveArray(dictionaryUnarchive!) as Dictionary<NSUUID, Person>
XCTAssert(restoredDictionary == dictionaryPeeps, "Restored Dictionary is equal to the Source Data")
}
func testSetArchiveAndRestore(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let setPeeps: Set<Person> = [me, shelby]
let setArchive = NSKeyedArchiver.archivedDataWithRootObject(convertCollectionToArrayOfData(setPeeps))
let setUnarchive = NSKeyedUnarchiver.unarchiveObjectWithData(setArchive) as? NSMutableArray
let restoredSet = restoreFromArchiveArray(setUnarchive!) as Set<Person>
XCTAssert(restoredSet == setPeeps, "Restored Set is equal to the Source Data")
}
func testArchiveCollectionAtPath_Array(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let people = [me, shelby]
if let path = Archive.path {
println("Got a good archivePath: \(path)")
let result = archiveCollection(people, atPath: path)
XCTAssert(result == true, "Collection people was sucessfully archived")
let collection: Array<Person>? = restoreCollectionFromPath(path)
XCTAssert(collection! == people, "Collection People was successfully restored")
}
}
func testRestoreFromPathWhereNoDataHasBeenSaved_Array(){
let collection: Array<Person>? = restoreCollectionFromPath("someInvalidPath")
XCTAssert(collection == nil, "restoringCollectionfromPath returns nil")
}
func testArchiveCollectionAtPath_Dictionary(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let peopleDict = [NSUUID(): me, NSUUID():shelby]
if let path = Archive.path {
println("Got a good archivePath: \(path)")
let result = archiveCollection(peopleDict, atPath: path)
XCTAssert(result == true, "Collection people was sucessfully archived")
let collection: Dictionary<NSUUID,Person>? = restoreCollectionFromPath(path)
XCTAssert(collection! == peopleDict, "Collection People was successfully restored")
}
}
func testRestoreFromPathWhereNoDataHasBeenSaved_Dictionary(){
let collection: Dictionary<NSUUID,Person>? = restoreCollectionFromPath("someInvalidPath")
XCTAssert(collection == nil, "restoringCollectionfromPath returns nil")
}
func testArchiveCollectionAtPath_Set(){
let me = Person(name: "John", age: 30)
let shelby = Person(name: "Shelby", age: 31)
let setPeeps: Set<Person> = [me, shelby]
if let path = Archive.path {
println("Got a good archivePath: \(path)")
let result = archiveCollection(setPeeps, atPath: path)
XCTAssert(result == true, "Collection setPeeps was sucessfully archived")
let collection: Set<Person>? = restoreCollectionFromPath(path)
XCTAssert(collection! == setPeeps, "Collection setPeeps was successfully restored")
}
}
}
|
ec82cb0ac52af74c576c72c67c5f09f8
| 39.6 | 169 | 0.681386 | false | true | false | false |
juzooda/gift4
|
refs/heads/master
|
ios/Gift4/Gift4/Model/ProductsModel.swift
|
artistic-2.0
|
1
|
//
// ProductsModel.swift
// Gift4
//
// Created by Rafael Juzo G Oda on 4/11/15.
// Copyright (c) 2015 Rafael Juzo Gomes Oda. All rights reserved.
//
import Foundation
class ProducsModel
{
func listAllCategories() -> Array<Category>
{
var categories = [Category]()
if let jsonData = openJSON("Categories", extn: "json") {
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let productCategories = jsonObject["product_categories"] as? NSArray{
for categoryInList in productCategories{
var category = Category()
let count = categoryInList["count"] as? Int
let name = categoryInList["name"] as? String
let slug = categoryInList["slug"] as? String
println("Hello, \(category)!")
}
}
}
return categories
}
func openJSON(fileName: String, extn: String) -> NSData?{
if let fileURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: extn) {
if let data = NSData(contentsOfURL: fileURL) {
return data
}
}
return nil
}
}
|
d57027d9a6d1fa54b980b0ca670e10fd
| 28.408163 | 151 | 0.527778 | false | false | false | false |
jonandersen/calendar
|
refs/heads/master
|
Calendar/Sources/CalendarDateCell.swift
|
mit
|
1
|
//
// CalendarDateCell.swift
// leapsecond
//
// Created by Jon Andersen on 1/10/16.
// Copyright © 2016 Andersen. All rights reserved.
//
import Foundation
public class CalendarDateCell: UICollectionViewCell {
static let identifier: String = "CalendarDateCell"
@IBOutlet public weak var textLabel: UILabel!
@IBOutlet public weak var circleView: UIView!
@IBOutlet public weak var imageView: UIImageView!
private let circleRatio: CGFloat = 1.0
var calendarDate: CalendarDate = CalendarDate.empty()
public override func awakeFromNib() {
circleView.backgroundColor = UIColor(red: 0x33/256, green: 0xB3/256, blue: 0xB3/256, alpha: 0.5)
self.clipsToBounds = true
imageView.clipsToBounds = true
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
self.circleView.hidden = true
self.imageView.hidden = true
self.textLabel.textColor = UIColor.darkTextColor()
}
public override func layoutSubviews() {
super.layoutSubviews()
CATransaction.begin()
var sizeCircle = min(self.frame.size.width, self.frame.size.height)
sizeCircle = sizeCircle * circleRatio
sizeCircle = CGFloat(roundf(Float(sizeCircle)))
circleView.frame = CGRect(x: 0, y: 0, width: sizeCircle, height: sizeCircle)
circleView.center = CGPoint(x: self.frame.size.width / 2.0, y: self.frame.size.height / 2.0)
circleView.layer.cornerRadius = sizeCircle / 2.0
imageView.frame = self.circleView.frame
imageView.layer.cornerRadius = self.circleView.layer.cornerRadius
CATransaction.commit()
}
}
|
34d680dd4907305177829800f007c8ba
| 38.232558 | 104 | 0.691168 | false | false | false | false |
Yalantis/AppearanceNavigationController
|
refs/heads/develop
|
AppearanceNavigationController/NavigationController/Appearance.swift
|
mit
|
1
|
import Foundation
import UIKit
public struct Appearance: Equatable {
public struct Bar: Equatable {
var style: UIBarStyle = .default
var backgroundColor = UIColor(red: 234 / 255, green: 46 / 255, blue: 73 / 255, alpha: 1)
var tintColor = UIColor.white
var barTintColor: UIColor?
}
var statusBarStyle: UIStatusBarStyle = .default
var navigationBar = Bar()
var toolbar = Bar()
}
public func ==(lhs: Appearance.Bar, rhs: Appearance.Bar) -> Bool {
return lhs.style == rhs.style &&
lhs.backgroundColor == rhs.backgroundColor &&
lhs.tintColor == rhs.tintColor &&
rhs.barTintColor == lhs.barTintColor
}
public func ==(lhs: Appearance, rhs: Appearance) -> Bool {
return lhs.statusBarStyle == rhs.statusBarStyle && lhs.navigationBar == rhs.navigationBar && lhs.toolbar == rhs.toolbar
}
|
1bd75178bb4239f6586b27c5c52af581
| 29.482759 | 123 | 0.649321 | false | false | false | false |
trungphamduc/Calendar
|
refs/heads/master
|
Example/AAA/CalendarLogic.swift
|
mit
|
2
|
//
// CalLogic.swift
// CalendarLogic
//
// Created by Lancy on 01/06/15.
// Copyright (c) 2015 Lancy. All rights reserved.
//
import Foundation
class CalendarLogic: Hashable {
var hashValue: Int {
return baseDate.hashValue
}
// Mark: Public variables and methods.
var baseDate: NSDate {
didSet {
calculateVisibleDays()
}
}
private lazy var dateFormatter = NSDateFormatter()
var currentMonthAndYear: NSString {
dateFormatter.dateFormat = calendarSettings.monthYearFormat
return dateFormatter.stringFromDate(baseDate)
}
var currentMonthDays: [Date]?
var previousMonthVisibleDays: [Date]?
var nextMonthVisibleDays: [Date]?
init(date: NSDate) {
baseDate = date.firstDayOfTheMonth
calculateVisibleDays()
}
func retreatToPreviousMonth() {
baseDate = baseDate.firstDayOfPreviousMonth
}
func advanceToNextMonth() {
baseDate = baseDate.firstDayOfFollowingMonth
}
func moveToMonth(date: NSDate) {
baseDate = date
}
func isVisible(date: NSDate) -> Bool {
let internalDate = Date(date: date)
if contains(currentMonthDays!, internalDate) {
return true
} else if contains(previousMonthVisibleDays!, internalDate) {
return true
} else if contains(nextMonthVisibleDays!, internalDate) {
return true
}
return false
}
func containsDate(date: NSDate) -> Bool {
let date = Date(date: date)
let logicBaseDate = Date(date: baseDate)
if (date.month == logicBaseDate.month) &&
(date.year == logicBaseDate.year) {
return true
}
return false
}
//Mark: Private methods.
private var numberOfDaysInPreviousPartialWeek: Int {
return baseDate.weekDay - 1
}
private var numberOfVisibleDaysforFollowingMonth: Int {
// Traverse to the last day of the month.
let parts = baseDate.monthDayAndYearComponents
parts.day = baseDate.numberOfDaysInMonth
let date = NSCalendar.currentCalendar().dateFromComponents(parts)
// 7*6 = 42 :- 7 columns (7 days in a week) and 6 rows (max 6 weeks in a month)
return 42 - (numberOfDaysInPreviousPartialWeek + baseDate.numberOfDaysInMonth)
}
private var calculateCurrentMonthVisibleDays: [Date] {
var dates = [Date]()
let numberOfDaysInMonth = baseDate.numberOfDaysInMonth
let component = baseDate.monthDayAndYearComponents
for var i = 1; i <= numberOfDaysInMonth; i++ {
dates.append(Date(day: i, month: component.month, year: component.year))
}
return dates
}
private var calculatePreviousMonthVisibleDays: [Date] {
var dates = [Date]()
let date = baseDate.firstDayOfPreviousMonth
let numberOfDaysInMonth = date.numberOfDaysInMonth
let numberOfVisibleDays = numberOfDaysInPreviousPartialWeek
let parts = date.monthDayAndYearComponents
for var i = numberOfDaysInMonth - (numberOfVisibleDays - 1); i <= numberOfDaysInMonth; i++ {
dates.append(Date(day: i, month: parts.month, year: parts.year))
}
return dates
}
private var calculateFollowingMonthVisibleDays: [Date] {
var dates = [Date]()
let date = baseDate.firstDayOfFollowingMonth
let numberOfDays = numberOfVisibleDaysforFollowingMonth
let parts = date.monthDayAndYearComponents
for var i = 1; i <= numberOfVisibleDaysforFollowingMonth; i++ {
dates.append(Date(day: i, month: parts.month, year: parts.year))
}
return dates
}
private func calculateVisibleDays() {
currentMonthDays = calculateCurrentMonthVisibleDays
previousMonthVisibleDays = calculatePreviousMonthVisibleDays
nextMonthVisibleDays = calculateFollowingMonthVisibleDays
}
}
func ==(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool {
return lhs.hashValue == rhs.hashValue
}
func <(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool {
return (lhs.baseDate.compare(rhs.baseDate) == .OrderedAscending)
}
func >(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool {
return (lhs.baseDate.compare(rhs.baseDate) == .OrderedDescending)
}
|
6683d2407df09c0f7b7e818bd7129b8f
| 26.789116 | 96 | 0.697674 | false | false | false | false |
joshuajharris/dotfiles
|
refs/heads/master
|
Alfred.alfredpreferences/workflows/user.workflow.7CC242B6-984A-48B5-8B68-DA9C29C0EC44/imgpbcopy.swift
|
mit
|
1
|
// Ported from http://www.alecjacobson.com/weblog/?p=3816
import Foundation
import Cocoa
let args = CommandLine.arguments
let path = args[1]
let image = NSImage(contentsOfFile: path)!
let pasteboard = NSPasteboard.general()
pasteboard.clearContents()
pasteboard.writeObjects([image])
|
f890bbeab6218edb1436ad3880ba80c3
| 22.916667 | 57 | 0.780488 | false | false | false | false |
fthomasmorel/insapp-iOS
|
refs/heads/master
|
Insapp/SeeMoreViewController.swift
|
mit
|
1
|
//
// SeeMoreViewController.swift
// Insapp
//
// Created by Guillaume Courtet on 21/12/2016.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import UIKit
class SeeMoreViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var resultLabel: UILabel!
var users: [User] = []
var events: [Event] = []
var posts: [Post] = []
var associations: [Association] = []
var associationTable: [String: Association] = [:]
var searchedText: String!
var type: Int!
var prt: UIViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.resultLabel.text = searchedText!
self.tableView.register(UINib(nibName: "SearchUserCell", bundle: nil), forCellReuseIdentifier: kSearchUserCell)
self.tableView.register(UINib(nibName: "SearchEventCell", bundle: nil), forCellReuseIdentifier: kSearchEventCell)
self.tableView.register(UINib(nibName: "PostCell", bundle: nil), forCellReuseIdentifier: kPostCell)
self.tableView.register(UINib(nibName: "SearchPostCell", bundle: nil), forCellReuseIdentifier: kSearchPostCell)
self.tableView.register(UINib(nibName: "SearchAssociationCell", bundle: nil), forCellReuseIdentifier: kSearchAssociationCell)
self.tableView.tableFooterView = UIView()
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (self.type) {
case 1:
return 1
case 2:
return 1
case 3:
return self.events.count
default:
return self.users.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch (self.type) {
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchAssociationCell, for: indexPath) as! SearchAssociationCell
cell.parent = self.prt
cell.more = 1
cell.associations = self.associations
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchPostCell, for: indexPath) as! SearchPostCell
cell.more = 1
cell.parent = self.prt
cell.loadPosts(self.posts)
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchEventCell, for: indexPath) as! SearchEventCell
let event = self.events[indexPath.row]
cell.load(event: event)
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: kSearchUserCell, for: indexPath) as! SearchUserCell
let user = self.users[indexPath.row]
cell.loadUser(user: user)
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch self.type {
case 1:
let test = self.associations.count%3 == 0 ? self.associations.count/3 : self.associations.count/3 + 1
let nb = CGFloat(test)
let res = self.tableView.frame.width/3 * nb
return res
case 2:
let test = self.posts.count%3 == 0 ? self.posts.count/3 : self.posts.count/3 + 1
let nb = CGFloat(test)
return self.tableView.frame.width/3 * nb
case 3:
return 70
default:
return 50
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch self.type {
case 1:
return
case 2:
return
case 3:
let event = self.events[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "EventViewController") as! EventViewController
vc.association = self.associationTable[event.association!]!
vc.event = event
self.prt.navigationController?.pushViewController(vc, animated: true)
default:
let user = self.users[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "UserViewController") as! UserViewController
vc.user_id = user.id
vc.setEditable(false)
vc.canReturn(true)
self.prt.navigationController?.pushViewController(vc, animated: true)
}
}
@IBAction func dismissAction(_ sender: AnyObject) {
self.navigationController!.popViewController(animated: true)
}
}
|
1a1cd8633681e2cd8114119f863f2572
| 37.42963 | 138 | 0.606207 | false | false | false | false |
0x73/SwiftIconFont
|
refs/heads/master
|
SwiftIconFont/Classes/Shared/SwiftIconFont.swift
|
mit
|
1
|
//
// UIFont+SwiftIconFont.swift
// SwiftIconFont
//
// Created by Sedat Ciftci on 18/03/16.
// Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
public struct SwiftIcon {
let font: Fonts
let code: String
let color: Color
let imageSize: CGSize
let fontSize: CGFloat
}
public enum Fonts: String {
case fontAwesome5 = "FontAwesome5Free-Regular"
case fontAwesome5Brand = "FontAwesome5Brands-Regular"
case fontAwesome5Solid = "FontAwesome5Free-Solid"
case iconic = "open-iconic"
case ionicon = "Ionicons"
case octicon = "octicons"
case themify = "themify"
case mapIcon = "map-icons"
case materialIcon = "MaterialIcons-Regular"
case segoeMDL2 = "SegoeMDL2Assets"
case foundation = "fontcustom"
case elegantIcon = "ElegantIcons"
case captain = "captainicon"
var fontFamilyName: String {
switch self {
case .fontAwesome5:
return "Font Awesome 5 Free"
case .fontAwesome5Brand:
return "Font Awesome 5 Brands"
case .fontAwesome5Solid:
return "Font Awesome 5 Free"
case .iconic:
return "Icons"
case .ionicon:
return "Ionicons"
case .octicon:
return "octicons"
case .themify:
return "Themify"
case .mapIcon:
return "map-icons"
case .materialIcon:
return "Material Icons"
case .segoeMDL2:
return "Segoe MDL2 Assets"
case .foundation:
return "fontcustom"
case .elegantIcon:
return "ElegantIcons"
case .captain:
return "captainicon"
}
}
}
func replace(withText string: NSString) -> NSString {
if string.lowercased.range(of: "-") != nil {
return string.replacingOccurrences(of: "-", with: "_") as NSString
}
return string
}
func getAttributedString(_ text: NSString, ofSize size: CGFloat) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: text as String)
for substring in ((text as String).split{$0 == " "}.map(String.init)) {
var splitArr = ["", ""]
splitArr = substring.split{$0 == ":"}.map(String.init)
if splitArr.count < 2 {
continue
}
let substringRange = text.range(of: substring)
let fontPrefix: String = splitArr[0].lowercased()
var fontCode: String = splitArr[1]
if fontCode.lowercased().range(of: "_") != nil {
fontCode = (fontCode as NSString).replacingOccurrences(of: "_", with: "-")
}
var fontType: Fonts = .fontAwesome5
var fontArr: [String: String] = ["": ""]
if fontPrefix == "ic" {
fontType = Fonts.iconic
fontArr = iconicIconArr
} else if fontPrefix == "io" {
fontType = Fonts.ionicon
fontArr = ioniconArr
} else if fontPrefix == "oc" {
fontType = Fonts.octicon
fontArr = octiconArr
} else if fontPrefix == "ti" {
fontType = Fonts.themify
fontArr = temifyIconArr
} else if fontPrefix == "mi" {
fontType = Fonts.mapIcon
fontArr = mapIconArr
} else if fontPrefix == "ma" {
fontType = Fonts.materialIcon
fontArr = materialIconArr
} else if fontPrefix == "sm" {
fontType = Fonts.segoeMDL2
fontArr = segoeMDL2
} else if fontPrefix == "fa5" {
fontType = Fonts.fontAwesome5
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5b" {
fontType = Fonts.fontAwesome5Brand
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5s" {
fontType = Fonts.fontAwesome5Solid
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fo" {
fontType = .foundation
fontArr = foundationIconArr
} else if fontPrefix == "el" {
fontType = .elegantIcon
fontArr = elegantIconArr
} else if fontPrefix == "cp" {
fontType = .captain
fontArr = captainIconArr
}
if let _ = fontArr[fontCode] {
attributedString.replaceCharacters(in: substringRange, with: String.getIcon(from: fontType, code: fontCode)!)
let newRange = NSRange(location: substringRange.location, length: 1)
attributedString.addAttribute(.font, value: Font.icon(from: fontType, ofSize: size), range: newRange)
}
}
return attributedString
}
func getAttributedStringForRuntimeReplace(_ text: NSString, ofSize size: CGFloat) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: text as String)
do {
let input = text as String
let regex = try NSRegularExpression(pattern: "icon:\\((\\w+):(\\w+)\\)", options: NSRegularExpression.Options.caseInsensitive)
let matches = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
if let match = matches.first {
var fontPrefix = ""
var fontCode = ""
let iconLibraryNameRange = match.range(at: 1)
let iconNameRange = match.range(at: 2)
if let swiftRange = iconLibraryNameRange.range(for: text as String) {
fontPrefix = String(input[swiftRange])
}
if let swiftRange = iconNameRange.range(for: text as String) {
fontCode = String(input[swiftRange])
}
if fontPrefix.utf16.count > 0 && fontCode.utf16.count > 0 {
var fontType: Fonts = .fontAwesome5
var fontArr: [String: String] = ["": ""]
if fontPrefix == "ic" {
fontType = Fonts.iconic
fontArr = iconicIconArr
} else if fontPrefix == "io" {
fontType = Fonts.ionicon
fontArr = ioniconArr
} else if fontPrefix == "oc" {
fontType = Fonts.octicon
fontArr = octiconArr
} else if fontPrefix == "ti" {
fontType = Fonts.themify
fontArr = temifyIconArr
} else if fontPrefix == "mi" {
fontType = Fonts.mapIcon
fontArr = mapIconArr
} else if fontPrefix == "ma" {
fontType = Fonts.materialIcon
fontArr = materialIconArr
} else if fontPrefix == "sm" {
fontType = Fonts.segoeMDL2
fontArr = segoeMDL2
} else if fontPrefix == "fa5" {
fontType = Fonts.fontAwesome5
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5b" {
fontType = Fonts.fontAwesome5Brand
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fa5s" {
fontType = Fonts.fontAwesome5Solid
fontArr = fontAwesome5IconArr
} else if fontPrefix == "fo" {
fontType = .foundation
fontArr = foundationIconArr
} else if fontPrefix == "el" {
fontType = .elegantIcon
fontArr = elegantIconArr
} else if fontPrefix == "cp" {
fontType = .captain
fontArr = captainIconArr
}
if let _ = fontArr[fontCode] {
attributedString.replaceCharacters(in: match.range, with: String.getIcon(from: fontType, code: fontCode)!)
let newRange = NSRange(location: match.range.location, length: 1)
attributedString.addAttribute(.font, value: Font.icon(from: fontType, ofSize: size), range: newRange)
}
}
}
} catch {
// regex was bad!
}
return attributedString
}
public func GetIconIndexWithSelectedIcon(_ icon: String) -> String {
let text = icon as NSString
var iconIndex: String = ""
for substring in ((text as String).split{$0 == " "}.map(String.init)) {
var splitArr = ["", ""]
splitArr = substring.split{$0 == ":"}.map(String.init)
if splitArr.count == 1{
continue
}
var fontCode: String = splitArr[1]
if fontCode.lowercased().range(of: "_") != nil {
fontCode = fontCode.replacingOccurrences(of: "_", with: "-")
}
iconIndex = fontCode
}
return iconIndex
}
public func GetFontTypeWithSelectedIcon(_ icon: String) -> Fonts {
let text = icon as NSString
var fontType: Fonts = .fontAwesome5
for substring in ((text as String).split{$0 == " "}.map(String.init)) {
var splitArr = ["", ""]
splitArr = substring.split{$0 == ":"}.map(String.init)
if splitArr.count == 1{
continue
}
let fontPrefix: String = splitArr[0].lowercased()
var fontCode: String = splitArr[1]
if fontCode.lowercased().range(of: "_") != nil {
fontCode = (fontCode as NSString).replacingOccurrences(of: "_", with: "-")
}
if fontPrefix == "ic" {
fontType = Fonts.iconic
} else if fontPrefix == "io" {
fontType = Fonts.ionicon
} else if fontPrefix == "oc" {
fontType = Fonts.octicon
} else if fontPrefix == "ti" {
fontType = Fonts.themify
} else if fontPrefix == "mi" {
fontType = Fonts.mapIcon
} else if fontPrefix == "ma" {
fontType = Fonts.materialIcon
} else if fontPrefix == "sm" {
fontType = Fonts.segoeMDL2
} else if fontPrefix == "fa5" {
fontType = Fonts.fontAwesome5
} else if fontPrefix == "fa5b" {
fontType = Fonts.fontAwesome5Brand
} else if fontPrefix == "fa5s" {
fontType = Fonts.fontAwesome5Solid
} else if fontPrefix == "fo" {
fontType = .foundation
} else if fontPrefix == "el" {
fontType = .elegantIcon
} else if fontPrefix == "cp" {
fontType = .captain
}
}
return fontType
}
|
dfe1b0208ce122344122fdd3b9920ef2
| 33.61859 | 134 | 0.533839 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
refs/heads/master
|
Sources/AssistantV1/Models/LogMessageSource.swift
|
apache-2.0
|
1
|
/**
* (C) Copyright IBM Corp. 2021.
*
* 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
/**
An object that identifies the dialog element that generated the error message.
*/
public struct LogMessageSource: Codable, Equatable {
/**
A string that indicates the type of dialog element that generated the error message.
*/
public enum TypeEnum: String {
case dialogNode = "dialog_node"
}
/**
A string that indicates the type of dialog element that generated the error message.
*/
public var type: String?
/**
The unique identifier of the dialog node that generated the error message.
*/
public var dialogNode: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case type = "type"
case dialogNode = "dialog_node"
}
/**
Initialize a `LogMessageSource` with member variables.
- parameter type: A string that indicates the type of dialog element that generated the error message.
- parameter dialogNode: The unique identifier of the dialog node that generated the error message.
- returns: An initialized `LogMessageSource`.
*/
public init(
type: String? = nil,
dialogNode: String? = nil
)
{
self.type = type
self.dialogNode = dialogNode
}
}
|
46f572f5651b897586bc9e1d7619331b
| 29.125 | 108 | 0.681535 | false | false | false | false |
yangligeryang/codepath
|
refs/heads/master
|
assignments/DropboxDemo/DropboxDemo/SignInFormViewController.swift
|
apache-2.0
|
1
|
//
// SignInFormViewController.swift
// DropboxDemo
//
// Created by Yang Yang on 10/15/16.
// Copyright © 2016 Yang Yang. All rights reserved.
//
import UIKit
class SignInFormViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var formImage: UIImageView!
let resetImage = UIImage(named: "sign_in")
let activeImage = UIImage(named: "sign_in1")
override func viewDidLoad() {
super.viewDidLoad()
emailField.delegate = self
emailField.becomeFirstResponder()
passwordField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if emailField.isFirstResponder {
emailField.resignFirstResponder()
passwordField.becomeFirstResponder()
} else if passwordField.isFirstResponder {
let characterCount = passwordField.text?.characters.count
if characterCount! > 0 {
performSegue(withIdentifier: "existingAccount", sender: nil)
}
}
return false
}
@IBAction func onBack(_ sender: UIButton) {
navigationController!.popViewController(animated: true)
}
@IBAction func onCreate(_ sender: UIButton) {
performSegue(withIdentifier: "existingAccount", sender: nil)
}
@IBAction func didTap(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
@IBAction func onForgotPassword(_ sender: UIButton) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let forgotAction = UIAlertAction(title: "Forgot Password?", style: .default) { (action) in
}
alertController.addAction(forgotAction)
let ssoAction = UIAlertAction(title: "Single Sign-On", style: .default) { (action) in
}
alertController.addAction(ssoAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
}
alertController.addAction(cancelAction)
present(alertController, animated: true) {}
}
@IBAction func onPasswordChanged(_ sender: UITextField) {
let characterCount = passwordField.text?.characters.count
if characterCount! > 0 {
signInButton.isEnabled = true
formImage.image = activeImage
} else {
formImage.image = resetImage
signInButton.isEnabled = false
}
}
}
|
accfaf1fc3deaba091e51aa940ab2d6d
| 30.142857 | 103 | 0.634439 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
refs/heads/master
|
Pods/HXPHPicker/Sources/HXPHPicker/Core/Extension/Core+CALayer.swift
|
mit
|
1
|
//
// Core+CALayer.swift
// HXPHPicker
//
// Created by Slience on 2021/7/14.
//
import UIKit
extension CALayer {
func convertedToImage(
size: CGSize = .zero,
scale: CGFloat = UIScreen.main.scale
) -> UIImage? {
var toSize: CGSize
if size.equalTo(.zero) {
toSize = frame.size
}else {
toSize = size
}
UIGraphicsBeginImageContextWithOptions(toSize, false, scale)
let context = UIGraphicsGetCurrentContext()
render(in: context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
|
5304ea80f8d6daf93b362047d7a03e7e
| 22.714286 | 68 | 0.60241 | false | false | false | false |
leizh007/HiPDA
|
refs/heads/master
|
HiPDA/HiPDA/Sections/Home/Post/Html/HtmlManager.swift
|
mit
|
1
|
//
// HtmlManager.swift
// HiPDA
//
// Created by leizh007 on 2017/5/18.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
struct HtmlManager {
fileprivate enum Attribute {
static let content = "####content here####"
static let style = "####style here####"
static let script = "####script here####"
static let maxWidth = "####max width####"
static let blockQuoteWidth = "####blockquote width####"
static let blockcodeWidth = "####blockcode width#### "
static let screenScale = "####screen scale####"
static let seperatorLineHeight = "####seperator line height####"
}
fileprivate static let baseHtml: String = {
enum HtmlResource {
static let name = "post"
enum ResourceType {
static let html = "html"
static let css = "css"
static let js = "js"
}
}
guard let htmlPath = Bundle.main.path(forResource: HtmlResource.name, ofType: HtmlResource.ResourceType.html),
let cssPath = Bundle.main.path(forResource: HtmlResource.name, ofType: HtmlResource.ResourceType.css),
let jsPath = Bundle.main.path(forResource: HtmlResource.name, ofType: HtmlResource.ResourceType.js),
let html = try? String(contentsOfFile: htmlPath, encoding: .utf8),
var css = try? String(contentsOfFile: cssPath, encoding: .utf8),
let js = try? String(contentsOfFile: jsPath, encoding: .utf8) else {
fatalError("Load Html Error!")
}
let contentMargin = CGFloat(8.0)
let blockquoteMargin = CGFloat(16.0)
let seperatorLineHeight = 1.0 / C.UI.screenScale
css = css.replacingOccurrences(of: Attribute.maxWidth, with: "\(Int(C.UI.screenWidth - 2 * contentMargin))px")
.replacingOccurrences(of: Attribute.blockQuoteWidth, with: "\(Int(C.UI.screenWidth - 2 * contentMargin - 2 * blockquoteMargin))px")
.replacingOccurrences(of: Attribute.blockcodeWidth, with: "\(Int(C.UI.screenWidth - 2 * contentMargin))px")
.replacingOccurrences(of: Attribute.screenScale, with: "\(Int(C.UI.screenScale))").replacingOccurrences(of: Attribute.seperatorLineHeight, with: String(format:"%.3f", seperatorLineHeight))
return html.replacingOccurrences(of: Attribute.style, with: css)
.replacingOccurrences(of: Attribute.script, with: js)
}()
static func html(with content: String) -> String {
return HtmlManager.baseHtml.replacingOccurrences(of: Attribute.content, with: content)
}
}
|
750431a4a32aa9701a253643bc4442e0
| 46.410714 | 200 | 0.626365 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.