hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
014002b26da3ad7bebe9b18189f82c0425958f48
7,114
// // LayoutConstraintsExtension.swift // Pods // // Created by Candost Dagdeviren on 01/11/2016. // // import Foundation internal extension UIView { func cd_alignToTop(of view: UIView, margin: CGFloat, multiplier: CGFloat) { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: multiplier, constant: margin)) } func cd_alignTopToParent(with margin: CGFloat) { cd_alignToTop(of: self.superview ?? UIView(), margin: margin, multiplier: 1) } func cd_alignBottomToParent(with margin: CGFloat) { cd_alignToBottom(of: self.superview!, margin: margin) } func cd_alignToBottom(of view: UIView, margin: CGFloat) { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: -margin)) } func cd_alignLeftToParent(with margin: CGFloat) { cd_alignToLeft(of: self.superview!, margin: margin) } func cd_alignToLeft(of view: UIView, margin: CGFloat) { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: margin)) } func cd_alignRightToParent(with margin: CGFloat) { cd_alignToRight(of: self.superview!, margin: margin) } func cd_alignToRight(of view: UIView, margin: CGFloat) { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: -margin)) } func cd_alignToParent(with margin: CGFloat) { translatesAutoresizingMaskIntoConstraints = false cd_alignTopToParent(with: margin) cd_alignLeftToParent(with: margin) cd_alignRightToParent(with: margin) cd_alignBottomToParent(with: margin) } func cd_setHeight(_ height: CGFloat) { self.addConstraint(NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)) } func cd_setMaxHeight(_ height: CGFloat) { self.addConstraint(NSLayoutConstraint(item: self, attribute: .height, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)) } func cd_setWidth(_ width: CGFloat) { self.addConstraint(NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)) } func cd_centerHorizontally() { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: self.superview, attribute: .centerX, multiplier: 1, constant: 0)) } func cd_centerVertically() { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: self.superview, attribute: .centerY, multiplier: 1, constant: 0)) } func cd_place(below view: UIView, margin: CGFloat) { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: margin)) } func cd_place(above view: UIView, margin: CGFloat) { self.superview!.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: margin)) } }
48.726027
84
0.354231
d9782736d9305ffa659c2af5354ebbfae08dd235
16,554
// // Money, https://github.com/danthorpe/Money // Created by Dan Thorpe, @danthorpe // // The MIT License (MIT) // // Copyright (c) 2015 Daniel Thorpe // // 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 /** # DecimalNumberBehaviorType Defines the decimal number behavior, i.e. `NSDecimalNumberBehaviors` of the type. */ public protocol DecimalNumberBehaviorType { /// Specify the decimal number (i.e. rounding, scale etc) for base 10 calculations static var decimalNumberBehaviors: NSDecimalNumberBehaviors { get } } /** # DecimalNumberBehavior This is a name space of types which conform to `DecimalNumberBehaviorType` with common rounding modes. All have maximum precision, of 38 significant digits. */ public struct DecimalNumberBehavior { /// Plain rounding mode public struct Plain: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behavior(withMode: .plain) } /// Round down mode public struct RoundDown: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behavior(withMode: .down) } /// Round up mode public struct RoundUp: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behavior(withMode: .up) } /// Bankers rounding mode, see `NSRoundingMode.RoundBankers` for info. public struct Bankers: DecimalNumberBehaviorType { public static let decimalNumberBehaviors = DecimalNumberBehavior.behavior(withMode: .bankers) } private static func behavior(withMode mode: NSDecimalNumber.RoundingMode, scale: Int16 = 38) -> NSDecimalNumberBehaviors { return NSDecimalNumberHandler(roundingMode: mode, scale: 38, raiseOnExactness: false, raiseOnOverflow: true, raiseOnUnderflow: true, raiseOnDivideByZero: true) } } /** # DecimalNumberType A protocol which defines the necessary interface to support decimal number calculations and operators. */ public protocol DecimalNumberType: Hashable, SignedNumber, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, CustomStringConvertible { associatedtype DecimalStorageType associatedtype DecimalNumberBehavior: DecimalNumberBehaviorType /// Access the underlying storage var storage: DecimalStorageType { get } /// Flag to indicate if the decimal number is less than zero var isNegative: Bool { get } /** Negates the receiver, equivalent to multiplying it by -1 - returns: another instance of this type. */ var negative: Self { get } /// Access an integer value representation var integerValue: IntegerLiteralType { get } /// Access a float value representation var floatValue: FloatLiteralType { get } /** Initialize a new `DecimalNumberType` with the underlying storage. This is necessary in order to convert between different decimal number types. - parameter storage: the underlying decimal storage type e.g. NSDecimalNumber or NSDecimal */ init(storage: DecimalStorageType) /** Subtract a matching `DecimalNumberType` from the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func subtracting(_: Self) -> Self /** Add a matching `DecimalNumberType` to the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func adding(_: Self) -> Self /** Multiply the receive by 10^n - parameter n: an `Int` for the 10 power index - returns: another instance of this type. */ func multiplying(byPowerOf10: Int16) -> Self /** Multiply a matching `DecimalNumberType` with the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func multiplying(by: Self) -> Self /** Multiply another `DecimalNumberType` with the receiver. The other `DecimalNumberType` must have the same underlying `DecimalStorageType` as this `DecimalNumberType`. - parameter other: another `DecimalNumberType` value of different type. - returns: a different `DecimalNumberType` value. */ func multiplying<Other: DecimalNumberType>(by: Other) -> Other where Other.DecimalStorageType == DecimalStorageType /** Divide the receiver by a matching `DecimalNumberType`. - parameter other: another instance of this type. - returns: another instance of this type. */ func dividing(by: Self) -> Self /** Divide the receiver by another `DecimalNumberType`. The other `DecimalNumberType` must have the same underlying `DecimalStorageType` as this `DecimalNumberType`. - parameter other: another `DecimalNumberType` value of different type. - returns: another instance of this type. */ func dividing<Other: DecimalNumberType>(by: Other) -> Other where Other.DecimalStorageType == DecimalStorageType /** The remainder of dividing another `DecimalNumberType` into the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func remainder(_: Self) -> Self } // MARK: - Extensions /** Extensions on `DecimalNumberType` where the underlying storage type is `NSDecimalNumber`. */ public extension DecimalNumberType where DecimalStorageType == NSDecimalNumber { /// Flag to indicate if the decimal number is less than zero var isNegative: Bool { return storage.isNegative } /// The negative of Self. /// - returns: a `_Decimal<Behavior>` var negative: Self { return Self(storage: storage.negate(withBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /// Access an integer value representation var integerValue: Int { return storage.intValue } /// Access a float value representation var floatValue: Double { return storage.doubleValue } /// Text description. var description: String { return "\(storage.description)" } /// Hash value var hashValue: Int { return storage.hashValue } /// Initialize a new decimal with an `Int`. /// - parameter value: an `Int`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int) { switch value { case 0: self.init(storage: NSDecimalNumber.zero) case 1: self.init(storage: NSDecimalNumber.one) default: self.init(storage: NSDecimalNumber(integerLiteral: value).rounding(accordingToBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } } /// Initialize a new decimal with an `UInt8`. /// - parameter value: an `UInt8`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt8) { self.init(Int(value)) } /// Initialize a new decimal with an `Int8`. /// - parameter value: an `Int8`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int8) { self.init(Int(value)) } /// Initialize a new decimal with an `UInt16`. /// - parameter value: an `UInt16`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt16) { self.init(Int(value)) } /// Initialize a new decimal with an `Int16`. /// - parameter value: an `Int16`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int16) { self.init(Int(value)) } /// Initialize a new decimal with an `UInt32`. /// - parameter value: an `UInt32`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt32) { self.init(Int(value)) } /// Initialize a new decimal with an `Int32`. /// - parameter value: an `Int32`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int32) { self.init(Int(value)) } /// Initialize a new decimal with an `UInt64`. /// - parameter value: an `UInt64`. /// - returns: an initialized `DecimalNumberType`. init(_ value: UInt64) { self.init(Int(value)) } /// Initialize a new decimal with an `Int64`. /// - parameter value: an `Int64`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Int64) { self.init(Int(value)) } /** Initialize a new value using a `IntegerLiteralType` - parameter integerLiteral: a `IntegerLiteralType` for the system, probably `Int`. */ init(integerLiteral value: Swift.IntegerLiteralType) { self.init(value) } /// Initialize a new decimal with an `Double`. /// - parameter value: an `Double`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Double) { self.init(storage: NSDecimalNumber(floatLiteral: value).rounding(accordingToBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /// Initialize a new decimal with a `Float`. /// - parameter value: an `Float`. /// - returns: an initialized `DecimalNumberType`. init(_ value: Float) { self.init(Double(value)) } /** Initialize a new value using a `FloatLiteralType` - parameter floatLiteral: a `FloatLiteralType` for the system, probably `Double`. */ init(floatLiteral value: Swift.FloatLiteralType) { self.init(value) } /** Subtract a matching `DecimalNumberType` from the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func subtracting(_ other: Self) -> Self { return Self(storage: storage.subtracting(other.storage, withBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Add a matching `DecimalNumberType` from the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func adding(_ other: Self) -> Self { return Self(storage: storage.adding(other.storage, withBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Multiply the receive by 10^n - parameter n: an `Int` for the 10 power index - returns: another instance of this type. */ func multiplying(byPowerOf10 index: Int16) -> Self { return Self(storage: storage.multiplying(byPowerOf10: index, withBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Multiply a matching `DecimalNumberType` with the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func multiplying(by other: Self) -> Self { return Self(storage: storage.multiplying(by: other.storage, withBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Multiply a different `DecimalNumberType` which also has `NSDecimalNumber` as the storage type with the receiver. - parameter other: another `DecimalNumberType` with `NSDecimalNumber` storage. - returns: another instance of this type. */ func multiplying<Other: DecimalNumberType>(by other: Other) -> Other where Other.DecimalStorageType == NSDecimalNumber { return Other(storage: storage.multiplying(by: other.storage, withBehavior: Other.DecimalNumberBehavior.decimalNumberBehaviors) ) } /** Divide the receiver by another instance of this type. - parameter other: another instance of this type. - returns: another instance of this type. */ func dividing(by other: Self) -> Self { return Self(storage: storage.dividing(by: other.storage, withBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } /** Divide the receiver by a different `DecimalNumberType` which also has `NSDecimalNumber` as the storage type. - parameter other: another `DecimalNumberType` with `NSDecimalNumber` storage. - returns: another instance of this type. */ func dividing<Other: DecimalNumberType>(by other: Other) -> Other where Other.DecimalStorageType == NSDecimalNumber { return Other(storage: storage.dividing(by: other.storage, withBehavior: Other.DecimalNumberBehavior.decimalNumberBehaviors)) } /** The remainder of dividing another instance of this type into the receiver. - parameter other: another instance of this type. - returns: another instance of this type. */ func remainder(_ other: Self) -> Self { return Self(storage: storage.remainder(other.storage, withBehavior: DecimalNumberBehavior.decimalNumberBehaviors)) } } extension DecimalNumberType where Self.IntegerLiteralType == Int { /// Get the reciprocal of the receiver. public var reciprocal: Self { return Self(integerLiteral: 1).dividing(by: self) } } // MARK: - Operators // MARK: - Subtraction public func -<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.subtracting(rhs) } public func -<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs - T(integerLiteral: rhs) } public func -<T: DecimalNumberType>(lhs: T.IntegerLiteralType, rhs: T) -> T { return T(integerLiteral: lhs) - rhs } public func -<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs - T(floatLiteral: rhs) } public func -<T: DecimalNumberType>(lhs: T.FloatLiteralType, rhs: T) -> T { return T(floatLiteral: lhs) - rhs } // MARK: - Addition public func +<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.adding(rhs) } public func +<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs + T(integerLiteral: rhs) } public func +<T: DecimalNumberType>(lhs: T.IntegerLiteralType, rhs: T) -> T { return T(integerLiteral: lhs) + rhs } public func +<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs + T(floatLiteral: rhs) } public func +<T: DecimalNumberType>(lhs: T.FloatLiteralType, rhs: T) -> T { return T(floatLiteral: lhs) + rhs } // MARK: - Multiplication public func *<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.multiplying(by: rhs) } public func *<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs * T(integerLiteral: rhs) } public func *<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs * T(floatLiteral: rhs) } public func *<T: DecimalNumberType>(lhs: T.IntegerLiteralType, rhs: T) -> T { return rhs * lhs } public func *<T: DecimalNumberType>(lhs: T.FloatLiteralType, rhs: T) -> T { return rhs * lhs } public func *<T, V>(lhs: T, rhs: V) -> V where T: DecimalNumberType, V: DecimalNumberType, T.DecimalStorageType == V.DecimalStorageType { return lhs.multiplying(by: rhs) } // MARK: - Division public func /<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.dividing(by: rhs) } public func /<T: DecimalNumberType>(lhs: T, rhs: T.IntegerLiteralType) -> T { return lhs / T(integerLiteral: rhs) } public func /<T: DecimalNumberType>(lhs: T, rhs: T.FloatLiteralType) -> T { return lhs / T(floatLiteral: rhs) } public func /<T, V>(lhs: T, rhs: V) -> V where T: DecimalNumberType, V: DecimalNumberType, T.DecimalStorageType == V.DecimalStorageType { return lhs.dividing(by: rhs) } // MARK: - Remainder public func %<T: DecimalNumberType>(lhs: T, rhs: T) -> T { return lhs.remainder(rhs) }
31.957529
167
0.682675
39fa438cdf9d0df2896abfecb3c7e1c5c57830f0
9,728
// // PendingBooking.swift // VVV // // Created by James Swiney on 21/2/17. // Copyright © 2017 Vroom Vroom Vroom. All rights reserved. // import Foundation /** The Pending Booking object is the object created when selecting a search result, it contains more information such as fees, extras and Driver details. It can be submitted to create a booking. */ @objc(VVVPendingBooking) public class PendingBooking : SearchResult,APIRequestPerformer { /** The pickup and return depots and the supplier for the booking */ public let depots : DepotPair /** The dateRange for the booking */ public let dateRange : DateRange /** The age group of the driver for the booking */ public let age : AgeGroup /** The country of residency of the driver for the booking */ public let residency : Country /** An array of the fee breakdown for the booking (can be empty) */ public let fees : [Fee] /** An array of possible extras to be added to the booking (can be empty) */ public let extras : [PendingExtra] /** The personal driver details of the driver for the booking */ public var driver = Driver() /** Submit the pending booking to create a booking with Vroom and with the Supplier - Parameters: - completion: The completion block to be called - booking: A booking object if the booking was successfully placed - error: An error message to be displayed upon failing to place the booking. */ public func submit(completion:@escaping (_ booking:Booking?,_ error:String?)->()) { let request = CreateBookingRequest(pending: self, completion: completion) self.perform(apiRequest: request) } /** Request to increase an extras amount to the booking if the amount is 0 the extra is removed from the booking. - Parameters: - extra: The extra to change the amount of - byAmount: Amount of the extra to add must be lower than the max amount of the extra - Return: - ExtraRequestStatus: The status of the amendment to the extra. */ public func request(extra:PendingExtra,byAmount:Int) -> ExtraRequestStatus { if byAmount == 0 { extra.quatityRequested = 0 return .completed } if byAmount + extra.quatityRequested > extra.maxQuantity { return .overMaxQuantity } if extra.isSeatType() && byAmount + extra.quatityRequested + self.totalExtraSeatsRequested() > 2 { return .overTotalSeatsAllowed } extra.quatityRequested = extra.quatityRequested + byAmount return .completed } /** If the booking is at an airport adding a flight number ensures that the depot will have a car available if the flight is delayed. Will only accept valid flight numbers eg. "QA123" - Parameters: - flightNumber: The flight number - Return: Bool: if the flight number is valid returns true otherwise false */ public func add(flightNumber:String) -> Bool { if Utils.validate(flightNumber: flightNumber) { self.flightNumber = flightNumber return true } return false } /** Supplys an array of terms for a full list of terms and conditions from the supplier. Based on the details in the pending booking. - Parameters: - completion: - terms : The array of term objects if available. - error : The error string if available. */ public func fetchTermsAndConditions(completion:@escaping (_ terms:[SupplierTerm]?,_ error:String?)->()) { let request = TermsAndConditionsRequest(pendingBooking: self, completion: completion) self.perform(apiRequest: request) } /** the flight number for the booking if available */ var flightNumber : String? /** vehicle class id, used in the booking request */ let classID : Int /** vehicle category id, used in the booking request */ let categoryID : Int /** universal car rental id, used in the booking request */ let sippID : Int /** Init with the json object - Parameters: - json: json object from the search/vehicle request - depots: Depot pair for the booking - search: The search object for the booking */ init?(json: [String : Any], depots: DepotPair,search:Search) { guard let sippID = json["sippID"] as? Int, let categoryID = json["vehicleCategoryID"] as? Int, let classID = json["vehicleClassID"] as? Int else { print("failed to map pending \(json.debugDescription)") return nil } self.classID = classID self.categoryID = categoryID self.sippID = sippID self.depots = depots self.dateRange = search.dateRange self.age = search.age self.residency = search.residency var feeArray = [Fee]() if let feesJson = json["fees"] as? [[String:Any]] { for object in feesJson { guard let fee = Fee(json: object) else { continue } feeArray.append(fee) } } self.fees = feeArray var extraArray = [PendingExtra]() if let extraJson = json["extras"] as? [[String:Any]] { for object in extraJson { guard let extra = PendingExtra(json: object) else { continue } extraArray.append(extra) } } self.extras = extraArray super.init(json: json, supplier: depots.supplier) self.driver.setPhonePrefixFor(residency: self.residency) } /** Utility method calculation total seats, as there is a maximum amount of combined seats that can be added to a booking - Return: - Int: total number of seats requested */ func totalExtraSeatsRequested() -> Int { var count = 0 for extra in extras { if extra.isSeatType() { count = count + extra.quatityRequested } } return count } } /** An object representing an individual fee from the fees breakdown of a pending/booking. */ @objc(VVVFee) public class Fee : NSObject { /** The amount of the fee */ public let amount : Decimal /** The description of the fee eg. "Premium location surcharge" */ public let details : String /** Init with the json object from withing the fees jsonArray of search/vehicle and booking/create - Parameters: - json: json object */ init?(json:[String:Any]) { guard let amountString = json["amount"] as? String, let amount = Decimal(string: amountString), let details = json["description"] as? String else { return nil } self.amount = amount self.details = details super.init() } } /** An object representing an an optional extra for a pending booking. */ @objc(VVVPendingExtra) public class PendingExtra : NSObject { /** The display name of the Extra eg. "GPS" */ public let extraName : String /** The price of the Extra eg. "GPS" */ public let price : Decimal /** The maximam amount of this extra that can be added to a booking. eg for Baby seats it is 2 */ public let maxQuantity : Int /** The maximam amount of this extra that can be added to a booking. eg for Baby seats it is 2 */ public internal(set) var quatityRequested = 0 /** The maximam price of this extra if available */ var maxPrice : Decimal? /** The code identifier for the extra */ let code : Int /** The identifier for the extra */ let identifier : Int /** Init with the json object from withing the extra jsonArray of search/vehicle - Parameters: - json: json object */ init?(json: [String:Any]) { guard let code = json["equipmentCode"] as? Int, let identifier = json["extrasTypeID"] as? Int, let name = json["name"] as? String, let priceString = json["price"] as? String, let price = Decimal(string: priceString), let maxQuantity = json["maxQuantity"] as? Int else { print("skipping extra") return nil } self.code = code self.identifier = identifier self.extraName = name self.price = price if let maxPriceString = json["maxPrice"] as? String { self.maxPrice = Decimal(string: maxPriceString) } self.maxQuantity = maxQuantity super.init() } /** Determines whether or not the extra is a seat, as there is a maximum total amount of extra seats to a booking */ func isSeatType() -> Bool { switch identifier { case 2,3,4: return true default: return false } } } /** Status returned from Requesting an Extra on a pending booking - completed: pickup location variable on search is nil - overMaxQuantity: return location variable on search is nil - overTotalSeatsAllowed: The return date is before the pickupdate */ @objc(VVVExtraRequestStatus) public enum ExtraRequestStatus : Int,RawRepresentable { case completed = 0 case overMaxQuantity = 1 case overTotalSeatsAllowed = 2 }
31.179487
193
0.604544
145fbf9daf28ad7d96f770147abfaa4e68aca4f5
118
import XCTest import DynuRESTTests var tests = [XCTestCaseEntry]() tests += DynuRESTTests.allTests() XCTMain(tests)
14.75
33
0.779661
8fc6e45d59f976be8a8902b22a4603053f801897
6,989
// // CacheConverterSpec.swift // LaunchDarklyTests // // Copyright © 2019 Catamorphic Co. All rights reserved. // import Foundation import Quick import Nimble @testable import LaunchDarkly final class CacheConverterSpec: QuickSpec { struct TestContext { var clientServiceFactoryMock = ClientServiceMockFactory() var cacheConverter: CacheConverter var user: LDUser var config: LDConfig var featureFlagCachingMock: FeatureFlagCachingMock { clientServiceFactoryMock.makeFeatureFlagCacheReturnValue } var expiredCacheThreshold: Date init(createCacheData: Bool = false, deprecatedCacheData: DeprecatedCacheModel? = nil) { cacheConverter = CacheConverter(serviceFactory: clientServiceFactoryMock, maxCachedUsers: LDConfig.Defaults.maxCachedUsers) expiredCacheThreshold = Date().addingTimeInterval(CacheConverter.Constants.maxAge) if createCacheData { let (users, userEnvironmentFlagsCollection, mobileKeys) = CacheableUserEnvironmentFlags.stubCollection() user = users[users.count / 2] config = LDConfig(mobileKey: mobileKeys[mobileKeys.count / 2], environmentReporter: EnvironmentReportingMock()) featureFlagCachingMock.retrieveFeatureFlagsReturnValue = userEnvironmentFlagsCollection[user.key]?.environmentFlags[config.mobileKey]?.featureFlags } else { user = LDUser.stub() config = LDConfig.stub featureFlagCachingMock.retrieveFeatureFlagsReturnValue = nil } DeprecatedCacheModel.allCases.forEach { model in deprecatedCacheMock(for: model).retrieveFlagsReturnValue = (nil, nil) } if let deprecatedCacheData = deprecatedCacheData { let age = Date().addingTimeInterval(CacheConverter.Constants.maxAge + 1.0) deprecatedCacheMock(for: deprecatedCacheData).retrieveFlagsReturnValue = (FlagMaintainingMock.stubFlags(), age) } } func deprecatedCacheMock(for version: DeprecatedCacheModel) -> DeprecatedCacheMock { cacheConverter.deprecatedCaches[version] as! DeprecatedCacheMock } } override func spec() { initSpec() convertCacheDataSpec() } private func initSpec() { var testContext: TestContext! describe("init") { it("creates a cache converter") { testContext = TestContext() expect(testContext.clientServiceFactoryMock.makeFeatureFlagCacheCallCount) == 1 expect(testContext.cacheConverter.currentCache) === testContext.clientServiceFactoryMock.makeFeatureFlagCacheReturnValue DeprecatedCacheModel.allCases.forEach { deprecatedCacheModel in expect(testContext.cacheConverter.deprecatedCaches[deprecatedCacheModel]).toNot(beNil()) expect(testContext.clientServiceFactoryMock.makeDeprecatedCacheModelReceivedModels.contains(deprecatedCacheModel)) == true } } } } private func convertCacheDataSpec() { let cacheCases: [DeprecatedCacheModel?] = [.version5, .version4, .version3, .version2, nil] // Nil for no deprecated cache var testContext: TestContext! describe("convertCacheData") { afterEach { // The CacheConverter should always remove all expired data DeprecatedCacheModel.allCases.forEach { model in expect(testContext.deprecatedCacheMock(for: model).removeDataCallCount) == 1 expect(testContext.deprecatedCacheMock(for: model).removeDataReceivedExpirationDate? .isWithin(0.5, of: testContext.expiredCacheThreshold)) == true } } for deprecatedData in cacheCases { context("current cache and \(deprecatedData?.rawValue ?? "no") deprecated cache data exists") { it("does not load from deprecated caches") { testContext = TestContext(createCacheData: true, deprecatedCacheData: deprecatedData) testContext.cacheConverter.convertCacheData(for: testContext.user, and: testContext.config) DeprecatedCacheModel.allCases.forEach { expect(testContext.deprecatedCacheMock(for: $0).retrieveFlagsCallCount) == 0 } expect(testContext.featureFlagCachingMock.storeFeatureFlagsCallCount) == 0 } } context("no current cache data and \(deprecatedData?.rawValue ?? "no") deprecated cache data exists") { beforeEach { testContext = TestContext(createCacheData: false, deprecatedCacheData: deprecatedData) testContext.cacheConverter.convertCacheData(for: testContext.user, and: testContext.config) } it("looks in the deprecated caches for data") { let searchUpTo = cacheCases.firstIndex(of: deprecatedData)! DeprecatedCacheModel.allCases.forEach { expect(testContext.deprecatedCacheMock(for: $0).retrieveFlagsCallCount) == (cacheCases.firstIndex(of: $0)! <= searchUpTo ? 1 : 0) } } if let deprecatedData = deprecatedData { it("creates current cache data from the deprecated cache data") { expect(testContext.featureFlagCachingMock.storeFeatureFlagsCallCount) == 1 expect(testContext.featureFlagCachingMock.storeFeatureFlagsReceivedArguments?.featureFlags) == testContext.deprecatedCacheMock(for: deprecatedData).retrieveFlagsReturnValue?.featureFlags expect(testContext.featureFlagCachingMock.storeFeatureFlagsReceivedArguments?.userKey) == testContext.user.key expect(testContext.featureFlagCachingMock.storeFeatureFlagsReceivedArguments?.mobileKey) == testContext.config.mobileKey expect(testContext.featureFlagCachingMock.storeFeatureFlagsReceivedArguments?.lastUpdated) == testContext.deprecatedCacheMock(for: deprecatedData).retrieveFlagsReturnValue?.lastUpdated expect(testContext.featureFlagCachingMock.storeFeatureFlagsReceivedArguments?.storeMode) == .sync } } else { it("leaves the current cache data unchanged") { expect(testContext.featureFlagCachingMock.storeFeatureFlagsCallCount) == 0 } } } } } } }
55.468254
163
0.627701
5d6ef24ea2e405dd0b314709d8998c7c7c142617
2,978
// // AcdStartDetailEventTopicAcdStartEvent.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class AcdStartDetailEventTopicAcdStartEvent: Codable { public enum MediaType: String, Codable { case unknown = "UNKNOWN" case voice = "VOICE" case chat = "CHAT" case email = "EMAIL" case callback = "CALLBACK" case cobrowse = "COBROWSE" case video = "VIDEO" case screenshare = "SCREENSHARE" case message = "MESSAGE" } public enum Direction: String, Codable { case unknown = "UNKNOWN" case inbound = "INBOUND" case outbound = "OUTBOUND" } public enum MessageType: String, Codable { case unknown = "UNKNOWN" case sms = "SMS" case twitter = "TWITTER" case facebook = "FACEBOOK" case line = "LINE" case whatsapp = "WHATSAPP" case webmessaging = "WEBMESSAGING" case _open = "OPEN" case instagram = "INSTAGRAM" } public var eventTime: Int? public var conversationId: String? public var participantId: String? public var sessionId: String? public var mediaType: MediaType? public var provider: String? public var direction: Direction? public var ani: String? public var dnis: String? public var addressTo: String? public var addressFrom: String? public var callbackUserName: String? public var callbackNumbers: [String]? public var callbackScheduledTime: Int? public var subject: String? public var messageType: MessageType? public var queueId: String? public var divisionId: String? public init(eventTime: Int?, conversationId: String?, participantId: String?, sessionId: String?, mediaType: MediaType?, provider: String?, direction: Direction?, ani: String?, dnis: String?, addressTo: String?, addressFrom: String?, callbackUserName: String?, callbackNumbers: [String]?, callbackScheduledTime: Int?, subject: String?, messageType: MessageType?, queueId: String?, divisionId: String?) { self.eventTime = eventTime self.conversationId = conversationId self.participantId = participantId self.sessionId = sessionId self.mediaType = mediaType self.provider = provider self.direction = direction self.ani = ani self.dnis = dnis self.addressTo = addressTo self.addressFrom = addressFrom self.callbackUserName = callbackUserName self.callbackNumbers = callbackNumbers self.callbackScheduledTime = callbackScheduledTime self.subject = subject self.messageType = messageType self.queueId = queueId self.divisionId = divisionId } }
28.912621
407
0.623573
0e3463873951b14d396adeab80e72c21025f1ed5
441
// Copyright 2018, Oath Inc. // Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms. public enum UserActions { case play, pause, nothing } func reduce(state: UserActions, action: Action) -> UserActions { switch action { case is Play: return .play case is Pause: return .pause case is UpdateAdStreamRate: return .nothing default: return state } }
23.210526
95
0.662132
fcfd81e3e1c12075081887b9b2dc91989b1ba7eb
3,812
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_transparent.swift // RUN: llvm-bcanalyzer %t/def_transparent.swiftmodule | %FileCheck %s // RUN: %target-swift-frontend -emit-silgen -sil-link-all -I %t %s | %FileCheck %s -check-prefix=SIL // CHECK-NOT: UnknownCode import def_transparent // SIL-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { // SIL: [[RAW:%.+]] = global_addr @_T011transparent3rawSbvp : $*Bool // SIL: [[FUNC:%.+]] = function_ref @_T015def_transparent15testTransparentS2b1x_tF : $@convention(thin) (Bool) -> Bool // SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool // SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Bool var raw = testTransparent(x: false) // SIL: [[TMP:%.+]] = global_addr @_T011transparent3tmps5Int32Vvp : $*Int32 // SIL: [[FUNC2:%.+]] = function_ref @_T015def_transparent11testBuiltins5Int32VyF : $@convention(thin) () -> Int32 // SIL: [[RESULT2:%.+]] = apply [[FUNC2]]() : $@convention(thin) () -> Int32 // SIL: store [[RESULT2]] to [trivial] [[TMP]] : $*Int32 var tmp = testBuiltin() // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent15testTransparentS2b1x_tF : $@convention(thin) (Bool) -> Bool { // SIL: bb0(%0 : $Bool): // SIL: return %0 : $Bool // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent11testBuiltins5Int32VyF : $@convention(thin) () -> Int32 { // SIL: bb0: // SIL: integer_literal $Builtin.Int32, 300 // SIL: string_literal utf8 "foo" // SIL: return %{{.*}} : $Int32 // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7test_bryyF : $@convention(thin) () -> () { // SIL: bb{{.*}}: // SIL: cond_br %{{.*}}, bb{{.*}}, bb{{.*}} // SIL: bb{{.*}}: // SIL: br bb{{.*}} func wrap_br() { test_br() } // SIL-LABEL: sil public_external [serialized] @_T015def_transparent9do_switchyAA9MaybePairO1u_tF : $@convention(thin) (@owned MaybePair) -> () { // SIL: bb0(%0 : $MaybePair): // SIL: retain_value %0 : $MaybePair // SIL: switch_enum %0 : $MaybePair, case #MaybePair.Neither!enumelt: bb[[CASE1:[0-9]+]], case #MaybePair.Left!enumelt.1: bb[[CASE2:[0-9]+]], case #MaybePair.Right!enumelt.1: bb[[CASE3:[0-9]+]], case #MaybePair.Both!enumelt.1: bb[[CASE4:[0-9]+]] // SIL: bb[[CASE4]](%{{.*}} : $(Int32, String)): // SIL: bb[[CASE3]](%{{.*}} : $String): // SIL: bb[[CASE2]](%{{.*}} : $Int32): // SIL: bb[[CASE1]]: func test_switch(u: MaybePair) { do_switch(u: u) } // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperVACs5Int32V3Val_tcfC : $@convention(method) (Int32, @thin Wrapper.Type) -> Wrapper { // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperV8getValue{{[_0-9a-zA-Z]*}}F : $@convention(method) (Wrapper) -> Int32 { // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperV10valueAgains5Int32Vvg : $@convention(method) (Wrapper) -> Int32 { // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent7WrapperV13getValueAgain{{[_0-9a-zA-Z]*}}F : $@convention(method) (Wrapper) -> Int32 { func test_wrapper() { var w = Wrapper(Val: 42) print(w.value, terminator: "") print(w.getValue(), terminator: "") print(w.valueAgain, terminator: "") print(w.getValueAgain(), terminator: "") } // SIL-LABEL: sil public_external [transparent] [serialized] @_T015def_transparent17open_existentialsyAA1P_p1p_AA2CP_p2cptF func test_open_existentials(p: P, cp: CP) { // SIL: open_existential_addr immutable_access [[EXIST:%[0-9]+]] : $*P to $*@opened([[N:".*"]]) P // SIL: open_existential_ref [[EXIST:%[0-9]+]] : $CP to $@opened([[M:".*"]]) CP open_existentials(p: p, cp: cp) }
52.219178
245
0.673924
bbba23d008d6d4efc248683330824967a2cea7d0
4,954
// // M+Row.swift // // Copyright 2021 FlowAllocator 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 extension MTransaction: AllocRowed { public init(from row: DecodedRow) throws { guard let _action = row[CodingKeys.action.rawValue] as? MTransaction.Action else { throw AllocDataError.invalidPrimaryKey(CodingKeys.action.rawValue) } action = _action guard let _transactedAt = MTransaction.getDate(row, CodingKeys.transactedAt.rawValue) else { throw AllocDataError.invalidPrimaryKey(CodingKeys.transactedAt.rawValue) } transactedAt = _transactedAt accountID = MTransaction.getStr(row, CodingKeys.accountID.rawValue) ?? "" securityID = MTransaction.getStr(row, CodingKeys.securityID.rawValue) ?? "" lotID = MTransaction.getStr(row, CodingKeys.lotID.rawValue) ?? "" shareCount = MTransaction.getDouble(row, CodingKeys.shareCount.rawValue) ?? 0 // non-key attributes sharePrice = MTransaction.getDouble(row, CodingKeys.sharePrice.rawValue) realizedGainShort = MTransaction.getDouble(row, CodingKeys.realizedGainShort.rawValue) realizedGainLong = MTransaction.getDouble(row, CodingKeys.realizedGainLong.rawValue) } public mutating func update(from row: DecodedRow) throws { // ignore composite key if let val = MTransaction.getDouble(row, CodingKeys.sharePrice.rawValue) { sharePrice = val } if let val = MTransaction.getDouble(row, CodingKeys.realizedGainShort.rawValue) { realizedGainShort = val } if let val = MTransaction.getDouble(row, CodingKeys.realizedGainLong.rawValue) { realizedGainLong = val } } public static func getPrimaryKey(_ row: DecodedRow) throws -> Key { guard let _action = row[CodingKeys.action.rawValue] as? MTransaction.Action, let _transactedAt = getDate(row, CodingKeys.transactedAt.rawValue), let _shareCount = getDouble(row, CodingKeys.shareCount.rawValue) else { throw AllocDataError.invalidPrimaryKey("Transaction") } let _accountID = getStr(row, CodingKeys.accountID.rawValue) ?? "" let _securityID = getStr(row, CodingKeys.securityID.rawValue) ?? "" let _lotID = getStr(row, CodingKeys.lotID.rawValue) ?? "" return Key(action: _action, transactedAt: _transactedAt, accountID: _accountID, securityID: _securityID, lotID: _lotID, shareCount: _shareCount) } public static func decode(_ rawRows: [RawRow], rejectedRows: inout [RawRow]) throws -> [DecodedRow] { let ck = MTransaction.CodingKeys.self return rawRows.reduce(into: []) { array, rawRow in guard let rawAction = parseString(rawRow[ck.action.rawValue]), let action = Action(rawValue: rawAction), let transactedAt = parseDate(rawRow[ck.transactedAt.rawValue]) else { rejectedRows.append(rawRow) return } var decodedRow: DecodedRow = [ ck.action.rawValue: action, ck.transactedAt.rawValue: transactedAt, ] if let accountID = parseString(rawRow[ck.accountID.rawValue]) { decodedRow[ck.accountID.rawValue] = accountID } if let securityID = parseString(rawRow[ck.securityID.rawValue]) { decodedRow[ck.securityID.rawValue] = securityID } if let lotID = parseString(rawRow[ck.lotID.rawValue]) { decodedRow[ck.lotID.rawValue] = lotID } if let shareCount = parseDouble(rawRow[ck.shareCount.rawValue]) { decodedRow[ck.shareCount.rawValue] = shareCount } if let sharePrice = parseDouble(rawRow[ck.sharePrice.rawValue]) { decodedRow[ck.sharePrice.rawValue] = sharePrice } if let realizedGainShort = parseDouble(rawRow[ck.realizedGainShort.rawValue]) { decodedRow[ck.realizedGainShort.rawValue] = realizedGainShort } if let realizedGainLong = parseDouble(rawRow[ck.realizedGainLong.rawValue]) { decodedRow[ck.realizedGainLong.rawValue] = realizedGainLong } array.append(decodedRow) } } }
44.630631
115
0.650787
0938b6fda12ab28496868010073fa791e8cb794a
1,842
// // SetupBiometricsOperation.swift // AirWatchSDK // // Copyright © 2016 VMware, Inc. All rights reserved. This product is protected // by copyright and intellectual property laws in the United States and other // countries as well as by international treaties. VMware products are covered // by one or more patents listed at http://www.vmware.com/go/patents. // import Foundation import LocalAuthentication public struct BiometricsHelper { public static func isTouchIDSupported() -> Bool { let context = LAContext() var error: NSError? = nil let supported = context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error ) log(info: "policy evaluation for TouchID returned: \(supported) with error: \(String(describing: error))") return supported } } class BiometricsSetupOperation: SDKSetupAsyncOperation { override func startOperation() { guard BiometricsHelper.isTouchIDSupported() else { log(error: "Biometrics is not supported. closing the operations") self.markOperationComplete() return } let requiredMethod = self.dataStore.profileRequiredBiometricMethod if requiredMethod == AWSDK.BiometricMethod.touchID { self.dataStore.enableTouchIDAuthentication { (success, error) in guard success else { log(error: "Biometric error recieved \(error.debugDescription) when attempting to setup touch ID Authentication") self.markOperationFailed() return } self.dataStore.isTouchIDConfigured = true self.dataStore.currentBiometricMethod = requiredMethod self.markOperationComplete() } } } }
35.423077
133
0.661781
48b3e03f11d2cfc15941386f5ca0ddc4f0909cea
5,066
// // RyePresentation.swift // Rye // // Created by Andrei Hogea on 12/06/2019. // Copyright © 2019 Nodes. All rights reserved. // import UIKit // MARK: - Presentaion public extension RyeViewController { func show() { switch self.alertType! { case .toast: // create a new UIWindow let window = UIWindow(frame: UIScreen.main.bounds) window.windowLevel = .alert window.rootViewController = self window.backgroundColor = .clear window.makeKeyAndVisible() self.window = window case .snackBar: break } // check if we can show the RyeView guard !isShowing else { NSLog("An Rye is already showing. Multiple Ryes can not be presented at the same time") return } // update Rye state isShowing = true // create RyeView showRye(for: viewType) // force layout of the view to position the RyeView at the desired location parentView.setNeedsLayout() parentView.layoutIfNeeded() // animate the RyeView on screen animateRyeIn() } func dismiss(completion: (() -> Void)? = nil) { guard isShowing else { NSLog("Can not dismiss a Rye that it is not showing") return } // animate the RyeView off screen animateRyeOut(completion: { switch self.alertType! { case .toast: // remove the UIWindow self.window?.isHidden = true self.window?.removeFromSuperview() self.window = nil case .snackBar: // remove the Rye View self.ryeView.isHidden = true self.ryeView.removeFromSuperview() self.ryeView = nil } // update Rye state self.isShowing = false // call completion completion?() }) } internal func animateRyeIn() { // calculate safeArea based on UIDevice current orientation to facilitate a good positioning of RyeView func getSafeAreaSpacing() -> CGFloat { switch UIDevice.current.orientation { case .faceUp, .faceDown, .portrait, .unknown: return UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0 case .portraitUpsideDown: return UIApplication.shared.keyWindow?.safeAreaInsets.top ?? 0 case .landscapeLeft: return UIApplication.shared.keyWindow?.safeAreaInsets.left ?? 0 case .landscapeRight: return UIApplication.shared.keyWindow?.safeAreaInsets.right ?? 0 @unknown default: return UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0 } } func getRyeViewPositionConstant() -> CGFloat { let safeArea = getSafeAreaSpacing() // update RyeView bottom constraint to position it on screen switch position! { case .bottom(let inset): return -safeArea - inset case .top(let inset): return safeArea + inset } } switch self.animationType! { case .fadeInOut: ryeView.alpha = 0 ryeViewPositionConstraint.constant = getRyeViewPositionConstant() case .slideInOut: ryeView.alpha = 1 ryeViewPositionConstraint.constant = getRyeViewPositionConstant() } // animate UIView.animate(withDuration: animationDuration) { switch self.animationType! { case .fadeInOut: self.ryeView.alpha = 1 case .slideInOut: self.parentView.layoutIfNeeded() } } } internal func animateRyeOut(completion: @escaping () -> Void) { // update RyeView bottom constraint to position it off screen func getRyeViewPositionConstant() -> CGFloat { switch position! { case .bottom: return ryeView.frame.height case .top: return -ryeView.frame.height } } switch self.animationType! { case .fadeInOut: break case .slideInOut: ryeViewPositionConstraint.constant = getRyeViewPositionConstant() } // animate UIView.animate(withDuration: animationDuration, animations: { switch self.animationType! { case .fadeInOut: self.ryeView.alpha = 0 case .slideInOut: self.parentView.layoutIfNeeded() } }, completion: { _ in completion() }) } }
30.335329
111
0.529214
d5f15f7d88d11beec12bf5e77619a29557a32eb5
1,849
// // BarcodeImageView.swift // QRCode // // Created by larryhou on 22/12/2015. // Copyright © 2015 larryhou. All rights reserved. // import Foundation import UIKit @IBDesignable class BarcodeImageView:UIImageView { private static let DEFAULT_MESSAGE = "larryhou" private var ib_inputQuietSpace:Double = 7.0 private var ib_inputMessage:String = BarcodeImageView.DEFAULT_MESSAGE @IBInspectable var inputQuietSpace:Double { get {return ib_inputQuietSpace} set { ib_inputQuietSpace = newValue drawBarcodeImage() } } @IBInspectable var inputMessage:String { get {return ib_inputMessage} set { ib_inputMessage = newValue == "" ? BarcodeImageView.DEFAULT_MESSAGE : newValue drawBarcodeImage() } } func drawBarcodeImage() { let filter = CIFilter(name: "CICode128BarcodeGenerator") let data = NSString(string: inputMessage).dataUsingEncoding(NSUTF8StringEncoding) filter?.setValue(data, forKey: "inputMessage") filter?.setValue(inputQuietSpace, forKey: "inputQuietSpace") let image = (filter?.outputImage)! UIGraphicsBeginImageContext(frame.size) let context = UIGraphicsGetCurrentContext() CGContextSetInterpolationQuality(context, .None) let cgImage = CIContext().createCGImage(image, fromRect: image.extent) CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.image = scaledImage } override func prepareForInterfaceBuilder() { drawBarcodeImage() } }
26.042254
90
0.641969
20dded55c7a4dd33ca819e2140122f971000be45
34,743
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm #if swift(>=3.0) /// :nodoc: /// Internal class. Do not use directly. Used for reflection and initialization public class LinkingObjectsBase: NSObject, NSFastEnumeration { internal let objectClassName: String internal let propertyName: String private var cachedRLMResults: RLMResults<RLMObject>? @objc private var object: RLMWeakObjectHandle? @objc private var property: RLMProperty? internal var rlmResults: RLMResults<RLMObject> { if cachedRLMResults == nil { if let object = self.object, let property = self.property { cachedRLMResults = RLMDynamicGet(object.object, property)! as? RLMResults self.object = nil self.property = nil } else { cachedRLMResults = RLMResults.emptyDetached() } } return cachedRLMResults! } init(fromClassName objectClassName: String, property propertyName: String) { self.objectClassName = objectClassName self.propertyName = propertyName } // MARK: Fast Enumeration public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>!, count len: Int) -> Int { return Int(rlmResults.countByEnumerating(with: state, objects: buffer, count: UInt(len))) } } /** LinkingObjects is an auto-updating container type that represents a collection of objects that link to a given object. LinkingObjects can be queried with the same predicates as `List<T>` and `Results<T>`. LinkingObjects always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the linking objects when the enumeration is begun, even if some of them are deleted or modified to no longer link to the target object during the enumeration. LinkingObjects can only be used as a property on `Object` models. The property must be declared as `let` and cannot be `dynamic`. */ public final class LinkingObjects<T: Object>: LinkingObjectsBase { /// Element type contained in this collection. public typealias Element = T // MARK: Properties /// Returns the Realm these linking objects are associated with. public var realm: Realm? { return rlmResults.isAttached ? Realm(rlmResults.realm) : nil } /// Indicates if the linking objects can no longer be accessed. /// /// Linking objects can no longer be accessed if `invalidate` is called on the containing `Realm`. public var isInvalidated: Bool { return rlmResults.isInvalidated } /// Returns the number of objects in these linking objects. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers /** Creates a LinkingObjects. This initializer should only be called when declaring a property on a Realm model. - parameter type: The originating type linking to this object type. - parameter propertyName: The property name of the incoming relationship this LinkingObjects should refer to. */ public init(fromType type: T.Type, property propertyName: String) { let className = (T.self as Object.Type).className() super.init(fromClassName: className, property: propertyName) } /// Returns a human-readable description of the objects contained in these linking objects. public override var description: String { let type = "LinkingObjects<\(rlmResults.objectClassName)>" return gsub(pattern: "RLMResults <0x[a-z0-9]+>", template: type, string: rlmResults.description) ?? type } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not present. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not present. */ public func index(of object: T) -> Int? { return notFoundToNil(index: rlmResults.index(of: object.unsafeCastToRLMObject())) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicate: The predicate to filter the objects. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOfObject(for predicate: NSPredicate) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOfObject(for predicateFormat: String, _ args: Any...) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat, argumentArray: args))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return unsafeBitCast(rlmResults[UInt(index)], to: T.self) } } /// Returns the first object in the collection, or `nil` if empty. public var first: T? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<T>.self) } /// Returns the last object in the collection, or `nil` if empty. public var last: T? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<T>.self) } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ public override func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the collection's objects. - parameter keyPath: The key path to the property. - returns: Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the collection's objects. */ public override func value(forKeyPath keyPath: String) -> Any? { return rlmResults.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public override func setValue(_ value: Any?, forKey key: String) { return rlmResults.setValue(value, forKeyPath: key) } // MARK: Filtering /** Filters the collection to the objects that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: Results containing objects that match the given predicate. */ public func filter(using predicateFormat: String, _ args: Any...) -> Results<T> { return Results<T>(rlmResults.objects(with: NSPredicate(format: predicateFormat, argumentArray: args))) } /** Filters the collection to the objects that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: Results containing objects that match the given predicate. */ public func filter(using predicate: NSPredicate) -> Results<T> { return Results<T>(rlmResults.objects(with: predicate)) } // MARK: Sorting /** Returns `Results` with elements sorted by the given property name. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` with elements sorted by the given property name. */ public func sorted(onProperty property: String, ascending: Bool = true) -> Results<T> { return sorted(with: [SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: Sequence>(with sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { return Results<T>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ public func minimumValue<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ public func maximumValue<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the collection. */ public func sum<U: AddableType>(ofProperty property: String) -> U { return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property)) } /** Returns the average of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty. */ public func average<U: AddableType>(ofProperty property: String) -> U? { return rlmResults.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Notifications /** Register a block to be called each time the LinkingObjects changes. The block will be asynchronously called with the initial set of objects, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. This version of this method reports which of the objects in the collection were added, removed, or modified in each write transaction as indices within the collection. See the RealmCollectionChange documentation for more information on the change information supplied and an example of how to use it to update a UITableView. At the time when the block is called, the LinkingObjects object will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call realm.refresh(), accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial set of objects. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. let dog = realm.objects(Dog).first! let owners = dog.owners print("owners.count: \(owners.count)") // => 0 let token = owners.addNotificationBlock { (changes: RealmCollectionChange) in switch changes { case .Initial(let owners): // Will print "owners.count: 1" print("owners.count: \(owners.count)") break case .Update: // Will not be hit in this example break case .Error: break } } try! realm.write { realm.add(Person.self, value: ["name": "Mark", dogs: [dog]]) } // end of runloop execution context You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call stop() on the token. - warning: This method cannot be called during a write transaction, or when the source realm is read-only. - parameter block: The block to be called with the evaluated linking objects and change information. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(block: @escaping (RealmCollectionChange<LinkingObjects>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock { results, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension LinkingObjects : RealmCollection { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the results. public func makeIterator() -> RLMIterator<T> { return RLMIterator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after: Int) -> Int { return after + 1 } public func index(before: Int) -> Int { return before - 1 } /// :nodoc: public func _addNotificationBlock(block: @escaping (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: Unavailable extension LinkingObjects { @available(*, unavailable, renamed:"isInvalidated") public var invalidated : Bool { fatalError() } @available(*, unavailable, renamed:"indexOfObject(for:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed:"indexOfObject(for:_:)") public func index(of predicateFormat: String, _ args: Any...) -> Int? { fatalError() } @available(*, unavailable, renamed:"filter(using:)") public func filter(_ predicate: NSPredicate) -> Results<T> { fatalError() } @available(*, unavailable, renamed:"filter(using:_:)") public func filter(_ predicateFormat: String, _ args: Any...) -> Results<T> { fatalError() } @available(*, unavailable, renamed:"sorted(onProperty:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed:"sorted(with:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed:"minimumValue(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed:"maximumValue(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed:"sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed:"average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } } #else /// :nodoc: /// Internal class. Do not use directly. Used for reflection and initialization public class LinkingObjectsBase: NSObject, NSFastEnumeration { internal let objectClassName: String internal let propertyName: String private var cachedRLMResults: RLMResults? @objc private var object: RLMWeakObjectHandle? @objc private var property: RLMProperty? internal var rlmResults: RLMResults { if cachedRLMResults == nil { if let object = self.object, property = self.property { cachedRLMResults = RLMDynamicGet(object.object, property)! as? RLMResults self.object = nil self.property = nil } else { cachedRLMResults = RLMResults.emptyDetachedResults() } } return cachedRLMResults! } init(fromClassName objectClassName: String, property propertyName: String) { self.objectClassName = objectClassName self.propertyName = propertyName } // MARK: Fast Enumeration public func countByEnumeratingWithState(state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int { return Int(rlmResults.countByEnumeratingWithState(state, objects: buffer, count: UInt(len))) } } /** `LinkingObjects` is an auto-updating container type. It represents a collection of objects that link to its parent object. `LinkingObjects` can be queried with the same predicates as `List<T>` and `Results<T>`. `LinkingObjects` always reflects the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the linking objects that were present when the enumeration is begun, even if some of them are deleted or modified to no longer link to the target object during the enumeration. `LinkingObjects` can only be used as a property on `Object` models. Properties of this type must be declared as `let` and cannot be `dynamic`. */ public final class LinkingObjects<T: Object>: LinkingObjectsBase { /// The element type contained in this collection. public typealias Element = T // MARK: Properties /// The Realm which manages this linking objects collection, or `nil` if the collection is unmanaged. public var realm: Realm? { return rlmResults.attached ? Realm(rlmResults.realm) : nil } /// Indicates if the linking objects collection is no longer valid. /// /// The linking objects collection becomes invalid if `invalidate` is called on the containing `realm`. /// /// An invalidated linking objects can be accessed, but will always be empty. public var invalidated: Bool { return rlmResults.invalidated } /// The number of objects in the linking objects. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers /** Creates an instance of a `LinkingObjects`. This initializer should only be called when declaring a property on a Realm model. - parameter type: The type of the object owning the property this `LinkingObjects` should refer to. - parameter propertyName: The property name of the property this `LinkingObjects` should refer to. */ public init(fromType type: T.Type, property propertyName: String) { let className = (T.self as Object.Type).className() super.init(fromClassName: className, property: propertyName) } /// Returns a description of the objects contained within the linking objects. public override var description: String { let type = "LinkingObjects<\(rlmResults.objectClassName)>" return gsub("RLMResults <0x[a-z0-9]+>", template: type, string: rlmResults.description) ?? type } // MARK: Index Retrieval /** Returns the index of an object in the linking objects collection, or `nil` if the object is not present. - parameter object: The object whose index is being queried. */ public func indexOf(object: T) -> Int? { return notFoundToNil(rlmResults.indexOfObject(object.unsafeCastToRLMObject())) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(rlmResults.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return notFoundToNil(rlmResults.indexOfObjectWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return unsafeBitCast(rlmResults[UInt(index)], T.self) } } /// Returns the first object in the linking objects collection, or `nil` if the collection is empty. public var first: T? { return unsafeBitCast(rlmResults.firstObject(), Optional<T>.self) } /// Returns the last object in the linking objects collection, or `nil` if collection is empty. public var last: T? { return unsafeBitCast(rlmResults.lastObject(), Optional<T>.self) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the linking objects collection's objects. - parameter key: The name of the property whose values are desired. */ public override func valueForKey(key: String) -> AnyObject? { return rlmResults.valueForKey(key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the linking objects collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public override func valueForKeyPath(keyPath: String) -> AnyObject? { return rlmResults.valueForKeyPath(keyPath) } /** Invokes `setValue(_:forKey:)` on each of the linking objects collection's objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The value to set the property to. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(value: AnyObject?, forKey key: String) { return rlmResults.setValue(value, forKey: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the linking objects collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> { return Results<T>(rlmResults.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns a `Results` containing all objects matching the given predicate in the linking objects collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(rlmResults.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects in the linking objects collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted("age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns a `Results` containing the objects in the linking objects collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(_:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(rlmResults.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects represented by the linking objects collection. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. - returns: The minimum value of the property, or `nil` if the collection is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return rlmResults.minOfProperty(property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the objects represented by the linking objects collection. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. - returns: The maximum value of the property, or `nil` if the collection is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return rlmResults.maxOfProperty(property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the objects represented by the linking objects collection. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. - returns: The sum of the given property. */ public func sum<U: AddableType>(property: String) -> U { return dynamicBridgeCast(fromObjectiveC: rlmResults.sumOfProperty(property)) } /** Returns the average value of a given property over all the objects represented by the linking objects collection. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. - returns: The average value of the given property, or `nil` if the collection is empty. */ public func average<U: AddableType>(property: String) -> U? { return rlmResults.averageOfProperty(property).map(dynamicBridgeCast) } // MARK: Notifications /** Registers a block to be called each time the linking objects collection changes. The block will be asynchronously called with the initial linking objects collection, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the linking objects collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial set of objects. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let dog = realm.objects(Dog.self).first! let owners = dog.owners print("owners.count: \(owners.count)") // => 0 let token = owners.addNotificationBlock { changes in switch changes { case .Initial(let owners): // Will print "owners.count: 1" print("owners.count: \(owners.count)") break case .Update: // Will not be hit in this example break case .Error: break } } try! realm.write { realm.add(Person.self, value: ["name": "Mark", dogs: [dog]]) } // end of runloop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be retained for as long as you want updates to be delivered. */ @warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock") public func addNotificationBlock(block: (RealmCollectionChange<LinkingObjects> -> Void)) -> NotificationToken { return rlmResults.addNotificationBlock { results, change, error in block(RealmCollectionChange.fromObjc(self, change: change, error: error)) } } } extension LinkingObjects: RealmCollectionType { // MARK: Sequence Support /// Returns an `RLMGenerator` that yields successive elements in the results. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to `endIndex` in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// `endIndex` is not a valid argument to subscript, and is always reachable from `startIndex` by /// zero or more applications of `successor()`. public var endIndex: Int { return count } /// :nodoc: public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(anyCollection, change: change, error: error)) } } } #endif
40.730363
125
0.679014
7523cd3a2ad9f9791c41ff31be167cd20853ef48
256
// // WWViewControllerProtocol.swift // SJPushFlowDemo // // Created by work_mac on 2017/6/16. // Copyright © 2017年 IAsk. All rights reserved. // import Foundation public protocol SJPushDataVCProtocol { func upData(pushData: NSDictionary) }
13.473684
48
0.71875
699419e96041bdfd66a44a8a099c0294138a9a0e
749
import XCTest import SuperStepper class Tests: 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. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.827586
111
0.602136
1a4bd022ee8ad372cc9e670d23afab3b7a0c8d9b
879
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "PerfectHTTPServer", platforms: [ .macOS(.v10_15) ], products: [ .library(name: "PerfectHTTPServer", targets: ["PerfectHTTPServer"]) ], dependencies: [ .package(name: "PerfectNet", url: "https://github.com/123FLO321/Perfect-Net.git", .branch("swift5")), .package(name: "PerfectHTTP", url: "https://github.com/123FLO321/Perfect-HTTP.git", .branch("swift5")), .package(name: "PerfectCZlib", url: "https://github.com/123FLO321/Perfect-CZlib-src.git", .branch("swift5")) ], targets: [ .target(name: "PerfectCHTTPParser", dependencies: []), .target(name: "PerfectHTTPServer", dependencies: ["PerfectCHTTPParser", "PerfectNet", "PerfectHTTP", "PerfectCZlib"]), .testTarget(name: "PerfectHTTPServerTests", dependencies: ["PerfectHTTPServer"]) ] )
36.625
120
0.682594
ede22e62e23ec13590858316195cf67870e5f8c0
4,597
// // AppDelegate.swift // WeatherForecast // // Created by Ishan Alone on 08/02/19. // Copyright © 2019 IA. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "WeatherForecast") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
48.904255
285
0.687405
ac9c1ff72f4524a248ced95938627547e1bd5a1f
4,898
// // QueryRulesIntegrationTests.swift // // // Created by Vladislav Fitc on 05/05/2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class QueryRulesIntegrationTests: OnlineTestCase { override var indexNameSuffix: String? { return "rules" } func testQueryRules() throws { Logger.minSeverityLevel = .warning let index = client.index(withName: "rules") let records: [JSON] = [ ["objectID": "iphone_7", "brand": "Apple", "model": "7"], ["objectID": "iphone_8", "brand": "Apple", "model": "8"], ["objectID": "iphone_x", "brand": "Apple", "model": "X"], ["objectID": "one_plus_one", "brand": "OnePlus", "model": "One"], ["objectID": "one_plus_two", "brand": "OnePlus", "model": "Two"], ] try index.saveObjects(records).wait() let settings = Settings().set(\.attributesForFaceting, to: [.default("brand"), .default("model")]) try index.setSettings(settings).wait() let brandAutomaticFacetingRule = Rule(objectID: "brand_automatic_faceting") .set(\.isEnabled, to: false) .set(\.conditions, to: [.init(anchoring: .is, pattern: .facet("brand"), alternatives: nil)]) .set(\.consequence, to: Rule.Consequence() .set(\.automaticFacetFilters, to: [.init(attribute: "brand", score: 42, isDisjunctive: true)])) .set(\.validity, to: [ .init(from: Date(timeIntervalSince1970: 1532439300), until: Date(timeIntervalSince1970: 1532525700)), .init(from: Date(timeIntervalSince1970: 1532612100), until: Date(timeIntervalSince1970: 1532698500)), ]) .set(\.description, to: "Automatic apply the faceting on `brand` if a brand value is found in the query") try index.saveRule(brandAutomaticFacetingRule).wait() let queryEditsRule = Rule(objectID: "query_edits") .set(\.conditions, to: [.init(anchoring: .is, pattern: .literal("mobile phone"), alternatives: .true)]) .set(\.consequence, to: Rule.Consequence() .set(\.filterPromotes, to: false) .set(\.queryTextAlteration, to: .edits([ .remove("mobile"), .replace("phone", with: "iphone")]))) let queryPromoRule = Rule(objectID: "query_promo") .set(\.consequence, to: Rule.Consequence() .set(\.query, to: Query.empty.set(\.filters, to: "brand:OnePlus"))) let queryPromoSummerRule = Rule(objectID: "query_promo_summer") .set(\.conditions, to: [Rule.Condition().set(\.context, to: "summer")]) .set(\.consequence, to: Rule.Consequence() .set(\.query, to: Query.empty.set(\.filters, to: "brand:OnePlus"))) let rules = [ queryEditsRule, queryPromoRule, queryPromoSummerRule, ] try index.saveRules(rules).wait() let response = try index.searchRules(RuleQuery().set(\.context, to: "summer")) //TODO: understand why search for rules doesn't work after multi-condition introduction //XCTAssertEqual(response.nbHits, 1) let fetchedBrandAutomaticFacetingRule = try index.getRule(withID: brandAutomaticFacetingRule.objectID) try AssertEquallyEncoded(fetchedBrandAutomaticFacetingRule, brandAutomaticFacetingRule) let fetchedQueryEditsRule = try index.getRule(withID: queryEditsRule.objectID) try AssertEquallyEncoded(fetchedQueryEditsRule, queryEditsRule) let fetchedQueryPromoRule = try index.getRule(withID: queryPromoRule.objectID) try AssertEquallyEncoded(fetchedQueryPromoRule, queryPromoRule) let fetchedQueryPromoSummerRule = try index.getRule(withID: queryPromoSummerRule.objectID) try AssertEquallyEncoded(fetchedQueryPromoSummerRule, queryPromoSummerRule) let fetchedRules = try index.searchRules("").hits.map(\.rule) XCTAssertEqual(fetchedRules.count, 4) try AssertEquallyEncoded(fetchedRules.first(where: { $0.objectID == brandAutomaticFacetingRule.objectID}), brandAutomaticFacetingRule) try AssertEquallyEncoded(fetchedRules.first(where: { $0.objectID == queryEditsRule.objectID}), queryEditsRule) try AssertEquallyEncoded(fetchedRules.first(where: { $0.objectID == queryPromoRule.objectID}), queryPromoRule) try AssertEquallyEncoded(fetchedRules.first(where: { $0.objectID == queryPromoSummerRule.objectID}), queryPromoSummerRule) try index.deleteRule(withID: brandAutomaticFacetingRule.objectID).wait() try AssertThrowsHTTPError(index.getRule(withID: brandAutomaticFacetingRule.objectID), statusCode: 404) try index.clearRules().wait() try AssertThrowsHTTPError(index.getRule(withID: queryEditsRule.objectID), statusCode: 404) try AssertThrowsHTTPError(index.getRule(withID: queryPromoRule.objectID), statusCode: 404) try AssertThrowsHTTPError(index.getRule(withID: queryPromoSummerRule.objectID), statusCode: 404) XCTAssertEqual(try index.searchRules("").nbHits, 0) } }
43.732143
139
0.697836
3a08993e6ae35ae5c53524fe52e68590ee07ef64
42,226
/* See LICENSE folder for this sample’s licensing information. Abstract: Main view controller for the AR experience. */ import ARKit import Foundation import AVFoundation import SceneKit import UIKit import Photos import AudioKit class ViewController: UIViewController, ARSCNViewDelegate, UIPopoverPresentationControllerDelegate, VirtualObjectSelectionViewControllerDelegate { // MARK: - Main Setup & View Controller methods override func viewDidLoad() { super.viewDidLoad() Setting.registerDefaults() setupScene() setupDebug() setupUIControls() setupFocusSquare() setupTable() updateSettings() resetVirtualObject() //setupTapInsertPyramid() TapInsertDomino() setupRecognizers()//should include all gestures // set Recording button long press let longPress = UILongPressGestureRecognizer( target: self, action: #selector(ViewController.ScreenLongPress(recognizer:)) ) self.view.addGestureRecognizer(longPress) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Prevent the screen from being dimmed after a while. UIApplication.shared.isIdleTimerDisabled = true // Start the ARSession. restartPlaneDetection() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) session.pause() } // MARK: - ARKit / ARSCNView let session = ARSession() var sessionConfig: ARSessionConfiguration = ARWorldTrackingSessionConfiguration() var use3DOFTracking = false { didSet { if use3DOFTracking { sessionConfig = ARSessionConfiguration() } sessionConfig.isLightEstimationEnabled = UserDefaults.standard.bool(for: .ambientLightEstimation) session.run(sessionConfig) } } var use3DOFTrackingFallback = false @IBOutlet var sceneView: ARSCNView! var screenCenter: CGPoint? func setupScene() { // set up sceneView sceneView.delegate = self sceneView.session = session sceneView.antialiasingMode = .multisampling4X sceneView.automaticallyUpdatesLighting = false sceneView.preferredFramesPerSecond = 60 sceneView.contentScaleFactor = 1.3 //sceneView.scene.physicsWorld.contactDelegate = (self as! SCNPhysicsContactDelegate) enableEnvironmentMapWithIntensity(25.0) DispatchQueue.main.async { self.screenCenter = self.sceneView.bounds.mid } if let camera = sceneView.pointOfView?.camera { camera.wantsHDR = true camera.wantsExposureAdaptation = true camera.exposureOffset = -1 camera.minimumExposure = -1 } } func enableEnvironmentMapWithIntensity(_ intensity: CGFloat) { if sceneView.scene.lightingEnvironment.contents == nil { if let environmentMap = UIImage(named: "Models.scnassets/sharedImages/environment_blur.exr") { sceneView.scene.lightingEnvironment.contents = environmentMap } } sceneView.scene.lightingEnvironment.intensity = intensity } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { refreshFeaturePoints() DispatchQueue.main.async { self.updateFocusSquare() self.hitTestVisualization?.render() // If light estimation is enabled, update the intensity of the model's lights and the environment map if let lightEstimate = self.session.currentFrame?.lightEstimate { self.enableEnvironmentMapWithIntensity(lightEstimate.ambientIntensity / 40) } else { self.enableEnvironmentMapWithIntensity(25) } } } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { self.addPlane(node: node, anchor: planeAnchor) self.checkIfObjectShouldMoveOntoPlane(anchor: planeAnchor) self.lastPlaneNode = node self.lastPlaneAnchor = planeAnchor if self.showLoadModel{ let subScene = SCNScene(named: "Models.scnassets/test/cube.dae")! let childNodes = subScene.rootNode.childNodes for child in childNodes { child.scale = SCNVector3Make(0.01, 0.01, 0.01); child.position = SCNVector3Make(planeAnchor.center.x, 0, planeAnchor.center.z) node.addChildNode(child) } } } } } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { self.updatePlane(anchor: planeAnchor) self.checkIfObjectShouldMoveOntoPlane(anchor: planeAnchor) } } } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if let planeAnchor = anchor as? ARPlaneAnchor { self.removePlane(anchor: planeAnchor) } } } var trackingFallbackTimer: Timer? func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) { textManager.showTrackingQualityInfo(for: camera.trackingState, autoHide: !self.showDebugVisuals) switch camera.trackingState { case .notAvailable: textManager.escalateFeedback(for: camera.trackingState, inSeconds: 5.0) case .limited: if use3DOFTrackingFallback { // After 10 seconds of limited quality, fall back to 3DOF mode. trackingFallbackTimer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false, block: { _ in self.use3DOFTracking = true self.trackingFallbackTimer?.invalidate() self.trackingFallbackTimer = nil }) } else { textManager.escalateFeedback(for: camera.trackingState, inSeconds: 10.0) } case .normal: textManager.cancelScheduledMessage(forType: .trackingStateEscalation) if use3DOFTrackingFallback && trackingFallbackTimer != nil { trackingFallbackTimer!.invalidate() trackingFallbackTimer = nil } } } func session(_ session: ARSession, didFailWithError error: Error) { guard let arError = error as? ARError else { return } let nsError = error as NSError var sessionErrorMsg = "\(nsError.localizedDescription) \(nsError.localizedFailureReason ?? "")" if let recoveryOptions = nsError.localizedRecoveryOptions { for option in recoveryOptions { sessionErrorMsg.append("\(option).") } } let isRecoverable = (arError.code == .worldTrackingFailed) if isRecoverable { sessionErrorMsg += "\nYou can try resetting the session or quit the application." } else { sessionErrorMsg += "\nThis is an unrecoverable error that requires to quit the application." } displayErrorMessage(title: "We're sorry!", message: sessionErrorMsg, allowRestart: isRecoverable) } func sessionWasInterrupted(_ session: ARSession) { textManager.blurBackground() textManager.showAlert(title: "Session Interrupted", message: "The session will be reset after the interruption has ended.") } func sessionInterruptionEnded(_ session: ARSession) { textManager.unblurBackground() session.run(sessionConfig, options: [.resetTracking, .removeExistingAnchors]) restartExperience(self) textManager.showMessage("RESETTING SESSION") } // MARK: - Ambient Light Estimation func toggleAmbientLightEstimation(_ enabled: Bool) { if enabled { if !sessionConfig.isLightEstimationEnabled { // turn on light estimation sessionConfig.isLightEstimationEnabled = true session.run(sessionConfig) } } else { if sessionConfig.isLightEstimationEnabled { // turn off light estimation sessionConfig.isLightEstimationEnabled = false session.run(sessionConfig) } } } // MARK: - Gesture Recognizers var currentGesture: Gesture? override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let object = virtualObject else { return } if currentGesture == nil { currentGesture = Gesture.startGestureFromTouches(touches, self.sceneView, object) } else { currentGesture = currentGesture!.updateGestureFromTouches(touches, .touchBegan) } displayVirtualObjectTransform() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if virtualObject == nil { return } currentGesture = currentGesture?.updateGestureFromTouches(touches, .touchMoved) displayVirtualObjectTransform() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if virtualObject == nil { chooseObject(addObjectButton) return } currentGesture = currentGesture?.updateGestureFromTouches(touches, .touchEnded) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { if virtualObject == nil { return } currentGesture = currentGesture?.updateGestureFromTouches(touches, .touchCancelled) } // MARK: - Virtual Object Manipulation func displayVirtualObjectTransform() { guard let object = virtualObject, let cameraTransform = session.currentFrame?.camera.transform else { return } // Output the current translation, rotation & scale of the virtual object as text. let cameraPos = SCNVector3.positionFromTransform(cameraTransform) let vectorToCamera = cameraPos - object.position let distanceToUser = vectorToCamera.length() var angleDegrees = Int(((object.eulerAngles.y) * 180) / Float.pi) % 360 if angleDegrees < 0 { angleDegrees += 360 } let distance = String(format: "%.2f", distanceToUser) let scale = String(format: "%.2f", object.scale.x) textManager.showDebugMessage("Distance: \(distance) m\nRotation: \(angleDegrees)°\nScale: \(scale)x") } func moveVirtualObjectToPosition(_ pos: SCNVector3?, _ instantly: Bool, _ filterPosition: Bool) { guard let newPosition = pos else { textManager.showMessage("CANNOT PLACE OBJECT\nTry moving left or right.") // Reset the content selection in the menu only if the content has not yet been initially placed. if virtualObject == nil { resetVirtualObject() } return } if instantly { setNewVirtualObjectPosition(newPosition) } else { updateVirtualObjectPosition(newPosition, filterPosition) } } var dragOnInfinitePlanesEnabled = false func worldPositionFromScreenPosition(_ position: CGPoint, objectPos: SCNVector3?, infinitePlane: Bool = false) -> (position: SCNVector3?, planeAnchor: ARPlaneAnchor?, hitAPlane: Bool) { // ------------------------------------------------------------------------------- // 1. Always do a hit test against exisiting plane anchors first. // (If any such anchors exist & only within their extents.) let planeHitTestResults = sceneView.hitTest(position, types: .existingPlaneUsingExtent) if let result = planeHitTestResults.first { let planeHitTestPosition = SCNVector3.positionFromTransform(result.worldTransform) let planeAnchor = result.anchor // Return immediately - this is the best possible outcome. return (planeHitTestPosition, planeAnchor as? ARPlaneAnchor, true) } // ------------------------------------------------------------------------------- // 2. Collect more information about the environment by hit testing against // the feature point cloud, but do not return the result yet. var featureHitTestPosition: SCNVector3? var highQualityFeatureHitTestResult = false let highQualityfeatureHitTestResults = sceneView.hitTestWithFeatures(position, coneOpeningAngleInDegrees: 18, minDistance: 0.2, maxDistance: 2.0) if !highQualityfeatureHitTestResults.isEmpty { let result = highQualityfeatureHitTestResults[0] featureHitTestPosition = result.position highQualityFeatureHitTestResult = true } // ------------------------------------------------------------------------------- // 3. If desired or necessary (no good feature hit test result): Hit test // against an infinite, horizontal plane (ignoring the real world). if (infinitePlane && dragOnInfinitePlanesEnabled) || !highQualityFeatureHitTestResult { let pointOnPlane = objectPos ?? SCNVector3Zero let pointOnInfinitePlane = sceneView.hitTestWithInfiniteHorizontalPlane(position, pointOnPlane) if pointOnInfinitePlane != nil { return (pointOnInfinitePlane, nil, true) } } // ------------------------------------------------------------------------------- // 4. If available, return the result of the hit test against high quality // features if the hit tests against infinite planes were skipped or no // infinite plane was hit. if highQualityFeatureHitTestResult { return (featureHitTestPosition, nil, false) } // ------------------------------------------------------------------------------- // 5. As a last resort, perform a second, unfiltered hit test against features. // If there are no features in the scene, the result returned here will be nil. let unfilteredFeatureHitTestResults = sceneView.hitTestWithFeatures(position) if !unfilteredFeatureHitTestResults.isEmpty { let result = unfilteredFeatureHitTestResults[0] return (result.position, nil, false) } return (nil, nil, false) } // Use average of recent virtual object distances to avoid rapid changes in object scale. var recentVirtualObjectDistances = [CGFloat]() func setNewVirtualObjectPosition(_ pos: SCNVector3) { guard let object = virtualObject, let cameraTransform = session.currentFrame?.camera.transform else { return } recentVirtualObjectDistances.removeAll() let cameraWorldPos = SCNVector3.positionFromTransform(cameraTransform) var cameraToPosition = pos - cameraWorldPos // Limit the distance of the object from the camera to a maximum of 10 meters. cameraToPosition.setMaximumLength(10) object.position = cameraWorldPos + cameraToPosition if object.parent == nil { sceneView.scene.rootNode.addChildNode(object) } } func resetVirtualObject() { virtualObject?.unloadModel() virtualObject?.removeFromParentNode() virtualObject = nil addObjectButton.setImage(#imageLiteral(resourceName: "add"), for: []) addObjectButton.setImage(#imageLiteral(resourceName: "addPressed"), for: [.highlighted]) // Reset selected object id for row highlighting in object selection view controller. UserDefaults.standard.set(-1, for: .selectedObjectID) } func updateVirtualObjectPosition(_ pos: SCNVector3, _ filterPosition: Bool) { guard let object = virtualObject else { return } guard let cameraTransform = session.currentFrame?.camera.transform else { return } let cameraWorldPos = SCNVector3.positionFromTransform(cameraTransform) var cameraToPosition = pos - cameraWorldPos // Limit the distance of the object from the camera to a maximum of 10 meters. cameraToPosition.setMaximumLength(10) // Compute the average distance of the object from the camera over the last ten // updates. If filterPosition is true, compute a new position for the object // with this average. Notice that the distance is applied to the vector from // the camera to the content, so it only affects the percieved distance of the // object - the averaging does _not_ make the content "lag". let hitTestResultDistance = CGFloat(cameraToPosition.length()) recentVirtualObjectDistances.append(hitTestResultDistance) recentVirtualObjectDistances.keepLast(10) if filterPosition { let averageDistance = recentVirtualObjectDistances.average! cameraToPosition.setLength(Float(averageDistance)) let averagedDistancePos = cameraWorldPos + cameraToPosition object.position = averagedDistancePos } else { object.position = cameraWorldPos + cameraToPosition } } func checkIfObjectShouldMoveOntoPlane(anchor: ARPlaneAnchor) { guard let object = virtualObject, let planeAnchorNode = sceneView.node(for: anchor) else { return } // Get the object's position in the plane's coordinate system. let objectPos = planeAnchorNode.convertPosition(object.position, from: object.parent) if objectPos.y == 0 { return; // The object is already on the plane - nothing to do here. } // Add 10% tolerance to the corners of the plane. let tolerance: Float = 0.1 let minX: Float = anchor.center.x - anchor.extent.x / 2 - anchor.extent.x * tolerance let maxX: Float = anchor.center.x + anchor.extent.x / 2 + anchor.extent.x * tolerance let minZ: Float = anchor.center.z - anchor.extent.z / 2 - anchor.extent.z * tolerance let maxZ: Float = anchor.center.z + anchor.extent.z / 2 + anchor.extent.z * tolerance if objectPos.x < minX || objectPos.x > maxX || objectPos.z < minZ || objectPos.z > maxZ { return } // Drop the object onto the plane if it is near it. let verticalAllowance: Float = 0.03 if objectPos.y > -verticalAllowance && objectPos.y < verticalAllowance { textManager.showDebugMessage("OBJECT MOVED\nSurface detected nearby") SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) object.position.y = anchor.transform.columns.3.y SCNTransaction.commit() } } // MARK: - Virtual Object Loading var virtualObject: VirtualObject? var isLoadingObject: Bool = false { didSet { DispatchQueue.main.async { self.settingsButton.isEnabled = !self.isLoadingObject self.addObjectButton.isEnabled = !self.isLoadingObject self.screenshotButton.isEnabled = !self.isLoadingObject self.restartExperienceButton.isEnabled = !self.isLoadingObject } } } @IBOutlet weak var addObjectButton: UIButton! func loadVirtualObject(at index: Int) { //resetVirtualObject() // Show progress indicator let spinner = UIActivityIndicatorView() spinner.center = addObjectButton.center spinner.bounds.size = CGSize(width: addObjectButton.bounds.width - 5, height: addObjectButton.bounds.height - 5) addObjectButton.setImage(#imageLiteral(resourceName: "buttonring"), for: []) sceneView.addSubview(spinner) spinner.startAnimating() // Load the content asynchronously. DispatchQueue.global().async { self.isLoadingObject = true let object = VirtualObject.availableObjects[index] object.viewController = self self.virtualObject = object object.loadModel() DispatchQueue.main.async { // Immediately place the object in 3D space. if let lastFocusSquarePos = self.focusSquare?.lastPosition { self.setNewVirtualObjectPosition(lastFocusSquarePos) } else { self.setNewVirtualObjectPosition(SCNVector3Zero) } // Remove progress indicator spinner.removeFromSuperview() // Update the icon of the add object button let buttonImage = UIImage.composeButtonImage(from: object.thumbImage) let pressedButtonImage = UIImage.composeButtonImage(from: object.thumbImage, alpha: 0.3) self.addObjectButton.setImage(buttonImage, for: []) self.addObjectButton.setImage(pressedButtonImage, for: [.highlighted]) self.isLoadingObject = false } } } @IBAction func chooseObject(_ button: UIButton) { // Abort if we are about to load another object to avoid concurrent modifications of the scene. if isLoadingObject { return } textManager.cancelScheduledMessage(forType: .contentPlacement) let rowHeight = 45 let popoverSize = CGSize(width: 250, height: rowHeight * VirtualObject.availableObjects.count) let objectViewController = VirtualObjectSelectionViewController(size: popoverSize) objectViewController.delegate = self objectViewController.modalPresentationStyle = .popover objectViewController.popoverPresentationController?.delegate = self self.present(objectViewController, animated: true, completion: nil) objectViewController.popoverPresentationController?.sourceView = button objectViewController.popoverPresentationController?.sourceRect = button.bounds } // MARK: - VirtualObjectSelectionViewControllerDelegate func virtualObjectSelectionViewController(_: VirtualObjectSelectionViewController, didSelectObjectAt index: Int) { loadVirtualObject(at: index) } func virtualObjectSelectionViewControllerDidDeselectObject(_: VirtualObjectSelectionViewController) { } // MARK: - Planes var planes = [ARPlaneAnchor: Plane]() func addPlane(node: SCNNode, anchor: ARPlaneAnchor) { let pos = SCNVector3.positionFromTransform(anchor.transform) textManager.showDebugMessage("NEW SURFACE DETECTED AT \(pos.friendlyString())") let plane = Plane.init(anchor: anchor, isHidden: showDebugVisuals, with: Plane.currentMaterial() ) planes[anchor] = plane node.addChildNode(plane!) textManager.cancelScheduledMessage(forType: .planeEstimation) textManager.showMessage("SURFACE DETECTED") if virtualObject == nil { textManager.scheduleMessage("TAP + TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .contentPlacement) } } func updatePlane(anchor: ARPlaneAnchor) { if let plane = planes[anchor] { plane.update(anchor) } } func removePlane(anchor: ARPlaneAnchor) { if let plane = planes.removeValue(forKey: anchor) { plane.removeFromParentNode() } } func restartPlaneDetection() { // configure session if let worldSessionConfig = sessionConfig as? ARWorldTrackingSessionConfiguration { worldSessionConfig.planeDetection = .horizontal session.run(worldSessionConfig, options: [.resetTracking, .removeExistingAnchors]) } // reset timer if trackingFallbackTimer != nil { trackingFallbackTimer!.invalidate() trackingFallbackTimer = nil } textManager.scheduleMessage("FIND A SURFACE TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .planeEstimation) } // MARK: - Focus Square var focusSquare: FocusSquare? func setupFocusSquare() { focusSquare?.isHidden = true focusSquare?.removeFromParentNode() focusSquare = FocusSquare() sceneView.scene.rootNode.addChildNode(focusSquare!) textManager.scheduleMessage("TRY MOVING LEFT OR RIGHT", inSeconds: 5.0, messageType: .focusSquare) } func updateFocusSquare() { guard let screenCenter = screenCenter else { return } if virtualObject != nil && sceneView.isNode(virtualObject!, insideFrustumOf: sceneView.pointOfView!) { focusSquare?.hide() } else { focusSquare?.unhide() } let (worldPos, planeAnchor, _) = worldPositionFromScreenPosition(screenCenter, objectPos: focusSquare?.position) if let worldPos = worldPos { focusSquare?.update(for: worldPos, planeAnchor: planeAnchor, camera: self.session.currentFrame?.camera) textManager.cancelScheduledMessage(forType: .focusSquare) } } // MARK: - Hit Test Visualization var hitTestVisualization: HitTestVisualization? var showHitTestAPIVisualization = UserDefaults.standard.bool(for: .showHitTestAPI) { didSet { UserDefaults.standard.set(showHitTestAPIVisualization, for: .showHitTestAPI) if showHitTestAPIVisualization { hitTestVisualization = HitTestVisualization(sceneView: sceneView) } else { hitTestVisualization = nil } } } // MARK: - Debug Visualizations @IBOutlet var featurePointCountLabel: UILabel! func refreshFeaturePoints() { guard showDebugVisuals else { return } // retrieve cloud guard let cloud = session.currentFrame?.rawFeaturePoints else { return } DispatchQueue.main.async { self.featurePointCountLabel.text = "Features: \(cloud.count)".uppercased() } } var showDebugVisuals: Bool = UserDefaults.standard.bool(for: .debugMode) { didSet { featurePointCountLabel.isHidden = !showDebugVisuals debugMessageLabel.isHidden = !showDebugVisuals messagePanel.isHidden = !showDebugVisuals //planes.values.forEach { $0.showDebugVisualization(showDebugVisuals) } if showDebugVisuals { sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints, ARSCNDebugOptions.showWorldOrigin] } else { sceneView.debugOptions = [] } // save pref UserDefaults.standard.set(showDebugVisuals, for: .debugMode) } } func setupDebug() { // Set appearance of debug output panel messagePanel.layer.cornerRadius = 3.0 messagePanel.clipsToBounds = true } // MARK: - UI Elements and Actions @IBOutlet weak var messagePanel: UIView! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var debugMessageLabel: UILabel! var textManager: TextManager! func setupUIControls() { textManager = TextManager(viewController: self) // hide debug message view debugMessageLabel.isHidden = true featurePointCountLabel.text = "" debugMessageLabel.text = "" messageLabel.text = "" } @IBOutlet weak var restartExperienceButton: UIButton! var restartExperienceButtonIsEnabled = true @IBAction func restartExperience(_ sender: Any) { guard restartExperienceButtonIsEnabled, !isLoadingObject else { return } DispatchQueue.main.async { self.restartExperienceButtonIsEnabled = false self.textManager.cancelAllScheduledMessages() self.textManager.dismissPresentedAlert() self.textManager.showMessage("STARTING A NEW SESSION") self.use3DOFTracking = false self.setupFocusSquare() self.resetVirtualObject() self.restartPlaneDetection() self.restartExperienceButton.setImage(#imageLiteral(resourceName: "restart"), for: []) self.MusicTreeNode.stop() // Disable Restart button for five seconds in order to give the session enough time to restart. DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: { self.restartExperienceButtonIsEnabled = true }) } } @IBOutlet weak var screenshotButton: UIButton! @IBAction func takeScreenshot() { guard screenshotButton.isEnabled else { return } let takeScreenshotBlock = { UIImageWriteToSavedPhotosAlbum(self.sceneView.snapshot(), nil, nil, nil) DispatchQueue.main.async { // Briefly flash the screen. let flashOverlay = UIView(frame: self.sceneView.frame) flashOverlay.backgroundColor = UIColor.white self.sceneView.addSubview(flashOverlay) UIView.animate(withDuration: 0.25, animations: { flashOverlay.alpha = 0.0 }, completion: { _ in flashOverlay.removeFromSuperview() }) } } switch PHPhotoLibrary.authorizationStatus() { case .authorized: takeScreenshotBlock() case .restricted, .denied: let title = "Photos access denied" let message = "Please enable Photos access for this application in Settings > Privacy to allow saving screenshots." textManager.showAlert(title: title, message: message) case .notDetermined: PHPhotoLibrary.requestAuthorization({ (authorizationStatus) in if authorizationStatus == .authorized { takeScreenshotBlock() } }) } } // MARK: - Recording @IBOutlet weak var CameraHitArea: UIButton! var recordTimer:Timer! var recordImageList: [UIImage] = [] var isRecordStart: Bool = false; func ScreenLongPress(recognizer:UILongPressGestureRecognizer) { print(recognizer) let p = recognizer.location(in: self.sceneView) let view = self.sceneView.frame if recognizer.state == .began && p.x < 64 && p.y > view.height-64{ startRecording() } } func startRecording() { let takeReaordingBlock = { UIImageWriteToSavedPhotosAlbum(self.sceneView.snapshot(), nil, nil, nil) } switch PHPhotoLibrary.authorizationStatus() { case .authorized: if isRecordStart{ recordTimer.invalidate() imageListToVideo() isRecordStart = false self.screenshotButton.setImage(#imageLiteral(resourceName: "shutter"), for: []) } else{ recordTimer = Timer.scheduledTimer(timeInterval: 0.05,target:self,selector:#selector(ViewController.addUIimageIntoList),userInfo:nil,repeats:true) isRecordStart = true self.screenshotButton.setImage(#imageLiteral(resourceName: "shutterRecord"), for: []) } takeReaordingBlock() case .restricted, .denied: let title = "Photos access denied" let message = "Please enable Photos access for this application in Settings > Privacy to allow saving screenshots." textManager.showAlert(title: title, message: message) case .notDetermined: PHPhotoLibrary.requestAuthorization({ (authorizationStatus) in if authorizationStatus == .authorized { takeReaordingBlock() } }) } } func addUIimageIntoList(){ var img: UIImage = self.sceneView.snapshot() img = resizeImage(image: img,newWidth: 720)! recordImageList.append(img) } func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight)) image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } func imageListToVideo(){ let settings = RenderSettings() let imageAnimator = ImageAnimator(renderSettings: settings, recordImageList: recordImageList) imageAnimator.render() { let alertView = UIAlertController(title: "螢幕錄影", message: "已成功輸出AR影像到\"照片\"", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: { (alert) in }) alertView.addAction(action) self.present(alertView, animated: true, completion: nil) } } // MARK: - Fantacy @IBOutlet weak var FantacyButton: UIButton! @IBOutlet weak var FantacyView: UIStackView! func setupTable(){ FantacyView.layer.masksToBounds = true FantacyView.layer.cornerRadius = 30 FantacyView.subviews.forEach{ fantacyButton in fantacyButton.layer.addBorder(edge: UIRectEdge.bottom, color: UIColor.black, thickness: 0.5) } } @IBAction func showFantacy(_ button: UIButton) { FantacyView.isHidden = !FantacyView.isHidden; } // MARK: - Settings @IBOutlet weak var settingsButton: UIButton! @IBAction func showSettings(_ button: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: nil) guard let settingsViewController = storyboard.instantiateViewController(withIdentifier: "settingsViewController") as? SettingsViewController else { return } let barButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSettings)) settingsViewController.navigationItem.rightBarButtonItem = barButtonItem settingsViewController.title = "Options" let navigationController = UINavigationController(rootViewController: settingsViewController) navigationController.modalPresentationStyle = .popover navigationController.popoverPresentationController?.delegate = self navigationController.preferredContentSize = CGSize(width: sceneView.bounds.size.width - 20, height: sceneView.bounds.size.height - 50) self.present(navigationController, animated: true, completion: nil) navigationController.popoverPresentationController?.sourceView = settingsButton navigationController.popoverPresentationController?.sourceRect = settingsButton.bounds } @objc func dismissSettings() { self.dismiss(animated: true, completion: nil) updateSettings() } private func updateSettings() { let defaults = UserDefaults.standard showDebugVisuals = defaults.bool(for: .debugMode) toggleAmbientLightEstimation(defaults.bool(for: .ambientLightEstimation)) dragOnInfinitePlanesEnabled = defaults.bool(for: .dragOnInfinitePlanes) showHitTestAPIVisualization = defaults.bool(for: .showHitTestAPI) use3DOFTracking = defaults.bool(for: .use3DOFTracking) use3DOFTrackingFallback = defaults.bool(for: .use3DOFFallback) for (_, plane) in planes { // plane.updateOcclusionSetting() } } // MARK: - Error handling func displayErrorMessage(title: String, message: String, allowRestart: Bool = false) { // Blur the background. textManager.blurBackground() if allowRestart { // Present an alert informing about the error that has occurred. let restartAction = UIAlertAction(title: "Reset", style: .default) { _ in self.textManager.unblurBackground() self.restartExperience(self) } textManager.showAlert(title: title, message: message, actions: [restartAction]) } else { textManager.showAlert(title: title, message: message, actions: []) } } // MARK: - UIPopoverPresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { updateSettings() } // --------------Balloon Shooting-------------- @IBOutlet weak var BalloonShootingBtn: UIButton! @IBAction func clickBalloonShootingBtn(_ sender: Any) { FantacyView.isHidden = true self.addNewBalloon() } @IBAction func didTapScreen(_ sender: Any) { // fire bullet let bulletsNode = Bullet() let (direction, position) = self.getUserVector() bulletsNode.position = position // SceneKit/AR coordinates are in meters bulletsNode.physicsBody?.applyForce(direction, asImpulse: true) sceneView.scene.rootNode.addChildNode(bulletsNode) } func getUserVector() -> (SCNVector3, SCNVector3) { // (direction, position) if let frame = self.sceneView.session.currentFrame { let mat = SCNMatrix4FromMat4(frame.camera.transform) // 4x4 transform matrix describing camera in world space let dir = SCNVector3(-1 * mat.m31, -1 * mat.m32, -1 * mat.m33) // orientation of camera in world space let pos = SCNVector3(mat.m41, mat.m42, mat.m43) // location of camera in world space return (dir, pos) } return (SCNVector3(0, 0, -1), SCNVector3(0, 0, -0.2)) } func addNewBalloon() { let cubeNode = Balloon() let posX = floatBetween(-0.5, and: 0.5) let posY = floatBetween(-0.5, and: 0.5 ) cubeNode.position = SCNVector3(posX, posY, -1) // SceneKit/AR coordinates are in meters if let lastPlane = lastPlaneNode{ lastPlane.addChildNode(cubeNode) } else{ self.sceneView.scene.rootNode.addChildNode(cubeNode) } } func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) { //爆炸寫在這裡 contact.nodeA.removeFromParentNode() contact.nodeB.removeFromParentNode() print("Hit Balloon!") } func floatBetween(_ first: Float, and second: Float) -> Float { return (Float(arc4random()) / Float(UInt32.max)) * (first - second) + second } // -------------- Load Model -------------- var showLoadModel: Bool = false @IBOutlet weak var CubeButton: UIButton! @IBAction func clickCubeButton(_ sender: Any) { guard CubeButton.isEnabled else { return } if showLoadModel{ CubeButton.backgroundColor = UIColor.lightText showLoadModel = false } else{ CubeButton.backgroundColor = UIColor.blue showLoadModel = true } } // -------------- Music Tree -------------- var showMusicTree: Bool = false var MusicTreeNode: MusicTree = MusicTree() var lastPlaneNode: SCNNode? var lastPlaneAnchor: ARPlaneAnchor? @IBOutlet weak var musicTreeButton: UIButton! @IBAction func clickMusicTreeButton(_ sender: Any) { FantacyView.isHidden = true guard musicTreeButton.isEnabled else { return } DispatchQueue.main.async { // Immediately place the object in 3D space. if let anchor = self.lastPlaneAnchor, let node = self.lastPlaneNode { self.MusicTreeNode.position = SCNVector3Make(anchor.center.x, 0, anchor.center.z) node.addChildNode(self.MusicTreeNode) } else{ self.MusicTreeNode.position = SCNVector3Make(-0.2,-0.4,-0.5) self.sceneView.scene.rootNode.addChildNode(self.MusicTreeNode) } } //currentPlane.addChildNode(self.MusicTreeNode) if showMusicTree { self.MusicTreeNode.stop() showMusicTree = false } else{ self.MusicTreeNode.play() showMusicTree = true } } func longPressMusictreePlane(recognizer:UILongPressGestureRecognizer) { print("LongPress Plane") } // -------------- Pyramid Dropping -------------- var pyramids = [Pyramid]() func insertPyramid( hitResult :ARHitTestResult ){ let insertionYOffset:Float = 0.3; // the height of pyramid input let position : SCNVector3 = SCNVector3Make( hitResult.worldTransform.columns.3.x , hitResult.worldTransform.columns.3.y + insertionYOffset, hitResult.worldTransform.columns.3.z ) let pyramid = Pyramid.init(atPosition: position, with: Pyramid.currentMaterial()) pyramids.append( pyramid!) //record pyramids self.sceneView.scene.rootNode.addChildNode(pyramid!) } func InsertPyramidFrom(_ recognizer: UITapGestureRecognizer) { print("Tap Screen!") let tapPoint:CGPoint = recognizer.location(in: recognizer.view) let result = self.sceneView.hitTest(tapPoint, types:.existingPlaneUsingExtent) if result.count == 0{//the point has no planes return } let first :ARHitTestResult = result.first! self.insertPyramid(hitResult: first) } func setupTapInsertPyramid(){ let finger = UITapGestureRecognizer(target:self,action: #selector(self.InsertPyramidFrom(_:) )) finger.numberOfTapsRequired = 1 self.sceneView.addGestureRecognizer(finger) } //remove if the pyramid on the bottom // -------------- Domino -------------- var dominos = [Domino]() func insertDomino( hitResult :ARHitTestResult ){ let insertionYOffset:Float = 0; let position : SCNVector3 = SCNVector3Make( hitResult.worldTransform.columns.3.x , hitResult.worldTransform.columns.3.y + insertionYOffset, hitResult.worldTransform.columns.3.z ) let domino = Domino.init(atPosition: position, with: Domino.currentMaterial()) dominos.append( domino!) //record dominos self.sceneView.scene.rootNode.addChildNode(domino!) } func InsertDominoFrom(_ recognizer: UITapGestureRecognizer) { let tapPoint:CGPoint = recognizer.location(in: recognizer.view) let result = self.sceneView.hitTest(tapPoint, types:.existingPlaneUsingExtent) if result.count == 0{//the point has no planes return } let first :ARHitTestResult = result.first! self.insertDomino(hitResult: first) } func TapInsertDomino(){ let finger = UITapGestureRecognizer(target:self,action: #selector(self.InsertDominoFrom(_:) )) finger.numberOfTapsRequired = 1 self.sceneView.addGestureRecognizer(finger) } //a force to push domino func PushDomino(_ recognizer: UILongPressGestureRecognizer ){ let tapPoint:CGPoint = recognizer.location(in: recognizer.view) let result = self.sceneView.hitTest(tapPoint, options: nil)//find which domino for thing in result { let type:SCNNode = thing.node.parent! if( type.isMember(of: Domino.self) ) { let (direction, _) = self.getUserVector() thing.node.physicsBody?.applyForce(direction*2, asImpulse: true) return } } } //////////////////////////// //////Gesture////// func setupRecognizers(){ let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.PushDomino(_:))) lpgr.minimumPressDuration = 0.5 lpgr.delaysTouchesBegan = true self.view.addGestureRecognizer(lpgr) } } struct CollisionCategory: OptionSet { let rawValue: Int static let bullets = CollisionCategory(rawValue: 1 << 0) // 00...01 static let balloon = CollisionCategory(rawValue: 1 << 1) // 00..10 }
34.274351
162
0.67726
38420a38d6acbe640ffc7b7008f9a000338e2949
709
// // STADetailWordTableViewCell.swift // SkyEngTestApp // // Created by Вячеслав on 02/03/2020. // Copyright © 2020 PaRaDoX. All rights reserved. // import UIKit class STADetailWordTableViewCell: UITableViewCell { @IBOutlet var translateLabel: UILabel! @IBOutlet var noteLabel: UILabel! @IBOutlet var meaningImageView: UIImageView! @IBOutlet var loadActivityIndicator: UIActivityIndicatorView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
24.448276
65
0.703808
714f8c08d034e019fae75ad830f788ee10155a9b
5,165
// // ViewController.swift // AutolayoutAndPurelayout // // Created by dragonetail on 2018/12/11. // Copyright © 2018 dragonetail. All rights reserved. // import UIKit import PureLayout struct ExampleSection { var header: String? var footer: String? var examples: [Example] } struct Example { var name: String var exampleViewControllerType: BaseViewControllerWithAutolayout.Type } class ViewController: BaseViewControllerWithAutolayout { static let cellIdentifier = String(describing: UITableViewCell.self) let exampleSections = [ ExampleSection(header: "布局尺寸", footer: nil, examples: [ Example(name: "尺寸拉伸", exampleViewControllerType: HuggingExampleViewController.self), Example(name: "尺寸压缩", exampleViewControllerType: CompressionExampleViewController.self), Example(name: "Table图片+多行文字", exampleViewControllerType: CodeTableViewController.self) ]), ExampleSection(header: "Apple官方例子", footer: nil, examples: [ Example(name: "Dynamic Stack View", exampleViewControllerType: DynamicStackViewController.self), ]), ExampleSection(header: "Purelayout例子", footer: nil, examples: [ Example(name: "1.Basic Auto Layout", exampleViewControllerType: PurelayoutExample1ViewController.self), Example(name: "2.Working with Arrays of Views", exampleViewControllerType: PurelayoutExample2ViewController.self), Example(name: "3.Distributing Views", exampleViewControllerType: PurelayoutExample3ViewController.self), Example(name: "4.Leading & Trailing Attributes", exampleViewControllerType: PurelayoutExample4ViewController.self), Example(name: "5.Cross-Attribute Constraints", exampleViewControllerType: PurelayoutExample5ViewController.self), Example(name: "6.Priorities & Inequalities", exampleViewControllerType: PurelayoutExample6ViewController.self), Example(name: "7.Animating Constraints", exampleViewControllerType: PurelayoutExample7ViewController.self), Example(name: "8.Constraint Identifiers (iOS 7.0+)", exampleViewControllerType: PurelayoutExample8ViewController.self), Example(name: "9.Layout Margins (iOS 8.0+)", exampleViewControllerType: PurelayoutExample9ViewController.self), Example(name: "10.Constraints Without Installing", exampleViewControllerType: PurelayoutExample10ViewController.self), Example(name: "11.Basic UIScrollView", exampleViewControllerType: PurelayoutExample11ViewController.self), Example(name: "12.Basic Auto Layout with Constraint toggle", exampleViewControllerType: PurelayoutExample12ViewController.self) ]) ] lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero).configureForAutoLayout("tableView") tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: ViewController.cellIdentifier) return tableView }() override func loadView() { super.loadView() _ = self.view.configureForAutoresizingMask("main") setupAndComposeView() // bootstrap Auto Layout view.setNeedsUpdateConstraints() } override var accessibilityIdentifier: String { return "Main" } override func setupAndComposeView() { self.title = "Example List" view.addSubview(tableView) } override func setupConstraints() { tableView.autoPinEdgesToSuperviewEdges() } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return exampleSections.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return exampleSections[section].header } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return exampleSections[section].footer } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return exampleSections[section].examples.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ViewController.cellIdentifier, for: indexPath) cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 17) cell.textLabel?.text = exampleSections[indexPath.section].examples[indexPath.row].name cell.accessoryType = .disclosureIndicator return cell } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let example = exampleSections[indexPath.section].examples[indexPath.row] let exampleViewController = example.exampleViewControllerType.init() self.show(exampleViewController, sender: nil) //self.present(exampleViewController, animated: false) { //self.navigationController?.pushViewController(exampleViewController, animated: false) } }
40.992063
139
0.724298
8fbec6f8e184ad271c7812d3fdefaa99eca628cb
1,362
/// Represents a path into an element hierarchy. /// Used for disambiguation during diff operations. struct ElementPath: Hashable, CustomDebugStringConvertible { private var identifiersHash: Int? = nil private(set) var identifiers: [ElementIdentifier] = [] private mutating func setIdentifiersHash() { var hasher = Hasher() hasher.combine(identifiers) identifiersHash = hasher.finalize() } mutating func prepend(identifier: ElementIdentifier) { identifiers.insert(identifier, at: 0) setIdentifiersHash() } mutating func append(identifier: ElementIdentifier) { identifiers.append(identifier) setIdentifiersHash() } func prepending(identifier: ElementIdentifier) -> ElementPath { var result = self result.prepend(identifier: identifier) return result } func appending(identifier: ElementIdentifier) -> ElementPath { var result = self result.append(identifier: identifier) return result } static var empty: ElementPath { return ElementPath() } func hash(into hasher: inout Hasher) { hasher.combine(identifiersHash) } // MARK: CustomDebugStringConvertible var debugDescription: String { return identifiers.map { $0.debugDescription }.joined() } }
24.763636
67
0.667401
e6a8e1693dd15d87c1c9324bd8b9916aa4bb820f
6,468
import PostgresKit import SQLKitBenchmark import XCTest import Logging class PostgresKitTests: XCTestCase { func testSQLKitBenchmark() throws { let conn = try PostgresConnection.test(on: self.eventLoop).wait() defer { try! conn.close().wait() } conn.logger.logLevel = .trace let benchmark = SQLBenchmarker(on: conn.sql()) try benchmark.run() } func testPerformance() throws { let db = PostgresConnectionSource(configuration: .test) let pool = EventLoopGroupConnectionPool( source: db, maxConnectionsPerEventLoop: 2, on: self.eventLoopGroup ) defer { pool.shutdown() } // Postgres seems to take much longer on initial connections when using SCRAM-SHA-256 auth, // which causes XCTest to bail due to the first measurement having a very high deviation. // Spin the pool a bit before running the measurement to warm it up. for _ in 1...25 { _ = try! pool.withConnection { conn in return conn.query("SELECT 1;") }.wait() } self.measure { for _ in 1...100 { _ = try! pool.withConnection { conn in return conn.query("SELECT 1;") }.wait() } } } func testLeak() throws { struct Foo: Codable { var id: String var description: String? var latitude: Double var longitude: Double var created_by: String var created_at: Date var modified_by: String var modified_at: Date } let conn = try PostgresConnection.test(on: self.eventLoop).wait() defer { try! conn.close().wait() } let db = conn.sql() try db.raw("DROP TABLE IF EXISTS foos").run().wait() try db.raw(""" CREATE TABLE foos ( id TEXT PRIMARY KEY, description TEXT, latitude DOUBLE PRECISION, longitude DOUBLE PRECISION, created_by TEXT, created_at TIMESTAMPTZ, modified_by TEXT, modified_at TIMESTAMPTZ ) """).run().wait() defer { try? db.raw("DROP TABLE IF EXISTS foos").run().wait() } for i in 0..<5_000 { let zipcode = Foo( id: UUID().uuidString, description: "test \(i)", latitude: Double.random(in: 0...100), longitude: Double.random(in: 0...100), created_by: "test", created_at: Date(), modified_by: "test", modified_at: Date() ) try db.insert(into: "foos") .model(zipcode) .run().wait() } } func testArrayEncoding() throws { let conn = try PostgresConnection.test(on: self.eventLoop).wait() defer { try! conn.close().wait() } conn.logger.logLevel = .trace struct Foo: Codable { var bar: Int } let foos: [Foo] = [.init(bar: 1), .init(bar: 2)] try conn.sql().raw("SELECT \(bind: foos)::JSONB[] as foos") .run().wait() } func testDictionaryEncoding() throws { let conn = try PostgresConnection.test(on: self.eventLoop).wait() defer { try! conn.close().wait() } conn.logger.logLevel = .trace struct Foo: Codable { var bar: Int } } func testDecodeModelWithNil() throws { let conn = try PostgresConnection.test(on: self.eventLoop).wait() defer { try! conn.close().wait() } let rows = try conn.query("SELECT 'foo'::text as foo, null as bar, 'baz'::text as baz").wait() let row = rows[0] struct Test: Codable { var foo: String var bar: String? var baz: String? } let test = try row.sql().decode(model: Test.self) XCTAssertEqual(test.foo, "foo") XCTAssertEqual(test.bar, nil) XCTAssertEqual(test.baz, "baz") } func testEventLoopGroupSQL() throws { var configuration = PostgresConfiguration.test configuration.searchPath = ["foo", "bar", "baz"] let source = PostgresConnectionSource(configuration: configuration) let pool = EventLoopGroupConnectionPool(source: source, on: self.eventLoopGroup) defer { pool.shutdown() } let db = pool.database(logger: .init(label: "test")).sql() let rows = try db.raw("SELECT version();").all().wait() print(rows) } func testArrayEncoding_json() throws { let connection = try PostgresConnection.test(on: self.eventLoop).wait() defer { try! connection.close().wait() } _ = try connection.query("DROP TABLE IF EXISTS foo").wait() _ = try connection.query("CREATE TABLE foo (bar integer[] not null)").wait() defer { _ = try! connection.query("DROP TABLE foo").wait() } _ = try connection.query("INSERT INTO foo (bar) VALUES ($1)", [ PostgresDataEncoder().encode([Bar]()) ]).wait() let rows = try connection.query("SELECT * FROM foo").wait() print(rows) } func testEnum() throws { let connection = try PostgresConnection.test(on: self.eventLoop).wait() defer { try! connection.close().wait() } try SQLBenchmarker(on: connection.sql()).testEnum() } var eventLoop: EventLoop { self.eventLoopGroup.next() } var eventLoopGroup: EventLoopGroup! override func setUpWithError() throws { try super.setUpWithError() XCTAssertTrue(isLoggingConfigured) self.eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2) } override func tearDownWithError() throws { try self.eventLoopGroup.syncShutdownGracefully() self.eventLoopGroup = nil try super.tearDownWithError() } } enum Bar: Int, Codable { case one, two } extension Bar: PostgresDataConvertible { } let isLoggingConfigured: Bool = { LoggingSystem.bootstrap { label in var handler = StreamLogHandler.standardOutput(label: label) handler.logLevel = env("LOG_LEVEL").flatMap { Logger.Level(rawValue: $0) } ?? .debug return handler } return true }()
33
102
0.564626
e0e1362208074c6abe02ea0782082d19ce72aee7
253
// // Created by kwanghyun.won // Copyright © 2020 wonkwh. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.red } }
16.866667
48
0.675889
29322f825e04fc1694fccb1d686426344aed0a64
1,843
// // UIView+Extensions.swift // SpeakSelectionDemo // // Created by Adam Niepokój on 12/06/2021. // import UIKit extension UIView { /// Configures an existing view to not convert the autoresizing mask into constraints. /// - Returns: A configured view. @discardableResult func layoutable() -> Self { translatesAutoresizingMaskIntoConstraints = false return self } /// A type of layout for constraints to use. enum ConstraintsType { case edges(view: UIView), safeAreaLayout(view: UIView) /// SeeAlso: `UIView.topAnchor` var topAnchor: NSLayoutYAxisAnchor { switch self { case let .edges(view): return view.topAnchor case let .safeAreaLayout(view): return view.safeAreaLayoutGuide.topAnchor } } /// SeeAlso: `UIView.bottomAnchor` var bottomAnchor: NSLayoutYAxisAnchor { switch self { case let .edges(view): return view.bottomAnchor case let .safeAreaLayout(view): return view.safeAreaLayoutGuide.bottomAnchor } } /// SeeAlso: `UIView.leadingAnchor` var leadingAnchor: NSLayoutXAxisAnchor { switch self { case let .edges(view): return view.leadingAnchor case let .safeAreaLayout(view): return view.safeAreaLayoutGuide.leadingAnchor } } /// SeeAlso: `UIView.trailingAnchor` var trailingAnchor: NSLayoutXAxisAnchor { switch self { case let .edges(view): return view.trailingAnchor case let .safeAreaLayout(view): return view.safeAreaLayoutGuide.trailingAnchor } } } }
28.796875
90
0.577862
0adf815f3bfcb1557e2dd449ab178911ac9efcc3
2,350
// // AppDelegate.swift // ExampleApp // // Created by Artur Mkrtchyan on 2/28/18. // Copyright © 2018 Artur Mkrtchyan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // UserMoyaNetwork().getPopularUsers { (error, users) in // if let users = users { // // } // } 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:. } }
44.339623
285
0.725957
62bed8b8b46c3855c0c323057a2b3e986982d9fe
7,835
// // fdm_utils.swift // vox.Force // // Created by Feng Yang on 2020/7/31. // Copyright © 2020 Feng Yang. All rights reserved. // import Foundation //MARK:- 2D Operators /// Returns 2-D gradient vector from given 2-D scalar grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j). func gradient2(data:ConstArrayAccessor2<Float>, gridSpacing:Vector2F, i:size_t, j:size_t)->Vector2F { let ds:Size2 = data.size() VOX_ASSERT(i < ds.x && j < ds.y) let left:Float = data[(i > 0) ? i - 1 : i, j] let right:Float = data[(i + 1 < ds.x) ? i + 1 : i, j] let down:Float = data[i, (j > 0) ? j - 1 : j] let up:Float = data[i, (j + 1 < ds.y) ? j + 1 : j] return 0.5 * Vector2F(right - left, up - down) / gridSpacing } /// Returns 2-D gradient vectors from given 2-D vector grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j). func gradient2(data:ConstArrayAccessor2<Vector2F>, gridSpacing:Vector2F, i:size_t, j:size_t)->[Vector2F] { let ds:Size2 = data.size() VOX_ASSERT(i < ds.x && j < ds.y) let left:Vector2F = data[(i > 0) ? i - 1 : i, j] let right:Vector2F = data[(i + 1 < ds.x) ? i + 1 : i, j] let down:Vector2F = data[i, (j > 0) ? j - 1 : j] let up:Vector2F = data[i, (j + 1 < ds.y) ? j + 1 : j] var result = Array<Vector2F>(repeating: Vector2F(), count: 2) result[0] = 0.5 * Vector2F(right.x - left.x, up.x - down.x) / gridSpacing result[1] = 0.5 * Vector2F(right.y - left.y, up.y - down.y) / gridSpacing return result } /// Returns Laplacian value from given 2-D scalar grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j). func laplacian2(data:ConstArrayAccessor2<Float>, gridSpacing:Vector2F, i:size_t, j:size_t)->Float { let center:Float = data[i, j] let ds:Size2 = data.size() VOX_ASSERT(i < ds.x && j < ds.y) var dleft:Float = 0.0 var dright:Float = 0.0 var ddown:Float = 0.0 var dup:Float = 0.0 if (i > 0) { dleft = center - data[i - 1, j] } if (i + 1 < ds.x) { dright = data[i + 1, j] - center } if (j > 0) { ddown = center - data[i, j - 1] } if (j + 1 < ds.y) { dup = data[i, j + 1] - center } return (dright - dleft) / Math.square(of: gridSpacing.x) + (dup - ddown) / Math.square(of: gridSpacing.y) } /// Returns 2-D Laplacian vectors from given 2-D vector grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j). func laplacian2(data:ConstArrayAccessor2<Vector2F>, gridSpacing:Vector2F, i:size_t, j:size_t)->Vector2F { let center:Vector2F = data[i, j] let ds:Size2 = data.size() VOX_ASSERT(i < ds.x && j < ds.y) var dleft = Vector2F() var dright = Vector2F() var ddown = Vector2F() var dup = Vector2F() if (i > 0) { dleft = center - data[i - 1, j] } if (i + 1 < ds.x) { dright = data[i + 1, j] - center } if (j > 0) { ddown = center - data[i, j - 1] } if (j + 1 < ds.y) { dup = data[i, j + 1] - center } return (dright - dleft) / Math.square(of: gridSpacing.x) + (dup - ddown) / Math.square(of: gridSpacing.y) } //MARK:- 3D Operators /// Returns 3-D gradient vector from given 3-D scalar grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j, \p k). func gradient3(data:ConstArrayAccessor3<Float>, gridSpacing:Vector3F, i:size_t, j:size_t, k:size_t)->Vector3F { let ds:Size3 = data.size() VOX_ASSERT(i < ds.x && j < ds.y && k < ds.z) let left:Float = data[(i > 0) ? i - 1 : i, j, k] let right:Float = data[(i + 1 < ds.x) ? i + 1 : i, j, k] let down:Float = data[i, (j > 0) ? j - 1 : j, k] let up:Float = data[i, (j + 1 < ds.y) ? j + 1 : j, k] let back:Float = data[i, j, (k > 0) ? k - 1 : k] let front:Float = data[i, j, (k + 1 < ds.z) ? k + 1 : k] return 0.5 * Vector3F(right - left, up - down, front - back) / gridSpacing } /// Returns 3-D gradient vectors from given 3-D vector grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j, \p k). func gradient3(data:ConstArrayAccessor3<Vector3F>, gridSpacing:Vector3F, i:size_t, j:size_t, k:size_t)->[Vector3F] { let ds:Size3 = data.size() VOX_ASSERT(i < ds.x && j < ds.y && k < ds.z) let left:Vector3F = data[(i > 0) ? i - 1 : i, j, k] let right:Vector3F = data[(i + 1 < ds.x) ? i + 1 : i, j, k] let down:Vector3F = data[i, (j > 0) ? j - 1 : j, k] let up:Vector3F = data[i, (j + 1 < ds.y) ? j + 1 : j, k] let back:Vector3F = data[i, j, (k > 0) ? k - 1 : k] let front:Vector3F = data[i, j, (k + 1 < ds.z) ? k + 1 : k] var result = Array<Vector3F>(repeating: Vector3F(), count: 3) result[0] = 0.5 * Vector3F( right.x - left.x, up.x - down.x, front.x - back.x) / gridSpacing result[1] = 0.5 * Vector3F( right.y - left.y, up.y - down.y, front.y - back.y) / gridSpacing result[2] = 0.5 * Vector3F( right.z - left.z, up.z - down.z, front.z - back.z) / gridSpacing return result } /// Returns Laplacian value from given 3-D scalar grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j, \p k). func laplacian3(data:ConstArrayAccessor3<Float>, gridSpacing:Vector3F, i:size_t, j:size_t, k:size_t)->Float { let center:Float = data[i, j, k] let ds:Size3 = data.size() VOX_ASSERT(i < ds.x && j < ds.y && k < ds.z) var dleft:Float = 0.0 var dright:Float = 0.0 var ddown:Float = 0.0 var dup:Float = 0.0 var dback:Float = 0.0 var dfront:Float = 0.0 if (i > 0) { dleft = center - data[i - 1, j, k] } if (i + 1 < ds.x) { dright = data[i + 1, j, k] - center } if (j > 0) { ddown = center - data[i, j - 1, k] } if (j + 1 < ds.y) { dup = data[i, j + 1, k] - center } if (k > 0) { dback = center - data[i, j, k - 1] } if (k + 1 < ds.z) { dfront = data[i, j, k + 1] - center } return (dright - dleft) / Math.square(of: gridSpacing.x) + (dup - ddown) / Math.square(of: gridSpacing.y) + (dfront - dback) / Math.square(of: gridSpacing.z) } /// Returns 3-D Laplacian vectors from given 3-D vector grid-like array /// \p data, \p gridSpacing, and array index (\p i, \p j, \p k). func laplacian3(data:ConstArrayAccessor3<Vector3F>, gridSpacing:Vector3F, i:size_t, j:size_t, k:size_t)->Vector3F { let center:Vector3F = data[i, j, k] let ds:Size3 = data.size() VOX_ASSERT(i < ds.x && j < ds.y && k < ds.z) var dleft:Vector3F = Vector3F() var dright:Vector3F = Vector3F() var ddown:Vector3F = Vector3F() var dup:Vector3F = Vector3F() var dback:Vector3F = Vector3F() var dfront:Vector3F = Vector3F() if (i > 0) { dleft = center - data[i - 1, j, k] } if (i + 1 < ds.x) { dright = data[i + 1, j, k] - center } if (j > 0) { ddown = center - data[i, j - 1, k] } if (j + 1 < ds.y) { dup = data[i, j + 1, k] - center } if (k > 0) { dback = center - data[i, j, k - 1] } if (k + 1 < ds.z) { dfront = data[i, j, k + 1] - center } var result = (dright - dleft) / Math.square(of: gridSpacing.x) result += (dup - ddown) / Math.square(of: gridSpacing.y) return result + (dfront - dback) / Math.square(of: gridSpacing.z) }
31.849593
78
0.526867
d972ce2ef721ec2a9fa62e4fc45b9cb85e84067d
344
#if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif extension LayoutGuide: Pinnable { /// Equivalent to `bottomAnchor`. public var firstBaselineAnchor: NSLayoutYAxisAnchor { bottomAnchor } /// Equivalent to `bottomAnchor`. public var lastBaselineAnchor: NSLayoutYAxisAnchor { bottomAnchor } }
19.111111
55
0.75
c1ebec59042f503bc7c7b7a0a672189c629e43a1
1,132
// // UserDefault+T.swift // Building6 // // Created by edz on 2020/10/10. // Copyright © 2020 funlink-tech. All rights reserved. // import Foundation @propertyWrapper public struct UserDefault<T> { public let key: String public let defaultValue: T public init(_ key: String, defaultValue: T) { self.key = key self.defaultValue = defaultValue } public var wrappedValue: T { get { return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue } set { UserDefaults.standard.set(newValue, forKey: key) } } } //MARK: 使用示例 /* ///封装一个UserDefault配置文件 struct UserDefaultsConfig { ///告诉编译器 我要包裹的是hadShownGuideView这个值。 ///实际写法就是在UserDefault包裹器的初始化方法前加了个@ /// hadShownGuideView 属性的一些key和默认值已经在 UserDefault包裹器的构造方法中实现 @UserDefault("had_shown_guide_view", defaultValue: false) static var hadShownGuideView: Bool } ///具体的业务代码。 UserDefaultsConfig.hadShownGuideView = false print(UserDefaultsConfig.hadShownGuideView) // false UserDefaultsConfig.hadShownGuideView = true print(UserDefaultsConfig.hadShownGuideView) // true */
24.085106
82
0.70583
7155c3fd3db2f851d8c295e636a0f65152e7f914
3,397
// // Daily.swift // CalorieBurner // // Created by Dino Srdoč on 25/02/2018. // Copyright © 2018 Dino Srdoč. All rights reserved. // import CoreData @objc public enum Feelings: Int { case bad, dissatisfied, neutral, satisfied, happy } /// Representation of a single day containing a mass and an energy class Daily: NSManagedObject { // a hack to get around the fact that we can't store optional enums in Core Data public var mood: Feelings? { get { return (moodID?.intValue).flatMap(Feelings.init) } set { moodID = (newValue?.rawValue).flatMap(NSNumber.init) } } private var massValue: Double? { return mass?.value } private var energyValue: Double? { return energy?.value } /// Default fetch request, wrapping an NSFetchRequest call public class func makeFetchRequest() -> NSFetchRequest<Daily> { return NSFetchRequest<Daily>(entityName: "Daily") } /// Filter objects by day public class func fetchRequest(in date: Date) -> NSFetchRequest<Daily> { let request = NSFetchRequest<Daily>(entityName: "Daily") request.predicate = isInSameDayPredicate(as: date) return request } // Filter objects by a range of dates public class func fetchRequest(in dateRange: (start: Date, end: Date)) -> NSFetchRequest<Daily> { let request = NSFetchRequest<Daily>(entityName: "Daily") request.predicate = NSPredicate( format: "created >= %@ AND created <= %@", argumentArray: [dateRange.start.startOfDay, dateRange.end.endOfDay] ) request.sortDescriptors = [NSSortDescriptor(key: "created", ascending: false)] return request } /// A sorted list of all entries public class func tableFetchRequest() -> NSFetchRequest<Daily> { let request = NSFetchRequest<Daily>(entityName: "Daily") request.sortDescriptors = [NSSortDescriptor(key: "created", ascending: false)] return request } static let dateFormatter: DateFormatter = { let fmt = DateFormatter() fmt.dateFormat = "YYYY-MM-dd" return fmt }() public class func isInSameDayPredicate(as date: Date) -> NSPredicate { let startOfDay = date.startOfDay let endOfDay = date.endOfDay return NSPredicate( format: "created >= %@ AND created <= %@", argumentArray: [startOfDay, endOfDay] ) } public class func isInDateBetweenPredicate(start: Date, end: Date) -> NSPredicate { let startDate = start.startOfDay let endDate = end.endOfDay return NSPredicate( format: "created >= %@ AND created <= %@", argumentArray: [startDate, endDate] ) } convenience init(context: NSManagedObjectContext, date: Date) { self.init(context: context) created = date } public func updateValues(mass newMass: Double?, energy newEnergy: Double?) { mass = newMass.flatMap { Mass(value: $0, unit: .kilograms) } ?? mass energy = newEnergy.flatMap { Energy(value: $0, unit: .kilocalories) } ?? energy } public static var dateSortDescriptor = NSSortDescriptor(key: "created", ascending: false) }
31.453704
101
0.615543
711eb44ae49252dc139bd8e6d2fd69726a975468
4,061
// // Router.swift // iosApp // // Created by Daniele Baroncelli on 04/05/21. // Copyright © 2021 orgName. All rights reserved. // import SwiftUI import shared let twopaneWidthThreshold : CGFloat = 1000 extension Navigation { func isTwoPane() -> Bool { let width = UIScreen.main.bounds.width let height = UIScreen.main.bounds.height if width < height || width < twopaneWidthThreshold { return false } return true } @ViewBuilder func router() -> some View { ZStack { ForEach(self.level1ScreenIdentifiers, id: \.self.URI) { screenIdentifier in if !self.isTwoPane() { self.onePane(screenIdentifier) .opacity(screenIdentifier.URI == self.currentLevel1ScreenIdentifier.URI ? 1 : 0) } else { self.twoPane(screenIdentifier) .opacity(screenIdentifier.URI == self.currentLevel1ScreenIdentifier.URI ? 1 : 0) } } } .navigationBarColor(backgroundUIColor: UIColor(customBgColor), tintUIColor: .white) .toolbarColor(backgroundUIColor: UIColor(customBgColor), tintUIColor: .white) } func navigate(_ screen: Screen, _ params: ScreenParams?) -> ScreenIdentifier { return ScreenIdentifier.Factory().get(screen: screen, params: params) } } struct NavLink<Content: View>: View { var linkFunction: () -> ScreenIdentifier let content: () -> Content @EnvironmentObject var appObj: AppObservableObject @State private var selected : Bool = false var body: some View { if appObj.dkmpNav.isTwoPane() { Button(action: { let screenIdentifier = linkFunction() appObj.dkmpNav.navigateByScreenIdentifier(screenIdentifier: screenIdentifier) self.selected = true }) { VStack(spacing: 0) { HStack(spacing: 0) { content() Image(systemName: "chevron.right").resizable().frame(width: 6, height: 12).foregroundColor(lightGreyColor) } } } } else { let isActive = Binding<Bool> ( get: { selected && appObj.dkmpNav.isInCurrentVerticalBackstack(screenIdentifier: linkFunction()) }, set: { isActive in if isActive { let screenIdentifier = linkFunction() appObj.dkmpNav.navigateByScreenIdentifier(screenIdentifier: screenIdentifier) self.selected = true } } ) NavigationLink( destination: LazyDestinationView( appObj.dkmpNav.screenPicker(linkFunction()) .navigationBarTitle(appObj.dkmpNav.getTitle(screenIdentifier: linkFunction()), displayMode: .inline) .onDisappear { let screenIdentifier = linkFunction() //print("onDisappear: "+screenIdentifier.URI) if appObj.dkmpNav.isInCurrentVerticalBackstack(screenIdentifier: screenIdentifier) { //print("confimed disappear") self.selected = false isActive.wrappedValue = false appObj.dkmpNav.exitScreen(screenIdentifier: screenIdentifier, triggerRecomposition: false) } } ), isActive: isActive ) { content() } } } } struct LazyDestinationView<Content: View>: View { let build: () -> Content init(_ build: @autoclosure @escaping () -> Content) { self.build = build } var body: Content { build() } }
33.286885
130
0.530165
181c5771ebb0ae3547fe67d4c225611dfb34b241
381
// // KeyboardDismissing.swift // Notifire // // Created by David Bielik on 28/08/2018. // Copyright © 2018 David Bielik. All rights reserved. // import UIKit protocol KeyboardDismissing { var keyboardDismissableView: UIView { get set } } extension KeyboardDismissing { func setupKeyboardDismissing() { } } extension KeyboardDismissing where Self: UIView { }
15.875
55
0.716535
9c7b4d2cae5331bfb9ebd5b3a9ec6d0c641b1f20
1,419
/*   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 @objcMembers public class AutoRefreshCountConfig: NSObject { /** Delay (in seconds) for which to wait before performing an auto refresh. Note that this value is clamped between @c PBMAutoRefresh.AUTO_REFRESH_DELAY_MIN and @c PBMAutoRefresh.AUTO_REFRESH_DELAY_MAX. Also note that this will return @c nil if @c isInterstitial is set to @c YES. */ public var autoRefreshDelay: TimeInterval? /** Maximum number of times the BannerView should refresh. This value will be overwritten with any values received from the server. Using a value of 0 indicates there is no maximum. Default is 0. */ public var autoRefreshMax: Double? = 0 /** The number of times the BannerView has been refreshed. */ public var numRefreshes = 0 }
30.847826
85
0.723749
8f4d89c638a5d8dabb68de009f3dc338672a4719
3,540
// // PasscodeSettingsViewController.swift // PasscodeLockDemo // // Created by Yanko Dimitrov on 8/29/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import UIKit import PasscodeLock class PasscodeSettingsViewController: UIViewController { @IBOutlet weak var passcodeSwitch: UISwitch! @IBOutlet weak var changePasscodeButton: UIButton! @IBOutlet weak var testTextField: UITextField! @IBOutlet weak var testActivityButton: UIButton! private let configuration: PasscodeLockConfigurationType init(configuration: PasscodeLockConfigurationType) { self.configuration = configuration super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { let repository = UserDefaultsPasscodeRepository() configuration = PasscodeLockConfiguration(repository: repository) super.init(coder: aDecoder) } // MARK: - View override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updatePasscodeView() } func updatePasscodeView() { let hasPasscode = configuration.repository.hasPasscode changePasscodeButton.isHidden = !hasPasscode passcodeSwitch.isOn = hasPasscode } // MARK: - Actions @IBAction func passcodeSwitchValueChange(sender: UISwitch) { let passcodeVC: PasscodeLockViewController if passcodeSwitch.isOn { passcodeVC = PasscodeLockViewController(state: .SetPasscode, configuration: configuration) passcodeVC.touchIDView?.isHidden = true } else { passcodeVC = PasscodeLockViewController(state: .RemovePasscode, configuration: configuration) passcodeVC.touchIDView?.isHidden = false passcodeVC.successCallback = { lock in lock.repository.deletePasscode() } } passcodeVC.modalPresentationStyle = .overCurrentContext passcodeVC.modalTransitionStyle = .crossDissolve present(passcodeVC, animated: true, completion: nil) } @IBAction func changePasscodeButtonTap(_ sender: UIButton) { let repo = UserDefaultsPasscodeRepository() let config = PasscodeLockConfiguration(repository: repo) let passcodeLock = PasscodeLockViewController(state: .ChangePasscode, configuration: config) present(passcodeLock, animated: true, completion: nil) } @IBAction func testAlertButtonTap(_ sender: UIButton) { let alertVC = UIAlertController(title: "Test", message: "", preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) present(alertVC, animated: true, completion: nil) } @IBAction func testActivityButtonTap(_ sender: UIButton) { let activityVC = UIActivityViewController(activityItems: ["Test"], applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = testActivityButton activityVC.popoverPresentationController?.sourceRect = CGRect(x: 10, y: 20, width: 0, height: 0) present(activityVC, animated: true, completion: nil) } @IBAction func dismissKeyboard() { testTextField.resignFirstResponder() } }
31.327434
105
0.643785
e6fc4248a652278a9368306fae24d0e4f3659efe
2,447
// // LBFMVipAnimationView.swift // LBFM-Swift // // Created by liubo on 2019/3/1. // Copyright © 2019 刘博. All rights reserved. // import UIKit /// 上下浮动vip领取view class LBFMVipAnimationView: UIView { // 图片 private lazy var imageView:UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "vip") return imageView }() // 标题 private lazy var titleLabel:UILabel = { let label = UILabel() label.text = "VIP会员" label.textColor = UIColor.gray label.font = UIFont.systemFont(ofSize: 15) return label }() // 介绍 private lazy var desLabel:UILabel = { let label = UILabel() label.text = "免费领取7天会员" label.textColor = UIColor.gray label.font = UIFont.systemFont(ofSize: 13) return label }() // 箭头 private lazy var arrowsLabel:UILabel = { let label = UILabel() label.text = ">" label.font = UIFont.systemFont(ofSize: 20) label.textColor = UIColor.gray return label }() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.init(r: 212, g: 212, b: 212) setUpLayout() } func setUpLayout(){ self.addSubview(self.imageView) self.imageView.snp.makeConstraints { (make) in make.left.top.equalToSuperview().offset(5) make.width.height.equalTo(30) } self.addSubview(self.titleLabel) self.titleLabel.snp.makeConstraints { (make) in make.left.equalTo(self.imageView.snp.right).offset(5) make.width.equalTo(100) make.height.equalTo(20) make.centerY.equalTo(self.imageView) } self.addSubview(self.desLabel) self.desLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(5) make.top.equalTo(self.imageView.snp.bottom).offset(5) make.width.equalTo(180) make.height.equalTo(20) } self.addSubview(self.arrowsLabel) self.arrowsLabel.snp.makeConstraints { (make) in make.right.equalToSuperview() make.width.height.equalTo(20) make.top.equalTo(20) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
27.494382
67
0.57499
87049f8ec2b906217323043b8537b04d2ca2906b
1,598
//===----------------------------------------------------------------------===// // // This source file is part of the Hummingbird server framework project // // Copyright (c) 2021-2021 the Hummingbird authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation import Hummingbird import HummingbirdXCT import XCTest class HummingbirdDateTests: XCTestCase { func testRFC1123Renderer() { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "EEE, d MMM yyy HH:mm:ss z" formatter.timeZone = TimeZone(secondsFromGMT: 0) for _ in 0..<1000 { let time = Int.random(in: 1...4 * Int(Int32.max)) XCTAssertEqual(formatter.string(from: Date(timeIntervalSince1970: Double(time))), HBDateCache.formatRFC1123Date(time)) } } func testDateHeader() throws { let app = HBApplication(testing: .embedded) app.router.get("date") { _ in return "hello" } try app.XCTStart() defer { app.XCTStop() } app.XCTExecute(uri: "/date", method: .GET) { response in XCTAssertNotNil(response.headers["date"].first) } app.XCTExecute(uri: "/date", method: .GET) { response in XCTAssertNotNil(response.headers["date"].first) } } }
31.96
130
0.581352
8af2020e81dbe87902190ad180c889b5d181b3a7
5,279
/* * The MIT License (MIT) * * Copyright (c) 2019 Looker Data Sciences, Inc. * * 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 @available(OSX 10.15, *) open class APIMethods { public var authSession: IAuthorizer public var encoder = JSONEncoder() public init(_ authSession: IAuthorizer) { self.authSession = authSession } open func encode<T>(_ value: T) throws -> Data where T : Encodable { return try! encoder.encode(value) } open func ok<TSuccess, TError>(_ response: SDKResponse<TSuccess, TError>) throws -> TSuccess { switch response { case .success(let response): return response case .error(let error): // TODO implement logging // let message = error.errorDescription // ?? error.failureReason // ?? error.recoverySuggestion // ?? error.helpAnchor // ?? "Unknown SDK Error" // print("Error: \(message)") throw error } } open func authRequest<TSuccess: Codable, TError: Codable>( _ method: HttpMethod, _ path: String, _ queryParams: Values?, _ body: Any?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> { return self.authSession.transport.request( method, path, queryParams, body, { props -> URLRequest in do { let auth = try self.authSession.authenticate(props) return auth } catch { print("Auth Error: \(error)") return props } }, options ) } /** Make a GET request */ open func get<TSuccess: Codable, TError: Codable>( _ path: String, _ queryParams: Values?, _ body: Any?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> { return self.authRequest( HttpMethod.GET, path, queryParams, body, options ) } /** Make a HEAD request */ open func head<TSuccess: Codable, TError: Codable>( _ path: String, _ queryParams: Values?, _ body: Any?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> { return self.authRequest( HttpMethod.HEAD, path, queryParams, body, options ) } /** Make a DELETE request */ open func delete<TSuccess: Codable, TError: Codable>( _ path: String, _ queryParams: Values?, _ body: Any?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> { return self.authRequest( HttpMethod.DELETE, path, queryParams, body, options ) } /** Make a POST request */ open func post<TSuccess: Codable, TError: Codable>( _ path: String, _ queryParams: Values?, _ body: Any?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> { return self.authRequest( HttpMethod.POST, path, queryParams, body, options ) } /** Make a PUT request */ open func put<TSuccess: Codable, TError: Codable>( _ path: String, _ queryParams: Values?, _ body: Any?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> { return self.authRequest( HttpMethod.PUT, path, queryParams, body, options ) } /** Make a PATCH request */ open func patch<TSuccess: Codable, TError: Codable>( _ path: String, _ queryParams: Values?, _ body: Any?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> { return self.authRequest( HttpMethod.PATCH, path, queryParams, body, options ) } }
29.824859
98
0.562038
1ec4d2a228ae9415bb3d48d29093cc0825267ef2
611
// // Series.swift // // Copyright © 2018 Michael McMahon. All rights reserved worldwide. // http://github.com/mmpub/starlanes // import Foundation /// Persistable series model struct Series: Codable { /// Game configuration parameters, invariant throughout series. let gameConfig: GameConfig! /// House rules values, invariant throughout series. let houseRules: HouseRules! /// Player definitions, invariant throughout series. let playerDefs: [VmoPlayerDef]! /// Leaderboard model, containing unordered correlation of players with games won. var leaderboard: Leaderboard! }
30.55
86
0.729951
7525e4f3818e82dd0391f8dccf7f60bfaf680eb6
313
public enum Result<Element> { case success(Element) case error(Error) public var element: Element? { if case let .success(element) = self { return element } return nil } public var error: Error? { if case let .error(error) = self { return error } return nil } }
15.65
42
0.603834
2290a529af6f3154983ba5ea4403ca0a450c1801
950
// // nytimes_headlinesTests.swift // nytimes-headlinesTests // // Created by KUTAN ÇINGISIZ on 26.02.2019. // Copyright © 2019 KUTAN ÇINGISIZ. All rights reserved. // import XCTest @testable import nytimes_headlines class nytimes_headlinesTests: XCTestCase { override func 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. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.142857
111
0.669474
d9c79699af8b6836d2b9277fd96fbf034486cf8a
3,052
// // Created by Yichi Zhang on 2017-11-03. // Copyright (c) 2017-present yichizhang. All rights reserved. // import Foundation import Eureka // NB: This is based on ButtonRow/ButtonCell // MARK: CustomPushCell open class CustomPushCellOf<T: Equatable>: Cell<T>, CellType { required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func update() { super.update() selectionStyle = row.isDisabled ? .none : .default accessoryType = .none editingAccessoryType = accessoryType textLabel?.textAlignment = .center textLabel?.textColor = tintColor textLabel?.textColor = tintColor.withAlphaComponent(row.isDisabled ? 0.3 : 1.0) } open override func didSelect() { super.didSelect() row.deselect() } } public typealias CustomPushCell = CustomPushCellOf<String> // MARK: CustomPushRow open class _CustomPushRowOf<T: Equatable> : Row<CustomPushCellOf<T>> { open var presentationMode: PresentationMode<UIViewController>? open var maxSelectionCount: Int = 3 required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil cellStyle = .value1 } open override func customDidSelect() { super.customDidSelect() if !isDisabled { if let presentationMode = presentationMode { if let controller = presentationMode.makeController() { presentationMode.present(controller, row: self, presentingController: self.cell.formViewController()!) } else { presentationMode.present(nil, row: self, presentingController: self.cell.formViewController()!) } } } } open override func customUpdateCell() { super.customUpdateCell() let leftAligmnment = presentationMode != nil cell.textLabel?.textAlignment = leftAligmnment ? .left : .center cell.accessoryType = !leftAligmnment || isDisabled ? .none : .disclosureIndicator cell.editingAccessoryType = cell.accessoryType cell.textLabel?.textColor = !leftAligmnment ? cell.tintColor.withAlphaComponent(isDisabled ? 0.3 : 1.0) : nil cell.detailTextLabel?.text = displayValueFor?(value) ?? (self as? NoValueDisplayTextConformance)?.noValueDisplayText } open override func prepare(for segue: UIStoryboardSegue) { super.prepare(for: segue) (segue.destination as? RowControllerType)?.onDismissCallback = presentationMode?.onDismissCallback } } /// A generic row with a button. The action of this button can be anything but normally will push a new view controller public final class CustomPushRowOf<T: Equatable> : _CustomPushRowOf<T>, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with a button and String value. The action of this button can be anything but normally will push a new view controller public typealias CustomPushRow = CustomPushRowOf<String>
31.791667
128
0.71789
26e4626bcd7d48c8e385d0e74cf948236507f566
1,425
// // AppDelegate.swift // Openvidu Swift // // Created by Dario Pacchi on 06/07/2020. // Copyright © 2020 Dario Pacchi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.5
179
0.74807
d7e779d8ef387115cfaceb2b5288f8aed23340c5
2,055
// // BerzierView.swift // EOPPad // // Created by mwk_pro on 2018/8/24. // Copyright © 2018年 mwk_pro. All rights reserved. // import UIKit public class MWBezierView: UIView, CAAnimationDelegate { var animation : CAKeyframeAnimation! var animationLayer : CALayer! public static func startBezierAnimation(startPoint: CGPoint, endPoint: CGPoint, inLayer: CALayer) { let bezierView = MWBezierView() bezierView.initView(startPoint: startPoint, endPoint: endPoint, inLayer: inLayer) } func initView(startPoint: CGPoint, endPoint: CGPoint, inLayer: CALayer) { animationLayer = CALayer() animationLayer.bounds = CGRect(x: 0, y: 0, width: 30, height: 30) animationLayer.position = startPoint animationLayer.backgroundColor = UIColor.red.cgColor animationLayer.cornerRadius = 15 animationLayer.masksToBounds = true inLayer.addSublayer(animationLayer) let path = UIBezierPath() path.move(to: animationLayer.position) path.addQuadCurve(to: endPoint, controlPoint: CGPoint(x: endPoint.x, y: startPoint.y - 160)) animation = CAKeyframeAnimation(keyPath: "position") animation.autoreverses = false animation.duration = 0.6 animation.path = path.cgPath animation.isRemovedOnCompletion = false animation.fillMode = CAMediaTimingFillMode.forwards animation.rotationMode = CAAnimationRotationMode.rotateAuto animation.delegate = self animationLayer.add(animation, forKey: "") } //MARK:--CAAnimationDelegate public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { animation.delegate = nil self.animationLayer.removeFromSuperlayer() } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
32.109375
103
0.665693
03f812d28598ef2fbc09e9c211a3b76501ade0a4
729
import UIKit import CellKit import DiffableCellKit struct NibTableViewCellModel: ReusableCellConvertible, DifferentiableCellModel { var domainIdentifier: Int { return text.hashValue } func hasEqualContent(with other: CellModel) -> Bool { guard let other = other as? NibTableViewCellModel else { return false } return other.text == self.text } typealias Cell = NibTableViewCell let text: String let cellHeight: CGFloat = 170.0 } final class NibTableViewCell: UITableViewCell, CellConfigurable { @IBOutlet private weak var headerLabel: UILabel! func configure(with model: NibTableViewCellModel) { headerLabel.text = model.text } }
22.78125
80
0.698217
627bcb5872b90e06234d69697151944b38006d8d
997
// // Ibooks.swift // Pods // // Created by Mariam AlJamea on 1/2/16. // Copyright © 2016 kitz. All rights reserved. // public extension Applications { struct Ibooks: ExternalApplication { public typealias ActionType = Applications.Ibooks.Action public let scheme = "itms-Books:" public let fallbackURL = "https://itunes.apple.com/us/app/ibooks/id364709193?mt=8" public let appStoreId = "364709193" public init() {} } } // MARK: - Actions public extension Applications.Ibooks { enum Action { case open } } extension Applications.Ibooks.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
20.770833
90
0.537613
deeb40cc5d52fb37736ce7d9de7323c704b25875
4,341
// // UILabel+NXFoundation.swift // NXKit // // Created by niegaotao on 2020/5/7. // Copyright © 2020年 TIMESCAPE. All rights reserved. // import Foundation import UIKit extension UILabel { /* 初始化 frame:显示范围 text:文案 font:字号 color:颜色 alignment:对齐方式 */ public convenience init(frame: CGRect, text: String, font: UIFont, textColor: UIColor, textAlignment: NSTextAlignment, lineSpacing:CGFloat, completion:NX.Completion<String, NSMutableParagraphStyle>? = nil) { self.init(frame:frame) self.updateSubviews(text: text, font: font, textColor: textColor, textAlignment: textAlignment, lineSpacing: lineSpacing, numberOfLines: 0, completion: completion) } open func updateSubviews(text: String, font: UIFont, textColor: UIColor, textAlignment: NSTextAlignment, lineSpacing:CGFloat, numberOfLines:Int, completion:NX.Completion<String, NSMutableParagraphStyle>? = nil){ self.text = text self.font = font self.textColor = textColor self.textAlignment = textAlignment self.numberOfLines = numberOfLines let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .byCharWrapping paragraphStyle.firstLineHeadIndent = 0 paragraphStyle.paragraphSpacingBefore = 0 paragraphStyle.headIndent = 0 paragraphStyle.tailIndent = 0 paragraphStyle.alignment = textAlignment paragraphStyle.lineSpacing = lineSpacing completion?("", paragraphStyle) self.attributedText = NSAttributedString(string: text, attributes: [NSAttributedString.Key.font: font,NSAttributedString.Key.paragraphStyle: paragraphStyle]) } } /* 给label添加下方线条 */ extension UILabel { public convenience init(frame: CGRect?, text: String?, font: UIFont, color: UIColor, alignment: NSTextAlignment) { self.init() if frame != nil { self.frame = frame! } self.text = text self.font = font self.textColor = color self.textAlignment = alignment self.numberOfLines = 0 } public convenience init(frame: CGRect?, lineSpace: CGFloat, text: String, font: UIFont, color: UIColor, alignment: NSTextAlignment) { self.init() if frame != nil { self.frame = frame! } self.text = text self.font = font self.textColor = color self.textAlignment = alignment self.numberOfLines = 0 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .byCharWrapping paragraphStyle.firstLineHeadIndent = 0 paragraphStyle.paragraphSpacingBefore = 0 paragraphStyle.headIndent = 0 paragraphStyle.tailIndent = 0 paragraphStyle.alignment = alignment paragraphStyle.lineSpacing = lineSpace let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: paragraphStyle ] let attributeStr = NSAttributedString.init(string: text, attributes: attributes) self.attributedText = attributeStr } public func addBottomColorView(color: UIColor = NX.mainColor.withAlphaComponent(0.85), height: CGFloat = 7) { guard let str = self.text else { return } let width = str.stringWidth(font: self.font, size: CGSize(width: NXDevice.width, height: 50)) let view = UIView.init(frame: CGRect(x: 0, y: 0, width: width, height: height)) if let superView = self.superview { superView.addSubview(view) view.center = CGPoint(x: self.center.x, y: self.center.y + 10) superView.bringSubviewToFront(view) } } }
31.007143
165
0.573601
e83908849a355d8c27871a09f0307c30a96c5404
24,048
// // ExpandableLabel.swift // // Copyright (c) 2015 apploft. GmbH // // 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. typealias LineIndexTuple = (line: CTLine, index: Int) import UIKit /** * The delegate of ExpandableLabel. */ @objc public protocol ExpandableLabelDelegate: NSObjectProtocol { @objc func willExpandLabel(_ label: ExpandableLabel) @objc func didExpandLabel(_ label: ExpandableLabel) @objc func willCollapseLabel(_ label: ExpandableLabel) @objc func didCollapseLabel(_ label: ExpandableLabel) } /** * ExpandableLabel */ @objc open class ExpandableLabel: UILabel { public enum TextReplacementType { case character case word } /// The delegate of ExpandableLabel @objc weak open var delegate: ExpandableLabelDelegate? /// Animation duration for expanding/collapsing open var animationDuration: Double = 0.5 /// Set 'true' if the label should be collapsed or 'false' for expanded. @IBInspectable open var collapsed: Bool = true { didSet { super.attributedText = (collapsed) ? self.collapsedText : self.expandedText super.numberOfLines = (collapsed) ? self.collapsedNumberOfLines : 0 if let animationView = animationView { UIView.animate(withDuration: self.animationDuration) { animationView.layoutIfNeeded() } } } } /// Set 'true' if the label can be expanded or 'false' if not. /// The default value is 'true'. @IBInspectable open var shouldExpand: Bool = true /// Set 'true' if the label can be collapsed or 'false' if not. /// The default value is 'false'. @IBInspectable open var shouldCollapse: Bool = false /// Set the link name (and attributes) that is shown when collapsed. /// The default value is "More". Cannot be nil. @objc open var collapsedAttributedLink: NSAttributedString! { didSet { self.collapsedAttributedLink = collapsedAttributedLink.copyWithAddedFontAttribute(font) } } /// Set the link name (and attributes) that is shown when expanded. /// The default value is "Less". Can be nil. @objc open var expandedAttributedLink: NSAttributedString? /// Set the ellipsis that appears just after the text and before the link. /// The default value is "...". Can be nil. @objc open var ellipsis: NSAttributedString? { didSet { self.ellipsis = ellipsis?.copyWithAddedFontAttribute(font) } } /// Set a view to animate changes of the label collapsed state with. If this value is nil, no animation occurs. /// Usually you assign the superview of this label or a UIScrollView in which this label sits. /// Also don't forget to set the contentMode of this label to top to smoothly reveal the hidden lines. /// The default value is 'nil'. @objc open var animationView: UIView? open var textReplacementType: TextReplacementType = .word private var collapsedText: NSAttributedString? private var linkHighlighted: Bool = false private let touchSize = CGSize(width: 44, height: 44) private var linkRect: CGRect? private var collapsedNumberOfLines: NSInteger = 0 private var expandedLinkPosition: NSTextAlignment? private var collapsedLinkTextRange: NSRange? private var expandedLinkTextRange: NSRange? open override var numberOfLines: NSInteger { didSet { collapsedNumberOfLines = numberOfLines } } @objc public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } @objc public override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } @objc public init() { super.init(frame: .zero) } open override var text: String? { set(text) { if let text = text { self.attributedText = NSAttributedString(string: text) } else { self.attributedText = nil } } get { return self.attributedText?.string } } open private(set) var expandedText: NSAttributedString? open override var attributedText: NSAttributedString? { set(attributedText) { if let attributedText = attributedText?.copyWithAddedFontAttribute(font).copyWithParagraphAttribute(font), attributedText.length > 0 { self.collapsedText = getCollapsedText(for: attributedText, link: (linkHighlighted) ? collapsedAttributedLink.copyWithHighlightedColor() : self.collapsedAttributedLink) self.expandedText = getExpandedText(for: attributedText, link: (linkHighlighted) ? expandedAttributedLink?.copyWithHighlightedColor() : self.expandedAttributedLink) super.attributedText = (self.collapsed) ? self.collapsedText : self.expandedText } else { self.expandedText = nil self.collapsedText = nil super.attributedText = nil } } get { return super.attributedText } } open func setLessLinkWith(lessLink: String, attributes: [NSAttributedString.Key: AnyObject], position: NSTextAlignment?) { var alignedattributes = attributes if let pos = position { expandedLinkPosition = pos let titleParagraphStyle = NSMutableParagraphStyle() titleParagraphStyle.alignment = pos alignedattributes[.paragraphStyle] = titleParagraphStyle } expandedAttributedLink = NSMutableAttributedString(string: lessLink, attributes: alignedattributes) } } // MARK: - Touch Handling extension ExpandableLabel { open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { setLinkHighlighted(touches, event: event, highlighted: true) } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { setLinkHighlighted(touches, event: event, highlighted: false) } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } if !collapsed { guard let range = self.expandedLinkTextRange else { return } if shouldCollapse && check(touch: touch, isInRange: range) { delegate?.willCollapseLabel(self) collapsed = true delegate?.didCollapseLabel(self) linkHighlighted = isHighlighted setNeedsDisplay() } } else { if shouldExpand && setLinkHighlighted(touches, event: event, highlighted: false) { delegate?.willExpandLabel(self) collapsed = false delegate?.didExpandLabel(self) } } } open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { setLinkHighlighted(touches, event: event, highlighted: false) } } // MARK: Privates extension ExpandableLabel { private func commonInit() { isUserInteractionEnabled = true lineBreakMode = .byClipping collapsedNumberOfLines = numberOfLines expandedAttributedLink = nil collapsedAttributedLink = NSAttributedString(string: "More", attributes: [.font: UIFont.boldSystemFont(ofSize: font.pointSize)]) ellipsis = NSAttributedString(string: "...") } private func textReplaceWordWithLink(_ lineIndex: LineIndexTuple, text: NSAttributedString, linkName: NSAttributedString) -> NSAttributedString { let lineText = text.text(for: lineIndex.line) var lineTextWithLink = lineText (lineText.string as NSString).enumerateSubstrings(in: NSRange(location: 0, length: lineText.length), options: [.byWords, .reverse]) { (word, subRange, enclosingRange, stop) -> Void in let lineTextWithLastWordRemoved = lineText.attributedSubstring(from: NSRange(location: 0, length: subRange.location)) let lineTextWithAddedLink = NSMutableAttributedString(attributedString: lineTextWithLastWordRemoved) if let ellipsis = self.ellipsis { lineTextWithAddedLink.append(ellipsis) lineTextWithAddedLink.append(NSAttributedString(string: " ", attributes: [.font: self.font])) } lineTextWithAddedLink.append(linkName) let fits = self.textFitsWidth(lineTextWithAddedLink) if fits { lineTextWithLink = lineTextWithAddedLink let lineTextWithLastWordRemovedRect = lineTextWithLastWordRemoved.boundingRect(for: self.frame.size.width) let wordRect = linkName.boundingRect(for: self.frame.size.width) let width = lineTextWithLastWordRemoved.string == "" ? self.frame.width : wordRect.size.width self.linkRect = CGRect(x: lineTextWithLastWordRemovedRect.size.width, y: self.font.lineHeight * CGFloat(lineIndex.index), width: width, height: wordRect.size.height) stop.pointee = true } } return lineTextWithLink } private func textReplaceWithLink(_ lineIndex: LineIndexTuple, text: NSAttributedString, linkName: NSAttributedString) -> NSAttributedString { let lineText = text.text(for: lineIndex.line) let lineTextTrimmedNewLines = NSMutableAttributedString() lineTextTrimmedNewLines.append(lineText) let nsString = lineTextTrimmedNewLines.string as NSString let range = nsString.rangeOfCharacter(from: CharacterSet.newlines) if range.length > 0 { lineTextTrimmedNewLines.replaceCharacters(in: range, with: "") } let linkText = NSMutableAttributedString() if let ellipsis = self.ellipsis { linkText.append(ellipsis) linkText.append(NSAttributedString(string: " ", attributes: [.font: self.font])) } linkText.append(linkName) let lengthDifference = lineTextTrimmedNewLines.string.composedCount - linkText.string.composedCount let truncatedString = lineTextTrimmedNewLines.attributedSubstring( from: NSMakeRange(0, lengthDifference >= 0 ? lengthDifference : lineTextTrimmedNewLines.string.composedCount)) let lineTextWithLink = NSMutableAttributedString(attributedString: truncatedString) lineTextWithLink.append(linkText) return lineTextWithLink } private func getExpandedText(for text: NSAttributedString?, link: NSAttributedString?) -> NSAttributedString? { guard let text = text else { return nil } let expandedText = NSMutableAttributedString() expandedText.append(text) if let link = link, textWillBeTruncated(expandedText) { let spaceOrNewLine = expandedLinkPosition == nil ? " " : "\n" expandedText.append(NSAttributedString(string: "\(spaceOrNewLine)")) expandedText.append(NSMutableAttributedString(string: "\(link.string)", attributes: link.attributes(at: 0, effectiveRange: nil)).copyWithAddedFontAttribute(font)) expandedLinkTextRange = NSMakeRange(expandedText.length - link.length, link.length) } return expandedText } private func getCollapsedText(for text: NSAttributedString?, link: NSAttributedString) -> NSAttributedString? { guard let text = text else { return nil } let lines = text.lines(for: frame.size.width) if collapsedNumberOfLines > 0 && collapsedNumberOfLines < lines.count { let lastLineRef = lines[collapsedNumberOfLines-1] as CTLine var lineIndex: LineIndexTuple? var modifiedLastLineText: NSAttributedString? if self.textReplacementType == .word { lineIndex = findLineWithWords(lastLine: lastLineRef, text: text, lines: lines) if let lineIndex = lineIndex { modifiedLastLineText = textReplaceWordWithLink(lineIndex, text: text, linkName: link) } } else { lineIndex = (lastLineRef, collapsedNumberOfLines - 1) if let lineIndex = lineIndex { modifiedLastLineText = textReplaceWithLink(lineIndex, text: text, linkName: link) } } if let lineIndex = lineIndex, let modifiedLastLineText = modifiedLastLineText { let collapsedLines = NSMutableAttributedString() for index in 0..<lineIndex.index { collapsedLines.append(text.text(for:lines[index])) } collapsedLines.append(modifiedLastLineText) collapsedLinkTextRange = NSRange(location: collapsedLines.length - link.length, length: link.length) return collapsedLines } else { return nil } } return text } private func findLineWithWords(lastLine: CTLine, text: NSAttributedString, lines: [CTLine]) -> LineIndexTuple { var lastLineRef = lastLine var lastLineIndex = collapsedNumberOfLines - 1 var lineWords = spiltIntoWords(str: text.text(for: lastLineRef).string as NSString) while lineWords.count < 2 && lastLineIndex > 0 { lastLineIndex -= 1 lastLineRef = lines[lastLineIndex] as CTLine lineWords = spiltIntoWords(str: text.text(for: lastLineRef).string as NSString) } return (lastLineRef, lastLineIndex) } private func spiltIntoWords(str: NSString) -> [String] { var strings: [String] = [] str.enumerateSubstrings(in: NSRange(location: 0, length: str.length), options: [.byWords, .reverse]) { (word, subRange, enclosingRange, stop) -> Void in if let unwrappedWord = word { strings.append(unwrappedWord) } if strings.count > 1 { stop.pointee = true } } return strings } private func textFitsWidth(_ text: NSAttributedString) -> Bool { return (text.boundingRect(for: frame.size.width).size.height <= font.lineHeight) as Bool } private func textWillBeTruncated(_ text: NSAttributedString) -> Bool { let lines = text.lines(for: frame.size.width) return collapsedNumberOfLines > 0 && collapsedNumberOfLines < lines.count } private func textClicked(touches: Set<UITouch>?, event: UIEvent?) -> Bool { let touch = event?.allTouches?.first let location = touch?.location(in: self) let textRect = self.attributedText?.boundingRect(for: self.frame.width) if let location = location, let textRect = textRect { let finger = CGRect(x: location.x-touchSize.width/2, y: location.y-touchSize.height/2, width: touchSize.width, height: touchSize.height) if finger.intersects(textRect) { return true } } return false } @discardableResult private func setLinkHighlighted(_ touches: Set<UITouch>?, event: UIEvent?, highlighted: Bool) -> Bool { guard let touch = touches?.first else { return false } guard let range = self.collapsedLinkTextRange else { return false } if collapsed && check(touch: touch, isInRange: range) { linkHighlighted = highlighted setNeedsDisplay() return true } return false } } // MARK: Convenience Methods private extension NSAttributedString { func hasFontAttribute() -> Bool { guard !self.string.isEmpty else { return false } let font = self.attribute(.font, at: 0, effectiveRange: nil) as? UIFont return font != nil } func copyWithParagraphAttribute(_ font: UIFont) -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = 1.05 paragraphStyle.alignment = .left paragraphStyle.lineSpacing = 0.0 paragraphStyle.minimumLineHeight = font.lineHeight paragraphStyle.maximumLineHeight = font.lineHeight let copy = NSMutableAttributedString(attributedString: self) let range = NSRange(location: 0, length: copy.length) copy.addAttribute(.paragraphStyle, value: paragraphStyle, range: range) copy.addAttribute(.baselineOffset, value: font.pointSize * 0.08, range: range) return copy } func copyWithAddedFontAttribute(_ font: UIFont) -> NSAttributedString { if !hasFontAttribute() { let copy = NSMutableAttributedString(attributedString: self) copy.addAttribute(.font, value: font, range: NSRange(location: 0, length: copy.length)) return copy } return self.copy() as! NSAttributedString } func copyWithHighlightedColor() -> NSAttributedString { let alphaComponent = CGFloat(0.5) let baseColor: UIColor = (self.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor)?.withAlphaComponent(alphaComponent) ?? UIColor.black.withAlphaComponent(alphaComponent) let highlightedCopy = NSMutableAttributedString(attributedString: self) let range = NSRange(location: 0, length: highlightedCopy.length) highlightedCopy.removeAttribute(.foregroundColor, range: range) highlightedCopy.addAttribute(.foregroundColor, value: baseColor, range: range) return highlightedCopy } func lines(for width: CGFloat) -> [CTLine] { let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude)) let frameSetterRef: CTFramesetter = CTFramesetterCreateWithAttributedString(self as CFAttributedString) let frameRef: CTFrame = CTFramesetterCreateFrame(frameSetterRef, CFRange(location: 0, length: 0), path.cgPath, nil) let linesNS: NSArray = CTFrameGetLines(frameRef) let linesAO: [AnyObject] = linesNS as [AnyObject] let lines: [CTLine] = linesAO as! [CTLine] return lines } func text(for lineRef: CTLine) -> NSAttributedString { let lineRangeRef: CFRange = CTLineGetStringRange(lineRef) let range: NSRange = NSRange(location: lineRangeRef.location, length: lineRangeRef.length) return self.attributedSubstring(from: range) } func boundingRect(for width: CGFloat) -> CGRect { return self.boundingRect(with: CGSize(width: width, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) } } extension String { var composedCount : Int { var count = 0 enumerateSubstrings(in: startIndex..<endIndex, options: .byComposedCharacterSequences) { _,_,_,_ in count += 1 } return count } } extension UILabel { open func check(touch: UITouch, isInRange targetRange: NSRange) -> Bool { let touchPoint = touch.location(in: self) let index = characterIndex(at: touchPoint) return NSLocationInRange(index, targetRange) } private func characterIndex(at touchPoint: CGPoint) -> Int { guard let attributedString = attributedText else { return NSNotFound } if !bounds.contains(touchPoint) { return NSNotFound } let textRect = self.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines) if !textRect.contains(touchPoint) { return NSNotFound } var point = touchPoint // Offset tap coordinates by textRect origin to make them relative to the origin of frame point = CGPoint(x: point.x - textRect.origin.x, y: point.y - textRect.origin.y) // Convert tap coordinates (start at top left) to CT coordinates (start at bottom left) point = CGPoint(x: point.x, y: textRect.size.height - point.y) let framesetter = CTFramesetterCreateWithAttributedString(attributedString) let suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, attributedString.length), nil, CGSize(width: textRect.width, height: CGFloat.greatestFiniteMagnitude), nil) let path = CGMutablePath() path.addRect(CGRect(x: 0, y: 0, width: suggestedSize.width, height: CGFloat(ceilf(Float(suggestedSize.height))))) let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributedString.length), path, nil) let lines = CTFrameGetLines(frame) let linesCount = numberOfLines > 0 ? min(numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines) if linesCount == 0 { return NSNotFound } var lineOrigins = [CGPoint](repeating: .zero, count: linesCount) CTFrameGetLineOrigins(frame, CFRangeMake(0, linesCount), &lineOrigins) for (idx, lineOrigin) in lineOrigins.enumerated() { var lineOrigin = lineOrigin let lineIndex = CFIndex(idx) let line = unsafeBitCast(CFArrayGetValueAtIndex(lines, lineIndex), to: CTLine.self) // Get bounding information of line var ascent: CGFloat = 0.0 var descent: CGFloat = 0.0 var leading: CGFloat = 0.0 let width = CGFloat(CTLineGetTypographicBounds(line, &ascent, &descent, &leading)) let yMin = CGFloat(floor(lineOrigin.y - descent)) let yMax = CGFloat(ceil(lineOrigin.y + ascent)) // Apply penOffset using flushFactor for horizontal alignment to set lineOrigin since this is the horizontal offset from drawFramesetter let flushFactor = flushFactorForTextAlignment(textAlignment: textAlignment) let penOffset = CGFloat(CTLineGetPenOffsetForFlush(line, flushFactor, Double(textRect.size.width))) lineOrigin.x = penOffset // Check if we've already passed the line if point.y > yMax { return NSNotFound } // Check if the point is within this line vertically if point.y >= yMin { // Check if the point is within this line horizontally if point.x >= lineOrigin.x && point.x <= lineOrigin.x + width { // Convert CT coordinates to line-relative coordinates let relativePoint = CGPoint(x: point.x - lineOrigin.x, y: point.y - lineOrigin.y) return Int(CTLineGetStringIndexForPosition(line, relativePoint)) } } } return NSNotFound } private func flushFactorForTextAlignment(textAlignment: NSTextAlignment) -> CGFloat { switch textAlignment { case .center: return 0.5 case .right: return 1.0 case .left, .natural, .justified: return 0.0 } } }
43.174147
208
0.65677
f96482568616e3e8e2f14465a106fc3fa3d37140
15,398
// Copyright (c) 2020 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 XCLogParser struct LogParser { enum NoteType: String { case main case target case step } enum BuildCategoryType: String { case noop case incremental case clean } struct BuildCategorisation { let buildCategory: BuildCategoryType let buildCompiledCount: Int let targetsCategory: [String: BuildCategoryType] let targetsCompiledCount: [String: Int] } static func parseFromURL( _ url: URL, machineName: String, projectName: String, userId: String, userIdSHA256: String, isCI: Bool ) throws -> BuildMetrics { let activityLog = try ActivityParser().parseActivityLogInURL(url, redacted: true, withoutBuildSpecificInformation: true) let buildSteps = try ParserBuildSteps(machineName: machineName, omitWarningsDetails: false).parse(activityLog: activityLog).flatten() return toBuildMetrics( buildSteps, projectName: projectName, userId: userId, userIdSHA256: userIdSHA256, isCI: isCI ) } private static func toBuildMetrics( _ buildSteps: [BuildStep], projectName: String, userId: String, userIdSHA256: String, isCI: Bool ) -> BuildMetrics { var build = Build().withBuildStep(buildStep: buildSteps[0]) build.projectName = projectName build.userid = userId build.userid256 = userIdSHA256 build.wasSuspended = false build.tag = "" build.isCi = isCI let targetBuildSteps = buildSteps.filter { $0.type == .target } var targets = targetBuildSteps.map { step in return Target().withBuildStep(buildStep: step) } let steps = buildSteps.filter { $0.type == .detail && $0.detailStepType != .swiftAggregatedCompilation } let detailsBuild = steps.filter { $0.detailStepType != .swiftCompilation }.map { return Step().withBuildStep(buildStep: $0, buildIdentifier: buildSteps[0].identifier, targetIdentifier: $0.parentIdentifier) } var stepsBuild = detailsBuild + parseSwiftSteps(buildSteps: buildSteps, targets: targetBuildSteps, steps: steps) // Categorize build based on all build steps in the build log except non-compilation or linking phases. // Some tasks are ran by Xcode always, even on noop builds, so we want to filter them out and only // consider the compilation and linking steps for our categorisation. let buildCategorisation = parseBuildCategory( with: targets, steps: stepsBuild.filter { $0.type != "other" && $0.type != "scriptExecution" && $0.type != "copySwiftLibs" } ) targets = targets.map { target -> Target in let category = buildCategorisation.targetsCategory[target.id ?? ""]?.rawValue let count = buildCategorisation.targetsCompiledCount[target.id ?? ""] if let category = category, let count = count { return target .withCategory(category) .withCompiledCount(Int32(count)) } else if let category = category { return target .withCategory(category) } else if let count = count { return target .withCompiledCount(Int32(count)) } return target } // TODO: pass the HardwareFactsFetcherImplementation().sleepTime from the client build = build .withCategory(buildCategorisation.buildCategory.rawValue) .withCompiledCount(Int32(buildCategorisation.buildCompiledCount)) stepsBuild.sort { if $0.targetIdentifier == $1.targetIdentifier { return $0.startTimestamp > $1.startTimestamp } return $0.targetIdentifier > $1.targetIdentifier } let warnings = parseWarnings(buildSteps: buildSteps, targets: targetBuildSteps, steps: steps) let errors = parseErrors(buildSteps: buildSteps, targets: targetBuildSteps, steps: steps) let notes = parseNotes(buildSteps: buildSteps, targets: targetBuildSteps, steps: steps) let functionBuildTimes = steps.compactMap { step in step.swiftFunctionTimes?.map { SwiftFunction() .withBuildIdentifier(build.id ?? "") .withStepIdentifier(step.identifier) .withFunctionTime($0) } }.joined() let typeChecks = steps.compactMap { step in step.swiftTypeCheckTimes?.map { SwiftTypeChecks() .withBuildIdentifier(build.id ?? "") .withStepIdentifier(step.identifier) .withTypeCheck($0) } }.joined() return BuildMetrics(build: build, targets: targets, steps: stepsBuild, warnings: warnings, errors: errors, notes: notes, swiftFunctions: Array(functionBuildTimes), swiftTypeChecks: Array(typeChecks), host: fakeHost(buildIdentifier: build.id ?? ""), // TODO xcodeVersion: nil, // TODO buildMetadata: nil) // TODO .addDayToMetrics() } private static func parseSwiftSteps( buildSteps: [BuildStep], targets: [BuildStep], steps: [BuildStep] ) -> [Step] { let buildIdentifier = buildSteps[0].identifier let swiftAggregatedSteps = buildSteps.filter { $0.type == .detail && $0.detailStepType == .swiftAggregatedCompilation } let swiftAggregatedStepsIds = swiftAggregatedSteps.reduce([String: String]()) { dictionary, step -> [String: String] in return dictionary.merging(zip([step.identifier], [step.parentIdentifier])) { (_, new) in new } } let targetsIds = targets.reduce([String: String]()) { dictionary, target -> [String: String] in return dictionary.merging(zip([target.identifier], [target.identifier])) { (_, new) in new } } return steps .filter { $0.detailStepType == .swiftCompilation } .compactMap { step -> Step? in var targetId = step.parentIdentifier // A swift step can have either a target as a parent or a swiftAggregatedCompilation if targetsIds[step.parentIdentifier] == nil { // If the parent is a swiftAggregatedCompilation we use the target id from that parent step guard let swiftTargetId = swiftAggregatedStepsIds[step.parentIdentifier] else { return nil } targetId = swiftTargetId } return Step().withBuildStep(buildStep: step, buildIdentifier: buildIdentifier, targetIdentifier: targetId) } } private static func parseBuildCategory(with targets: [Target], steps: [Step]) -> BuildCategorisation { var targetsCompiledCount = [String: Int]() // Initialize map with all targets identifiers. for target in targets { targetsCompiledCount[target.id ?? ""] = 0 } // Compute how many steps were not fetched from cache for each target. for step in steps { if !step.fetchedFromCache { targetsCompiledCount[step.targetIdentifier, default: 0] += 1 } } // Compute how many steps in total were not fetched from cache. let buildCompiledCount = Array<Int>(targetsCompiledCount.values).reduce(0, +) // Classify each target based on how many steps were not fetched from cache and how many are actually present. var targetsCategory = [String: BuildCategoryType]() for (target, filesCompiledCount) in targetsCompiledCount { // If the number of steps not fetched from cache in 0, it was a noop build. // If the number of steps not fetched from cache is equal to the number of all steps in the target, it was a clean build. // If anything in between, it was an incremental build. // There's an edge case where some external run script phases don't have any files compiled and are classified // as noop, but we're fine with that since further down we classify a clean build if at least 50% of the targets // were built cleanly. switch filesCompiledCount { case 0: targetsCategory[target] = .noop case steps.filter { $0.targetIdentifier == target }.count: targetsCategory[target] = .clean default: targetsCategory[target] = .incremental } } // If all targets are noop, we categorise the build as noop. let isNoopBuild = Array<BuildCategoryType>(targetsCategory.values).allSatisfy { $0 == .noop } // If at least 50% of the targets are clean, we categorise the build as clean. let isCleanBuild = Array<BuildCategoryType>(targetsCategory.values).filter { $0 == .clean }.count > targets.count / 2 let buildCategory: BuildCategoryType if isCleanBuild { buildCategory = .clean } else if isNoopBuild { buildCategory = .noop } else { buildCategory = .incremental } return BuildCategorisation( buildCategory: buildCategory, buildCompiledCount: buildCompiledCount, targetsCategory: targetsCategory, targetsCompiledCount: targetsCompiledCount ) } private static func parseWarnings( buildSteps: [BuildStep], targets: [BuildStep], steps: [BuildStep] ) -> [BuildWarning] { let buildIdentifier = buildSteps[0].identifier let buildWarnings = buildSteps[0].warnings?.map { BuildWarning() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(buildIdentifier) .withParentType(NoteType.main.rawValue) .withNotice($0) } let targetWarnings = targets.compactMap { target in target.warnings?.map { BuildWarning() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(target.identifier) .withParentType(NoteType.target.rawValue) .withNotice($0) } }.joined() let stepsWarnings = steps.compactMap { step in step.warnings?.map { BuildWarning() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(step.identifier) .withParentType(NoteType.step.rawValue) .withNotice($0) } }.joined() return (buildWarnings ?? []) + targetWarnings + stepsWarnings } private static func parseErrors( buildSteps: [BuildStep], targets: [BuildStep], steps: [BuildStep] ) -> [BuildError] { let buildIdentifier = buildSteps[0].identifier let buildErrors = buildSteps[0].errors?.map { BuildError() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(buildIdentifier) .withParentType(NoteType.main.rawValue) .withNotice($0) } let targetErrors = targets.compactMap { target in target.errors?.map { BuildError() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(target.identifier) .withParentType(NoteType.target.rawValue) .withNotice($0) } }.joined() let stepsErrors = steps.compactMap { step in step.errors?.map { BuildError() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(step.identifier) .withParentType(NoteType.step.rawValue) .withNotice($0) } }.joined() return (buildErrors ?? []) + targetErrors + stepsErrors } private static func parseNotes( buildSteps: [BuildStep], targets: [BuildStep], steps: [BuildStep] ) -> [BuildNote] { let buildIdentifier = buildSteps[0].identifier let buildNotes = buildSteps[0].notes?.map { BuildNote() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(buildIdentifier) .withParentType(NoteType.main.rawValue) .withNotice($0) } let targetNotes = targets.compactMap { target in target.notes?.map { BuildNote() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(target.identifier) .withParentType(NoteType.target.rawValue) .withNotice($0) } }.joined() let stepsNotes = steps.compactMap { step in step.notes?.map { BuildNote() .withBuildIdentifier(buildIdentifier) .withParentIdentifier(step.identifier) .withParentType(NoteType.step.rawValue) .withNotice($0) } }.joined() return (buildNotes ?? []) + targetNotes + stepsNotes } private static func fakeHost(buildIdentifier: String) -> BuildHost { let host = BuildHost() host.buildIdentifier = buildIdentifier host.cpuCount = 2 host.cpuModel = "model" host.cpuSpeedGhz = 3.0 host.hostArchitecture = "x86" host.hostModel = "model" host.hostOs = "MacOS" host.hostOsFamily = "" host.hostOsVersion = "" host.isVirtual = false host.memoryFreeMb = 0.0 host.memoryTotalMb = 0.0 host.swapFreeMb = 0.0 host.swapTotalMb = 0.0 host.timezone = "CET" host.uptimeSeconds = 0 return host } }
40.203655
141
0.586894
91219f380f0abb76f70fe59f5f965d6f2603ef34
41,386
import UIKit import Mapbox import MapboxDirections import MapboxCoreNavigation import MapboxMobileEvents import Turf class ArrowFillPolyline: MGLPolylineFeature {} class ArrowStrokePolyline: ArrowFillPolyline {} class RouteMapViewController: UIViewController { var navigationView: NavigationView { return view as! NavigationView } var mapView: NavigationMapView { return navigationView.mapView } var reportButton: FloatingButton { return navigationView.reportButton } var topBannerContainerView: BannerContainerView { return navigationView.topBannerContainerView } var bottomBannerContainerView: BannerContainerView { return navigationView.bottomBannerContainerView } lazy var endOfRouteViewController: EndOfRouteViewController = { let storyboard = UIStoryboard(name: "Navigation", bundle: .mapboxNavigation) let viewController = storyboard.instantiateViewController(withIdentifier: "EndOfRouteViewController") as! EndOfRouteViewController return viewController }() private struct Actions { static let overview: Selector = #selector(RouteMapViewController.toggleOverview(_:)) static let mute: Selector = #selector(RouteMapViewController.toggleMute(_:)) static let feedback: Selector = #selector(RouteMapViewController.feedback(_:)) static let recenter: Selector = #selector(RouteMapViewController.recenter(_:)) } var route: Route { return navService.router.route } var previewInstructionsView: StepInstructionsView? var lastTimeUserRerouted: Date? private lazy var geocoder: CLGeocoder = CLGeocoder() var destination: Waypoint? var showsEndOfRoute: Bool = true var showsSpeedLimits: Bool = true { didSet { navigationView.speedLimitView.isAlwaysHidden = !showsSpeedLimits } } var detailedFeedbackEnabled: Bool = false var pendingCamera: MGLMapCamera? { guard let parent = parent as? NavigationViewController else { return nil } return parent.pendingCamera } var tiltedCamera: MGLMapCamera { get { let camera = mapView.camera camera.altitude = 1000 camera.pitch = 45 return camera } } var styleObservation: NSKeyValueObservation? weak var delegate: RouteMapViewControllerDelegate? var navService: NavigationService! { didSet { guard let destination = route.legs.last?.destination else { return } populateName(for: destination, populated: { self.destination = $0 }) } } var router: Router { return navService.router } let distanceFormatter = DistanceFormatter() var arrowCurrentStep: RouteStep? var isInOverviewMode = false { didSet { if isInOverviewMode { navigationView.overviewButton.isHidden = true navigationView.resumeButton.isHidden = false navigationView.wayNameView.isHidden = true mapView.logoView.isHidden = true } else { navigationView.overviewButton.isHidden = false navigationView.resumeButton.isHidden = true mapView.logoView.isHidden = false } } } var currentLegIndexMapped = 0 var currentStepIndexMapped = 0 /** A Boolean value that determines whether the map annotates the locations at which instructions are spoken for debugging purposes. */ var annotatesSpokenInstructions = false var overheadInsets: UIEdgeInsets { return UIEdgeInsets(top: topBannerContainerView.bounds.height, left: 20, bottom: bottomBannerContainerView.bounds.height, right: 20) } var routeLineTracksTraversal = false typealias LabelRoadNameCompletionHandler = (_ defaultRaodNameAssigned: Bool) -> Void var labelRoadNameCompletionHandler: (LabelRoadNameCompletionHandler)? /** A Boolean value that determines whether the map altitude should change based on internal conditions. */ var supressAutomaticAltitudeChanges: Bool = false convenience init(navigationService: NavigationService, delegate: RouteMapViewControllerDelegate? = nil, topBanner: ContainerViewController, bottomBanner: ContainerViewController) { self.init() self.navService = navigationService self.delegate = delegate automaticallyAdjustsScrollViewInsets = false let topContainer = navigationView.topBannerContainerView embed(topBanner, in: topContainer) { (parent, banner) -> [NSLayoutConstraint] in banner.view.translatesAutoresizingMaskIntoConstraints = false return banner.view.constraintsForPinning(to: self.navigationView.topBannerContainerView) } topContainer.backgroundColor = .clear let bottomContainer = navigationView.bottomBannerContainerView embed(bottomBanner, in: bottomContainer) { (parent, banner) -> [NSLayoutConstraint] in banner.view.translatesAutoresizingMaskIntoConstraints = false return banner.view.constraintsForPinning(to: self.navigationView.bottomBannerContainerView) } bottomContainer.backgroundColor = .clear view.bringSubviewToFront(topBannerContainerView) } override func loadView() { view = NavigationView(delegate: self) view.frame = parent?.view.bounds ?? UIScreen.main.bounds } override func viewDidLoad() { super.viewDidLoad() let mapView = self.mapView mapView.contentInset = contentInset(forOverviewing: false) view.layoutIfNeeded() mapView.tracksUserCourse = true styleObservation = mapView.observe(\.style, options: .new) { [weak self] (mapView, change) in guard change.newValue != nil else { return } self?.showRouteIfNeeded() mapView.localizeLabels() mapView.showsTraffic = false // FIXME: In case when building highlighting feature is enabled due to style changes and no info currently being stored // regarding building identification such highlighted building will disappear. } makeGestureRecognizersResetFrameRate() navigationView.overviewButton.addTarget(self, action: Actions.overview, for: .touchUpInside) navigationView.muteButton.addTarget(self, action: Actions.mute, for: .touchUpInside) navigationView.reportButton.addTarget(self, action: Actions.feedback, for: .touchUpInside) navigationView.resumeButton.addTarget(self, action: Actions.recenter, for: .touchUpInside) resumeNotifications() } deinit { suspendNotifications() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationView.muteButton.isSelected = NavigationSettings.shared.voiceMuted mapView.compassView.isHidden = true mapView.tracksUserCourse = true if let camera = pendingCamera { mapView.camera = camera } else if let location = router.location, location.course > 0 { mapView.updateCourseTracking(location: location, animated: false) } else if let coordinates = router.routeProgress.currentLegProgress.currentStep.shape?.coordinates, let firstCoordinate = coordinates.first, coordinates.count > 1 { let secondCoordinate = coordinates[1] let course = firstCoordinate.direction(to: secondCoordinate) let newLocation = CLLocation(coordinate: router.location?.coordinate ?? firstCoordinate, altitude: 0, horizontalAccuracy: 0, verticalAccuracy: 0, course: course, speed: 0, timestamp: Date()) mapView.updateCourseTracking(location: newLocation, animated: false) } else { mapView.setCamera(tiltedCamera, animated: false) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) annotatesSpokenInstructions = delegate?.mapViewControllerShouldAnnotateSpokenInstructions(self) ?? false showRouteIfNeeded() currentLegIndexMapped = router.routeProgress.legIndex currentStepIndexMapped = router.routeProgress.currentLegProgress.stepIndex } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) styleObservation = nil } func resumeNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) subscribeToKeyboardNotifications() } func suspendNotifications() { NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil) unsubscribeFromKeyboardNotifications() } func embed(_ child: UIViewController, in container: UIView, constrainedBy constraints: ((RouteMapViewController, UIViewController) -> [NSLayoutConstraint])?) { child.willMove(toParent: self) addChild(child) container.addSubview(child.view) if let childConstraints: [NSLayoutConstraint] = constraints?(self, child) { view.addConstraints(childConstraints) } child.didMove(toParent: self) } @objc func recenter(_ sender: AnyObject) { mapView.tracksUserCourse = true mapView.enableFrameByFrameCourseViewTracking(for: 3) isInOverviewMode = false mapView.updateCourseTracking(location: mapView.userLocationForCourseTracking) updateCameraAltitude(for: router.routeProgress) mapView.addArrow(route: router.route, legIndex: router.routeProgress.legIndex, stepIndex: router.routeProgress.currentLegProgress.stepIndex + 1) delegate?.mapViewController(self, didCenterOn: mapView.userLocationForCourseTracking!) } func center(on step: RouteStep, route: Route, legIndex: Int, stepIndex: Int, animated: Bool = true, completion: CompletionHandler? = nil) { mapView.enableFrameByFrameCourseViewTracking(for: 1) mapView.tracksUserCourse = false mapView.setCenter(step.maneuverLocation, zoomLevel: mapView.zoomLevel, direction: step.initialHeading!, animated: animated, completionHandler: completion) guard isViewLoaded && view.window != nil else { return } mapView.addArrow(route: router.routeProgress.route, legIndex: legIndex, stepIndex: stepIndex) } @objc func toggleOverview(_ sender: Any) { mapView.enableFrameByFrameCourseViewTracking(for: 3) if let shape = router.route.shape, let userLocation = router.location { mapView.setOverheadCameraView(from: userLocation, along: shape, for: contentInset(forOverviewing: true)) } isInOverviewMode = true } @objc func toggleMute(_ sender: UIButton) { sender.isSelected = !sender.isSelected let muted = sender.isSelected NavigationSettings.shared.voiceMuted = muted } @objc func feedback(_ sender: Any) { showFeedback() } func showFeedback(source: FeedbackSource = .user) { guard let parent = parent else { return } let feedbackViewController = FeedbackViewController(eventsManager: navService.eventsManager) feedbackViewController.detailedFeedbackEnabled = detailedFeedbackEnabled parent.present(feedbackViewController, animated: true, completion: nil) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) mapView.enableFrameByFrameCourseViewTracking(for: 3) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if (mapView.showsUserLocation && !mapView.tracksUserCourse) { // Don't move mapView content on rotation or when e.g. top banner expands. return } updateMapViewContentInsets() } func updateMapViewContentInsets(animated: Bool = false, completion: CompletionHandler? = nil) { mapView.setContentInset(contentInset(forOverviewing: isInOverviewMode), animated: animated, completionHandler: completion) mapView.setNeedsUpdateConstraints() } @objc func applicationWillEnterForeground(notification: NSNotification) { mapView.updateCourseTracking(location: router.location, animated: false) } func updateMapOverlays(for routeProgress: RouteProgress) { if routeProgress.currentLegProgress.followOnStep != nil { mapView.addArrow(route: route, legIndex: router.routeProgress.legIndex, stepIndex: router.routeProgress.currentLegProgress.stepIndex + 1) } else { mapView.removeArrow() } } func updateCameraAltitude(for routeProgress: RouteProgress, completion: CompletionHandler? = nil) { guard mapView.tracksUserCourse else { return } //only adjust when we are actively tracking user course let zoomOutAltitude = mapView.zoomedOutMotorwayAltitude let defaultAltitude = mapView.defaultAltitude let isLongRoad = routeProgress.distanceRemaining >= mapView.longManeuverDistance let currentStep = routeProgress.currentLegProgress.currentStep let upComingStep = routeProgress.currentLegProgress.upcomingStep //If the user is at the last turn maneuver, the map should zoom in to the default altitude. let currentInstruction = routeProgress.currentLegProgress.currentStepProgress.currentSpokenInstruction //If the user is on a motorway, not exiting, and their segment is sufficently long, the map should zoom out to the motorway altitude. //otherwise, zoom in if it's the last instruction on the step. let currentStepIsMotorway = currentStep.isMotorway let nextStepIsMotorway = upComingStep?.isMotorway ?? false if currentStepIsMotorway, nextStepIsMotorway, isLongRoad { setCamera(altitude: zoomOutAltitude) } else if currentInstruction == currentStep.lastInstruction { setCamera(altitude: defaultAltitude) } } private func setCamera(altitude: Double) { guard mapView.altitude != altitude else { return } mapView.altitude = altitude } /** Modifies the gesture recognizers to also update the map’s frame rate. */ func makeGestureRecognizersResetFrameRate() { for gestureRecognizer in mapView.gestureRecognizers ?? [] { gestureRecognizer.addTarget(self, action: #selector(resetFrameRate(_:))) } } @objc func resetFrameRate(_ sender: UIGestureRecognizer) { mapView.preferredFramesPerSecond = NavigationMapView.FrameIntervalOptions.defaultFramesPerSecond } func contentInset(forOverviewing overviewing: Bool) -> UIEdgeInsets { let instructionBannerHeight = topBannerContainerView.bounds.height let bottomBannerHeight = bottomBannerContainerView.bounds.height // Inset by the safe area to avoid notches. var insets = mapView.safeArea insets.top += instructionBannerHeight insets.bottom += bottomBannerHeight if overviewing { insets += NavigationMapView.courseViewMinimumInsets let routeLineWidths = MBRouteLineWidthByZoomLevel.compactMap { $0.value.constantValue as? Int } insets += UIEdgeInsets(floatLiteral: Double(routeLineWidths.max() ?? 0)) } else if mapView.tracksUserCourse { // Puck position calculation - position it just above the bottom of the content area. var contentFrame = mapView.bounds.inset(by: insets) // Avoid letting the puck go partially off-screen, and add a comfortable padding beyond that. let courseViewBounds = mapView.userCourseView.bounds // If it is not possible to position it right above the content area, center it at the remaining space. contentFrame = contentFrame.insetBy(dx: min(NavigationMapView.courseViewMinimumInsets.left + courseViewBounds.width / 2.0, contentFrame.width / 2.0), dy: min(NavigationMapView.courseViewMinimumInsets.top + courseViewBounds.height / 2.0, contentFrame.height / 2.0)) assert(!contentFrame.isInfinite) let y = contentFrame.maxY let height = mapView.bounds.height insets.top = height - insets.bottom - 2 * (height - insets.bottom - y) } return insets } // MARK: End Of Route func embedEndOfRoute() { let endOfRoute = endOfRouteViewController addChild(endOfRoute) navigationView.endOfRouteView = endOfRoute.view navigationView.constrainEndOfRoute() endOfRoute.didMove(toParent: self) endOfRoute.dismissHandler = { [weak self] (stars, comment) in guard let rating = self?.rating(for: stars) else { return } let feedback = EndOfRouteFeedback(rating: rating, comment: comment) self?.navService.endNavigation(feedback: feedback) self?.delegate?.mapViewControllerDidDismiss(self!, byCanceling: false) } } func unembedEndOfRoute() { let endOfRoute = endOfRouteViewController endOfRoute.willMove(toParent: nil) endOfRoute.removeFromParent() } func showEndOfRoute(duration: TimeInterval = 1.0, completion: ((Bool) -> Void)? = nil) { embedEndOfRoute() endOfRouteViewController.destination = destination navigationView.endOfRouteView?.isHidden = false view.layoutIfNeeded() //flush layout queue navigationView.endOfRouteHideConstraint?.isActive = false navigationView.endOfRouteShowConstraint?.isActive = true mapView.enableFrameByFrameCourseViewTracking(for: duration) mapView.setNeedsUpdateConstraints() let animate = { self.view.layoutIfNeeded() self.navigationView.floatingStackView.alpha = 0.0 } let noAnimation = { animate(); completion?(true) } guard duration > 0.0 else { return noAnimation() } navigationView.mapView.tracksUserCourse = false UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear], animations: animate, completion: completion) guard let height = navigationView.endOfRouteHeightConstraint?.constant else { return } let insets = UIEdgeInsets(top: topBannerContainerView.bounds.height, left: 20, bottom: height + 20, right: 20) if let shape = route.shape, let userLocation = navService.router.location?.coordinate, !shape.coordinates.isEmpty { let slicedLineString = shape.sliced(from: userLocation)! let line = MGLPolyline(slicedLineString) let camera = navigationView.mapView.cameraThatFitsShape(line, direction: navigationView.mapView.camera.heading, edgePadding: insets) camera.pitch = 0 camera.altitude = navigationView.mapView.camera.altitude navigationView.mapView.setCamera(camera, animated: true) } } fileprivate func rating(for stars: Int) -> Int { assert(stars >= 0 && stars <= 5) guard stars > 0 else { return MMEEventsManager.unrated } //zero stars means this was unrated. return (stars - 1) * 25 } fileprivate func populateName(for waypoint: Waypoint, populated: @escaping (Waypoint) -> Void) { guard waypoint.name == nil else { return populated(waypoint) } let location = CLLocation(latitude: waypoint.coordinate.latitude, longitude: waypoint.coordinate.longitude) CLGeocoder().reverseGeocodeLocation(location) { (places, error) in guard let place = places?.first, let placeName = place.name, error == nil else { return } let named = Waypoint(coordinate: waypoint.coordinate, name: placeName) return populated(named) } } fileprivate func leg(containing step: RouteStep) -> RouteLeg? { return route.legs.first { $0.steps.contains(step) } } } // MARK: - NavigationComponent extension RouteMapViewController: NavigationComponent { func navigationService(_ service: NavigationService, didUpdate progress: RouteProgress, with location: CLLocation, rawLocation: CLLocation) { let route = progress.route let legIndex = progress.legIndex let stepIndex = progress.currentLegProgress.stepIndex mapView.updatePreferredFrameRate(for: progress) if currentLegIndexMapped != legIndex { mapView.showWaypoints(on: route, legIndex: legIndex) mapView.show([route], legIndex: legIndex) currentLegIndexMapped = legIndex } if currentStepIndexMapped != stepIndex { updateMapOverlays(for: progress) currentStepIndexMapped = stepIndex } if annotatesSpokenInstructions { mapView.showVoiceInstructionsOnMap(route: route) } if routeLineTracksTraversal { mapView.updateRoute(progress) } navigationView.speedLimitView.signStandard = progress.currentLegProgress.currentStep.speedLimitSignStandard navigationView.speedLimitView.speedLimit = progress.currentLegProgress.currentSpeedLimit } public func navigationService(_ service: NavigationService, didPassSpokenInstructionPoint instruction: SpokenInstruction, routeProgress: RouteProgress) { if !supressAutomaticAltitudeChanges { updateCameraAltitude(for: routeProgress) } } func navigationService(_ service: NavigationService, didRerouteAlong route: Route, at location: CLLocation?, proactive: Bool) { currentStepIndexMapped = 0 let route = router.route let stepIndex = router.routeProgress.currentLegProgress.stepIndex let legIndex = router.routeProgress.legIndex mapView.addArrow(route: route, legIndex: legIndex, stepIndex: stepIndex + 1) mapView.show([route], legIndex: legIndex) mapView.showWaypoints(on: route) if annotatesSpokenInstructions { mapView.showVoiceInstructionsOnMap(route: route) } if isInOverviewMode { if let shape = route.shape, let userLocation = router.location { mapView.setOverheadCameraView(from: userLocation, along: shape, for: contentInset(forOverviewing: true)) } } else { mapView.tracksUserCourse = true navigationView.wayNameView.isHidden = true } } func navigationService(_ service: NavigationService, didRefresh routeProgress: RouteProgress) { mapView.show([routeProgress.route], legIndex: routeProgress.legIndex) if routeLineTracksTraversal { mapView.updateRoute(routeProgress) } } } // MARK: - UIContentContainer extension RouteMapViewController { override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) { navigationView.endOfRouteHeightConstraint?.constant = container.preferredContentSize.height UIView.animate(withDuration: 0.3, animations: view.layoutIfNeeded) } } // MARK: - NavigationViewDelegate extension RouteMapViewController: NavigationViewDelegate { // MARK: NavigationViewDelegate func navigationView(_ view: NavigationView, didTapCancelButton: CancelButton) { delegate?.mapViewControllerDidDismiss(self, byCanceling: true) } // MARK: VisualInstructionDelegate func label(_ label: InstructionLabel, willPresent instruction: VisualInstruction, as presented: NSAttributedString) -> NSAttributedString? { return delegate?.label(label, willPresent: instruction, as: presented) } // MARK: NavigationMapViewCourseTrackingDelegate func navigationMapViewDidStartTrackingCourse(_ mapView: NavigationMapView) { navigationView.resumeButton.isHidden = true mapView.logoView.isHidden = false } func navigationMapViewDidStopTrackingCourse(_ mapView: NavigationMapView) { navigationView.resumeButton.isHidden = false navigationView.wayNameView.isHidden = true mapView.logoView.isHidden = true } //MARK: NavigationMapViewDelegate func navigationMapView(_ mapView: NavigationMapView, mainRouteStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? { return delegate?.navigationMapView(mapView, mainRouteStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, mainRouteCasingStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? { return delegate?.navigationMapView(mapView, mainRouteCasingStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, alternativeRouteStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? { return delegate?.navigationMapView(mapView, alternativeRouteStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, alternativeRouteCasingStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? { return delegate?.navigationMapView(mapView, alternativeRouteCasingStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, waypointStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? { return delegate?.navigationMapView(mapView, waypointStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, waypointSymbolStyleLayerWithIdentifier identifier: String, source: MGLSource) -> MGLStyleLayer? { return delegate?.navigationMapView(mapView, waypointSymbolStyleLayerWithIdentifier: identifier, source: source) } func navigationMapView(_ mapView: NavigationMapView, shapeFor waypoints: [Waypoint], legIndex: Int) -> MGLShape? { return delegate?.navigationMapView(mapView, shapeFor: waypoints, legIndex: legIndex) } func navigationMapView(_ mapView: NavigationMapView, shapeFor routes: [Route]) -> MGLShape? { return delegate?.navigationMapView(mapView, shapeFor: routes) } func navigationMapView(_ mapView: NavigationMapView, didSelect route: Route) { delegate?.navigationMapView(mapView, didSelect: route) } func navigationMapView(_ mapView: NavigationMapView, simplifiedShapeFor route: Route) -> MGLShape? { return delegate?.navigationMapView(mapView, simplifiedShapeFor: route) } func navigationMapViewUserAnchorPoint(_ mapView: NavigationMapView) -> CGPoint { //If the end of route component is showing, then put the anchor point slightly above the middle of the map if navigationView.endOfRouteView != nil, let show = navigationView.endOfRouteShowConstraint, show.isActive { return CGPoint(x: mapView.bounds.midX, y: (mapView.bounds.height * 0.4)) } //otherwise, ask the delegate or return .zero return delegate?.navigationMapViewUserAnchorPoint(mapView) ?? .zero } /** Updates the current road name label to reflect the road on which the user is currently traveling. - parameter location: The user’s current location. */ func labelCurrentRoad(at rawLocation: CLLocation, for snappedLocation: CLLocation? = nil) { guard navigationView.resumeButton.isHidden else { return } let roadName = delegate?.mapViewController(self, roadNameAt: rawLocation) guard roadName == nil else { if let roadName = roadName { navigationView.wayNameView.text = roadName navigationView.wayNameView.isHidden = roadName.isEmpty } return } // Avoid aggressively opting the developer into Mapbox services if they // haven’t provided an access token. guard let _ = MGLAccountManager.accessToken else { navigationView.wayNameView.isHidden = true return } let location = snappedLocation ?? rawLocation labelCurrentRoadFeature(at: location) if let labelRoadNameCompletionHandler = labelRoadNameCompletionHandler { labelRoadNameCompletionHandler(true) } } func labelCurrentRoadFeature(at location: CLLocation) { guard let style = mapView.style, let stepShape = router.routeProgress.currentLegProgress.currentStep.shape, !stepShape.coordinates.isEmpty else { return } let closestCoordinate = location.coordinate let roadLabelStyleLayerIdentifier = "\(identifierNamespace).roadLabels" var streetsSources: [MGLVectorTileSource] = style.sources.compactMap { $0 as? MGLVectorTileSource }.filter { $0.isMapboxStreets } // Add Mapbox Streets if the map does not already have it if streetsSources.isEmpty { let source = MGLVectorTileSource(identifier: "com.mapbox.MapboxStreets", configurationURL: URL(string: "mapbox://mapbox.mapbox-streets-v8")!) style.addSource(source) streetsSources.append(source) } if let mapboxStreetsSource = streetsSources.first, style.layer(withIdentifier: roadLabelStyleLayerIdentifier) == nil { let streetLabelLayer = MGLLineStyleLayer(identifier: roadLabelStyleLayerIdentifier, source: mapboxStreetsSource) streetLabelLayer.sourceLayerIdentifier = mapboxStreetsSource.roadLabelLayerIdentifier streetLabelLayer.lineOpacity = NSExpression(forConstantValue: 1) streetLabelLayer.lineWidth = NSExpression(forConstantValue: 20) streetLabelLayer.lineColor = NSExpression(forConstantValue: UIColor.white) style.insertLayer(streetLabelLayer, at: 0) } let userPuck = mapView.convert(closestCoordinate, toPointTo: mapView) let features = mapView.visibleFeatures(at: userPuck, styleLayerIdentifiers: Set([roadLabelStyleLayerIdentifier])) var smallestLabelDistance = Double.infinity var currentName: String? var currentShieldName: NSAttributedString? for feature in features { var allLines: [MGLPolyline] = [] if let line = feature as? MGLPolylineFeature { allLines.append(line) } else if let lines = feature as? MGLMultiPolylineFeature { allLines = lines.polylines } for line in allLines { guard line.pointCount > 0 else { continue } let featureCoordinates = Array(UnsafeBufferPointer(start: line.coordinates, count: Int(line.pointCount))) let featurePolyline = LineString(featureCoordinates) let slicedLine = stepShape.sliced(from: closestCoordinate)! let lookAheadDistance: CLLocationDistance = 10 guard let pointAheadFeature = featurePolyline.sliced(from: closestCoordinate)!.coordinateFromStart(distance: lookAheadDistance) else { continue } guard let pointAheadUser = slicedLine.coordinateFromStart(distance: lookAheadDistance) else { continue } guard let reversedPoint = LineString(featureCoordinates.reversed()).sliced(from: closestCoordinate)!.coordinateFromStart(distance: lookAheadDistance) else { continue } let distanceBetweenPointsAhead = pointAheadFeature.distance(to: pointAheadUser) let distanceBetweenReversedPoint = reversedPoint.distance(to: pointAheadUser) let minDistanceBetweenPoints = min(distanceBetweenPointsAhead, distanceBetweenReversedPoint) if minDistanceBetweenPoints < smallestLabelDistance { smallestLabelDistance = minDistanceBetweenPoints if let line = feature as? MGLPolylineFeature { let roadNameRecord = roadFeature(for: line) currentShieldName = roadNameRecord.shieldName currentName = roadNameRecord.roadName } else if let line = feature as? MGLMultiPolylineFeature { let roadNameRecord = roadFeature(for: line) currentShieldName = roadNameRecord.shieldName currentName = roadNameRecord.roadName } } } } let hasWayName = currentName != nil || currentShieldName != nil if smallestLabelDistance < 5 && hasWayName { if let currentShieldName = currentShieldName { navigationView.wayNameView.attributedText = currentShieldName } else if let currentName = currentName { navigationView.wayNameView.text = currentName } navigationView.wayNameView.isHidden = false } else { navigationView.wayNameView.isHidden = true } } private func roadFeature(for line: MGLFeature) -> (roadName: String?, shieldName: NSAttributedString?) { var currentShieldName: NSAttributedString?, currentRoadName: String? if let ref = line.attribute(forKey: "ref") as? String, let shield = line.attribute(forKey: "shield") as? String, let reflen = line.attribute(forKey: "reflen") as? Int { let textColor = roadShieldTextColor(line: line) ?? .black let imageName = "\(shield)-\(reflen)" currentShieldName = roadShieldAttributedText(for: ref, textColor: textColor, imageName: imageName) } if let roadName = line.attribute(forKey: "name") as? String { currentRoadName = roadName } if let compositeShieldImage = currentShieldName, let roadName = currentRoadName { let compositeShield = NSMutableAttributedString(string: " \(roadName)") compositeShield.insert(compositeShieldImage, at: 0) currentShieldName = compositeShield } return (roadName: currentRoadName, shieldName: currentShieldName) } func roadShieldTextColor(line: MGLFeature) -> UIColor? { guard let shield = line.attribute(forKey: "shield") as? String else { return nil } // shield_text_color is present in Mapbox Streets source v8 but not v7. guard let shieldTextColor = line.attribute(forKey: "shield_text_color") as? String else { let currentShield = HighwayShield.RoadType(rawValue: shield) return currentShield?.textColor } switch shieldTextColor { case "black": return .black case "blue": return .blue case "white": return .white case "yellow": return .yellow case "orange": return .orange default: return .black } } private func roadShieldAttributedText(for text: String, textColor: UIColor, imageName: String) -> NSAttributedString? { guard let image = mapView.style?.image(forName: imageName) else { return nil } let attachment = ShieldAttachment() attachment.image = image.withCenteredText(text, color: textColor, font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize), scale: UIScreen.main.scale) return NSAttributedString(attachment: attachment) } func showRouteIfNeeded() { guard isViewLoaded && view.window != nil else { return } guard !mapView.showsRoute else { return } mapView.show([router.route], legIndex: router.routeProgress.legIndex) mapView.showWaypoints(on: router.route, legIndex: router.routeProgress.legIndex) let currentLegProgress = router.routeProgress.currentLegProgress let nextStepIndex = currentLegProgress.stepIndex + 1 if nextStepIndex <= currentLegProgress.leg.steps.count { mapView.addArrow(route: router.route, legIndex: router.routeProgress.legIndex, stepIndex: nextStepIndex) } if annotatesSpokenInstructions { mapView.showVoiceInstructionsOnMap(route: router.route) } } } // MARK: - Keyboard Handling extension RouteMapViewController { fileprivate func subscribeToKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(RouteMapViewController.keyboardWillShow(notification:)), name:UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RouteMapViewController.keyboardWillHide(notification:)), name:UIResponder.keyboardWillHideNotification, object: nil) } fileprivate func unsubscribeFromKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } @objc fileprivate func keyboardWillShow(notification: NSNotification) { guard navigationView.endOfRouteView != nil else { return } guard let userInfo = notification.userInfo else { return } guard let curveValue = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int else { return } guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return } guard let keyBoardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } let keyboardHeight = keyBoardRect.size.height if #available(iOS 11.0, *) { navigationView.endOfRouteShowConstraint?.constant = -1 * (keyboardHeight - view.safeAreaInsets.bottom) //subtract the safe area, which is part of the keyboard's frame } else { navigationView.endOfRouteShowConstraint?.constant = -1 * keyboardHeight } let curve = UIView.AnimationCurve(rawValue: curveValue) ?? .easeIn let options = UIView.AnimationOptions(curve: curve) ?? .curveEaseIn UIView.animate(withDuration: duration, delay: 0, options: options, animations: view.layoutIfNeeded, completion: nil) } @objc fileprivate func keyboardWillHide(notification: NSNotification) { guard navigationView.endOfRouteView != nil else { return } guard let userInfo = notification.userInfo else { return } guard let curveValue = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int else { return } guard let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return } navigationView.endOfRouteShowConstraint?.constant = 0 let curve = UIView.AnimationCurve(rawValue: curveValue) ?? .easeOut let options = UIView.AnimationOptions(curve: curve) ?? .curveEaseOut UIView.animate(withDuration: duration, delay: 0, options: options, animations: view.layoutIfNeeded, completion: nil) } } internal extension UIView.AnimationOptions { init?(curve: UIView.AnimationCurve) { switch curve { case .easeIn: self = .curveEaseIn case .easeOut: self = .curveEaseOut case .easeInOut: self = .curveEaseInOut case .linear: self = .curveLinear default: // Some private UIViewAnimationCurve values unknown to the compiler can leak through notifications. return nil } } } protocol RouteMapViewControllerDelegate: NavigationMapViewDelegate, VisualInstructionDelegate { func mapViewControllerDidDismiss(_ mapViewController: RouteMapViewController, byCanceling canceled: Bool) func mapViewControllerShouldAnnotateSpokenInstructions(_ routeMapViewController: RouteMapViewController) -> Bool /** Called to allow the delegate to customize the contents of the road name label that is displayed towards the bottom of the map view. This method is called on each location update. By default, the label displays the name of the road the user is currently traveling on. - parameter mapViewController: The route map view controller that will display the road name. - parameter location: The user’s current location. - return: The road name to display in the label, or the empty string to hide the label, or nil to query the map’s vector tiles for the road name. */ func mapViewController(_ mapViewController: RouteMapViewController, roadNameAt location: CLLocation) -> String? func mapViewController(_ mapViewController: RouteMapViewController, didCenterOn location: CLLocation) }
45.629548
202
0.691683
76bab154f18efa9773db459b3b559328826396af
1,872
// // Solution.swift // Problem 34 // // Created by sebastien FOCK CHOW THO on 2019-06-28. // Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved. // import Foundation extension String { func isPalindrome() -> Bool { let mid = self.count / 2 return String(self.prefix(mid)) == String(self.suffix(mid).reversed()) } func findLargestPartWithSymetry() -> [(String, Int)] { var copy = self var reversed = String(self.reversed()) var index = 0 while !copy.isEmpty { if copy.isPalindrome() && reversed.isPalindrome() { return [(copy, index), (reversed, 0)] } if copy.isPalindrome() { return [(copy, index)] } if reversed.isPalindrome() { return [(reversed, 0)] } _ = copy.removeFirst() _ = reversed.removeFirst() index += 1 } return [] } func findPalindrome() -> String { let candidates = self.findLargestPartWithSymetry() return candidates.map{ buildPalindrome(base: self, part: $0) }.sorted{ $0 < $1 }.first ?? "" } } func buildPalindrome(base: String, part: (value: String, index: Int)) -> String { var result = base if part.index == 0 { let boundary = part.value.count % 2 == 0 ? part.value.count - 1 : part.value.count for i in boundary..<base.count { result.insert(base[base.index(base.startIndex, offsetBy: i)], at: result.startIndex) } } else { var i = part.index while i >= 0 { result.insert(base[base.index(base.startIndex, offsetBy: i)], at: result.endIndex) i -= 1 } } return result }
26.742857
100
0.518697
db88b410f8b35290838f9fb71ef0fef1ae152231
1,077
// MIT license. Copyright (c) 2019 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class ButtonsViewController: FormViewController { override func populate(_ builder: FormBuilder) { builder.navigationTitle = "Buttons" builder.toolbarMode = .none builder += SectionHeaderTitleFormItem().title("Table Row Buttons") builder += button0 builder += button1 builder += button2 } lazy var button0: ButtonFormItem = { let instance = ButtonFormItem() instance.title = "Button 0" instance.action = { [weak self] in self?.form_simpleAlert("Button 0", "Button clicked") } return instance }() lazy var button1: ButtonFormItem = { let instance = ButtonFormItem() instance.title = "Button 1" instance.action = { [weak self] in self?.form_simpleAlert("Button 1", "Button clicked") } return instance }() lazy var button2: ButtonFormItem = { let instance = ButtonFormItem() instance.title = "Button 2" instance.action = { [weak self] in self?.form_simpleAlert("Button 2", "Button clicked") } return instance }() }
25.642857
68
0.705664
870fcc872de61f15094180e11870362e2a742915
554
// Copyright © 2017 Stefan van den Oord. All rights reserved. import ReSwift struct TestState: StateType { let someString: String let someFloat: Float let numbers: [Int] let maybeInt: Int? let sections: [TestSectionModel] init(someString: String, someFloat: Float, numbers: [Int], maybeInt: Int? = nil, sections: [TestSectionModel] = []) { self.someString = someString self.someFloat = someFloat self.numbers = numbers self.maybeInt = maybeInt self.sections = sections } }
26.380952
67
0.648014
387034df93d3f048efd6a512fc6a25efb768319f
3,423
/* * Copyright 2019, Undefined Labs * * 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. */ @testable import OpenTelemetryApi import XCTest final class SpanIdTests: XCTestCase { let firstBytes: [UInt8] = [0, 0, 0, 0, 0, 0, 0, UInt8(ascii: "a")] let secondBytes: [UInt8] = [0xFF, 0, 0, 0, 0, 0, 0, UInt8(ascii: "A")] var first: SpanId! var second: SpanId! override func setUp() { first = SpanId(fromBytes: firstBytes) second = SpanId(fromBytes: secondBytes) } func testIsValid() { XCTAssertFalse(SpanId.invalid.isValid) XCTAssertTrue(first.isValid) XCTAssertTrue(second.isValid) } func testFromHexString() { XCTAssertEqual(SpanId(fromHexString: "0000000000000000"), SpanId.invalid) XCTAssertEqual(SpanId(fromHexString: "0000000000000061"), first) XCTAssertEqual(SpanId(fromHexString: "ff00000000000041"), second) } func testFromHexString_WithOffset() { XCTAssertEqual(SpanId(fromHexString: "XX0000000000000000AA", withOffset: 2), SpanId.invalid) XCTAssertEqual(SpanId(fromHexString: "YY0000000000000061BB", withOffset: 2), first) XCTAssertEqual(SpanId(fromHexString: "ZZff00000000000041CC", withOffset: 2), second) } func testToHexString() { XCTAssertEqual(SpanId.invalid.hexString, "0000000000000000") XCTAssertEqual(first.hexString, "0000000000000061") XCTAssertEqual(second.hexString, "ff00000000000041") } func testSpanId_CompareTo() { XCTAssertLessThan(first, second) XCTAssertGreaterThan(second, first) XCTAssertEqual(first, SpanId(fromBytes: firstBytes)) } func testTraceId_EqualsAndHashCode() { XCTAssertEqual(SpanId.invalid, SpanId.invalid) XCTAssertNotEqual(SpanId.invalid, first) XCTAssertNotEqual(SpanId.invalid, SpanId(fromBytes: firstBytes)) XCTAssertNotEqual(SpanId.invalid, second) XCTAssertNotEqual(SpanId.invalid, SpanId(fromBytes: secondBytes)) XCTAssertEqual(first, SpanId(fromBytes: firstBytes)) XCTAssertNotEqual(first, second) XCTAssertNotEqual(first, SpanId(fromBytes: secondBytes)) XCTAssertEqual(second, SpanId(fromBytes: secondBytes)) } func testTraceId_ToString() { XCTAssertTrue(SpanId.invalid.description.contains("0000000000000000")) XCTAssertTrue(first.description.contains("0000000000000061")) XCTAssertTrue(second.description.contains("ff00000000000041")) } static var allTests = [ ("testIsValid", testIsValid), ("testFromHexString", testFromHexString), ("testToHexString", testToHexString), ("testToHexString", testToHexString), ("testSpanId_CompareTo", testSpanId_CompareTo), ("testTraceId_EqualsAndHashCode", testTraceId_EqualsAndHashCode), ("testTraceId_ToString", testTraceId_ToString), ] }
38.460674
100
0.704061
2f550bc78f25edc237f64091eaf09c474552cbcc
4,005
// // SendTabViewController.swift // RaccoonWallet // // Created by Taizo Kusuda on 2018/09/02. // Copyright © 2018年 T TECH, LIMITED LIABILITY CO. All rights reserved. // import UIKit import NVActivityIndicatorView class SendTabViewController : BaseViewController { var presenter: SendTabPresentation! { didSet { basePresenter = presenter } } @IBOutlet weak var destinationHeadline: UILabel! @IBOutlet weak var destination: UITextField! @IBOutlet weak var paste: UIButton! @IBOutlet weak var clear: UIButton! @IBOutlet weak var userInputs: UIStackView! @IBOutlet weak var ok: PrimaryButton! //@IBOutlet weak var loading: NVActivityIndicatorView! @IBOutlet weak var scrollView: UIScrollView! var loading: FullScreenLoadingView! override func setup() { super.setup() destinationHeadline.text = R.string.localizable.send_destination() destination.placeholder = R.string.localizable.send_input_address() loading = createFullScreenLoadingView() //loading.setup() } override func keyboardWillShow(keyboardFrame: CGRect, duration: TimeInterval) { let convertedKeyboardFrame = scrollView.convert(keyboardFrame, from: nil) let targetViewFrame = scrollView.convert(ok.frame, from: ok.superview) let offsetY: CGFloat = targetViewFrame.maxY - convertedKeyboardFrame.minY if offsetY < 0 { return } scrollView.setOffsetY(offsetY, duration: duration) } override func keyboardWillHide() { scrollView.clearOffset() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onChangedDestination(_ sender: Any) { if let text = destination.text { presenter.didChangeDestination(text) } } @IBAction func onEndedDestination(_ sender: Any) { destination.resignFirstResponder() } @IBAction func onTouchedClear(_ sender: Any) { presenter.didClickClear() } @IBAction func onTouchedPaste(_ sender: Any) { presenter.didClickPaste() } @IBAction func onTouchedOk(_ sender: Any) { presenter.didClickOk() } } extension SendTabViewController : SendTabView { func setDestination(_ destination: String) { self.destination.text = destination presenter.didChangeDestination(destination) } func showPaste() { paste.isHidden = false clear.isHidden = true } func showClear() { paste.isHidden = true clear.isHidden = false } func showOk() { loading.stopLoading() //ok.isHidden = false //loading.isHidden = true //loading.stopAnimating() //userInputs.isUserInteractionEnabled = true } func showLoading() { loading.startLoading() //ok.isHidden = true //loading.isHidden = false //loading.startAnimating() //userInputs.isUserInteractionEnabled = false } func showNewbieDialog() { let dialog = MessageDialogRouter.assembleModule( headline: R.string.localizable.send_newbie_caution_title(), messages: [R.string.localizable.send_newbie_caution_message()]) { [weak self] _ in self?.presenter.didClickNewbieOk() } navigationController?.present(dialog, animated: true) } func showNotSetPinError() { let dialog = MessageDialogPreset.createErrorNotSetPin { result in if result == .ok { self.presenter.didClickGoPinSetting() } } navigationController?.present(dialog, animated: true) } func showNotSelectWalletError() { let dialog = MessageDialogPreset.createErrorNotSelectWallet { result in if result == .ok { self.presenter.didClickGoWalletSelect() } } navigationController?.present(dialog, animated: true) } }
29.021739
98
0.652185
eb60b93659c92b86beddea956a5f0301d236412b
5,225
// // Timer.swift // UIKitActions IOS // // Created by incetro on 2/19/18. // import UIKit // MARK: - UIBarButtonItem /// Extension that provides methods to add actions to bar button items extension UIBarButtonItem { /// Initializes a new item using the specified image and other properties /// - Parameters: /// - image: The images displayed on the bar are derived from this image. /// If this image is too large to fit on the bar, it is scaled to fit. /// Typically, the size of a toolbar and navigation bar image is 20 x 20 points. /// The alpha values in the source image are used to create the images—opaque values are ignored. /// - landscapeImagePhone: The style of the item. One of the constants defined in UIBarButtonItemStyle. nil by default /// - style: The style of the item. One of the constants defined in UIBarButtonItemStyle. (.Plain by default) /// - action: The action to be called when the button is tapped public convenience init<T: UIBarButtonItem>( image: UIImage?, landscapeImagePhone: UIImage? = nil, style: UIBarButtonItem.Style = .plain, action: @escaping (T) -> Void ) { let action = ParametizedAction(action: action) self.init(image: image, landscapeImagePhone: landscapeImagePhone, style: style, target: action, action: action.selector) retainAction(action, self) } /// Initializes a new item using the specified image and other properties /// - Parameters: /// - image: The images displayed on the bar are derived from this image. /// If this image is too large to fit on the bar, it is scaled to fit. /// Typically, the size of a toolbar and navigation bar image is 20 x 20 points. /// The alpha values in the source image are used to create the images—opaque values are ignored. /// - landscapeImagePhone: The style of the item. One of the constants defined in UIBarButtonItemStyle. nil by default /// - style: The style of the item. One of the constants defined in UIBarButtonItemStyle. (.Plain by default) /// - action: The action to be called when the button is tapped public convenience init( image: UIImage?, landscapeImagePhone: UIImage? = nil, style: UIBarButtonItem.Style = .plain, action: @escaping () -> Void ) { let action = VoidAction(action: action) self.init(image: image, landscapeImagePhone: landscapeImagePhone, style: style, target: action, action: action.selector) retainAction(action, self) } /// Initializes a new item using the specified title and other properties /// - Parameters: /// - title: the item’s title /// - style: the style of the item. One of the constants defined in UIBarButtonItemStyle /// - action: the action to be called when the button is tapped public convenience init<T: UIBarButtonItem>( title: String?, style: UIBarButtonItem.Style = .plain, action: @escaping (T) -> Void ) { let action = ParametizedAction(action: action) self.init(title: title, style: style, target: action, action: action.selector) retainAction(action, self) } /// Initializes a new item using the specified title and other properties /// - Parameters: /// - title: the item’s title /// - style: the style of the item. One of the constants defined in UIBarButtonItemStyle /// - action: the action to be called when the button is tapped public convenience init( title: String?, style: UIBarButtonItem.Style = .plain, action: @escaping () -> Void ) { let action = VoidAction(action: action) self.init(title: title, style: style, target: action, action: action.selector) retainAction(action, self) } /// Initializes a new item containing the specified system item /// - Parameters: /// - systemItem: the system item to use as the first item on the bar. /// One of the constants defined in UIBarButtonSystemItem /// - action: the action to be called when the button is tapped public convenience init<T: UIBarButtonItem>( barButtonSystemItem systemItem: UIBarButtonItem.SystemItem, action: @escaping (T) -> Void ) { let action = ParametizedAction(action: action) self.init(barButtonSystemItem: systemItem, target: action, action: action.selector) retainAction(action, self) } /// Initializes a new item containing the specified system item /// - Parameters: /// - systemItem: the system item to use as the first item on the bar. /// One of the constants defined in UIBarButtonSystemItem /// - action: the action to be called when the button is tapped public convenience init( barButtonSystemItem systemItem: UIBarButtonItem.SystemItem, action: @escaping () -> Void ) { let action = VoidAction(action: action) self.init(barButtonSystemItem: systemItem, target: action, action: action.selector) retainAction(action, self) } }
46.238938
128
0.65799
564864eb0fe08aeb1f157cdf387e57da73b30cff
4,794
// // ProgressCalculator.swift // Qualaroo // // Created by Marcin Robaczyński on 13/07/2018. // Copyright © 2018 Mihály Papp. All rights reserved. // import Foundation class ProgressCalculator { private let surveyWireframe: SurveyWireframeProtocol private var nodes: Set<GraphNode> = [] private var graph: Graph? = nil init(_ wireframe: SurveyWireframeProtocol) { self.surveyWireframe = wireframe initGraphNodes() } public func setCurrentStep(_ nodeId: Int64) { if let node = nodeById(nodeId) { graph = Graph(node) } } public func getStepsLeft() -> Int { return graph?.longestPathFromRoot() ?? 0 } private func initGraphNodes() { if let rootNode = surveyWireframe.firstNode() { buildFromRootNode(rootNode) } } private func node(_ question: Question) -> GraphNode { if let node = nodeById(question.nodeId()) { return node } var children = [GraphNode]() question.answerList.forEach { let response = QuestionResponse( id: question.nodeId(), alias: "", answerList: [AnswerResponse(id: $0.answerId, alias: "", text: "")] ) if let answerNode = surveyWireframe.nextNode(for: question.nodeId(), response: NodeResponse.question(response)) { children.append(buildNode(answerNode)) } } if let nextNodeId = question.nextId(), let nextNode = surveyWireframe.nextNode(for: nextNodeId, response: nil) { children.append(buildNode(nextNode)) } let (_, result) = nodes.insert(GraphNode(question.nodeId(), children)) return result } private func node(_ leadGen: LeadGenForm) -> GraphNode { if let node = nodeById(leadGen.nodeId()) { return node } var children = [GraphNode]() if let nextNode = surveyWireframe.nextNode(for: leadGen.nodeId(), response: nil) { children.append(buildNode(nextNode)) } let (_, result) = nodes.insert(GraphNode(leadGen.nodeId(), children)) return result } private func node(_ message: Message) -> GraphNode { if let node = nodeById(message.nodeId()) { return node } let (_, result) = nodes.insert(GraphNode(message.nodeId(), [])) return result } @discardableResult private func buildFromRootNode(_ rootNode: Node) -> GraphNode { return buildNode(rootNode) } private func buildNode(_ fromNode: Node) -> GraphNode { if let question = fromNode as? Question { return node(question) } if let leadGen = fromNode as? LeadGenForm { return node(leadGen) } if let message = fromNode as? Message { return node(message) } return GraphNode(0, []) } private func nodeById(_ id: Int64) -> GraphNode? { return nodes.first(where: { $0.id == id }) } } class Graph { let root: GraphNode init(_ root: GraphNode) { self.root = root } func longestPathFromRoot() -> Int { let nodes = topologicalSort(root) var distanceToNodes: [GraphNode: Int] = [:] nodes.forEach { distanceToNodes[$0] = 0 } for node in nodes { for child in node.children { if (distanceToNodes[child]! < distanceToNodes[node]! + 1) { distanceToNodes[child] = distanceToNodes[node]! + 1 } } } return distanceToNodes.values.max() ?? 0 } private func topologicalSort(_ root: GraphNode) -> [GraphNode] { var visited = Set<GraphNode>() var result: [GraphNode] = [] topologicalSort(root, &visited, &result) result.reverse() return result } private func topologicalSort(_ node: GraphNode, _ visited: inout Set<GraphNode>, _ result: inout [GraphNode]) { if (visited.contains(node)) { return } for child in node.children { topologicalSort(child, &visited, &result) } visited.insert(node) result.append(node) } } class GraphNode : Hashable, Equatable { static func == (lhs: GraphNode, rhs: GraphNode) -> Bool { return lhs.id == rhs.id } let id: Int64 let children: [GraphNode] init(_ id: Int64, _ children: [GraphNode]) { self.id = id self.children = children } func hash(into hasher: inout Hasher) { hasher.combine(id) } }
27.551724
125
0.561952
e61b66f6ce2ab951a8a6a7f6f000eebaa551e1f0
548
// // EmployeeContainer.swift // ROJSONParsing // // Created by Robin Oster on 08/08/14. // Copyright (c) 2014 Robin Oster. All rights reserved. // import Foundation class EmployeeContainer : ROJSONObject { required init() { super.init(); } required init(jsonData:AnyObject) { super.init(jsonData: jsonData) } required init(jsonString: String) { super.init(jsonString:jsonString) } lazy var employees:[Employee] = { return Value<[Employee]>.getArray(self) as [Employee] }() }
20.296296
61
0.638686
eb5f0a8f72062b900866a946d97a6a18472d291b
266
// // ProductCollectionViewCell.swift // moltin tvOS Example // // Created by Craig Tweedy on 21/03/2018. // import UIKit class ProductCategoryCollectionViewCell: UICollectionViewCell { @IBOutlet var label: UILabel! @IBOutlet var image: UIImageView! }
17.733333
63
0.736842
d5280a5b40fb6d2b0559433e51ef67788806a718
670
// // ViewController.swift // ZXSCocoaPods // // Created by VinnyZhang on 05/22/2018. // Copyright (c) 2018 VinnyZhang. All rights reserved. // import UIKit import ZXSCocoaPods import Pods_ZXSCocoaPods_Tests import Pods_ZXSCocoaPods_Example class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // let btn = ZXSCPBtn() // btn.lo } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.705882
80
0.658209
1aa2b2c25ce27eb8629d0236b320553b4ccc15ea
1,067
// // AnalyticsConfiguration.swift // PRODUCTNAME // // Created by LEADDEVELOPER on TODAYSDATE. // Copyright © THISYEAR ORGANIZATION. All rights reserved. // import Swiftilities import UIKit struct AnalyticsConfiguration: AppLifecycle, PageNameConfiguration { // By default page names are the VC class name minus the suffix "ViewController" converted from camel case to title case. Adding a class to this list will use the provided string for that view controller. // e.g. ObjectIdentifier(SigninViewController.self): "Sign in", static let nameOverrides: [ObjectIdentifier: String] = [:] // Add any ViewControllers that you don't want to see in Analytics to the ignoreList // e.g. HomeTabBarViewController isn't really a screen to be tracked static let ignoreList: [ObjectIdentifier] = [] var isEnabled: Bool { return true } func onDidLaunch(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey: Any]?) { DefaultBehaviors(behaviors: [GoogleTrackPageViewBehavior()]).inject() } }
35.566667
208
0.737582
8af7b024699a03c47c92d86257ba75fae53180b8
151
import Foundation enum eSurveyStep: Int, Codable { case landing case fittest case phoneverification case survey case completed }
15.1
32
0.708609
08e029c5345d6788c09ac2a44146ada4b9cfcddf
9,382
// // MLHomeCommentController.swift // MissLi // // Created by chengxianghe on 16/7/23. // Copyright © 2016年 cn. All rights reserved. // import UIKit import MJRefresh import YYText import ObjectMapper class MLHomeCommentController: BaseViewController, UITableViewDelegate, UITableViewDataSource { var aid = "" var dataSource = [MLTopicCommentCellLayout]() let commentListRequest = MLHomeCommentListRequest() var currentIndex = 0 @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.configRefresh() } //MARK: - 刷新 func configRefresh() { self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[unowned self] () -> Void in if self.tableView.mj_footer.isRefreshing { return } self.loadData(1) }) self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[unowned self] () -> Void in if self.tableView.mj_header.isRefreshing { return } self.loadData(self.currentIndex + 1) }) (self.tableView.mj_footer as! MJRefreshAutoNormalFooter).huaBanFooterConfig() (self.tableView.mj_header as! MJRefreshNormalHeader).huaBanHeaderConfig() self.tableView.mj_header.beginRefreshing() } //MARK: - 数据请求 func loadData(_ page: Int){ self.showLoading("正在加载...") commentListRequest.page = page commentListRequest.aid = aid commentListRequest.send(success: {[unowned self] (baseRequest, responseObject) in self.hideHud() self.tableView.mj_header.endRefreshing() var modelArray: [MLTopicCommentModel]? = nil if let list = ((responseObject as! NSDictionary)["content"] as! NSDictionary)["comlist"] as? [[String:Any]] { modelArray = list.map({ MLTopicCommentModel(JSON: $0)! }) //modelArray = NSArray.yy_modelArray(with: MLTopicCommentModel.classForCoder(), json: list) as? [MLTopicCommentModel] } let array = modelArray?.map({ (model) -> MLTopicCommentCellLayout in return MLTopicCommentCellLayout(model: model) }) if array != nil && array!.count > 0 { if page == 1 { self.dataSource.removeAll() self.dataSource.append(contentsOf: array!) self.tableView.reloadData() } else { self.tableView.beginUpdates() let lastItem = self.dataSource.count self.dataSource.append(contentsOf: array!) let indexPaths = (lastItem..<self.dataSource.count).map { IndexPath(row: $0, section: 0) } self.tableView.insertRows(at: indexPaths, with: UITableViewRowAnimation.fade) self.tableView.endUpdates() } if array!.count < 20 { self.tableView.mj_footer.endRefreshingWithNoMoreData() } else { self.currentIndex = page self.tableView.mj_footer.endRefreshing() } } else { if page == 1 { self.dataSource.removeAll() self.tableView.reloadData() } self.tableView.mj_footer.endRefreshingWithNoMoreData() } }) { (baseRequest, error) in self.tableView.mj_header.endRefreshing() self.tableView.mj_footer.endRefreshing() print(error) } } @IBAction func onCommentBtnClick(_ sender: UIButton) { if !MLNetConfig.isUserLogin() { let goLogin = UIAlertAction.init(title: "去登录", style: UIAlertActionStyle.default, handler: {[weak self] (action) in let loginVCNav = kLoadVCFromSB(nil, stroyBoard: "Account")! self?.present(loginVCNav, animated: true, completion: nil) }) let cancel = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil) self.showAlert("您还未登录", message: nil, actions: [cancel, goLogin]) return } self.performSegue(withIdentifier: "HomeCommentToPublish", sender: nil) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "MLTopicCommentCell") as? MLTopicCommentCell if cell == nil { cell = MLTopicCommentCell(style: .default, reuseIdentifier: "MLTopicCommentCell") cell?.delegate = self } cell!.setInfo(self.dataSource[(indexPath as NSIndexPath).row]); return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if !MLNetConfig.isUserLogin() { let goLogin = UIAlertAction.init(title: "去登录", style: UIAlertActionStyle.default, handler: {[weak self] (action) in let loginVCNav = kLoadVCFromSB(nil, stroyBoard: "Account")! self?.present(loginVCNav, animated: true, completion: nil) }) let cancel = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil) self.showAlert("您还未登录", message: nil, actions: [cancel, goLogin]) return } self.performSegue(withIdentifier: "HomeCommentToPublish", sender: self.dataSource[(indexPath as NSIndexPath).row]) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let model = self.dataSource[(indexPath as NSIndexPath).row] return MLTopicCommentCell.height(model) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 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?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "HomeCommentToPublish" { let vc = (segue.destination as! UINavigationController).topViewController as! MLPostTopicController vc.postType = PostTopicType.articleComment vc.aid = aid vc.dismissClosure = {(isSucceed) in print("HomeCommentToPublish \(isSucceed)"); } if sender != nil { let model = (sender as! MLTopicCommentCellLayout).joke vc.cid = (model?.cid)! } } else if segue.identifier == "CommentToUser" { let vc = segue.destination as! MLUserController vc.uid = (sender as! MLTopicCommentCellLayout).joke.uid } } } extension MLHomeCommentController: MLTopicCommentCellDelegate { func cellDidClickIcon(_ cell: MLTopicCommentCell) { self.performSegue(withIdentifier: "CommentToUser", sender: cell.layout) } func cellDidClickName(_ cell: MLTopicCommentCell) { self.performSegue(withIdentifier: "CommentToUser", sender: cell.layout) } func cellDidClickOther(_ cell: MLTopicCommentCell) { print("cellDidClickOther") } func cellDidClickLike(_ cell: MLTopicCommentCell) { print("cellDidClickLike") } func cell(_ cell: MLTopicCommentCell, didClickContentWithLongPress longPress: Bool) { print("didClickContentWithLongPress") } func cell(_ cell: MLTopicCommentCell, didClickTextInLabel label: YYLabel!, textRange: NSRange) { let text = label.textLayout!.text; if (textRange.location >= text.length) {return}; let highlight = text.yy_attribute(YYTextHighlightAttributeName, at: UInt(textRange.location)) as! YYTextHighlight let info = highlight.userInfo; if (info?.count == 0) {return}; if (info?[kSquareLinkAtName] != nil) { let name = info![kSquareLinkAtName]; print("didClickTextInLabel Name: \(String(describing: name))"); // name = [name stringByURLEncode]; // if (name.length) { // NSString *url = [NSString stringWithFormat:@"http://m.weibo.cn/n/%@",name]; // YYSimpleWebViewController *vc = [[YYSimpleWebViewController alloc] initWithURL:[NSURL URLWithString:url]]; // [self.navigationController pushViewController:vc animated:YES]; // } return; } } }
38.609053
133
0.594543
e671e7e0a64b6fd72d113a5ed227c331ea2d4fd5
2,802
// // SceneDelegate.swift // WeatherApp // // Created by David Rifkin on 10/8/19. // Copyright © 2019 David Rifkin. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } let firstVC = FirstViewController() let PhotosVC = PhotosViewController() let navVC = UINavigationController(rootViewController: firstVC) let tabController = UITabBarController() let bestTab = UITabBarItem(tabBarSystemItem: .search, tag: 2) //UITabBarItem(tabBarSystemItem: .more, tag: 2) let favTab = UITabBarItem(tabBarSystemItem: .favorites, tag: 2) //UITabBarItem(tabBarSystemItem: .bookmarks, tag: 1) navVC.tabBarItem = bestTab PhotosVC.tabBarItem = favTab tabController.viewControllers = [navVC,PhotosVC,] window = UIWindow(frame: UIScreen.main.bounds) window?.windowScene = windowScene window?.rootViewController = tabController window?.makeKeyAndVisible() } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
40.028571
141
0.688437
114eb2c23538f136ab986af80b6b0138f3baf909
1,722
/** * BulletinBoard * Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license. */ import UIKit /** * A shape layer that animates its path inside a block. */ private class AnimatingShapeLayer: CAShapeLayer { override class func defaultAction(forKey event: String) -> CAAction? { if event == "path" { return CABasicAnimation(keyPath: event) } else { return super.defaultAction(forKey: event) } } } /** * A layer whose corners are rounded with a continuous mask (“squircle“). */ open class ContinuousMaskLayer: CALayer { /// The corner radius. open var continuousCornerRadius: CGFloat = 0 { didSet { refreshMask() } } /// The corners to round. open var roundedCorners: UIRectCorner = .allCorners { didSet { refreshMask() } } // MARK: - Initialization public override init(layer: Any) { super.init(layer: layer) } public override init() { super.init() self.mask = AnimatingShapeLayer() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout open override func layoutSublayers() { super.layoutSublayers() refreshMask() } private func refreshMask() { guard let mask = mask as? CAShapeLayer else { return } let radii = CGSize(width: continuousCornerRadius, height: continuousCornerRadius) let roundedPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundedCorners, cornerRadii: radii) mask.path = roundedPath.cgPath } }
22.076923
114
0.61266
1e9bd98d725fdec6aad85948579eb2a77e8de73d
76
import PackageDescription let package = Package( name: "ColorSlider" )
12.666667
25
0.736842
238fdcf312c0bd968fdc03b4f4c3b91a38e70117
3,333
// // ViewController.swift // DouBanFm // // Created by Caulifeld on 2019/4/28. // Copyright © 2019 caulifeld. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import Kingfisher //import AlamofireImage class ViewController:UIViewController,UITableViewDataSource,UITableViewDelegate { //背景 @IBOutlet weak var bg: UIImageView! //歌曲封面 @IBOutlet weak var cover: EkoImage! // 歌曲列表 @IBOutlet weak var musicList: UITableView! // 定义一个变量接收歌曲数据 var songDate:[JSON] = [] // 定义一个变量接收频道数据 var channelData:[JSON] = [] //网络操作实例 var ehttp:HttpController = HttpController() override func viewDidLoad() { super.viewDidLoad() cover.onRotaion() //设置背景模糊 // 设置模糊样式 let blurEffect = UIBlurEffect(style: .light) let blurView = UIVisualEffectView(effect: blurEffect) // 定义模糊大小 blurView.frame.size = CGSize(width: view.frame.width, height: view.frame.height) // 添加模糊 bg.addSubview(blurView) // 设置tableview 数据源和代理 musicList.dataSource = self musicList.delegate = self // 获取频道 // ehttp.requestChannels() // 获取频道0的歌曲 ehttp.requestMusic { (results) in let json = JSON(results) let song = json["song"].array //self.songDate = song self.songDate.append(contentsOf: song!) self.musicList.reloadData() // print(songDate) } // ehttp.onSearch(url: "https://douban.fm/j/mine/playlist?type=s&sid=331663&pt=112.3&channel=3770138&pb=64&from=mainsite&r=a91682610b") // Do any additional setup after loading the view. } //实现表格代理协议 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return songDate.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "douban") as! UITableViewCell let rowData = songDate[indexPath.row] // 设置标题 cell.textLabel?.text = rowData["title"].string cell.detailTextLabel?.text = rowData["artist"].string let url1 = rowData["picture"].string ?? "" let urlStr = URL(string: url1) // let data = NSData(contentsOf: urlStr! as URL) // let image = UIImage(data: data! as Data) cell.imageView?.bounds = CGRect.init(x:0,y:0,width: cell.bounds.height, height: cell.bounds.height) cell.imageView?.contentMode = .scaleAspectFill cell.imageView?.clipsToBounds = true // cell.imageView?.kf.indicatorType = .activity cell.imageView?.kf.setImage(with: urlStr, placeholder: UIImage(named: "defult")) // let url = URL(string: url1)! // cell.imageView?.af_setImage(withURL: url) // print(url1) // // Alamofire.request(url1, method: .get).streamImage(){ (data) -> Void in // Alamofire.request(url1, method: .get).res(){ (data) -> Void in // let image:UIImage? = data // // // cell.imageView?.image = image // } return cell } }
31.149533
142
0.59556
d9d10d6a8f8c4986b16f646903e5651e57d9ceef
39,875
// // CryptorRSA.swift // CryptorRSA // // Created by Bill Abt on 1/17/17. // // Copyright © 2017 IBM. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation #if os(Linux) import OpenSSL #endif // MARK: - // MARK: - /// /// RSA Encryption/Decryption, Signing/Verification /// @available(macOS 10.12, iOS 10.3, watchOS 3.3, tvOS 12.0, *) public class CryptorRSA { // MARK: Class Functions /// /// Create a plaintext data container. /// /// - Parameters: /// - data: `Data` containing the key data. /// /// - Returns: Newly initialized `PlaintextData`. /// public class func createPlaintext(with data: Data) -> PlaintextData { return PlaintextData(with: data) } /// /// Creates a message from a plaintext string, with the specified encoding. /// /// - Parameters: /// - string: String value of the plaintext message /// - encoding: Encoding to use to generate the clear data /// /// - Returns: Newly initialized `PlaintextData`. /// public class func createPlaintext(with string: String, using encoding: String.Encoding) throws -> PlaintextData { return try PlaintextData(with: string, using: encoding) } /// /// Create an encrypted data container. /// /// - Parameters: /// - data: `Data` containing the encrypted data. /// /// - Returns: Newly initialized `EncryptedData`. /// public class func createEncrypted(with data: Data) -> EncryptedData { return EncryptedData(with: data) } /// /// Creates a message with a encrypted base64-encoded string. /// /// - Parameters: /// - base64String: Base64-encoded data of an encrypted message /// /// - Returns: Newly initialized `EncryptedData`. /// public class func createEncrypted(with base64String: String) throws -> EncryptedData { return try EncryptedData(withBase64: base64String) } /// /// Create an signed data container. /// /// - Parameters: /// - data: `Data` containing the signed data. /// /// - Returns: Newly initialized `SignedData`. /// public class func createSigned(with data: Data) -> SignedData { return SignedData(with: data) } /// /// RSA Data Object: Allows for RSA Encryption/Decryption, Signing/Verification and various utility functions. /// public class RSAData { // MARK: Enums /// Denotes the type of data this represents. public enum DataType { /// Plaintext case plaintextType /// Encrypted case encryptedType /// Signed case signedType } // MARK: -- Properties /// Data of the message public let data: Data /// Represents the type of data contained. public internal(set) var type: DataType = .plaintextType /// Base64-encoded string of the message data public var base64String: String { return data.base64EncodedString() } // MARK: -- Initializers /// /// Initialize a new RSAData object. /// /// - Parameters: /// - data: `Data` containing the data. /// - type: Type of data contained. /// /// - Returns: Newly initialized `RSAData`. /// internal init(with data: Data, type: DataType) { self.data = data self.type = type } /// /// Creates a RSAData with a encrypted base64-encoded string. /// /// - Parameters: /// - base64String: Base64-encoded data of an encrypted message /// /// - Returns: Newly initialized `RSAData`. /// internal init(withBase64 base64String: String) throws { guard let data = Data(base64Encoded: base64String) else { throw Error(code: CryptorRSA.ERR_BASE64_PEM_DATA, reason: "Couldn't convert base 64 encoded string ") } self.data = data self.type = .encryptedType } /// /// Creates a message from a plaintext string, with the specified encoding. /// /// - Parameters: /// - string: String value of the plaintext message /// - encoding: Encoding to use to generate the clear data /// /// - Returns: Newly initialized `RSAData`. /// internal init(with string: String, using encoding: String.Encoding) throws { guard let data = string.data(using: encoding) else { throw Error(code: CryptorRSA.ERR_STRING_ENCODING, reason: "Couldn't convert string to data using specified encoding") } self.data = data self.type = .plaintextType } // MARK: -- Functions // MARK: --- Encrypt/Decrypt /// /// Encrypt the data. /// /// - Parameters: /// - key: The `PublicKey` /// - algorithm: The algorithm to use (`Data.Algorithm`). /// /// - Returns: A new optional `EncryptedData` containing the encrypted data. /// public func encrypted(with key: PublicKey, algorithm: Data.Algorithm) throws -> EncryptedData? { // Must be plaintext... guard self.type == .plaintextType else { throw Error(code: CryptorRSA.ERR_NOT_PLAINTEXT, reason: "Data is not plaintext") } // Key must be public... guard key.type == .publicType else { throw Error(code: CryptorRSA.ERR_KEY_NOT_PUBLIC, reason: "Supplied key is not public") } #if os(Linux) switch algorithm { case .gcm: return try encryptedGCM(with: key) case .sha1, .sha224, .sha256, .sha384, .sha512: // Same algorithm is used regardless of sha return try encryptedCBC(with: key) } #else var response: Unmanaged<CFError>? = nil let eData = SecKeyCreateEncryptedData(key.reference, algorithm.alogrithmForEncryption, self.data as CFData, &response) if response != nil { guard let error = response?.takeRetainedValue() else { throw Error(code: CryptorRSA.ERR_ENCRYPTION_FAILED, reason: "Encryption failed. Unable to determine error.") } throw Error(code: CryptorRSA.ERR_ENCRYPTION_FAILED, reason: "Encryption failed with error: \(error)") } return EncryptedData(with: eData! as Data) #endif } /// /// Decrypt the data. /// /// - Parameters: /// - key: The `PrivateKey` /// - algorithm: The algorithm to use (`Data.Algorithm`). /// /// - Returns: A new optional `PlaintextData` containing the decrypted data. /// public func decrypted(with key: PrivateKey, algorithm: Data.Algorithm) throws -> PlaintextData? { // Must be encrypted... guard self.type == .encryptedType else { throw Error(code: CryptorRSA.ERR_NOT_ENCRYPTED, reason: "Data is plaintext") } // Key must be private... guard key.type == .privateType else { throw Error(code: CryptorRSA.ERR_KEY_NOT_PUBLIC, reason: "Supplied key is not private") } #if os(Linux) switch algorithm { case .gcm: return try decryptedGCM(with: key) case .sha1, .sha224, .sha256, .sha384, .sha512: // Same algorithm is used regardless of sha return try decryptedCBC(with: key) } #else var response: Unmanaged<CFError>? = nil let pData = SecKeyCreateDecryptedData(key.reference, algorithm.alogrithmForEncryption, self.data as CFData, &response) if response != nil { guard let error = response?.takeRetainedValue() else { throw Error(code: CryptorRSA.ERR_DECRYPTION_FAILED, reason: "Decryption failed. Unable to determine error.") } throw Error(code: CryptorRSA.ERR_DECRYPTION_FAILED, reason: "Decryption failed with error: \(error)") } return PlaintextData(with: pData! as Data) #endif } #if os(Linux) /// /// Encrypt the data using AES GCM SHA1 for cross platform support. /// /// - Parameters: /// - key: Public key to use. /// /// - Returns: Encrypted data object. /// func encryptedGCM(with key: PublicKey) throws -> EncryptedData? { // Initialize encryption context let rsaEncryptCtx = EVP_CIPHER_CTX_new_wrapper() EVP_CIPHER_CTX_init_wrapper(rsaEncryptCtx) defer { // On completion deallocate the memory EVP_CIPHER_CTX_reset_wrapper(rsaEncryptCtx) EVP_CIPHER_CTX_free_wrapper(rsaEncryptCtx) } // get rsaKey guard let rsaKey = EVP_PKEY_get1_RSA(.make(optional: key.reference)) else { let source = "Couldn't create key reference from key data" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ADD_KEY, reason: reason) } throw Error(code: ERR_ADD_KEY, reason: source + ": No OpenSSL error reported.") } defer { RSA_free(rsaKey) } // Set the additional authenticated data (aad) as the RSA key modulus and publicExponent in an ASN1 sequence. guard let aad = key.publicKeyBytes else { let source = "Encryption failed" throw Error(code: ERR_ENCRYPTION_FAILED, reason: source + ": Failed to decode public key") } // if the RSA key is >= 4096 bits, use aes_256_gcm. let encryptedCapacity: Int let keySize: Int if aad.count > 525 { // Set the rsaEncryptCtx to use EVP_aes_256_gcm encryption. guard EVP_EncryptInit_ex(rsaEncryptCtx, EVP_aes_256_gcm(), nil, nil, nil) == 1 else { throw Error(code: ERR_ENCRYPTION_FAILED, reason: "Encryption failed: Failed to initialize encryption context") } encryptedCapacity = 512 keySize = 32 } else { // Set the rsaEncryptCtx to use EVP_aes_128_gcm encryption. guard EVP_EncryptInit_ex(rsaEncryptCtx, EVP_aes_128_gcm(), nil, nil, nil) == 1 else { throw Error(code: ERR_ENCRYPTION_FAILED, reason: "Encryption failed: Failed to initialize encryption context") } if aad.count > 300 { encryptedCapacity = 384 } else if aad.count > 260 { encryptedCapacity = 256 } else { encryptedCapacity = 128 } keySize = 16 } // Allocate encryption memory let aeskey = UnsafeMutablePointer<UInt8>.allocate(capacity: keySize) let encryptedKey = UnsafeMutablePointer<UInt8>.allocate(capacity: encryptedCapacity) let tag = UnsafeMutablePointer<UInt8>.allocate(capacity: 16) let encrypted = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count + 16) defer { #if swift(>=4.1) aeskey.deallocate() encryptedKey.deallocate() tag.deallocate() encrypted.deallocate() #else aeskey.deallocate(capacity: keySize) encryptedKey.deallocate(capacity: encryptedCapacity) tag.deallocate(capacity: 16) encrypted.deallocate(capacity: data.count + 16) #endif } var processedLength: Int32 = 0 var encLength: Int32 = 0 // Apple use a 16 byte all 0 IV. This is allowed since a random key is generated for each encryption. let iv = [UInt8](repeating: 0, count: 16) // Set the IV length to be 16 to match Apple. guard EVP_CIPHER_CTX_ctrl(rsaEncryptCtx, EVP_CTRL_GCM_SET_IVLEN, 16, nil) == 1, // Generate 16/32 random bytes that will be used as the AES key. EVP_CIPHER_CTX_rand_key(rsaEncryptCtx, aeskey) == 1, // Set the aeskey and iv for the symmetric encryption. EVP_EncryptInit_ex(rsaEncryptCtx, nil, nil, aeskey, iv) == 1, // Encrypt the aes key using the rsa public key with SHA1, OAEP padding. RSA_public_encrypt(Int32(keySize), aeskey, encryptedKey, .make(optional: rsaKey), RSA_PKCS1_OAEP_PADDING) == encryptedCapacity, // Add the aad to the encryption context. // This is used in generating the GCM tag. We don't use this processedLength. EVP_EncryptUpdate(rsaEncryptCtx, nil, &processedLength, [UInt8](aad), Int32(aad.count)) == 1 else { let source = "Encryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ENCRYPTION_FAILED, reason: reason) } throw Error(code: ERR_ENCRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } // Encrypt the plaintext into encrypted using gcmAlgorithm with the random aes key and all 0 iv. guard(self.data.withUnsafeBytes({ (plaintext: UnsafeRawBufferPointer) -> Int32 in return EVP_EncryptUpdate(rsaEncryptCtx, encrypted, &processedLength, plaintext.baseAddress?.assumingMemoryBound(to: UInt8.self), Int32(data.count)) })) == 1 else { let source = "Encryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ENCRYPTION_FAILED, reason: reason) } throw Error(code: ERR_ENCRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } encLength += processedLength // Finalize the encryption so no more data will be added and generate the GCM tag. guard EVP_EncryptFinal_ex(rsaEncryptCtx, encrypted.advanced(by: Int(encLength)), &processedLength) == 1 else { let source = "Encryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ENCRYPTION_FAILED, reason: reason) } throw Error(code: ERR_ENCRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } encLength += processedLength // Get the 16 byte GCM tag. guard EVP_CIPHER_CTX_ctrl(rsaEncryptCtx, EVP_CTRL_GCM_GET_TAG, 16, tag) == 1 else { let source = "Encryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ENCRYPTION_FAILED, reason: reason) } throw Error(code: ERR_ENCRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } // Construct the envelope by combining the encrypted AES key, the encrypted date and the GCM tag. let ekFinal = Data(bytes: encryptedKey, count: encryptedCapacity) let cipher = Data(bytes: encrypted, count: Int(encLength)) let tagFinal = Data(bytes: tag, count: 16) return EncryptedData(with: ekFinal + cipher + tagFinal) } /// /// Encrypt the data using CBC for cross platform support. /// /// - Parameters: /// - key: Public key to use. /// /// - Returns: Encrypted data object. /// func encryptedCBC(with key: PublicKey) throws -> EncryptedData? { // Copy the EVP Key var evp_key = EVP_PKEY_new() let rsa = EVP_PKEY_get1_RSA(.make(optional: key.reference)) EVP_PKEY_set1_RSA(evp_key, rsa) RSA_free(rsa) defer { EVP_PKEY_free(evp_key) } // TODO: hash type option is not being used right now. let enc = EVP_aes_256_cbc() let padding = RSA_PKCS1_OAEP_PADDING let rsaEncryptCtx = EVP_CIPHER_CTX_new_wrapper() defer { EVP_CIPHER_CTX_reset_wrapper(rsaEncryptCtx) EVP_CIPHER_CTX_free_wrapper(rsaEncryptCtx) } EVP_CIPHER_CTX_set_padding(rsaEncryptCtx, padding) // Initialize the AES encryption key array (of size 1) typealias UInt8Ptr = UnsafeMutablePointer<UInt8>? var ek: UInt8Ptr ek = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(EVP_PKEY_size(.make(optional: key.reference)))) let ekPtr = UnsafeMutablePointer<UInt8Ptr>.allocate(capacity: MemoryLayout<UInt8Ptr>.size) ekPtr.pointee = ek // Assign size of the corresponding cipher's IV let IVLength = EVP_CIPHER_iv_length(.make(optional: enc)) let iv = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(IVLength)) let encrypted = UnsafeMutablePointer<UInt8>.allocate(capacity: self.data.count + Int(IVLength)) defer { #if swift(>=4.1) ek?.deallocate() ekPtr.deallocate() iv.deallocate() encrypted.deallocate() #else ek?.deallocate(capacity: Int(EVP_PKEY_size(.make(optional: key.reference)))) ekPtr.deallocate(capacity: MemoryLayout<UInt8Ptr>.size) iv.deallocate(capacity: Int(IVLength)) encrypted.deallocate(capacity: self.data.count + Int(IVLength)) #endif } var encKeyLength: Int32 = 0 var processedLength: Int32 = 0 var encLength: Int32 = 0 // Initializes a cipher context ctx for encryption with cipher type using a random secret key and IV. // The secret key is encrypted using the public key (evp_key can be an array of public keys) // Here we are using just 1 public key var status = EVP_SealInit(rsaEncryptCtx, .make(optional: enc), ekPtr, &encKeyLength, iv, &evp_key, 1) // SealInit should return the number of public keys that were input, here it is only 1 guard status == 1 else { let source = "Encryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ENCRYPTION_FAILED, reason: reason) } throw Error(code: ERR_ENCRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } // EVP_SealUpdate is a complex macros and therefore the compiler doesnt // convert it directly to swift. From /usr/local/opt/openssl/include/openssl/evp.h: _ = self.data.withUnsafeBytes({ (plaintext: UnsafeRawBufferPointer) -> Int32 in return EVP_EncryptUpdate(rsaEncryptCtx, encrypted, &processedLength, plaintext.baseAddress?.assumingMemoryBound(to: UInt8.self), Int32(self.data.count)) }) encLength = processedLength status = EVP_SealFinal(rsaEncryptCtx, encrypted.advanced(by: Int(encLength)), &processedLength) guard status == 1 else { let source = "Encryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ENCRYPTION_FAILED, reason: reason) } throw Error(code: ERR_ENCRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } encLength += processedLength let cipher = Data(bytes: encrypted, count: Int(encLength)) let ekFinal = Data(bytes: ek!, count: Int(encKeyLength)) let ivFinal = Data(bytes: iv, count: Int(IVLength)) return EncryptedData(with: ekFinal + cipher + ivFinal) } /// /// Decrypt the data using AES GCM for cross platform support. /// /// - Parameters: /// - key: Private key to use. /// /// - Returns: Decrypted data object. /// func decryptedGCM(with key: PrivateKey) throws -> PlaintextData? { // Initialize the decryption context. let rsaDecryptCtx = EVP_CIPHER_CTX_new() EVP_CIPHER_CTX_init_wrapper(rsaDecryptCtx) defer { // On completion deallocate the memory EVP_CIPHER_CTX_reset_wrapper(rsaDecryptCtx) EVP_CIPHER_CTX_free_wrapper(rsaDecryptCtx) } // get rsaKey guard let rsaKey = EVP_PKEY_get1_RSA(.make(optional: key.reference)) else { let source = "Couldn't create key reference from key data" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_ADD_KEY, reason: reason) } throw Error(code: ERR_ADD_KEY, reason: source + ": No OpenSSL error reported.") } defer { RSA_free(rsaKey) } // Set the additional authenticated data (aad) as the RSA key modulus and publicExponent in an ASN1 sequence. guard let aad = key.publicKeyBytes else { let source = "Decryption failed" throw Error(code: ERR_DECRYPTION_FAILED, reason: source + ": Failed to decode public key") } // if the RSA key is larger than 4096 bits, use aes_256_gcm. let encKeyLength: Int let keySize: Int if aad.count > 525 { // Set the envelope decryption algorithm as 128 bit AES-GCM. guard EVP_DecryptInit_ex(rsaDecryptCtx, EVP_aes_256_gcm(), nil, nil, nil) == 1 else { throw Error(code: ERR_DECRYPTION_FAILED, reason: "Decryption failed: Failed to initialize decryption context") } encKeyLength = 512 keySize = 32 } else { // Set the envelope decryption algorithm as 128 bit AES-GCM. guard EVP_DecryptInit_ex(rsaDecryptCtx, EVP_aes_128_gcm(), nil, nil, nil) == 1 else { throw Error(code: ERR_DECRYPTION_FAILED, reason: "Decryption failed: Failed to initialize decryption context") } if aad.count > 300 { encKeyLength = 384 } else if aad.count > 260 { encKeyLength = 256 } else { encKeyLength = 128 } keySize = 16 } let tagLength = 16 let encryptedDataLength = Int(data.count) - encKeyLength - tagLength // Extract encryptedAESKey, encryptedData, GCM tag from data let encryptedKey = data.subdata(in: 0..<encKeyLength) let encryptedData = data.subdata(in: encKeyLength..<encKeyLength+encryptedDataLength) var tagData = data.subdata(in: encKeyLength+encryptedDataLength..<data.count) // Allocate memory for decryption let aeskey = UnsafeMutablePointer<UInt8>.allocate(capacity: keySize) let decrypted = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(encryptedData.count + 16)) defer { // On completion deallocate the memory #if swift(>=4.1) aeskey.deallocate() decrypted.deallocate() #else aeskey.deallocate(capacity: keySize) decrypted.deallocate(capacity: Int(encryptedData.count + 16)) #endif } // processedLen is the number of bytes that each EVP_DecryptUpdate/EVP_DecryptFinal decrypts. // The sum of processedLen is the total size of the decrypted message (decMsgLen) var processedLen: Int32 = 0 var decMsgLen: Int32 = 0 // Use a 16-byte all zero initialization vector (IV) to match Apple Security. let iv = [UInt8](repeating: 0, count: 16) // Decrypt the encryptedKey into the aeskey using the RSA private key guard RSA_private_decrypt(Int32(encryptedKey.count), [UInt8](encryptedKey), aeskey, rsaKey, RSA_PKCS1_OAEP_PADDING) != 0, // Set the IV length to be 16 bytes. EVP_CIPHER_CTX_ctrl(rsaDecryptCtx, EVP_CTRL_GCM_SET_IVLEN, 16, nil) == 1, // Set the AES key to be 16 bytes. EVP_CIPHER_CTX_set_key_length(rsaDecryptCtx, Int32(keySize)) == 1, // Set the envelope decryption context AES key and IV. EVP_DecryptInit_ex(rsaDecryptCtx, nil, nil, aeskey, iv) == 1, EVP_DecryptUpdate(rsaDecryptCtx, nil, &processedLen, [UInt8](aad), Int32(aad.count)) == 1 else { let source = "Decryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_DECRYPTION_FAILED, reason: reason) } throw Error(code: ERR_DECRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } // Decrypt the encrypted data using the symmetric key. guard encryptedData.withUnsafeBytes({ (enc: UnsafeRawBufferPointer) -> Int32 in return EVP_DecryptUpdate(rsaDecryptCtx, decrypted, &processedLen, enc.baseAddress?.assumingMemoryBound(to: UInt8.self), Int32(encryptedData.count)) }) != 0 else { let source = "Decryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_DECRYPTION_FAILED, reason: reason) } throw Error(code: ERR_DECRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } decMsgLen += processedLen // Verify the provided GCM tag. guard tagData.withUnsafeMutableBytes({ (tag: UnsafeMutableRawBufferPointer) -> Int32 in return EVP_CIPHER_CTX_ctrl(rsaDecryptCtx, EVP_CTRL_GCM_SET_TAG, 16, tag.baseAddress) }) == 1, EVP_DecryptFinal_ex(rsaDecryptCtx, decrypted.advanced(by: Int(decMsgLen)), &processedLen) == 1 else { let source = "Decryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_DECRYPTION_FAILED, reason: reason) } throw Error(code: ERR_DECRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } decMsgLen += processedLen // return the decrypted plaintext. return PlaintextData(with: Data(bytes: decrypted, count: Int(decMsgLen))) } /// /// Decrypt the data using CBC for cross platform support. /// /// - Parameters: /// - key: Private key to use. /// /// - Returns: Decrypted data object. /// func decryptedCBC(with key: PrivateKey) throws -> PlaintextData? { // Convert RSA key to EVP let encType = EVP_aes_256_cbc() let padding = RSA_PKCS1_OAEP_PADDING // Size of symmetric encryption let encKeyLength = Int(EVP_PKEY_size(.make(optional: key.reference))) // Size of the corresponding cipher's IV let encIVLength = Int(EVP_CIPHER_iv_length(.make(optional: encType))) // Size of encryptedKey let encryptedDataLength = Int(self.data.count) - encKeyLength - encIVLength // Extract encryptedKey, encryptedData, encryptedIV from data // self.data = encryptedKey + encryptedData + encryptedIV let encryptedKey = self.data.subdata(in: 0..<encKeyLength) let encryptedData = self.data.subdata(in: encKeyLength..<encKeyLength+encryptedDataLength) let encryptedIV = self.data.subdata(in: encKeyLength+encryptedDataLength..<self.data.count) let rsaDecryptCtx = EVP_CIPHER_CTX_new_wrapper() defer { EVP_CIPHER_CTX_reset_wrapper(rsaDecryptCtx) EVP_CIPHER_CTX_free_wrapper(rsaDecryptCtx) } EVP_CIPHER_CTX_set_padding(rsaDecryptCtx, padding) // processedLen is the number of bytes that each EVP_DecryptUpdate/EVP_DecryptFinal decrypts. // The sum of processedLen is the total size of the decrypted message (decMsgLen) var processedLen: Int32 = 0 var decMsgLen: Int32 = 0 let decrypted = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(encryptedData.count + encryptedIV.count)) defer { #if swift(>=4.1) decrypted.deallocate() #else decrypted.deallocate(capacity: Int(encryptedData.count + encryptedIV.count)) #endif } // EVP_OpenInit returns 0 on error or the recovered secret key size if successful var status = encryptedKey.withUnsafeBytes({ (ek: UnsafeRawBufferPointer) -> Int32 in return encryptedIV.withUnsafeBytes({ (iv: UnsafeRawBufferPointer) -> Int32 in return EVP_OpenInit(rsaDecryptCtx, .make(optional: encType), ek.baseAddress?.assumingMemoryBound(to: UInt8.self), Int32(encryptedKey.count), iv.baseAddress?.assumingMemoryBound(to: UInt8.self), .make(optional: key.reference)) }) }) guard status != 0 else { let source = "Decryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_DECRYPTION_FAILED, reason: reason) } throw Error(code: ERR_DECRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } // EVP_OpenUpdate is a complex macros and therefore the compiler doesnt // convert it directly to Swift. From /usr/local/opt/openssl/include/openssl/evp.h: _ = encryptedData.withUnsafeBytes({ (enc: UnsafeRawBufferPointer) -> Int32 in return EVP_DecryptUpdate(rsaDecryptCtx, decrypted, &processedLen, enc.baseAddress?.assumingMemoryBound(to: UInt8.self), Int32(encryptedData.count)) }) decMsgLen = processedLen status = EVP_OpenFinal(rsaDecryptCtx, decrypted.advanced(by: Int(decMsgLen)), &processedLen) guard status != 0 else { let source = "Decryption failed" if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_DECRYPTION_FAILED, reason: reason) } throw Error(code: ERR_DECRYPTION_FAILED, reason: source + ": No OpenSSL error reported.") } decMsgLen += processedLen return PlaintextData(with: Data(bytes: decrypted, count: Int(decMsgLen))) } #endif // MARK: --- Sign/Verification /// /// Sign the data /// /// - Parameters: /// - key: The `PrivateKey`. /// - algorithm: The algorithm to use (`Data.Algorithm`). /// - usePSS: Bool stating whether or not to use RSA-PSS (Probabilistic signature scheme). /// /// - Returns: A new optional `SignedData` containing the digital signature. /// public func signed(with key: PrivateKey, algorithm: Data.Algorithm, usePSS: Bool = false) throws -> SignedData? { // Must be plaintext... guard self.type == .plaintextType else { throw Error(code: CryptorRSA.ERR_NOT_PLAINTEXT, reason: "Data is not plaintext") } // Key must be private... guard key.type == .privateType else { throw Error(code: CryptorRSA.ERR_KEY_NOT_PRIVATE, reason: "Supplied key is not private") } #if os(Linux) let md_ctx = EVP_MD_CTX_new_wrapper() defer { EVP_MD_CTX_free_wrapper(md_ctx) } let (md, _) = algorithm.algorithmForSignature if usePSS { // If using PSS padding, create a PKEY and set it's padding, mask generation function and salt length. // NID_rsassaPss is `EVP_PKEY_RSA_PSS` as defined in evp.h var pkey_ctx = EVP_PKEY_CTX_new_id(NID_rsassaPss, nil) EVP_DigestSignInit(md_ctx, &pkey_ctx, .make(optional: md), nil, .make(optional: key.reference)) EVP_PKEY_CTX_ctrl(pkey_ctx, EVP_PKEY_RSA, -1, EVP_PKEY_CTRL_RSA_PADDING, RSA_PKCS1_PSS_PADDING, nil) EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_SIGN, EVP_PKEY_CTRL_RSA_MGF1_MD, 0, .make(optional: md)) // Sets salt length to be equal to message digest length EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_SIGN, EVP_PKEY_CTRL_RSA_PSS_SALTLEN, -1, .make(optional: md)) } else { // Provide a pkey_ctx to EVP_DigestSignInit so that the EVP_PKEY_CTX of the signing operation // is written to it, to allow alternative signing options to be set EVP_DigestSignInit(md_ctx, nil, .make(optional: md), nil, .make(optional: key.reference)) } // Convert Data to UnsafeRawPointer! _ = self.data.withUnsafeBytes({ (message: UnsafeRawBufferPointer) -> Int32 in return EVP_DigestUpdate(md_ctx, message.baseAddress?.assumingMemoryBound(to: UInt8.self), self.data.count) }) // Determine the size of the actual signature var sig_len: Int = 0 EVP_DigestSignFinal(md_ctx, nil, &sig_len) let sig = UnsafeMutablePointer<UInt8>.allocate(capacity: sig_len) defer { #if swift(>=4.1) sig.deallocate() #else sig.deallocate(capacity: sig_len) #endif } let rc = EVP_DigestSignFinal(md_ctx, sig, &sig_len) guard rc == 1, sig_len > 0 else { let source = "Signing failed." if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_SIGNING_FAILED, reason: reason) } throw Error(code: ERR_SIGNING_FAILED, reason: source + ": No OpenSSL error reported.") } return SignedData(with: Data(bytes: sig, count: sig_len)) #else let signingAlgorithm: SecKeyAlgorithm if usePSS { if #available(macOS 10.13, iOS 11.0, watchOS 4.0, *) { signingAlgorithm = usePSS ? algorithm.algorithmForPssSignature : algorithm.algorithmForSignature } else { throw Error(code: ERR_NOT_IMPLEMENTED, reason: "RSA-PSS only supported on macOS 10.13/iOS 10.0 and above.") } } else { signingAlgorithm = algorithm.algorithmForSignature } var response: Unmanaged<CFError>? = nil let sData = SecKeyCreateSignature(key.reference, signingAlgorithm, self.data as CFData, &response) if response != nil { guard let error = response?.takeRetainedValue() else { throw Error(code: CryptorRSA.ERR_SIGNING_FAILED, reason: "Signing failed. Unable to determine error.") } throw Error(code: CryptorRSA.ERR_SIGNING_FAILED, reason: "Signing failed with error: \(error)") } return SignedData(with: sData! as Data) #endif } /// /// Verify the signature /// /// - Parameters: /// - key: The `PublicKey`. /// - signature: The `SignedData` containing the signature to verify against. /// - algorithm: The algorithm to use (`Data.Algorithm`). /// - usePSS: Bool stating whether or not to use RSA-PSS (Probabilistic signature scheme). /// /// - Returns: True if verification is successful, false otherwise /// public func verify(with key: PublicKey, signature: SignedData, algorithm: Data.Algorithm, usePSS: Bool = false) throws -> Bool { // Must be plaintext... guard self.type == .plaintextType else { throw Error(code: CryptorRSA.ERR_NOT_PLAINTEXT, reason: "Data is not plaintext") } // Key must be public... guard key.type == .publicType else { throw Error(code: CryptorRSA.ERR_KEY_NOT_PRIVATE, reason: "Supplied key is not public") } // Signature must be signed data... guard signature.type == .signedType else { throw Error(code: CryptorRSA.ERR_NOT_SIGNED_DATA, reason: "Supplied signature is not of signed data type") } #if os(Linux) let md_ctx = EVP_MD_CTX_new_wrapper() defer { EVP_MD_CTX_free_wrapper(md_ctx) } let (md, _) = algorithm.algorithmForSignature if usePSS { // If using PSS padding, create a PKEY and set it's padding and mask generation function. var pkey_ctx = EVP_PKEY_CTX_new_id(NID_rsassaPss, nil) EVP_DigestVerifyInit(md_ctx, &pkey_ctx, .make(optional: md), nil, .make(optional: key.reference)) EVP_PKEY_CTX_ctrl(pkey_ctx, EVP_PKEY_RSA, -1, EVP_PKEY_CTRL_RSA_PADDING, RSA_PKCS1_PSS_PADDING, nil) EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_VERIFY, EVP_PKEY_CTRL_RSA_MGF1_MD, 0, .make(optional: md)) } else { // Provide a pkey_ctx to EVP_DigestSignInit so that the EVP_PKEY_CTX of the signing operation // is written to it, to allow alternative signing options to be set EVP_DigestVerifyInit(md_ctx, nil, .make(optional: md), nil, .make(optional: key.reference)) } var rc = self.data.withUnsafeBytes({ (message: UnsafeRawBufferPointer) -> Int32 in return EVP_DigestUpdate(md_ctx, message.baseAddress?.assumingMemoryBound(to: UInt8.self), self.data.count) }) guard rc == 1 else { let source = "Signature verification failed." if let reason = CryptorRSA.getLastError(source: source) { throw Error(code: ERR_VERIFICATION_FAILED, reason: reason) } throw Error(code: ERR_VERIFICATION_FAILED, reason: source + ": No OpenSSL error reported.") } // Unlike other return values above, this return indicates if signature verifies or not rc = signature.data.withUnsafeBytes({ (sig: UnsafeRawBufferPointer) -> Int32 in // Wrapper for OpenSSL EVP_DigestVerifyFinal function defined in // Kitura-Next/OpenSSL/shim.h, to provide compatibility with OpenSSL // 1.0.1 and 1.0.2 on Ubuntu 14.04 and 16.04, respectively. return SSL_EVP_digestVerifyFinal_wrapper(md_ctx, sig.baseAddress?.assumingMemoryBound(to: UInt8.self), signature.data.count) }) return (rc == 1) ? true : false #else let signingAlgorithm: SecKeyAlgorithm if usePSS { if #available(macOS 10.13, iOS 11.0, watchOS 4.0, *) { signingAlgorithm = usePSS ? algorithm.algorithmForPssSignature : algorithm.algorithmForSignature } else { throw Error(code: ERR_NOT_IMPLEMENTED, reason: "RSA-PSS only supported on macOS 10.13/iOS 10.0 and above.") } } else { signingAlgorithm = algorithm.algorithmForSignature } var response: Unmanaged<CFError>? = nil let result = SecKeyVerifySignature(key.reference, signingAlgorithm, self.data as CFData, signature.data as CFData, &response) if response != nil { guard let error = response?.takeRetainedValue() else { throw Error(code: CryptorRSA.ERR_VERIFICATION_FAILED, reason: "Signature verification failed. Unable to determine error.") } throw Error(code: CryptorRSA.ERR_VERIFICATION_FAILED, reason: "Signature verification failed with error: \(error)") } return result #endif } // MARK: --- Utility /// /// Retrieve a digest of the data using the specified algorithm. /// /// - Parameters: /// - algorithm: Algoririthm to use. /// /// - Returns: `Data` containing the digest. /// public func digest(using algorithm: Data.Algorithm) throws -> Data { return try self.data.digest(using: algorithm) } /// /// String representation of message in specified string encoding. /// /// - Parameters: /// - encoding: Encoding to use during the string conversion /// /// - Returns: String representation of the message /// public func string(using encoding: String.Encoding) throws -> String { guard let str = String(data: data, encoding: encoding) else { throw Error(code: CryptorRSA.ERR_STRING_ENCODING, reason: "Couldn't convert data to string representation") } return str } } // MARK: - /// /// Plaintext Data - Represents data not encrypted or signed. /// public class PlaintextData: RSAData { // MARK: Initializers /// /// Initialize a new PlaintextData object. /// /// - Parameters: /// - data: `Data` containing the data. /// /// - Returns: Newly initialized `PlaintextData`. /// internal init(with data: Data) { super.init(with: data, type: .plaintextType) } /// /// Creates a message from a plaintext string, with the specified encoding. /// /// - Parameters: /// - string: String value of the plaintext message /// - encoding: Encoding to use to generate the clear data /// /// - Returns: Newly initialized `RSAData`. /// internal override init(with string: String, using encoding: String.Encoding) throws { try super.init(with: string, using: encoding) } } // MARK: - /// /// Encrypted Data - Represents data encrypted. /// public class EncryptedData: RSAData { // MARK: Initializers /// /// Initialize a new EncryptedData object. /// /// - Parameters: /// - data: `Data` containing the data. /// /// - Returns: Newly initialized EncryptedData`. /// public init(with data: Data) { super.init(with: data, type: .encryptedType) } /// /// Creates a RSAData with a encrypted base64-encoded string. /// /// - Parameters: /// - base64String: Base64-encoded data of an encrypted message /// /// - Returns: Newly initialized `RSAData`. /// public override init(withBase64 base64String: String) throws { try super.init(withBase64: base64String) } } // MARK: - /// /// Signed Data - Represents data that is signed. /// public class SignedData: RSAData { // MARK: -- Initializers /// /// Initialize a new SignedData object. /// /// - Parameters: /// - data: `Data` containing the data. /// /// - Returns: Newly initialized `SignedData`. /// public init(with data: Data) { super.init(with: data, type: .signedType) } } }
35.858813
231
0.657956
e9d7862d455c72e6e3ac5c846b5ed26c394a53e1
3,493
// // DataHandler.swift // EverliveSwift // // Created by Dimitar Dimitrov on 2/15/16. // Copyright © 2016 ddimitrov. All rights reserved. // import Foundation import Alamofire import EVReflection public class DataHandler<T : DataItem> { var connection: EverliveConnection var typeName: String! init(connection: EverliveConnection){ self.connection = connection self.typeName = self.getTypeName() //TODO: discuss the time format let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") EVReflection.setDateFormatter(formatter) } public func getById(id:String)-> GetByIdHandler<T> { return GetByIdHandler(id: id, connection: self.connection, typeName: self.typeName) } public func getAll() -> GetAllHandler<T> { return GetAllHandler(connection: self.connection, typeName: self.typeName) } public func getByFilter(filter: EverliveQuery) -> GetByFilter<T>{ return GetByFilter(filter: filter, connection: self.connection, typeName: self.typeName) } public func create(item: T) -> CreateSingleHandler<T> { return CreateSingleHandler(newItem: item, connection: self.connection, typeName: self.typeName) } public func create(items: [T]) -> CreateMultipleHandler<T> { return CreateMultipleHandler(newItems: items, connection: self.connection, typeName: self.typeName) } public func deleteById(id:String) -> DeleteByIdHandler{ return DeleteByIdHandler(id: id, connection: self.connection, typeName: self.typeName) } public func deleteAll() -> DeleteAllHandler { return DeleteAllHandler(connection: self.connection, typeName: self.typeName) } public func updateById(id:String, updateObject: Updateable) -> UpdateByIdHandler { return UpdateByIdHandler(id: id, updateObject: updateObject, connection: self.connection, typeName: self.typeName) } public func updateByFilter(query: QueryProtocol, updateObject: Updateable) -> UpdateByFilterHandler { return UpdateByFilterHandler(query: query, updateObject: updateObject, connection: self.connection, typeName: self.typeName) } public func update(item: T) -> UpdateByIdHandler { let itemId = (item as DataItem).Id return UpdateByIdHandler(id: itemId!, updateObject: item, connection: self.connection, typeName: self.typeName) } public func getCount() -> GetCountHandler { return GetCountHandler(connection: self.connection, typeName: self.typeName) } public func getCountByFilter(filter:QueryProtocol) -> GetCountHandler{ return GetCountHandler(filter: filter, connection: self.connection, typeName: self.typeName) } private func getTypeName() -> String { let currentType = T() let typeName = currentType.getTypeName() if typeName != "" { return typeName } else { let fullName: String = NSStringFromClass(T.self as AnyClass) let range = fullName.rangeOfString(".", options: .BackwardsSearch) if let range = range { return fullName.substringFromIndex(range.endIndex) } else { return fullName } } } }
37.159574
132
0.671629
874d9bf6b8f15044ff802c88ddff7b8a85861f20
1,565
// // FYYQTableViewCell.swift // news // // Created by wang on 2018/9/20. // Copyright © 2018年 wang. All rights reserved. // import UIKit class FYYQTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(isBigIcon : Bool ,modelArr:NSArray) { if isBigIcon { let model = modelArr.firstObject as! comicsModel self.contentView.addSubview(self.bigImage) self.bigImage.sd_setImage(with: NSURL(string: model.cover!)! as URL, placeholderImage: UIImage.init(named: ""), options: [], completed: nil) } else { let iconW = (self.contentView.width - 15*4)/3 for i in 0...2 { let model = modelArr[i + 1] as! comicsModel let iconX = CGFloat(i) * iconW + CGFloat(i+1) * 15 let smallIcon = UIImageView.init(frame: CGRect(x: iconX, y: 0, width: iconW, height: iconW)) smallIcon.sd_setImage(with: NSURL(string: model.cover!)! as URL, placeholderImage: UIImage.init(named: ""), options: [], completed: nil) self.contentView.addSubview(smallIcon) } } } lazy var bigImage = {() -> UIImageView in let bgimage = UIImageView() bgimage.frame = self.contentView.frame return bgimage }() }
34.021739
152
0.603195
794f31619db2c40608823e7c705096e3b3c5dcbb
769
// // Configuration.swift // Common // // Created by Ronan on 09/02/2019. // Copyright © 2019 Sonomos. All rights reserved. // import UIKit public struct Configuration { public static var uiTesting: Bool { let arguments = ProcessInfo.processInfo.arguments return arguments.contains("UITesting") } public static var networkTesting: Bool { let arguments = CommandLine.arguments return arguments.contains("NetworkTesting") } public static var searchErrorTesting: Bool { return CommandLine.arguments.contains("Error_401") } public static var asyncTesting: Bool { let arguments = ProcessInfo.processInfo.arguments return arguments.contains("AsyncTesting") } }
24.03125
58
0.669701
4b9c09bc69ed5dc10f78fbd92082515985462afe
13,117
// // ImagingManifest.swift // HealthSoftware // // Generated from FHIR 3.0.1.11917 (http://hl7.org/fhir/StructureDefinition/ImagingManifest) // Copyright 2020 Apple 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 FMCore /** Key Object Selection. A text description of the DICOM SOP instances selected in the ImagingManifest; or the reason for, or significance of, the selection. */ open class ImagingManifest: DomainResource { override open class var resourceType: ResourceType { return .imagingManifest } /// SOP Instance UID public var identifier: Identifier? /// Patient of the selected objects public var patient: Reference /// Time when the selection of instances was made public var authoringTime: FHIRPrimitive<DateTime>? /// Author (human or machine) public var author: Reference? /// Description text public var description_fhir: FHIRPrimitive<FHIRString>? /// Study identity of the selected instances public var study: [ImagingManifestStudy] /// Designated initializer taking all required properties public init(patient: Reference, study: [ImagingManifestStudy]) { self.patient = patient self.study = study super.init() } /// Convenience initializer public convenience init( author: Reference? = nil, authoringTime: FHIRPrimitive<DateTime>? = nil, contained: [ResourceProxy]? = nil, description_fhir: FHIRPrimitive<FHIRString>? = nil, `extension`: [Extension]? = nil, id: FHIRPrimitive<FHIRString>? = nil, identifier: Identifier? = nil, implicitRules: FHIRPrimitive<FHIRURI>? = nil, language: FHIRPrimitive<FHIRString>? = nil, meta: Meta? = nil, modifierExtension: [Extension]? = nil, patient: Reference, study: [ImagingManifestStudy], text: Narrative? = nil) { self.init(patient: patient, study: study) self.author = author self.authoringTime = authoringTime self.contained = contained self.description_fhir = description_fhir self.`extension` = `extension` self.id = id self.identifier = identifier self.implicitRules = implicitRules self.language = language self.meta = meta self.modifierExtension = modifierExtension self.text = text } // MARK: - Codable private enum CodingKeys: String, CodingKey { case author case authoringTime; case _authoringTime case description_fhir = "description"; case _description_fhir = "_description" case identifier case patient case study } /// Initializer for Decodable public required init(from decoder: Decoder) throws { let _container = try decoder.container(keyedBy: CodingKeys.self) // Decode all our properties self.author = try Reference(from: _container, forKeyIfPresent: .author) self.authoringTime = try FHIRPrimitive<DateTime>(from: _container, forKeyIfPresent: .authoringTime, auxiliaryKey: ._authoringTime) self.description_fhir = try FHIRPrimitive<FHIRString>(from: _container, forKeyIfPresent: .description_fhir, auxiliaryKey: ._description_fhir) self.identifier = try Identifier(from: _container, forKeyIfPresent: .identifier) self.patient = try Reference(from: _container, forKey: .patient) self.study = try [ImagingManifestStudy](from: _container, forKey: .study) try super.init(from: decoder) } /// Encodable public override func encode(to encoder: Encoder) throws { var _container = encoder.container(keyedBy: CodingKeys.self) // Encode all our properties try author?.encode(on: &_container, forKey: .author) try authoringTime?.encode(on: &_container, forKey: .authoringTime, auxiliaryKey: ._authoringTime) try description_fhir?.encode(on: &_container, forKey: .description_fhir, auxiliaryKey: ._description_fhir) try identifier?.encode(on: &_container, forKey: .identifier) try patient.encode(on: &_container, forKey: .patient) try study.encode(on: &_container, forKey: .study) try super.encode(to: encoder) } // MARK: - Equatable & Hashable public override func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? ImagingManifest else { return false } guard super.isEqual(to: _other) else { return false } return author == _other.author && authoringTime == _other.authoringTime && description_fhir == _other.description_fhir && identifier == _other.identifier && patient == _other.patient && study == _other.study } public override func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(author) hasher.combine(authoringTime) hasher.combine(description_fhir) hasher.combine(identifier) hasher.combine(patient) hasher.combine(study) } } /** Study identity of the selected instances. Study identity and locating information of the DICOM SOP instances in the selection. */ open class ImagingManifestStudy: BackboneElement { /// Study instance UID public var uid: FHIRPrimitive<FHIRURI> /// Reference to ImagingStudy public var imagingStudy: Reference? /// Study access service endpoint public var endpoint: [Reference]? /// Series identity of the selected instances public var series: [ImagingManifestStudySeries] /// Designated initializer taking all required properties public init(series: [ImagingManifestStudySeries], uid: FHIRPrimitive<FHIRURI>) { self.series = series self.uid = uid super.init() } /// Convenience initializer public convenience init( endpoint: [Reference]? = nil, `extension`: [Extension]? = nil, id: FHIRPrimitive<FHIRString>? = nil, imagingStudy: Reference? = nil, modifierExtension: [Extension]? = nil, series: [ImagingManifestStudySeries], uid: FHIRPrimitive<FHIRURI>) { self.init(series: series, uid: uid) self.endpoint = endpoint self.`extension` = `extension` self.id = id self.imagingStudy = imagingStudy self.modifierExtension = modifierExtension } // MARK: - Codable private enum CodingKeys: String, CodingKey { case endpoint case imagingStudy case series case uid; case _uid } /// Initializer for Decodable public required init(from decoder: Decoder) throws { let _container = try decoder.container(keyedBy: CodingKeys.self) // Decode all our properties self.endpoint = try [Reference](from: _container, forKeyIfPresent: .endpoint) self.imagingStudy = try Reference(from: _container, forKeyIfPresent: .imagingStudy) self.series = try [ImagingManifestStudySeries](from: _container, forKey: .series) self.uid = try FHIRPrimitive<FHIRURI>(from: _container, forKey: .uid, auxiliaryKey: ._uid) try super.init(from: decoder) } /// Encodable public override func encode(to encoder: Encoder) throws { var _container = encoder.container(keyedBy: CodingKeys.self) // Encode all our properties try endpoint?.encode(on: &_container, forKey: .endpoint) try imagingStudy?.encode(on: &_container, forKey: .imagingStudy) try series.encode(on: &_container, forKey: .series) try uid.encode(on: &_container, forKey: .uid, auxiliaryKey: ._uid) try super.encode(to: encoder) } // MARK: - Equatable & Hashable public override func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? ImagingManifestStudy else { return false } guard super.isEqual(to: _other) else { return false } return endpoint == _other.endpoint && imagingStudy == _other.imagingStudy && series == _other.series && uid == _other.uid } public override func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(endpoint) hasher.combine(imagingStudy) hasher.combine(series) hasher.combine(uid) } } /** Series identity of the selected instances. Series identity and locating information of the DICOM SOP instances in the selection. */ open class ImagingManifestStudySeries: BackboneElement { /// Series instance UID public var uid: FHIRPrimitive<FHIRURI> /// Series access endpoint public var endpoint: [Reference]? /// The selected instance public var instance: [ImagingManifestStudySeriesInstance] /// Designated initializer taking all required properties public init(instance: [ImagingManifestStudySeriesInstance], uid: FHIRPrimitive<FHIRURI>) { self.instance = instance self.uid = uid super.init() } /// Convenience initializer public convenience init( endpoint: [Reference]? = nil, `extension`: [Extension]? = nil, id: FHIRPrimitive<FHIRString>? = nil, instance: [ImagingManifestStudySeriesInstance], modifierExtension: [Extension]? = nil, uid: FHIRPrimitive<FHIRURI>) { self.init(instance: instance, uid: uid) self.endpoint = endpoint self.`extension` = `extension` self.id = id self.modifierExtension = modifierExtension } // MARK: - Codable private enum CodingKeys: String, CodingKey { case endpoint case instance case uid; case _uid } /// Initializer for Decodable public required init(from decoder: Decoder) throws { let _container = try decoder.container(keyedBy: CodingKeys.self) // Decode all our properties self.endpoint = try [Reference](from: _container, forKeyIfPresent: .endpoint) self.instance = try [ImagingManifestStudySeriesInstance](from: _container, forKey: .instance) self.uid = try FHIRPrimitive<FHIRURI>(from: _container, forKey: .uid, auxiliaryKey: ._uid) try super.init(from: decoder) } /// Encodable public override func encode(to encoder: Encoder) throws { var _container = encoder.container(keyedBy: CodingKeys.self) // Encode all our properties try endpoint?.encode(on: &_container, forKey: .endpoint) try instance.encode(on: &_container, forKey: .instance) try uid.encode(on: &_container, forKey: .uid, auxiliaryKey: ._uid) try super.encode(to: encoder) } // MARK: - Equatable & Hashable public override func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? ImagingManifestStudySeries else { return false } guard super.isEqual(to: _other) else { return false } return endpoint == _other.endpoint && instance == _other.instance && uid == _other.uid } public override func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(endpoint) hasher.combine(instance) hasher.combine(uid) } } /** The selected instance. Identity and locating information of the selected DICOM SOP instances. */ open class ImagingManifestStudySeriesInstance: BackboneElement { /// SOP class UID of instance public var sopClass: FHIRPrimitive<FHIRURI> /// Selected instance UID public var uid: FHIRPrimitive<FHIRURI> /// Designated initializer taking all required properties public init(sopClass: FHIRPrimitive<FHIRURI>, uid: FHIRPrimitive<FHIRURI>) { self.sopClass = sopClass self.uid = uid super.init() } /// Convenience initializer public convenience init( `extension`: [Extension]? = nil, id: FHIRPrimitive<FHIRString>? = nil, modifierExtension: [Extension]? = nil, sopClass: FHIRPrimitive<FHIRURI>, uid: FHIRPrimitive<FHIRURI>) { self.init(sopClass: sopClass, uid: uid) self.`extension` = `extension` self.id = id self.modifierExtension = modifierExtension } // MARK: - Codable private enum CodingKeys: String, CodingKey { case sopClass; case _sopClass case uid; case _uid } /// Initializer for Decodable public required init(from decoder: Decoder) throws { let _container = try decoder.container(keyedBy: CodingKeys.self) // Decode all our properties self.sopClass = try FHIRPrimitive<FHIRURI>(from: _container, forKey: .sopClass, auxiliaryKey: ._sopClass) self.uid = try FHIRPrimitive<FHIRURI>(from: _container, forKey: .uid, auxiliaryKey: ._uid) try super.init(from: decoder) } /// Encodable public override func encode(to encoder: Encoder) throws { var _container = encoder.container(keyedBy: CodingKeys.self) // Encode all our properties try sopClass.encode(on: &_container, forKey: .sopClass, auxiliaryKey: ._sopClass) try uid.encode(on: &_container, forKey: .uid, auxiliaryKey: ._uid) try super.encode(to: encoder) } // MARK: - Equatable & Hashable public override func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? ImagingManifestStudySeriesInstance else { return false } guard super.isEqual(to: _other) else { return false } return sopClass == _other.sopClass && uid == _other.uid } public override func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(sopClass) hasher.combine(uid) } }
30.647196
143
0.720973
e8c92b91cfcee473ccc86a4211fd4b72a6a278e9
2,747
// // NetworkLink.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML NetworkLink /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="NetworkLink" type="kml:NetworkLinkType" substitutionGroup="kml:AbstractFeatureGroup"/> public class NetworkLink :SPXMLElement, AbstractFeatureGroup , HasXMLElementValue{ public static var elementName: String = "NetworkLink" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Document: v.value.abstractFeatureGroup.append(self) case let v as Folder: v.value.abstractFeatureGroup.append(self) default: break } } } } public var value : NetworkLinkType public required init(attributes:[String:String]){ self.value = NetworkLinkType(attributes: attributes) super.init(attributes: attributes) } public var abstractObject : AbstractObjectType { return self.value } public var abstractFeature : AbstractFeatureType { return self.value } } /// KML NetworkLinkType /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <complexType name="NetworkLinkType" final="#all"> /// <complexContent> /// <extension base="kml:AbstractFeatureType"> /// <sequence> /// <element ref="kml:refreshVisibility" minOccurs="0"/> /// <element ref="kml:flyToView" minOccurs="0"/> /// <choice> /// <annotation> /// <documentation>Url deprecated in 2.2</documentation> /// </annotation> /// <element ref="kml:Url" minOccurs="0"/> /// <element ref="kml:Link" minOccurs="0"/> /// </choice> /// <element ref="kml:NetworkLinkSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// <element ref="kml:NetworkLinkObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// </sequence> /// </extension> /// </complexContent> /// </complexType> /// <element name="NetworkLinkSimpleExtensionGroup" abstract="true" type="anySimpleType"/> /// <element name="NetworkLinkObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/> public class NetworkLinkType: AbstractFeatureType { public var refreshVisibility:RefreshVisibility! public var flyToView:FlyToView! // var link:Link? public var networkLinkSimpleExtensionGroup:[AnyObject] = [] public var networkLinkObjectExtensionGroup:[AbstractObjectGroup] = [] }
38.690141
117
0.662905
9ccae7f0803b26d5c5d995c87f049e31129ef246
640
// // Reusable.swift // Coyote // // Created by Antoine van der Lee on 14/04/2017. // Copyright © 2017 WeTransfer. All rights reserved. // import UIKit typealias ReuseIdentifier = String /// A protocol defining a reusable view type protocol Reusable { /// Returns default reuseIdentifier for this content type. static var reuseIdentifier: ReuseIdentifier { get } } extension Reusable { static var reuseIdentifier: ReuseIdentifier { return String(describing: self) } } extension UITableViewCell: Reusable { } extension UICollectionReusableView: Reusable {} extension UITableViewHeaderFooterView: Reusable { }
23.703704
62
0.739063
912b01926ba7694e12b4d0bd0c4e8bab831d0dd9
368
// // ResultCallback.swift // // // Created by Vladislav Fitc on 03/03/2020. // import Foundation public typealias ResultCallback<T> = (Result<T, Error>) -> Void public typealias ResultTaskCallback<T: Task & Codable> = (Result<WaitableWrapper<T>, Error>) -> Void public typealias ResultBatchesCallback = (Result<WaitableWrapper<BatchesResponse>, Error>) -> Void
28.307692
100
0.733696
69107c477da5d7f3d0a7e6c070c5bd8d507e2fb0
242
// // FavoritebookApp.swift // Favoritebook // // Created by Adem Deliaslan on 6.03.2022. // import SwiftUI @main struct FavoritebookApp: App { var body: some Scene { WindowGroup { ContentView() } } }
13.444444
43
0.586777
8f4c1debd6b7ce006173e3d4f3bcbf4f222d2271
3,452
/// MIT License /// /// Copyright (c) 2020 linhey /// /// 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 // // Stuart // // github: https://github.com/linhay/Stuart // Copyright (c) 2019 linhay - https://github.com/linhay // // 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 import UIKit open class SectionHorizontalListCell: UICollectionViewCell { public let sectionView = SectionView() private(set) lazy var manager = SectionManager(sectionView: sectionView) override init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder: NSCoder) { super.init(coder: coder) initialize() } open func config(section: SectionProtocol) { self.manager.update(sections: [section]) } private func initialize() { contentView.addSubview(sectionView) sectionView.scrollDirection = .horizontal sectionView.translatesAutoresizingMaskIntoConstraints = false sectionView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true sectionView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true sectionView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true sectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true } }
43.15
94
0.733488
dd94d2a6e16c99e1d57c18b368a3c626afb97a31
1,820
// // PickerViewController.swift // ColorPicker // // Created by Robert Vojta on 07.10.15. // Copyright © 2015 Robert Vojta. All rights reserved. // import UIKit class PickerViewController: UIViewController { @IBOutlet var pickerPlaceholder: UIView! @IBOutlet var selectedColorView: UIView! @IBOutlet var selectedColorLabel: UILabel! @IBOutlet var forceTouchActiveLabel: UILabel! let pickerView = ColorPicker() override func viewDidLoad() { super.viewDidLoad() selectedColorLabel.text = nil forceTouchActiveLabel.alpha = 0.0 selectedColorView.layer.borderColor = UIColor.blackColor().CGColor selectedColorView.layer.borderWidth = 1.0 pickerPlaceholder.addSubview(pickerView) pickerView.translatesAutoresizingMaskIntoConstraints = false pickerView.centerXAnchor.constraintEqualToAnchor(pickerPlaceholder.centerXAnchor).active = true pickerView.centerYAnchor.constraintEqualToAnchor(pickerPlaceholder.centerYAnchor).active = true pickerView.didChangeColor = { [weak self] color in self?.selectedColorView.backgroundColor = color var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: nil) { let h = Int(hue * 360) let s = Int(saturation * 100) let b = Int(brightness * 100) self?.selectedColorLabel.text = "HSB \(h)° \(s)% \(b)%" self?.forceTouchActiveLabel.alpha = 1.0 - brightness } } pickerView.didChangeColor?(pickerView.color) } }
33.703704
103
0.625824
eba744d552818b8f17bec24b574199b3c54f2a51
3,216
import ProjectDescription extension TargetScript { public static func sourceryScript() -> TargetScript { let sourceryPath = "$PODS_ROOT/Sourcery/bin/sourcery" return .pre( script: "\"\(sourceryPath)\"", name: "Sourcery", basedOnDependencyAnalysis: true ) } public static func rswiftScript() -> TargetScript { let rswiftPath = "$PODS_ROOT/R.swift/rswift" let outputPath = "$SRCROOT/$PROJECT_NAME/Sources/Supports/Helpers/Rswift/R.generated.swift" return .pre( script: "\"\(rswiftPath)\" generate \"\(outputPath)\"", name: "R.swift", outputPaths: ["\(outputPath)"], basedOnDependencyAnalysis: false ) } public static func swiftLintScript() -> TargetScript { let swiftLintPath = """ if [ -z "$CI" ]; then ${PODS_ROOT}/SwiftLint/swiftlint fi """ return .pre( script: swiftLintPath, name: "SwiftLint", basedOnDependencyAnalysis: true ) } public static func swiftFormatScript() -> TargetScript { let runSwiftFormat = """ if [ -z "$CI" ]; then "${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" "$SRCROOT" fi """ return .pre( script: runSwiftFormat, name: "SwiftFormat", basedOnDependencyAnalysis: true ) } public static func swiftFormatLintScript() -> TargetScript { let runSwiftFormat = """ if [ -z "$CI" ]; then "${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat" "$SRCROOT" --lint --lenient fi """ return .pre( script: runSwiftFormat, name: "SwiftFormat Lint", basedOnDependencyAnalysis: true ) } public static func firebaseScript() -> TargetScript { let debugStagingName = BuildConfiguration.debugStaging.name.rawValue let releaseStagingName = BuildConfiguration.releaseStaging.name.rawValue let debugProductionName = BuildConfiguration.debugProduction.name.rawValue let releaseProductionName = BuildConfiguration.releaseProduction.name.rawValue let googleServicePath = "$SRCROOT/$PROJECT_NAME/Configurations/Plists/GoogleService" let stagingPlistPath = "$PATH_TO_GOOGLE_PLISTS/Staging/GoogleService-Info.plist" let productionPlistPath = "$PATH_TO_GOOGLE_PLISTS/Production/GoogleService-Info.plist" let appPlistPath = "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/GoogleService-Info.plist" let script = """ PATH_TO_GOOGLE_PLISTS="\(googleServicePath)" case "${CONFIGURATION}" in "\(debugStagingName)" | "\(releaseStagingName)" ) cp -r "\(stagingPlistPath)" "\(appPlistPath)" ;; "\(debugProductionName)" | "\(releaseProductionName)" ) cp -r "\(productionPlistPath)" "\(appPlistPath)" ;; *) ;; esac """ return .post( script: script, name: "Copy GoogleService-Info.plist", basedOnDependencyAnalysis: true ) } }
33.5
99
0.596082
76a96a1c919ad9527f271f0db550cdc1a1137656
4,819
// // SwiftAsyncSocket.swift // SwiftAsyncSocket // // Created by chouheiwa on 2018/12/7. // Copyright © 2018 chouheiwa. All rights reserved. // import Foundation struct SwiftAsyncSocketKeys { static let socketNull: Int32 = -1 static let socketQueueName: String = "SwiftAsyncSocket" static let asyncSocketThreadName: String = "SwiftAsyncSocket-CFStream" static let threadQueueName: String = "SwiftAsyncSocket-CFStreamThreadSetup" init() {} } public class SwiftAsyncSocket: NSObject { var flags: SwiftAsyncSocketFlags = [] var config: SwiftAsyncSocketConfig = [] /// Real storable delagate weak var delegateStore: SwiftAsyncSocketDelegate? var delegateQueueStore: DispatchQueue? public internal(set) var socket4FD: Int32 = SwiftAsyncSocketKeys.socketNull public internal(set) var socket6FD: Int32 = SwiftAsyncSocketKeys.socketNull public internal(set) var socketUN: Int32 = SwiftAsyncSocketKeys.socketNull var socketURL: URL? var stateIndex: Int = 0 var connectInterface4: Data? var connectInterface6: Data? var connectInterfaceUN: Data? var socketQueue: DispatchQueue var accept4Source: DispatchSourceRead? var accept6Source: DispatchSourceRead? var acceptUNSource: DispatchSourceRead? var connectTimer: DispatchSourceTimer? var readSource: DispatchSourceRead? var writeSource: DispatchSourceWrite? var readTimer: DispatchSourceTimer? var writeTimer: DispatchSourceTimer? var readQueue: [SwiftAsyncPacketProtocol] = [] var writeQueue: [SwiftAsyncPacketProtocol] = [] var currentRead: SwiftAsyncPacketProtocol? var currentWrite: SwiftAsyncPacketProtocol? var socketFDBytesAvailable: UInt = 0 var preBuffer: SwiftAsyncSocketBuffer #if os(iOS) var streamContext: CFStreamClientContext = CFStreamClientContext() var readStream: CFReadStream? var writeStream: CFWriteStream? #endif var sslContext: SSLContext? var sslPreBuffer: SwiftAsyncSocketBuffer? var sslWriteCachedLength: size_t = 0 var sslErrCode: OSStatus = 0 var lastSSLHandshakeError: OSStatus = 0 let queueKey: DispatchSpecificKey<SwiftAsyncSocket> = DispatchSpecificKey<SwiftAsyncSocket>() var userDataStore: Any? var alternateAddressDelayStore: TimeInterval = 0 public init(delegate: SwiftAsyncSocketDelegate? = nil, delegateQueue: DispatchQueue? = nil, socketQueue: DispatchQueue? = nil) { delegateStore = delegate delegateQueueStore = delegateQueue if let socketQueue = socketQueue { assert(socketQueue != DispatchQueue.global(qos: .utility), SwiftAsyncSocketAssertError.queueLevel.description) assert(socketQueue != DispatchQueue.global(qos: .userInitiated), SwiftAsyncSocketAssertError.queueLevel.description) assert(socketQueue != DispatchQueue.global(qos: .default), SwiftAsyncSocketAssertError.queueLevel.description) self.socketQueue = socketQueue } else { self.socketQueue = DispatchQueue(label: SwiftAsyncSocketKeys.socketQueueName) } preBuffer = SwiftAsyncSocketPreBuffer(capacity: 4 * 1024) super.init() self.socketQueue.setSpecific(key: queueKey, value: self) } deinit { flags.insert(.dealloc) socketQueueDo { self.closeSocket(error: nil) } delegate = nil delegateQueue = nil } } // MARK: - init Function extension SwiftAsyncSocket { convenience init(from connectedSocketFD: Int32, delegate: SwiftAsyncSocketDelegate? = nil, delegateQueue: DispatchQueue?, socketQueue: DispatchQueue?) throws { self.init(delegate: delegate, delegateQueue: delegateQueue, socketQueue: socketQueue) try self.socketQueue.sync { var addr: sockaddr = sockaddr() var addrSize = socklen_t(MemoryLayout.size(ofValue: addr)) let result = Darwin.getpeername(connectedSocketFD, &addr, &addrSize) guard result == 0 else { throw SwiftAsyncSocketError(msg: "Attempt to create socket from socket FD failed. getpeername() failed") } if addr.sa_family == Darwin.AF_INET { socket4FD = connectedSocketFD } else if addr.sa_family == AF_INET6 { socket6FD = connectedSocketFD } else { throw SwiftAsyncSocketError(msg: "Attempt to create socket from socket FD failed. socket FD is neither IPv4 nor IPv6") } flags = .started didConnect(stateIndex) } } }
28.514793
120
0.671301
f91e58ec537ae2ccd71e031ed53e9c30e9395052
1,124
// // NibView.swift // FyreSwiftExtensions // // Created by Travis Delly on 4/22/19. // import UIKit /// A base UIView subclass that instaniates a view /// from a nib file of the same class name in order to /// allow reusable views to be created. public protocol NibView where Self: UIView { } extension NibView { /// Initializes the view from a xib /// file and configure initial constrains. public func xibSetup() { backgroundColor = .clear let view = loadViewFromNib() addEdgeConstrainedSubView(view: view) } /// Loads a view from it's xib file. /// /// - Returns: an instantiated view from the Nib file of the same class name. fileprivate func loadViewFromNib<T: UIView>() -> T { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) guard let view = nib.instantiate(withOwner: self, options: nil).first as? T else { fatalError("Cannot instantiate a UIView from the nib for class \(type(of: self))") } return view } }
28.1
94
0.637011
f95e39a6399554997159911fb8dd609d04996499
1,724
// // ObservableTypeFilters.swift // WalletCore // // Created by Teodor Penkov on 1.02.18. // Copyright © 2018 Lykke. All rights reserved. // import Foundation import RxSwift // MARK: - Default unwrapped implementation public extension ObservableType { func filterSuccess<T>() -> Observable<T> where Self.E == ApiResult<T> { return map { $0.getSuccess() } .filterNil() } public func filterError<T>() -> Observable<[AnyHashable : Any]> where Self.E == ApiResult<T>{ return map { $0.getError() } .filterNil() } public func filterNotAuthorized<T>() -> Observable<Bool> where Self.E == ApiResult<T> { return filter { $0.notAuthorized } .map { _ in true } } public func isLoading<T>() -> Observable<Bool> where Self.E == ApiResult<T> { return map { $0.isLoading } } public func filterForbidden<T>() -> Observable<Void> where Self.E == ApiResult<T> { return filter { $0.isForbidden } .map{ _ in () } } } // MARK: - Concrecte implementations public extension ObservableType where Self.E == ApiResult<LWSpotWallet?> { public func filterSuccess() -> Observable<LWSpotWallet?> { return filter{ $0.isSuccess } .map { return $0.getSuccess() ?? nil } } } public extension ObservableType where Self.E == (apiResult: ApiResult<LWPacketGraphData>, interval: Bool) { public func filterSuccess() -> Observable<LWPacketGraphData> { return map { $0.apiResult.getSuccess() } .filterNil() } public func isLoading() -> Observable<Bool> { return filter{!$0.interval}.map{$0.apiResult.isLoading} } }
28.733333
107
0.610789
917fcf57328facabf788ffb6605c7cb42d144297
888
// // Stream_it_iOSApp.swift // Stream.it iOS // // Created by Mark Howard on 26/09/2021. // import SwiftUI import AVFAudio @main struct Stream_it_iOSApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playback, mode: .moviePlayback, options: [.allowAirPlay, .allowBluetooth]) } catch { print("Setting category to AVAudioSessionCategoryPlayback failed.") } return true } }
25.371429
117
0.649775
16046107d4acb2741bd609493a999ca45f834899
1,292
// // ProcessViewController.swift // Go Study // // Created by Himself65 on 2018/2/12. // Copyright © 2018年 Himself65. All rights reserved. // import UIKit class ProcessViewController: SuperViewController { @IBOutlet weak var progerssView: ProgressView! var param = userDefault.integer(forKey: "lastDuration") var maxtime = userDefault.integer(forKey: "lastDuration") override func viewDidLoad() { super.viewDidLoad() let time = TimeInterval(exactly: (param * 60)) let timer = Timer.scheduledTimer(timeInterval: time!, target: self, selector: #selector(timeChange), userInfo: nil, repeats: true) RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) } @objc func timeChange() { param = param - 1 if param == -1 { noticeTop("结束倒计时") dismiss(animated: true , completion: nil) } else { let dur = (param / maxtime) * 100 progerssView.setProgress(dur, aimated: true, withDuration: 0.55) } } @IBAction func exit(_ sender: Any) { self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
27.489362
138
0.612229
335a854438ec50906ff502f1a9db03f720c3da6b
14,260
// // MoviesViewController.swift // MovieReviews // // Created by drishi on 9/13/17. // Copyright © 2017 Droan Rishi. All rights reserved. // import UIKit import AFNetworking import MBProgressHUD import Foundation import SystemConfiguration class MoviesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet var parentView: UIView! @IBOutlet weak var movieTableView: UITableView! @IBOutlet weak var movieCollectionView: UICollectionView! @IBOutlet weak var errorView: UIView! var movies: [NSDictionary]? var filteredMovies: [NSDictionary]? var endpoint = NSString() var searchBar: UISearchBar! var gridView: Bool! var internetAvailable: Bool! override func viewDidLoad() { super.viewDidLoad() self.gridView = false self.searchBar = UISearchBar() self.searchBar.sizeToFit() self.searchBar.delegate = self navigationItem.titleView = self.searchBar let layoutButton = UIBarButtonItem(image: UIImage(named: "grid-icon"), style: .plain, target: self, action: #selector(changeLayout)) navigationItem.leftBarButtonItem = layoutButton let textFieldSearchBar = self.searchBar.value(forKey: "searchField") as? UITextField textFieldSearchBar?.textColor = UIColor.red textFieldSearchBar?.backgroundColor = UIColor.black textFieldSearchBar?.tintColor = UIColor.red textFieldSearchBar?.attributedPlaceholder = NSAttributedString(string: "Search for a movie", attributes: [NSForegroundColorAttributeName: UIColor.red]) let glassIconView = textFieldSearchBar?.leftView as? UIImageView glassIconView?.image = glassIconView?.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) glassIconView?.tintColor = UIColor.red if !isInternetAvailable() { self.internetAvailable = false movieTableView.isHidden = true movieCollectionView.isHidden = true errorView.isHidden = false return } self.internetAvailable = true movieTableView.dataSource = self movieTableView.delegate = self movieCollectionView.dataSource = self movieCollectionView.delegate = self movieCollectionView.isHidden = true movieCollectionView!.contentInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) errorView.isHidden = true let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = URL(string: "https://api.themoviedb.org/3/movie/\(self.endpoint)?api_key=\(apiKey)") let request = URLRequest(url: url!) let session = URLSession( configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main ) let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) movieTableView.insertSubview(refreshControl, at: 0) MBProgressHUD.showAdded(to: self.parentView, animated: true) let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: {(dataOrNil, response, error) in if let data = dataOrNil { if let responseDictionary = try! JSONSerialization.jsonObject( with: data, options: []) as? NSDictionary { NSLog("response: \(responseDictionary)") self.movies = responseDictionary["results"] as? [NSDictionary] self.filteredMovies = responseDictionary["results"] as? [NSDictionary] self.movieTableView.reloadData() self.movieCollectionView.reloadData() MBProgressHUD.hide(for: self.parentView, animated: true) } } }) task.resume() } func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String) { self.filteredMovies = textSearched.isEmpty ? self.movies: self.movies?.filter{ (item: NSDictionary) -> Bool in title = item["title"] as! String if title != nil { return (title!.range(of: textSearched, options: .caseInsensitive, range: nil, locale: nil) != nil) } return false } self.movieTableView.reloadData() self.movieCollectionView.reloadData() } func changeLayout(_ layoutButton: UIBarButtonItem) { if self.gridView { layoutButton.image = UIImage(named: "grid-icon") if (self.internetAvailable) { self.movieCollectionView.isHidden = true self.movieTableView.isHidden = false } self.gridView = false } else { layoutButton.image = UIImage(named: "list-icon") if (self.internetAvailable) { self.movieTableView.isHidden = true self.movieCollectionView.isHidden = false } self.gridView = true } } func refreshControlAction(_ refreshControl: UIRefreshControl) { let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)") let request = URLRequest(url: url!) let session = URLSession( configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main ) let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: {(dataOrNil, response, error) in if let data = dataOrNil { if let responseDictionary = try! JSONSerialization.jsonObject( with: data, options: []) as? NSDictionary { NSLog("response: \(responseDictionary)") self.movies = responseDictionary["results"] as! [NSDictionary] self.movieTableView.reloadData() refreshControl.endRefreshing() } } }) task.resume() } func isInternetAvailable() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let movie = filteredMovies { return (filteredMovies?.count)! } else { return 0 } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let movie = filteredMovies { return (filteredMovies?.count)! } else { return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionCell", for: indexPath) as! MovieCollectionViewCell let movie = filteredMovies![indexPath.row] let title = movie["title"] as! String let posterPath = movie["poster_path"] as! String let baseUrl = "https://image.tmdb.org/t/p/w500/" let posterUrl = NSURL(string: baseUrl+posterPath) let posterUrlRequest = NSURLRequest(url: (posterUrl as URL?)!) cell.posterView.setImageWith(posterUrlRequest as URLRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in // imageResponse will be nil if the image is cached if imageResponse != nil { cell.posterView.alpha = 0.0 cell.posterView.image = image UIView.animate(withDuration: 0.8, animations: { () -> Void in cell.posterView.alpha = 1.0 }, completion: nil) } else { cell.posterView.image = image } }, failure: { (imageRequest, imageResponse, error) -> Void in // do something for the failure condition }) cell.posterView.layer.masksToBounds = true cell.posterView.layer.cornerRadius = 5 print ("Row \(indexPath.row)") cell.isSelected = false return cell } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell let movie = filteredMovies![indexPath.row] let title = movie["title"] as! String let overview = movie["overview"] as! String let posterPath = movie["poster_path"] as! String var rating = movie["vote_average"] as! Float rating = rating / 2 cell.movieTitle.text = title cell.overviewLabel.text = overview //cell.movieRatingLabel.updateOnTouch = false cell.movieRatingLabel.rating = Double(rating) cell.movieRatingLabel.settings.updateOnTouch = false let baseUrl = "https://image.tmdb.org/t/p/w500/" let posterUrl = NSURL(string: baseUrl+posterPath) let posterUrlRequest = NSURLRequest(url: (posterUrl as URL?)!) cell.posterView.setImageWith(posterUrlRequest as URLRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in // imageResponse will be nil if the image is cached if imageResponse != nil { cell.posterView.alpha = 0.0 cell.posterView.image = image UIView.animate(withDuration: 0.5, animations: { () -> Void in cell.posterView.alpha = 1.0 }, completion: nil) } else { cell.posterView.image = image } }, failure: { (imageRequest, imageResponse, error) -> Void in // do something for the failure condition }) cell.posterView.layer.cornerRadius = 5.0 cell.posterView.clipsToBounds = true print ("Row \(indexPath.row)") cell.selectionStyle = .none return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showMovieDetailsSegue" { let cell = sender as! MovieCell if let indexPath = movieTableView.indexPath(for: cell) { let movieDetailsController = segue.destination as! MovieDetailsViewController movieDetailsController.movie = (self.filteredMovies?[indexPath.row])! movieTableView.deselectRow(at: indexPath, animated: true) } } else if segue.identifier == "showMovieDetailsSegue2" { let cell = sender as! MovieCollectionViewCell if let indexPath = movieCollectionView.indexPath(for: cell) { let movieDetailsController = segue.destination as! MovieDetailsViewController movieDetailsController.movie = (self.filteredMovies?[indexPath.row])! movieTableView.deselectRow(at: indexPath, animated: true) } } } /* // 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?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
47.375415
165
0.554769
f78c300daa3898b9c6f39a977e2d485f1a36a968
3,643
// // KeyboardView.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import UIKit public protocol KeyboardDelegate { func noteOn(note: Int) func noteOff(note: Int) } public class KeyboardView: UIView { public var delegate: KeyboardDelegate? var keys: [UIView] = [] let notesWithFlats = ["C", "D♭", "D", "E♭", "E", "F", "G♭", "G", "A♭", "A", "B♭", "B"] let notesWithSharps = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] public init(width: Int, height: Int, lowestKey: Int = 48, totalKeys: Int = 37) { super.init(frame: CGRect(x: 0, y: 0, width: width, height: height)) let allowedNotes = notesWithSharps //["A", "B", "C#", "D", "E", "F#", "G"] let keyWidth = width / totalKeys - 1 let height = Int(frame.height) let blackFrame = UIView(frame: CGRect(x: 0, y: 0, width: (keyWidth + 1) * totalKeys + 1, height: height)) blackFrame.backgroundColor = UIColor.blackColor() self.addSubview(blackFrame) var keyCount = 0 var increment = 0 while keyCount < totalKeys { if allowedNotes.indexOf(notesWithFlats[(lowestKey + increment) % 12]) != nil || allowedNotes.indexOf(notesWithSharps[(lowestKey + increment) % 12]) != nil { let newButton = UIView(frame:CGRect(x: 0, y: 0, width: keyWidth, height: height - 2)) if notesWithSharps[(lowestKey + increment) % 12].rangeOfString("#") != nil { newButton.backgroundColor = UIColor.blackColor() } else { newButton.backgroundColor = UIColor.whiteColor() } newButton.setNeedsDisplay() newButton.frame.origin.x = CGFloat(keyCount * (keyWidth + 1)) + 1 newButton.frame.origin.y = CGFloat(1) newButton.tag = lowestKey + increment keys.append(newButton) self.addSubview(newButton) keyCount += 1 } increment += 1 } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // ********************************************************* // MARK: - Handle Touches // ********************************************************* override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { for key in keys { if CGRectContainsPoint(key.frame, touch.locationInView(self)) { delegate?.noteOn(key.tag) } } } } override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { for key in keys { if CGRectContainsPoint(key.frame, touch.locationInView(self)) { delegate?.noteOn(key.tag) } } // determine vertical value //setPercentagesWithTouchPoint(touchPoint) } } override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { for key in keys { if CGRectContainsPoint(key.frame, touch.locationInView(self)) { delegate?.noteOff(key.tag) } } } } }
34.695238
169
0.507823
d52b52fbb009612136c57c6507d59ee227d1e7ea
4,827
// // Created by khoi on 9/30/18. // Copyright (c) 2018 khoi. All rights reserved. // import Foundation import RxFlow import UIKit class BudgetFlow: Flow { var root: Presentable { return rootViewController } private let services: AppServices private let rootViewController = UINavigationController() init(services: AppServices) { self.services = services } deinit { print("\(type(of: self)): \(#function)") } func navigate(to step: Step) -> NextFlowItems { guard let step = step as? AppStep else { return .none } switch step { case .walletList: return navigateToWalletList() case .createWallet: return navigateToCreateBudget() case .createWalletSuccess: return popToRootViewController() case let .transactionList(walletId): return navigateToTransactionList(walletId: walletId) case let .addTransaction(walletId): return navigateToAddTransaction(walletId: walletId) case .categorySelection: return navigateToCategorySelection() case let .categorySelected(category): return popBackToTransactionList(with: category) case .addTransactionSuccess, .addCategorySuccess: return popViewController() case .addCategory: return navigateToAddCategory() } } private func popBackToTransactionList(with selectedCategory: Category) -> NextFlowItems { rootViewController.popViewController(animated: true) if let addTransactionVc = rootViewController.topViewController as? AddTransactionViewController, let addTransactionViewModel = addTransactionVc.viewModel { addTransactionViewModel.selectCategory.accept(selectedCategory) } return .none } private func navigateToCategorySelection() -> NextFlowItems { let viewModel = CategorySelectionViewModel(budgetService: services.budgetService) var viewController = CategorySelectionViewController() viewController.bindViewModel(to: viewModel) rootViewController.pushViewController(viewController, animated: true) return .one(flowItem: NextFlowItem(nextPresentable: viewController, nextStepper: viewModel)) } private func navigateToWalletList() -> NextFlowItems { let viewModel = WalletListViewModel(budgetService: services.budgetService) var viewController = WalletListViewController() viewController.title = "Wallet List" viewController.bindViewModel(to: viewModel) rootViewController.pushViewController(viewController, animated: true) return .one(flowItem: NextFlowItem(nextPresentable: viewController, nextStepper: viewModel)) } private func navigateToCreateBudget() -> NextFlowItems { let viewModel = CreateWalletViewModel(budgetService: services.budgetService) var viewController = CreateWalletViewController() viewController.title = "Create Wallet" viewController.bindViewModel(to: viewModel) rootViewController.pushViewController(viewController, animated: true) return .one(flowItem: NextFlowItem(nextPresentable: viewController, nextStepper: viewModel)) } private func navigateToTransactionList(walletId: String) -> NextFlowItems { let viewModel = TransactionListViewModel(budgetService: services.budgetService, walletId: walletId) var viewController = TransactionListViewController() viewController.title = "Transaction List" viewController.bindViewModel(to: viewModel) rootViewController.pushViewController(viewController, animated: true) return .one(flowItem: NextFlowItem(nextPresentable: viewController, nextStepper: viewModel)) } private func popToRootViewController() -> NextFlowItems { rootViewController.popToRootViewController(animated: true) return .none } private func navigateToAddTransaction(walletId: String) -> NextFlowItems { let addTransactionViewModel = AddTransactionViewModel(budgetService: services.budgetService, walletId: walletId) var addTransactionVC = AddTransactionViewController() addTransactionVC.title = "Add Transaction" addTransactionVC.bindViewModel(to: addTransactionViewModel) rootViewController.pushViewController(addTransactionVC, animated: true) return .one(flowItem: NextFlowItem(nextPresentable: addTransactionVC, nextStepper: addTransactionViewModel)) } private func popViewController() -> NextFlowItems { rootViewController.popViewController(animated: true) return .none } private func navigateToAddCategory() -> NextFlowItems { let viewModel = AddCategoryViewModel(budgetService: services.budgetService) var viewController = AddCategoryViewController() viewController.bindViewModel(to: viewModel) rootViewController.pushViewController(viewController, animated: true) return .one(flowItem: NextFlowItem(nextPresentable: viewController, nextStepper: viewModel)) } }
35.233577
116
0.769422
fb964b516e43b83fa8d1f0de2ec85d298ff6cf65
8,417
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import PackageModel public let moduleMapFilename = "module.modulemap" /// A protocol for targets which might have a modulemap. protocol ModuleMapProtocol { var moduleMapPath: AbsolutePath { get } var moduleMapDirectory: AbsolutePath { get } } extension SystemLibraryTarget: ModuleMapProtocol { var moduleMapDirectory: AbsolutePath { return path } public var moduleMapPath: AbsolutePath { return moduleMapDirectory.appending(component: moduleMapFilename) } } extension ClangTarget: ModuleMapProtocol { var moduleMapDirectory: AbsolutePath { return includeDir } public var moduleMapPath: AbsolutePath { return moduleMapDirectory.appending(component: moduleMapFilename) } } /// A modulemap generator for clang targets. /// /// Modulemap is generated under the following rules provided it is not already present in include directory: /// /// * "include/foo/foo.h" exists and `foo` is the only directory under include directory. /// Generates: `umbrella header "/path/to/include/foo/foo.h"` /// * "include/foo.h" exists and include contains no other directory. /// Generates: `umbrella header "/path/to/include/foo.h"` /// * Otherwise in all other cases. /// Generates: `umbrella "path/to/include"` public struct ModuleMapGenerator { /// The clang target to operate on. private let target: ClangTarget /// The file system to be used. private var fileSystem: FileSystem /// Stream on which warnings will be emitted. private let warningStream: OutputByteStream public init( for target: ClangTarget, fileSystem: FileSystem = localFileSystem, warningStream: OutputByteStream = stdoutStream ) { self.target = target self.fileSystem = fileSystem self.warningStream = warningStream } public enum ModuleMapError: Swift.Error { case unsupportedIncludeLayoutForModule(String, UnsupportedIncludeLayoutType) public enum UnsupportedIncludeLayoutType { case umbrellaHeaderWithAdditionalNonEmptyDirectories(AbsolutePath, [AbsolutePath]) case umbrellaHeaderWithAdditionalDirectoriesInIncludeDirectory(AbsolutePath, [AbsolutePath]) case umbrellaHeaderWithAdditionalFilesInIncludeDirectory(AbsolutePath, [AbsolutePath]) } } /// Create the synthesized modulemap, if necessary. /// Note: modulemap is not generated for test targets. public mutating func generateModuleMap(inDir wd: AbsolutePath) throws { assert(target.type == .library) // Return if modulemap is already present. guard !fileSystem.isFile(target.moduleMapPath) else { return } let includeDir = target.includeDir // Warn and return if no include directory. guard fileSystem.isDirectory(includeDir) else { warningStream <<< ("warning: no include directory found for target '\(target.name)'; " + "libraries cannot be imported without public headers") warningStream.flush() return } let walked = try fileSystem.getDirectoryContents(includeDir).map({ includeDir.appending(component: $0) }) let files = walked.filter({ fileSystem.isFile($0) && $0.suffix == ".h" }) let dirs = walked.filter({ fileSystem.isDirectory($0) }) let umbrellaHeaderFlat = includeDir.appending(component: target.c99name + ".h") if fileSystem.isFile(umbrellaHeaderFlat) { guard dirs.isEmpty else { throw ModuleMapError.unsupportedIncludeLayoutForModule( target.name, .umbrellaHeaderWithAdditionalNonEmptyDirectories(umbrellaHeaderFlat, dirs)) } try createModuleMap(inDir: wd, type: .header(umbrellaHeaderFlat)) return } diagnoseInvalidUmbrellaHeader(includeDir) let umbrellaHeader = includeDir.appending(components: target.c99name, target.c99name + ".h") if fileSystem.isFile(umbrellaHeader) { guard dirs.count == 1 else { throw ModuleMapError.unsupportedIncludeLayoutForModule( target.name, .umbrellaHeaderWithAdditionalDirectoriesInIncludeDirectory(umbrellaHeader, dirs)) } guard files.isEmpty else { throw ModuleMapError.unsupportedIncludeLayoutForModule( target.name, .umbrellaHeaderWithAdditionalFilesInIncludeDirectory(umbrellaHeader, files)) } try createModuleMap(inDir: wd, type: .header(umbrellaHeader)) return } diagnoseInvalidUmbrellaHeader(includeDir.appending(component: target.c99name)) try createModuleMap(inDir: wd, type: .directory(includeDir)) } /// Warn user if in case target name and c99name are different and there is a /// `name.h` umbrella header. private func diagnoseInvalidUmbrellaHeader(_ path: AbsolutePath) { let umbrellaHeader = path.appending(component: target.c99name + ".h") let invalidUmbrellaHeader = path.appending(component: target.name + ".h") if target.c99name != target.name && fileSystem.isFile(invalidUmbrellaHeader) { warningStream <<< ("warning: \(invalidUmbrellaHeader.asString) should be renamed to " + "\(umbrellaHeader.asString) to be used as an umbrella header") warningStream.flush() } } private enum UmbrellaType { case header(AbsolutePath) case directory(AbsolutePath) } private mutating func createModuleMap(inDir wd: AbsolutePath, type: UmbrellaType) throws { let stream = BufferedOutputByteStream() stream <<< "module \(target.c99name) {\n" switch type { case .header(let header): stream <<< " umbrella header \"\(header.asString)\"\n" case .directory(let path): stream <<< " umbrella \"\(path.asString)\"\n" } stream <<< " export *\n" stream <<< "}\n" // FIXME: This doesn't belong here. try fileSystem.createDirectory(wd, recursive: true) let file = wd.appending(component: moduleMapFilename) // If the file exists with the identical contents, we don't need to rewrite it. // Otherwise, compiler will recompile even if nothing else has changed. if let contents = try? localFileSystem.readFileContents(file), contents == stream.bytes { return } try fileSystem.writeFileContents(file, bytes: stream.bytes) } } extension ModuleMapGenerator.ModuleMapError: CustomStringConvertible { public var description: String { switch self { case .unsupportedIncludeLayoutForModule(let (name, problem)): return "target '\(name)' failed modulemap generation; \(problem)" } } } extension ModuleMapGenerator.ModuleMapError.UnsupportedIncludeLayoutType: CustomStringConvertible { public var description: String { switch self { case .umbrellaHeaderWithAdditionalNonEmptyDirectories(let (umbrella, dirs)): return "umbrella header defined at '\(umbrella.asString)', but directories exist: " + dirs.map({ $0.asString }).sorted().joined(separator: ", ") + "; consider removing them" case .umbrellaHeaderWithAdditionalDirectoriesInIncludeDirectory(let (umbrella, dirs)): return "umbrella header defined at '\(umbrella.asString)', but more than one directories exist: " + dirs.map({ $0.asString }).sorted().joined(separator: ", ") + "; consider reducing them to one" case .umbrellaHeaderWithAdditionalFilesInIncludeDirectory(let (umbrella, files)): return "umbrella header defined at '\(umbrella.asString)', but files exist:" + files.map({ $0.asString }).sorted().joined(separator: ", ") + "; consider removing them" } } }
40.080952
113
0.663894
3869fd082a5ee2ac1422d018d353157fa132faec
109
import XCTest import JawsTests var tests = [XCTestCaseEntry]() tests += JawsTests.allTests() XCTMain(tests)
15.571429
31
0.770642
e9030dbd58244964c397c8e030ff2c48d25019d3
58,997
/* * Copyright (c) 2020, Nordic Semiconductor * 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 nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 CoreBluetooth open class CBMCentralManagerMock: NSObject, CBMCentralManager { /// Mock RSSI deviation. /// /// Returned RSSI values will be in range /// `(base RSSI - deviation)...(base RSSI + deviation)`. fileprivate static let rssiDeviation = 15 // dBm /// A list of all mock managers instantiated by user. // private static var managers: [WeakRef<CBMCentralManagerMock>] = [] private static let managers = NSHashTable<CBMCentralManagerMock>.weakObjects() /// A list of peripherals known to the system. private static var peripherals: [CBMPeripheralSpec] = [] { didSet { print("↗️↗️ did set peripherals \(CBMCentralManagerMock.managers.allObjects) -> Periherals: \(CBMCentralManagerMock.peripherals.map { $0.identifier })") } } /// The global state of the Bluetooth adapter on the device. fileprivate private(set) static var managerState: CBMManagerState = .poweredOff { didSet { print("↗️ update manger state \(managers.allObjects)") // For all existing managers... managers.allObjects .forEach { manager in // ...stop scanning if state changed to any other state // than `.poweredOn`. Also, forget all peripherals. if managerState != .poweredOn { manager.isScanning = false manager.scanFilter = nil manager.scanOptions = nil manager.peripherals.values.forEach { $0.managerPoweredOff() } print("↗️↗️ set state \(CBMCentralManagerMock.managers.allObjects) -> Periherals: \(CBMCentralManagerMock.peripherals.map { $0.identifier })") manager.peripherals.removeAll() } // ...and notify delegate. manager.queue.async { manager.delegate?.centralManagerDidUpdateState(manager) } } } } open weak var delegate: CBMCentralManagerDelegate? open var state: CBMManagerState { return initialized ? CBMCentralManagerMock.managerState : .unknown } open private(set) var isScanning: Bool private var scanFilter: [CBMUUID]? private var scanOptions: [String : Any]? /// The dispatch queue used for all callbacks. fileprivate let queue: DispatchQueue /// A map of peripherals known to this central manager. private var peripherals: [UUID : CBMPeripheralMock] = [:] /// A flag set to true few milliseconds after the manager is created. /// Some features, like the state or retrieving peripherals are not /// available when manager hasn't been initialized yet. private var initialized: Bool { // This method returns true if the manager is added to // the list of managers. // Calling tearDownSimulation() will remove all managers // from that list, making them uninitialized again. return CBMCentralManagerMock.managers.contains(self) } // MARK: - Initializers public required override init() { self.isScanning = false self.queue = DispatchQueue.main super.init() initialize() } deinit { print("↗️ deinit CBMCentralManagerMock") } public required init(delegate: CBMCentralManagerDelegate?, queue: DispatchQueue?) { self.isScanning = false self.queue = queue ?? DispatchQueue.main self.delegate = delegate super.init() initialize() } @available(iOS 7.0, *) public required init(delegate: CBMCentralManagerDelegate?, queue: DispatchQueue?, options: [String : Any]?) { self.isScanning = false self.queue = queue ?? DispatchQueue.main self.delegate = delegate super.init() if let options = options, let identifierKey = options[CBMCentralManagerOptionRestoreIdentifierKey] as? String, let dict = CBMCentralManagerFactory .simulateStateRestoration?(identifierKey) { var state: [String : Any] = [:] if let peripheralKeys = dict[CBMCentralManagerRestoredStatePeripheralsKey] { state[CBMCentralManagerRestoredStatePeripheralsKey] = peripheralKeys } if let scanServiceKey = dict[CBMCentralManagerRestoredStateScanServicesKey] { state[CBMCentralManagerRestoredStateScanServicesKey] = scanServiceKey } if let scanOptions = dict[CBMCentralManagerRestoredStateScanOptionsKey] { state[CBMCentralManagerRestoredStateScanOptionsKey] = scanOptions } delegate?.centralManager(self, willRestoreState: state) } initialize() } private func initialize() { print("↗️ init init init \(self) -> \(CBMCentralManagerMock.managers.allObjects)") if CBMCentralManagerMock.managerState == .poweredOn && CBMCentralManagerMock.peripherals.isEmpty { NSLog("Warning: No simulated peripherals. " + "Call simulatePeripherals(:) before creating central manager") } // Let's say initialization takes 10 ms. Less or more. queue.asyncAfter(deadline: .now() + .milliseconds(10)) { [weak self] in if let self = self { CBMCentralManagerMock.managers.add(self) self.delegate?.centralManagerDidUpdateState(self) } } } /// Removes all active central manager instances and peripherals from the /// simulation, resetting it to the initial state. /// /// Use this to tear down your mocks between tests, e.g. in `tearDownWithError()`. /// All manager delegates will receive a `.unknown` state update. public static func tearDownSimulation() { // Set the state of all currently existing cenral manager instances to // .unknown, which will make them invalid. managerState = .unknown // Remove all central manager instances. managers.removeAllObjects() // Set the manager state to powered Off. managerState = .poweredOff peripherals.removeAll() } // MARK: - Central manager simulation methods /// Sets the initial state of the Bluetooth central manager. /// /// This method should only be called ones, before any central manager /// is created. By default, the initial state is `.poweredOff`. /// - Parameter state: The initial state of the central manager. public static func simulateInitialState(_ state: CBMManagerState) { managerState = state } /// This method sets a list of simulated peripherals. /// /// Peripherals added using this method will be available for scanning /// and connecting, depending on their proximity. Use peripheral's /// `simulateProximity(of:didChangeTo:)` to modify proximity. /// /// This method may only be called before any central manager was created /// or when Bluetooth state is `.poweredOff`. Existing list of peripherals /// will be overritten. /// - Parameter peripherals: Peripherals specifications. public static func simulatePeripherals(_ peripherals: [CBMPeripheralSpec]) { guard managers.count == 0 || managerState == .poweredOff else { NSLog("Warning: Peripherals can not be added while the simulation is running. " + "Add peripherals before getting any central manager instance, " + "or when manager is powered off.") return } CBMCentralManagerMock.peripherals = peripherals print("↗️↗️ simulatePeripherals \(CBMCentralManagerMock.managers.allObjects) -> Periherals: \(CBMCentralManagerMock.peripherals.map { $0.identifier })") } /// Simulates turning the Bluetooth adapter on. public static func simulatePowerOn() { guard managerState != .poweredOn else { return } managerState = .poweredOn } /// Simulate turning the Bluetooth adapter off. public static func simulatePowerOff() { guard managerState != .poweredOff else { return } managerState = .poweredOff } // MARK: - Peripheral simulation methods /// Simulates a situation when the given peripheral was moved closer /// or away from the phone. /// /// If the proximity is changed to `.outOfRange`, the peripheral will /// be disconnected and will not appear on scan results. /// - Parameter peripheral: The peripheral that was repositioned. /// - Parameter proximity: The new peripheral proximity. internal static func proximity(of peripheral: CBMPeripheralSpec, didChangeTo proximity: CBMProximity) { guard peripheral.proximity != proximity else { return } // Is the peripheral simulated? guard peripherals.contains(peripheral) else { return } peripheral.proximity = proximity if proximity == .outOfRange { self.peripheral(peripheral, didDisconnectWithError: CBMError(.connectionTimeout)) } else { self.peripheralBecameAvailable(peripheral) } } /// Simulates a situation when the device changes its services. /// - Parameters: /// - peripheral: The peripheral that changed services. /// - newName: New device name. /// - newServices: New list of device services. internal static func peripheral(_ peripheral: CBMPeripheralSpec, didUpdateName newName: String?, andServices newServices: [CBMServiceMock]) { // Is the peripheral simulated? guard peripherals.contains(peripheral) else { return } peripheral.services = newServices guard peripheral.virtualConnections > 0 else { return } let existingManagers = managers.allObjects existingManagers.forEach { manager in manager.peripherals[peripheral.identifier]? .notifyServicesChanged() } // Notify that the name has changed. if peripheral.name != newName { peripheral.name = newName existingManagers.forEach { manager in // TODO: This needs to be verified. // Should a local peripheral copy be created if no such? // Are all central managers notified about any device // changing name? manager.peripherals[peripheral.identifier]? .notifyNameChanged() } } } /// Simulates a notification sent from the peripheral. /// /// All central managers that have enabled notifications on it /// will receive `peripheral(:didUpdateValueFor:error)`. /// - Parameter characteristic: The characteristic from which /// notification is to be sent. internal static func peripheral(_ peripheral: CBMPeripheralSpec, didUpdateValueFor characteristic: CBMCharacteristicMock) { // Is the peripheral simulated? guard peripherals.contains(peripheral) else { return } guard peripheral.virtualConnections > 0 else { return } managers.allObjects .forEach { manager in manager.peripherals[peripheral.identifier]? .notifyValueChanged(for: characteristic) } } /// This method simulates a new virtual connection to the given /// peripheral, as if some other application connected to it. /// /// Central managers will not be notified about the state change unless /// they registered for connection events using /// `registerForConnectionEvents(options:)`. /// Even without registering (which is available since iOS 13), they /// can retrieve the connected peripheral using /// `retrieveConnectedPeripherals(withServices:)`. /// /// The peripheral does not need to be registered before. /// - Parameter peripheral: The peripheral that has connected. internal static func peripheralDidConnect(_ peripheral: CBMPeripheralSpec) { // Is the peripheral simulated? guard peripherals.contains(peripheral) else { return } peripheral.virtualConnections += 1 // TODO: notify a user registered for connection events } /// Method called when a peripheral becomes available (in range). /// If there is a pending connection request, it will connect. /// - Parameter peripheral: The peripheral that came in range. internal static func peripheralBecameAvailable(_ peripheral: CBMPeripheralSpec) { // Is the peripheral simulated? guard peripherals.contains(peripheral) else { return } managers.allObjects .forEach { manager in if let target = manager.peripherals[peripheral.identifier], target.state == .connecting { target.connect() { result in switch result { case .success: manager.delegate?.centralManager(manager, didConnect: target) case .failure(let error): manager.delegate?.centralManager(manager, didFailToConnect: target, error: error) } } } } } /// Simulates the peripheral to disconnect from the device. /// All connected mock central managers will receive /// `peripheral(:didDisconnected:error)` callback. /// - Parameter peripheral: The peripheral to disconnect. /// - Parameter error: The disconnection reason. Use `CBError` or /// `CBATTError` errors. internal static func peripheral(_ peripheral: CBMPeripheralSpec, didDisconnectWithError error: Error = CBError(.peripheralDisconnected)) { // Is the device connected at all? guard peripheral.isConnected else { return } // Is the peripheral simulated? guard peripherals.contains(peripheral) else { return } // The device has disconnected, so it can start advertising // immediately. peripheral.virtualConnections = 0 // Notify all central managers. managers.allObjects .forEach { manager in if let target = manager.peripherals[peripheral.identifier], target.state == .connected { target.disconnected(withError: error) { error in manager.delegate?.centralManager(manager, didDisconnectPeripheral: target, error: error) } } } // TODO: notify a user registered for connection events } // MARK: - CBCentralManager mock methods #if !os(macOS) @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) public static func supports(_ features: CBMCentralManager.Feature) -> Bool { return CBMCentralManagerFactory.simulateFeaturesSupport?(features) ?? false } #endif /// This is a Timer callback, that's called to emulate scanning for Bluetooth LE /// devices. When the `CBCentralManagerScanOptionAllowDuplicatesKey` options /// was set when scanning was started, the timer will repeat every advertising /// interval until scanning is stopped. /// /// The scanned peripheral is set as `userInfo`. /// - Parameter timer: The timer that is fired. @objc private func notify(timer: Timer) { guard let mock = timer.userInfo as? CBMPeripheralSpec, let advertisementData = mock.advertisementData, isScanning else { timer.invalidate() return } guard mock.proximity != .outOfRange else { return } guard !mock.isConnected || mock.isAdvertisingWhenConnected else { return } // Get or create local peripheral instance. if peripherals[mock.identifier] == nil { peripherals[mock.identifier] = CBMPeripheralMock(basedOn: mock, by: self) } let peripheral = peripherals[mock.identifier]! // Emulate RSSI based on proximity. Apply some deviation. let rssi = mock.proximity.RSSI let delta = CBMCentralManagerMock.rssiDeviation let deviation = Int.random(in: -delta...delta) delegate?.centralManager(self, didDiscover: peripheral, advertisementData: advertisementData, rssi: (rssi + deviation) as NSNumber) // The first scan result is returned without a name. // This flag must then be called after it has been reported. // Setting this flag will cause the advertising name to be // returned from CBPeripheral.name. peripheral.wasScanned = true let allowDuplicates = scanOptions?[CBMCentralManagerScanOptionAllowDuplicatesKey] as? NSNumber ?? false as NSNumber if !allowDuplicates.boolValue { timer.invalidate() } } open func scanForPeripherals(withServices serviceUUIDs: [CBMUUID]?, options: [String : Any]?) { // Central manager must be in powered on state. guard ensurePoweredOn() else { return } if isScanning { stopScan() } isScanning = true scanFilter = serviceUUIDs scanOptions = options CBMCentralManagerMock.peripherals // For all advertising peripherals, .filter { $0.advertisementData != nil && $0.advertisingInterval != nil && $0.advertisingInterval! > 0 } .forEach { mock in // If no Service UUID was used, or the device matches at least one service, // report it to the delegate (call will be delayed using a Timer). let services = mock.advertisementData![CBMAdvertisementDataServiceUUIDsKey] as? [CBMUUID] if serviceUUIDs == nil || services?.contains(where: serviceUUIDs!.contains) ?? false { // The timer will be called multiple times, even if // CBCentralManagerScanOptionAllowDuplicatesKey was not set. // In that case, the timer will be invalidated after the // device has been reported for the first time. // // Timer works only on queues with a active run loop. DispatchQueue.main.async { Timer.scheduledTimer( timeInterval: mock.advertisingInterval!, target: self, selector: #selector(self.notify(timer:)), userInfo: mock, repeats: true ) } } } } open func stopScan() { // Central manager must be in powered on state. guard ensurePoweredOn() else { return } isScanning = false scanFilter = nil scanOptions = nil } open func connect(_ peripheral: CBMPeripheral, options: [String : Any]?) { // Central manager must be in powered on state. guard ensurePoweredOn() else { return } if let o = options, !o.isEmpty { NSLog("Warning: Connection options are not supported in mock central manager") } // Ignore peripherals that are not mocks. guard let mock = peripheral as? CBMPeripheralMock else { return } // The peripheral must come from this central manager. Ignore other. // To connect a peripheral obtained using another central manager // use `retrievePeripherals(withIdentifiers:)` or // `retrieveConnectedPeripherals(withServices:)`. guard peripherals.values.contains(mock) else { return } mock.connect() { result in switch result { case .success: self.delegate?.centralManager(self, didConnect: mock) case .failure(let error): self.delegate?.centralManager(self, didFailToConnect: mock, error: error) } } } open func cancelPeripheralConnection(_ peripheral: CBMPeripheral) { // Central manager must be in powered on state. guard ensurePoweredOn() else { return } // Ignore peripherals that are not mocks. guard let mock = peripheral as? CBMPeripheralMock else { return } // It is not possible to cancel connection of a peripheral obtained // from another central manager. guard peripherals.values.contains(mock) else { return } mock.disconnect() { self.delegate?.centralManager(self, didDisconnectPeripheral: mock, error: nil) } } open func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> [CBMPeripheral] { // Starting from iOS 13, this method returns peripherals only in ON state. guard ensurePoweredOn() else { return [] } // Get the peripherals already known to this central manager. print("↗️ retrieve", peripherals, identifiers) peripherals.forEach { dict in print("↗️↗️", dict.key, dict.value) } let localPeripherals = peripherals[identifiers] // If all were found, return them. if localPeripherals.count == identifiers.count { return localPeripherals } let missingIdentifiers = identifiers.filter { peripherals[$0] == nil } // Otherwise, we need to look for them among other managers, and // copy them to the local manager. let peripheralsKnownByOtherManagers = missingIdentifiers .flatMap { i in CBMCentralManagerMock.managers.allObjects .compactMap { $0.peripherals[i] } } .map { CBMPeripheralMock(copy: $0, by: self) } peripheralsKnownByOtherManagers.forEach { peripherals[$0.identifier] = $0 } // Return them in the same order as requested, some may be missing. return (localPeripherals + peripheralsKnownByOtherManagers) .sorted { let firstIndex = identifiers.firstIndex(of: $0.identifier)! let secondIndex = identifiers.firstIndex(of: $1.identifier)! return firstIndex < secondIndex } } open func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBMUUID]) -> [CBMPeripheral] { // Starting from iOS 13, this method returns peripherals only in ON state. guard ensurePoweredOn() else { return [] } // Get the connected peripherals with at least one of the given services // that are already known to this central manager. let peripheralsConnectedByThisManager = peripherals[serviceUUIDs] .filter { $0.state == .connected } // Other central managers may know some connected peripherals that // are not known to the local one. let peripheralsConnectedByOtherManagers = CBMCentralManagerMock.managers.allObjects // Look for connected peripherals known to other managers. .flatMap { $0.peripherals[serviceUUIDs] .filter { $0.state == .connected } } // Search for ones that are not known to the local manager. .filter { peripherals[$0.identifier] == nil } // Create a local copy. .map { CBMPeripheralMock(copy: $0, by: self) } // Add those copies to the local manager. peripheralsConnectedByOtherManagers.forEach { peripherals[$0.identifier] = $0 } let peripheralsConnectedByOtherApps = CBMCentralManagerMock.peripherals .filter { $0.isConnected } // Search for ones that are not known to the local manager. .filter { peripherals[$0.identifier] == nil } // And only those that match any of given service UUIDs. .filter { $0.services!.contains { service in serviceUUIDs.contains(service.uuid) } } // Create a local copy. .map { CBMPeripheralMock(basedOn: $0, by: self) } return peripheralsConnectedByThisManager + peripheralsConnectedByOtherManagers + peripheralsConnectedByOtherApps } @available(iOS 13.0, *) open func registerForConnectionEvents(options: [CBMConnectionEventMatchingOption : Any]?) { fatalError("Mock connection events are not implemented") } fileprivate func ensurePoweredOn() -> Bool { print("↗️ ensurePoweredOn \(CBMCentralManagerMock.managers.allObjects)") guard state == .poweredOn else { NSLog("[CoreBluetoothMock] API MISUSE: \(self) can only accept this command while in the powered on state") return false } return true } } // MARK: - CBPeripheralMock implementation open class CBMPeripheralMock: CBMPeer, CBMPeripheral { /// The parent central manager. private let manager: CBMCentralManagerMock /// The dispatch queue to call delegate methods on. private var queue: DispatchQueue { return manager.queue } /// The mock peripheral with user-defined implementation. private let mock: CBMPeripheralSpec /// Size of the outgoing buffer. Only this many packets /// can be written without response in a loop, without /// waiting for `canSendWriteWithoutResponse`. private let bufferSize = 20 /// The supervision timeout is a time after which a device realizes /// that a connected peer has disconnected, had there been no signal /// from it. private let supervisionTimeout = 4.0 /// The current buffer size. private var availableWriteWithoutResponseBuffer: Int private var _canSendWriteWithoutResponse: Bool = false /// A flag set to <i>true</i> when the device was scanned /// at least once. fileprivate var wasScanned: Bool = false /// A flag set to <i>true</i> when the device was connected /// and iOS had chance to read device name. fileprivate var wasConnected: Bool = false open var delegate: CBMPeripheralDelegate? open override var identifier: UUID { return mock.identifier } open var name: String? { // If the device wasn't connected and has just been scanned first time, // return nil. When scanning continued, the Local Name from the // advertisement data is returned. When the device was connected, the // central reads the Device Name characteristic and returns cached value. return wasConnected ? mock.name : wasScanned ? mock.advertisementData?[CBMAdvertisementDataLocalNameKey] as? String : nil } @available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) open var canSendWriteWithoutResponse: Bool { return _canSendWriteWithoutResponse } open private(set) var ancsAuthorized: Bool = false open private(set) var state: CBMPeripheralState = .disconnected open private(set) var services: [CBMService]? = nil // MARK: Initializers fileprivate init(basedOn mock: CBMPeripheralSpec, by manager: CBMCentralManagerMock) { self.mock = mock self.manager = manager self.availableWriteWithoutResponseBuffer = bufferSize } fileprivate init(copy: CBMPeripheralMock, by manager: CBMCentralManagerMock) { self.mock = copy.mock self.manager = manager self.availableWriteWithoutResponseBuffer = bufferSize } // MARK: Connection fileprivate func connect(completion: @escaping (Result<Void, Error>) -> ()) { // Ensure the device is disconnected. guard state == .disconnected || state == .connecting else { return } // Connection is pending. state = .connecting // Ensure the device is connectable and in range. guard let delegate = mock.connectionDelegate, let interval = mock.connectionInterval, mock.proximity != .outOfRange else { // There's no timeout on iOS. The device will connect when brought back // into range. To cancel pending connection, call disconnect(). return } let result = delegate.peripheralDidReceiveConnectionRequest(mock) queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connecting { if case .success = result { self.state = .connected self._canSendWriteWithoutResponse = true self.mock.virtualConnections += 1 } else { self.state = .disconnected } completion(result) } } } fileprivate func disconnect(completion: @escaping () -> ()) { // Cancel pending connection. guard state != .connecting else { state = .disconnected queue.async { completion() } return } // Ensure the device is connectable and connected. guard let interval = mock.connectionInterval, state == .connected else { return } if #available(iOS 9.0, *), case .connected = state { state = .disconnecting } queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, CBMCentralManagerMock.managerState == .poweredOn { self.state = .disconnected self.services = nil self._canSendWriteWithoutResponse = false self.mock.virtualConnections -= 1 self.mock.connectionDelegate?.peripheral(self.mock, didDisconnect: nil) completion() } } } fileprivate func disconnected(withError error: Error, completion: @escaping (Error?) -> ()) { // Ensure the device is connected. guard var interval = mock.connectionInterval, state == .connected else { return } // If a device disconnected with a timeout, the central waits // for the duration of supervision timeout before accepting // disconnection. if let error = error as? CBMError, error.code == .connectionTimeout { interval = supervisionTimeout } queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, CBMCentralManagerMock.managerState == .poweredOn { self.state = .disconnected self.services = nil self._canSendWriteWithoutResponse = false // If the disconnection happen without an error, the device // must have been disconnected disconnected from central // manager. self.mock.virtualConnections = 0 self.mock.connectionDelegate?.peripheral(self.mock, didDisconnect: error) completion(error) } } } // MARK: Service modification fileprivate func notifyNameChanged() { guard state == .connected, let interval = mock.connectionInterval else { return } queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheralDidUpdateName(self) } } } fileprivate func notifyServicesChanged() { guard state == .connected, let oldServices = services, let interval = mock.connectionInterval else { return } // Keep only services that hadn't changed. services = services! .filter { service in mock.services!.contains(where: { $0.identifier == service.identifier }) } let invalidatedServices = oldServices.filter({ !services!.contains($0) }) queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didModifyServices: invalidatedServices) } } } fileprivate func notifyValueChanged(for originalCharacteristic: CBMCharacteristicMock) { guard state == .connected, let interval = mock.connectionInterval, let service = services?.first(where: { $0.characteristics?.contains(where: { $0.identifier == originalCharacteristic.identifier }) ?? false }), let characteristic = service.characteristics?.first(where: { $0.identifier == originalCharacteristic.identifier }), characteristic.isNotifying else { return } characteristic.value = originalCharacteristic.value queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didUpdateValueFor: characteristic, error: nil) } } } fileprivate func managerPoweredOff() { state = .disconnected services = nil _canSendWriteWithoutResponse = false mock.virtualConnections = 0 } // MARK: Service discovery open func discoverServices(_ serviceUUIDs: [CBMUUID]?) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval, let allServices = mock.services else { return } switch delegate.peripheral(mock, didReceiveServiceDiscoveryRequest: serviceUUIDs) { case .success: services = services ?? [] let initialSize = services!.count services = services! + allServices // Filter all device services that match given list (if set). .filter { serviceUUIDs?.contains($0.uuid) ?? true } // Filter those of them, that are not already in discovered services. .filter { s in !services! .contains(where: { ds in s.identifier == ds.identifier }) } // Copy the service info, without included services or characteristics. .map { CBMService(shallowCopy: $0, for: self) } let newServicesCount = services!.count - initialSize // Service discovery may takes the more time, the more services // are discovered. queue.asyncAfter(deadline: .now() + interval * Double(newServicesCount)) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverServices: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverServices: error) } } } } open func discoverIncludedServices(_ includedServiceUUIDs: [CBMUUID]?, for service: CBMService) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval, let allServices = mock.services else { return } guard let services = services, services.contains(service), let originalService = allServices.first(where: { $0.identifier == service.identifier }) else { return } guard let originalIncludedServices = originalService.includedServices else { return } switch delegate.peripheral(mock, didReceiveIncludedServiceDiscoveryRequest: includedServiceUUIDs, for: service as! CBMServiceMock) { case .success: service._includedServices = service._includedServices ?? [] let initialSize = service._includedServices!.count service._includedServices = service._includedServices! + originalIncludedServices // Filter all included service that match given list (if set). .filter { includedServiceUUIDs?.contains($0.uuid) ?? true } // Filter those of them, that are not already in discovered services. .filter { s in !service._includedServices! .contains(where: { ds in s.identifier == ds.identifier }) } // Copy the service info, without included characteristics. .map { CBMService(shallowCopy: $0, for: self) } let newServicesCount = service._includedServices!.count - initialSize // Service discovery may takes the more time, the more services // are discovered. queue.asyncAfter(deadline: .now() + interval * Double(newServicesCount)) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverIncludedServicesFor: service, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverIncludedServicesFor: service, error: error) } } } } open func discoverCharacteristics(_ characteristicUUIDs: [CBMUUID]?, for service: CBMService) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval, let allServices = mock.services else { return } guard let services = services, services.contains(service), let originalService = allServices.first(where: { $0.identifier == service.identifier }) else { return } guard let originalCharacteristics = originalService.characteristics else { return } switch delegate.peripheral(mock, didReceiveCharacteristicsDiscoveryRequest: characteristicUUIDs, for: service) { case .success: service._characteristics = service._characteristics ?? [] let initialSize = service._characteristics!.count service._characteristics = service._characteristics! + originalCharacteristics // Filter all service characteristics that match given list (if set). .filter { characteristicUUIDs?.contains($0.uuid) ?? true } // Filter those of them, that are not already in discovered characteristics. .filter { c in !service._characteristics! .contains(where: { dc in c.identifier == dc.identifier }) } // Copy the characteristic info, without included descriptors or value. .map { CBMCharacteristic(shallowCopy: $0, in: service) } let newCharacteristicsCount = service._characteristics!.count - initialSize // Characteristics discovery may takes the more time, the more characteristics // are discovered. queue.asyncAfter(deadline: .now() + interval * Double(newCharacteristicsCount)) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverCharacteristicsFor: service, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverCharacteristicsFor: service, error: error) } } } } open func discoverDescriptors(for characteristic: CBMCharacteristic) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval, let allServices = mock.services else { return } guard let services = services, services.contains(characteristic.service), let originalService = allServices.first(where: { $0.identifier == characteristic.service.identifier }), let originalCharacteristic = originalService.characteristics?.first(where: { $0.identifier == characteristic.identifier }) else { return } guard let originalDescriptors = originalCharacteristic.descriptors else { return } switch delegate.peripheral(mock, didReceiveDescriptorsDiscoveryRequestFor: characteristic) { case .success: characteristic._descriptors = characteristic._descriptors ?? [] let initialSize = characteristic._descriptors!.count characteristic._descriptors = characteristic._descriptors! + originalDescriptors // Filter those of them, that are not already in discovered descriptors. .filter { d in !characteristic._descriptors! .contains(where: { dd in d.identifier == dd.identifier }) } // Copy the descriptors info, without the value. .map { CBMDescriptor(shallowCopy: $0, in: characteristic) } let newDescriptorsCount = characteristic._descriptors!.count - initialSize // Descriptors discovery may takes the more time, the more descriptors // are discovered. queue.asyncAfter(deadline: .now() + interval * Double(newDescriptorsCount)) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverDescriptorsFor: characteristic, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didDiscoverDescriptorsFor: characteristic, error: error) } } } } // MARK: Read requests open func readValue(for characteristic: CBMCharacteristic) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval else { return } guard let services = services, services.contains(characteristic.service) else { return } switch delegate.peripheral(mock, didReceiveReadRequestFor: characteristic) { case .success(let data): characteristic.value = data queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didUpdateValueFor: characteristic, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didUpdateValueFor: characteristic, error: error) } } } } open func readValue(for descriptor: CBMDescriptor) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval else { return } guard let services = services, services.contains(descriptor.characteristic.service) else { return } switch delegate.peripheral(mock, didReceiveReadRequestFor: descriptor) { case .success(let data): descriptor.value = data queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didUpdateValueFor: descriptor, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didUpdateValueFor: descriptor, error: error) } } } } // MARK: Write requests open func writeValue(_ data: Data, for characteristic: CBMCharacteristic, type: CBMCharacteristicWriteType) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval, let mtu = mock.mtu else { return } guard let services = services, services.contains(characteristic.service) else { return } if type == .withResponse { switch delegate.peripheral(mock, didReceiveWriteRequestFor: characteristic, data: data) { case .success: let packetsCount = max(1, (data.count + mtu - 2) / (mtu - 3)) queue.asyncAfter(deadline: .now() + interval * Double(packetsCount)) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didWriteValueFor: characteristic, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didWriteValueFor: characteristic, error: error) } } } } else { let decreaseBuffer = { [weak self] in guard let strongSelf = self, strongSelf.availableWriteWithoutResponseBuffer > 0 else { return } strongSelf.availableWriteWithoutResponseBuffer -= 1 strongSelf._canSendWriteWithoutResponse = false } if DispatchQueue.main.label == queue.label { decreaseBuffer() } else { queue.sync { decreaseBuffer() } } delegate.peripheral(mock, didReceiveWriteCommandFor: characteristic, data: data.subdata(in: 0..<mtu - 3)) queue.async { [weak self] in if let self = self, self.state == .connected { let increaseBuffer = { self.availableWriteWithoutResponseBuffer += 1 self._canSendWriteWithoutResponse = true } if DispatchQueue.main.label == self.queue.label { increaseBuffer() } else { self.queue.sync { increaseBuffer() } } if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { self.delegate?.peripheralIsReady(toSendWriteWithoutResponse: self) } } } } } open func writeValue(_ data: Data, for descriptor: CBMDescriptor) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval else { return } guard let services = services, services.contains(descriptor.characteristic.service) else { return } switch delegate.peripheral(mock, didReceiveWriteRequestFor: descriptor, data: data) { case .success: queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didWriteValueFor: descriptor, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didWriteValueFor: descriptor, error: error) } } } } @available(iOS 9.0, *) open func maximumWriteValueLength(for type: CBMCharacteristicWriteType) -> Int { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return 0 } guard state == .connected, let mtu = mock.mtu else { return 0 } return type == .withResponse ? 512 : mtu - 3 } // MARK: Enabling notifications and indications open func setNotifyValue(_ enabled: Bool, for characteristic: CBMCharacteristic) { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } guard state == .connected, let delegate = mock.connectionDelegate, let interval = mock.connectionInterval else { return } guard let services = services, services.contains(characteristic.service) else { return } guard enabled != characteristic.isNotifying else { return } switch delegate.peripheral(mock, didReceiveSetNotifyRequest: enabled, for: characteristic) { case .success: queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { characteristic.isNotifying = enabled self.delegate?.peripheral(self, didUpdateNotificationStateFor: characteristic, error: nil) } } case .failure(let error): queue.asyncAfter(deadline: .now() + interval) { [weak self] in if let self = self, self.state == .connected { self.delegate?.peripheral(self, didUpdateNotificationStateFor: characteristic, error: error) } } } } // MARK: Other open func readRSSI() { // Central manager must be in powered on state. guard manager.ensurePoweredOn() else { return } queue.async { [weak self] in if let self = self, self.state == .connected { let rssi = self.mock.proximity.RSSI let delta = CBMCentralManagerMock.rssiDeviation let deviation = Int.random(in: -delta...delta) self.delegate?.peripheral(self, didReadRSSI: (rssi + deviation) as NSNumber, error: nil) } } } @available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) open func openL2CAPChannel(_ PSM: CBML2CAPPSM) { fatalError("L2CAP mock is not implemented") } open override var hash: Int { return mock.identifier.hashValue } } // MARK: - Helpers private class WeakRef<T: AnyObject> { fileprivate private(set) weak var ref: T? fileprivate init(_ value: T) { self.ref = value } } private extension Dictionary where Key == UUID, Value == CBMPeripheralMock { subscript(identifiers: [UUID]) -> [CBMPeripheralMock] { return identifiers.compactMap { self[$0] } } subscript(serviceUUIDs: [CBMUUID]) -> [CBMPeripheralMock] { return filter { (_, peripheral) in peripheral.services? .contains(where: { service in serviceUUIDs.contains(service.uuid) }) ?? false }.map { $0.value } } }
43.09496
166
0.562283
72dda7000152d82904084665aade80bcead6e91f
10,760
// // FBSDKLiveVideo.swift // facebook-live-ios-sample // // Created by Hans Knoechel on 09.03.17. // Copyright © 2017 Hans Knoechel. All rights reserved. // import UIKit // MARK: FBSDKLiveVideoDelegate public protocol FBSDKLiveVideoDelegate { func liveVideo(_ liveVideo: FBSDKLiveVideo, didStartWith session: FBSDKLiveVideoSession); func liveVideo(_ liveVideo: FBSDKLiveVideo, didStopWith session: FBSDKLiveVideoSession); } public extension FBSDKLiveVideoDelegate { func liveVideo(_ liveVideo: FBSDKLiveVideo, didErrorWith error: Error) {} func liveVideo(_ liveVideo: FBSDKLiveVideo, didChange sessionState: FBSDKLiveVideoSessionState) {} func liveVideo(_ liveVideo: FBSDKLiveVideo, didAdd cameraSource: FBSDKLiveVideoSession) {} func liveVideo(_ liveVideo: FBSDKLiveVideo, didUpdate session: FBSDKLiveVideoSession) {} func liveVideo(_ liveVideo: FBSDKLiveVideo, didDelete session: FBSDKLiveVideoSession) {} } // MARK: Enumerations enum FBSDKLiveVideoPrivacy : StringLiteralType { case me = "SELF" case friends = "FRIENDS" case friendsOfFriends = "FRIENDS_OF_FRIENDS" case allFriends = "ALL_FRIENDS" case custom = "CUSTOM" } enum FBSDKLiveVideoStatus: StringLiteralType { case unpublished = "UNPUBLISHED" case liveNow = "LIVE_NOW" case scheduledUnpublished = "SCHEDULED_UNPUBLISHED" case scheduledLive = "SCHEDULED_LIVE" case scheduledCanceled = "SCHEDULED_CANCELED" } enum FBSDKLiveVideoType: StringLiteralType { case regular = "REGULAR" case ambient = "AMBIENT" } public enum FBSDKLiveVideoSessionState : IntegerLiteralType { case none = 0 case previewStarted case starting case started case ended case error } struct FBSDKLiveVideoParameter { var key: String! var value: String! } public class FBSDKLiveVideoSession : VCSimpleSession { // Subclass for more generic API-interface } open class FBSDKLiveVideo: NSObject { // MARK: - Live Video Parameters // MARK: Create var overlay: UIView! { didSet { if overlay.isDescendant(of: self.preview) { overlay.removeFromSuperview() } else { self.preview.addSubview(overlay) } } } var videoDescription: String! { didSet { self.createParameters["description"] = videoDescription } } var contentTags: [String]! { didSet { self.createParameters["content_tags"] = contentTags } } var privacy: FBSDKLiveVideoPrivacy = .me { didSet { self.createParameters["privacy"] = "{\"value\":\"\(privacy.rawValue)\"}" } } var plannedStartTime: Date! { didSet { self.createParameters["planned_start_time"] = String(plannedStartTime.timeIntervalSince1970 * 1000) } } var status: FBSDKLiveVideoStatus! { didSet { self.createParameters["status"] = status.rawValue } } var type: FBSDKLiveVideoType = .regular { didSet { self.createParameters["stream_type"] = type.rawValue } } var title: String! { didSet { self.createParameters["title"] = title } } var videoOnDemandEnabled: String! { didSet { self.createParameters["save_vod"] = videoOnDemandEnabled } } // MARK: Update var adBreakStartNow: Bool! { didSet { self.updateParameters["ad_break_start_now"] = adBreakStartNow } } var adBreakTimeOffset: Float! { didSet { self.updateParameters["ad_break_time_offset"] = adBreakTimeOffset } } var disturbing: Bool! { didSet { self.updateParameters["disturbing"] = disturbing } } var embeddable: Bool! { didSet { self.updateParameters["embeddable"] = embeddable } } var sponsorId: String! { didSet { self.createParameters["sponsor_id"] = sponsorId } } // MARK: - Utility API's var delegate: FBSDKLiveVideoDelegate! var url: URL! var id: String! var audience: String = "me" var frameRate: Int = 30 var bitRate: Int = 1000000 var preview: UIView! var isStreaming: Bool = false // MARK: - Internal API's private var session: FBSDKLiveVideoSession! private var createParameters: [String : Any] = [:] private var updateParameters: [String : Any] = [:] required public init(delegate: FBSDKLiveVideoDelegate, previewSize: CGRect, videoSize: CGSize) { super.init() self.delegate = delegate self.session = FBSDKLiveVideoSession(videoSize: videoSize, frameRate: Int32(self.frameRate), bitrate: Int32(self.bitRate), useInterfaceOrientation: false) self.session.previewView.frame = previewSize self.session.delegate = self self.preview = self.session.previewView } deinit { if self.session.rtmpSessionState != .ended { self.session.endRtmpSession() } self.delegate = nil self.session.delegate = nil self.preview = nil } // MARK: - Public API's func start() { guard FBSDKAccessToken.current().hasGranted("publish_video") else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "The \"publish_video\" permission has not been granted")) } let graphRequest = FBSDKGraphRequest(graphPath: "/\(self.audience)/live_videos", parameters: self.createParameters, httpMethod: "POST") DispatchQueue.main.async { _ = graphRequest?.start { (_, result, error) in guard error == nil, let dict = (result as? NSDictionary) else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "Error initializing the live video session: \(String(describing: error?.localizedDescription))")) } self.url = URL(string:(dict.value(forKey: "stream_url") as? String)!) self.id = dict.value(forKey: "id") as? String guard let streamPath = self.url?.lastPathComponent, let query = self.url?.query else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "The stream path is invalid")) } self.session.startRtmpSession(withURL: "rtmp://rtmp-api.facebook.com:80/rtmp/", andStreamKey: "\(streamPath)?\(query)") self.delegate.liveVideo(self, didStartWith:self.session) } } } func stop() { guard FBSDKAccessToken.current().hasGranted("publish_video") else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "The \"publish_video\" permission has not been granted")) } let graphRequest = FBSDKGraphRequest(graphPath: "/\(self.audience)/live_videos", parameters: ["end_live_video": true], httpMethod: "POST") DispatchQueue.main.async { _ = graphRequest?.start { (_, _, error) in guard error == nil else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "Error stopping the live video session: \(String(describing: error?.localizedDescription))")) } self.session.endRtmpSession() self.delegate.liveVideo(self, didStopWith:self.session) } } } func update() { guard FBSDKAccessToken.current().hasGranted("publish_video") else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "The \"publish_video\" permission has not been granted")) } let graphRequest = FBSDKGraphRequest(graphPath: "/\(self.id)", parameters: self.createParameters, httpMethod: "POST") DispatchQueue.main.async { _ = graphRequest?.start { (_, result, error) in guard error == nil else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "Error initializing the live video session: \(String(describing: error?.localizedDescription))")) } self.delegate.liveVideo(self, didUpdate: self.session) } } } func delete() { guard FBSDKAccessToken.current().hasGranted("publish_video") else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "The \"publish_video\" permission has not been granted")) } let graphRequest = FBSDKGraphRequest(graphPath: "/\(self.id)", parameters: ["end_live_video": true], httpMethod: "DELEGTE") DispatchQueue.main.async { _ = graphRequest?.start { (_, _, error) in guard error == nil else { return self.delegate.liveVideo(self, didErrorWith: FBSDKLiveVideo.errorFromDescription(description: "Error deleting the live video session: \(String(describing: error?.localizedDescription))")) } self.delegate.liveVideo(self, didDelete: self.session) } } } // MARK: Utilities internal class func errorFromDescription(description: String) -> Error { return NSError(domain: FBSDKErrorDomain, code: -1, userInfo: [NSLocalizedDescriptionKey : description]) } internal func updateLiveStreamParameters(with parameter: FBSDKLiveVideoParameter) { self.createParameters[parameter.key] = parameter.value } } extension FBSDKLiveVideo : VCSessionDelegate { public func connectionStatusChanged(_ sessionState: VCSessionState) { if sessionState == .started { self.isStreaming = true } else if sessionState == .ended || sessionState == .error { self.isStreaming = false } self.delegate.liveVideo(self, didChange: FBSDKLiveVideoSessionState(rawValue: sessionState.rawValue)!) } public func didAddCameraSource(_ session: VCSimpleSession!) { self.delegate.liveVideo(self, didAdd: session as! FBSDKLiveVideoSession) } }
31.83432
217
0.625651
0e5ea05b4a135a8e5120dfd26f3371fdaab82a25
2,000
// // NetworkUtils.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 30/10/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit import AlamofireImage func downloadImage(imageView: UIImageView, activityIndicator: UIActivityIndicatorView, urlString: String) { let placeholderImage: UIImage = UIImage.init(named: kContentPlaceholderImage)! activityIndicator.startAnimating() imageView.af_setImage( withURL: URL(string: urlString)!, placeholderImage: placeholderImage, //filter: AspectScaledToFillSizeWithRoundedCornersFilter(size: size, radius: 20.0), filter: nil, imageTransition: .crossDissolve(0.2), completion: { [weak activityIndicator] (dataResponseImage) in activityIndicator?.stopAnimating() } ) }
40.816327
107
0.732
f83cd20efa05c24bccf19c717c851260a18d661d
7,112
import Foundation import Capacitor import GoogleMobileAds #if canImport(AppTrackingTransparency) import AppTrackingTransparency #endif @objc(AdMob) public class AdMob: CAPPlugin { var testingDevices: [String] = [] private let bannerExecutor = BannerExecutor() private let adInterstitialExecutor = AdInterstitialExecutor() private let adRewardExecutor = AdRewardExecutor() /** * Enable SKAdNetwork to track conversions * https://developers.google.com/admob/ios/ios14 */ @objc func initialize(_ call: CAPPluginCall) { self.bannerExecutor.plugin = self self.adInterstitialExecutor.plugin = self self.adRewardExecutor.plugin = self let isTrack = call.getBool("requestTrackingAuthorization") ?? true self.setRequestConfiguration(call) if !isTrack { GADMobileAds.sharedInstance().start(completionHandler: nil) call.resolve([:]) } else if #available(iOS 14, *) { #if canImport(AppTrackingTransparency) ATTrackingManager.requestTrackingAuthorization(completionHandler: { _ in // iOS >= 14 GADMobileAds.sharedInstance().start(completionHandler: nil) call.resolve([:]) }) #else GADMobileAds.sharedInstance().start(completionHandler: nil) call.resolve([:]) #endif } else { // iOS < 14 GADMobileAds.sharedInstance().start(completionHandler: nil) call.resolve([:]) } } /** * AdMob: Banner * https://developers.google.com/ad-manager/mobile-ads-sdk/ios/banner?hl=ja */ @objc func showBanner(_ call: CAPPluginCall) { let adUnitID = getAdId(call, "ca-app-pub-3940256099942544/6300978111") let request = self.GADRequestWithOption(call.getBool("npa") ?? false) DispatchQueue.main.async { self.bannerExecutor.showBanner(call, request, adUnitID) } } @objc func hideBanner(_ call: CAPPluginCall) { DispatchQueue.main.async { self.bannerExecutor.hideBanner(call) } } @objc func resumeBanner(_ call: CAPPluginCall) { DispatchQueue.main.async { self.bannerExecutor.resumeBanner(call) } } @objc func removeBanner(_ call: CAPPluginCall) { DispatchQueue.main.async { self.bannerExecutor.removeBanner(call) } } /** * AdMob: Intertitial * https://developers.google.com/admob/ios/interstitial?hl=ja */ @objc func prepareInterstitial(_ call: CAPPluginCall) { let adUnitID = getAdId(call, "ca-app-pub-3940256099942544/1033173712") let request = self.GADRequestWithOption(call.getBool("npa") ?? false) DispatchQueue.main.async { self.adInterstitialExecutor.prepareInterstitial(call, request, adUnitID) } } @objc func showInterstitial(_ call: CAPPluginCall) { DispatchQueue.main.async { self.adInterstitialExecutor.showInterstitial(call) } } /** * AdMob: Rewarded Ads * https://developers.google.com/ad-manager/mobile-ads-sdk/ios/rewarded-ads?hl=ja */ @objc func prepareRewardVideoAd(_ call: CAPPluginCall) { let adUnitID = getAdId(call, "ca-app-pub-3940256099942544/1712485313") let request = self.GADRequestWithOption(call.getBool("npa") ?? false) DispatchQueue.main.async { self.adRewardExecutor.prepareRewardVideoAd(call, request, adUnitID) } } @objc func showRewardVideoAd(_ call: CAPPluginCall) { DispatchQueue.main.async { self.adRewardExecutor.showRewardVideoAd(call) } } @objc func trackingAuthorizationStatus(_ call: CAPPluginCall) { DispatchQueue.main.async { if #available(iOS 14, *) { switch ATTrackingManager.trackingAuthorizationStatus { case .authorized: call.resolve(["status": AuthorizationStatusEnum.Authorized.rawValue]) break case .denied: call.resolve(["status": AuthorizationStatusEnum.Denied.rawValue]) break case .restricted: call.resolve(["status": AuthorizationStatusEnum.Restricted.rawValue]) break case .notDetermined: call.resolve(["status": AuthorizationStatusEnum.NotDetermined.rawValue]) break @unknown default: call.reject("trackingAuthorizationStatus can't get status") } } else { call.resolve(["status": AuthorizationStatusEnum.Authorized]) } } } private func getAdId(_ call: CAPPluginCall, _ testingID: String) -> String { let adUnitID = call.getString("adId") ?? testingID let isTest = call.getBool("isTesting") ?? false if isTest { return testingID } return adUnitID } private func GADRequestWithOption(_ npa: Bool) -> GADRequest { let request = GADRequest() if npa { let extras = GADExtras() extras.additionalParameters = ["npa": "1"] request.register(extras) } return request } /** * https://developers.google.com/admob/ios/targeting?hl=ja */ private func setRequestConfiguration(_ call: CAPPluginCall) { if call.getBool("initializeForTesting") ?? false { GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = call.getArray("testingDevices", String.self) ?? [] } if call.getBool("tagForChildDirectedTreatment") != nil { GADMobileAds.sharedInstance().requestConfiguration.tag(forChildDirectedTreatment: call.getBool("tagForChildDirectedTreatment")!) } if call.getBool("tagForUnderAgeOfConsent") != nil { GADMobileAds.sharedInstance().requestConfiguration.tagForUnderAge(ofConsent: call.getBool("tagForUnderAgeOfConsent")!) } if call.getString("maxAdContentRating") != nil { switch call.getString("maxAdContentRating") { case "General": GADMobileAds.sharedInstance().requestConfiguration.maxAdContentRating = GADMaxAdContentRating.general case "ParentalGuidance": GADMobileAds.sharedInstance().requestConfiguration.maxAdContentRating = GADMaxAdContentRating.parentalGuidance case "Teen": GADMobileAds.sharedInstance().requestConfiguration.maxAdContentRating = GADMaxAdContentRating.teen case "MatureAudience": GADMobileAds.sharedInstance().requestConfiguration.maxAdContentRating = GADMaxAdContentRating.matureAudience default: print("maxAdContentRating can't find value") } } } }
34.692683
140
0.614454
b9621c7517aca69e87aa04288e89a336c2340e45
14,391
// // TouchGRLTests.swift // TouchGRLTests // // Created by Mohamed El-Halawani on 2015-02-06. // // import UIKit import XCTest class TouchGRLTests: XCTestCase { var dollarPRecognizer = DollarPRecoginzer() func testCalculateEuclideanDistanceZeroCase(){ let distance: Float = dollarPRecognizer.calculateEuclideanDistance(GesturePoint(x:30, y:7, strokeId:1), secondPoint: GesturePoint(x:30, y:7, strokeId:1)) XCTAssertEqual(Float(0.0), distance) } func testCalculateEuclideanDistance(){ let distance : Float = dollarPRecognizer.calculateEuclideanDistance(GesturePoint(x:50, y:80, strokeId:1), secondPoint: GesturePoint(x:30, y:7, strokeId:1)) XCTAssertEqualWithAccuracy(Float(75.6902), distance, 0.0001) } func testPathLength(){ let length : Float = dollarPRecognizer.pathLength([GesturePoint(x:50, y:80, strokeId:1), GesturePoint(x:30, y:7, strokeId:1)]) XCTAssertEqualWithAccuracy(Float(75.6902), length, 0.0001) } func testPathLengthDifferentPoints(){ let length : Float = dollarPRecognizer.pathLength([GesturePoint(x:50, y:80, strokeId:1), GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:88, y:70, strokeId:2), GesturePoint(x:32, y:63, strokeId:2), GesturePoint(x:32, y:63, strokeId:2)]) XCTAssertEqualWithAccuracy(Float(132.126), length, 0.001) } func testResampleWith2Points(){ var newPoints = dollarPRecognizer.resample([GesturePoint(x:50, y:80, strokeId:1), GesturePoint(x:30, y:7, strokeId:1)],samplingRate: 32) var expectedResults = [GesturePoint(x:50.000000, y:80.000000,strokeId:1), GesturePoint(x:49.354839, y:77.645164, strokeId:1), GesturePoint(x:48.709679, y:75.290329, strokeId:1), GesturePoint(x:48.064518, y:72.935493, strokeId:1), GesturePoint(x:47.419357, y:70.580658, strokeId:1), GesturePoint(x:46.774197, y:68.225822, strokeId:1), GesturePoint(x:46.129036, y:65.870987, strokeId:1), GesturePoint(x:45.483875, y:63.516148, strokeId:1), GesturePoint(x:44.838715, y:61.161308, strokeId:1), GesturePoint(x:44.193554, y:58.806469, strokeId:1), GesturePoint(x:43.548393, y:56.451630, strokeId:1), GesturePoint(x:42.903233, y:54.096790, strokeId:1), GesturePoint(x:42.258072, y:51.741951, strokeId:1), GesturePoint(x:41.612911, y:49.387112, strokeId:1), GesturePoint(x:40.967751, y:47.032272, strokeId:1), GesturePoint(x:40.322590, y:44.677433, strokeId:1), GesturePoint(x:39.677429, y:42.322594, strokeId:1), GesturePoint(x:39.032269, y:39.967754, strokeId:1), GesturePoint(x:38.387108, y:37.612915, strokeId:1), GesturePoint(x:37.741947, y:35.258076, strokeId:1), GesturePoint(x:37.096786, y:32.903236, strokeId:1), GesturePoint(x:36.451626, y:30.548397, strokeId:1), GesturePoint(x:35.806465, y:28.193558, strokeId:1), GesturePoint(x:35.161304, y:25.838718, strokeId:1), GesturePoint(x:34.516140, y:23.483879, strokeId:1), GesturePoint(x:33.870979, y:21.129040, strokeId:1), GesturePoint(x:33.225815, y:18.774200, strokeId:1), GesturePoint(x:32.580654, y:16.419361, strokeId:1), GesturePoint(x:31.935492, y:14.064523, strokeId:1), GesturePoint(x:31.290329, y:11.709684, strokeId:1), GesturePoint(x:30.645166, y:9.354846, strokeId:1), GesturePoint(x:30.000002, y:7.000008, strokeId:1)] XCTAssertEqual(newPoints.count, expectedResults.count) for var index = 0; index < newPoints.count; ++index { XCTAssertEqualWithAccuracy(newPoints[index].x, expectedResults[index].x, 0.0001, "X") XCTAssertEqualWithAccuracy(newPoints[index].y, expectedResults[index].y, 0.0001, "Y") } } func testResampleWith3Points(){ var newPoints = dollarPRecognizer.resample([GesturePoint(x:50, y:80, strokeId:1), GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:620, y:823, strokeId:1)], samplingRate: 32) var expectedResults = [GesturePoint(x:50.000000, y:80.000000, strokeId:1), GesturePoint(x:40.771851, y:46.317261, strokeId:1), GesturePoint(x:31.543705, y:12.634521, strokeId:1), GesturePoint(x:47.039791, y:30.566896, strokeId:1), GesturePoint(x:67.502655, y:58.868073, strokeId:1), GesturePoint(x:87.965515, y:87.169250, strokeId:1), GesturePoint(x:108.428375, y:115.470428, strokeId:1), GesturePoint(x:128.891235, y:143.771606, strokeId:1), GesturePoint(x:149.354095, y:172.072784, strokeId:1), GesturePoint(x:169.816956, y:200.373962, strokeId:1), GesturePoint(x:190.279816, y:228.675140, strokeId:1), GesturePoint(x:210.742676, y:256.976318, strokeId:1), GesturePoint(x:231.205536, y:285.277496, strokeId:1), GesturePoint(x:251.668396, y:313.578674, strokeId:1), GesturePoint(x:272.131256, y:341.879852, strokeId:1), GesturePoint(x:292.594116, y:370.181030, strokeId:1), GesturePoint(x:313.056976, y:398.482208, strokeId:1), GesturePoint(x:333.519836, y:426.783386, strokeId:1), GesturePoint(x:353.982697, y:455.084564, strokeId:1), GesturePoint(x:374.445557, y:483.385742, strokeId:1), GesturePoint(x:394.908417, y:511.686920, strokeId:1), GesturePoint(x:415.371277, y:539.988098, strokeId:1), GesturePoint(x:435.834137, y:568.289307, strokeId:1), GesturePoint(x:456.296997, y:596.590454, strokeId:1), GesturePoint(x:476.759857, y:624.891602, strokeId:1), GesturePoint(x:497.222717, y:653.192749, strokeId:1), GesturePoint(x:517.685547, y:681.493958, strokeId:1), GesturePoint(x:538.148438, y:709.795166, strokeId:1), GesturePoint(x:558.611328, y:738.096313, strokeId:1), GesturePoint(x:579.074158, y:766.397522, strokeId:1), GesturePoint(x:599.537048, y:794.698669, strokeId:1), GesturePoint(x:619.999878, y:822.999878, strokeId:1)] XCTAssertEqual(newPoints.count, expectedResults.count) for var index = 0; index < newPoints.count; ++index { XCTAssertEqualWithAccuracy(newPoints[index].x, expectedResults[index].x, 0.0001, "X") XCTAssertEqualWithAccuracy(newPoints[index].y, expectedResults[index].y, 0.0001, "Y") } } func testScale(){ var newPoints = dollarPRecognizer.scale([GesturePoint(x:50, y:80, strokeId:1), GesturePoint(x:30, y:7, strokeId:1)]) var expectedResults = [GesturePoint(x:0.273973, y:1.000000, strokeId:1), GesturePoint(x:0.000000, y:0.000000, strokeId:1)] XCTAssertEqual(newPoints.count, expectedResults.count) for var index = 0; index < newPoints.count; ++index { XCTAssertEqualWithAccuracy(newPoints[index].x, expectedResults[index].x, 0.0001, "X") XCTAssertEqualWithAccuracy(newPoints[index].y, expectedResults[index].y, 0.0001, "Y") } } func testTranslateToOrigin(){ var newPoints = dollarPRecognizer.translateToOrigin([GesturePoint(x:50, y:80, strokeId:1), GesturePoint(x:30, y:7, strokeId:1)]) var expectedResults = [GesturePoint(x:10.000000, y:36.500000, strokeId:1), GesturePoint(x:-10.000000, y:-36.500000, strokeId:1)] XCTAssertEqual(newPoints.count, expectedResults.count) for var index = 0; index < newPoints.count; ++index { XCTAssertEqualWithAccuracy(newPoints[index].x, expectedResults[index].x, 0.0001, "X") XCTAssertEqualWithAccuracy(newPoints[index].y, expectedResults[index].y, 0.0001, "Y") } } func testNormalize(){ var newPoints = dollarPRecognizer.normalize([GesturePoint(x:50, y:80, strokeId:1), GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:620, y:823, strokeId:1)],samplingRate: 32) var expectedResults = [GesturePoint(x:-0.315999, y:-0.383919, strokeId:1), GesturePoint(x:-0.327387, y:-0.425484, strokeId:1), GesturePoint(x:-0.338774, y:-0.467049, strokeId:1), GesturePoint(x:-0.319652, y:-0.444920, strokeId:1), GesturePoint(x:-0.294401, y:-0.409996, strokeId:1), GesturePoint(x:-0.269149, y:-0.375072, strokeId:1), GesturePoint(x:-0.243898, y:-0.340148, strokeId:1), GesturePoint(x:-0.218646, y:-0.305224, strokeId:1), GesturePoint(x:-0.193395, y:-0.270300, strokeId:1), GesturePoint(x:-0.168144, y:-0.235376, strokeId:1), GesturePoint(x:-0.142892, y:-0.200452, strokeId:1), GesturePoint(x:-0.117641, y:-0.165528, strokeId:1), GesturePoint(x:-0.092389, y:-0.130604, strokeId:1), GesturePoint(x:-0.067138, y:-0.095680, strokeId:1), GesturePoint(x:-0.041887, y:-0.060756, strokeId:1), GesturePoint(x:-0.016635, y:-0.025832, strokeId:1), GesturePoint(x:0.008616, y:0.009092, strokeId:1), GesturePoint(x:0.033868, y:0.044016, strokeId:1), GesturePoint(x:0.059119, y:0.078940, strokeId:1), GesturePoint(x:0.084370, y:0.113864, strokeId:1), GesturePoint(x:0.109622, y:0.148788, strokeId:1), GesturePoint(x:0.134873, y:0.183712, strokeId:1), GesturePoint(x:0.160125, y:0.218635, strokeId:1), GesturePoint(x:0.185376, y:0.253559, strokeId:1), GesturePoint(x:0.210627, y:0.288483, strokeId:1), GesturePoint(x:0.235879, y:0.323407, strokeId:1), GesturePoint(x:0.261130, y:0.358331, strokeId:1), GesturePoint(x:0.286382, y:0.393255, strokeId:1), GesturePoint(x:0.311633, y:0.428179, strokeId:1), GesturePoint(x:0.336884, y:0.463103, strokeId:1), GesturePoint(x:0.362136, y:0.498027, strokeId:1), GesturePoint(x:0.387387, y:0.532951, strokeId:1)] XCTAssertEqual(newPoints.count, expectedResults.count) for var index = 0; index < newPoints.count; ++index { XCTAssertEqualWithAccuracy(newPoints[index].x, expectedResults[index].x, 0.0001, "X") XCTAssertEqualWithAccuracy(newPoints[index].y, expectedResults[index].y, 0.0001, "Y") } } func testCloudDistanceExcat(){ var pointsArray = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var templatesArray = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var result = dollarPRecognizer.cloudDistance(points: pointsArray, templates: templatesArray, start: 0) XCTAssertEqualWithAccuracy(Float(0.0), result, 0.0001) } func testCloudDistanceDiffernt(){ var pointsArray = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var templatesArray = [GesturePoint(x:600, y:20, strokeId:1), GesturePoint(x:800, y:20, strokeId:1), GesturePoint(x:700, y:20, strokeId:2), GesturePoint(x:700, y:90, strokeId:2)] var result = dollarPRecognizer.cloudDistance(points: pointsArray, templates: templatesArray, start: 0) println("result = \(result)") XCTAssertEqualWithAccuracy(Float(2543.75), result, 0.01) } func testGreadyCloudMatchExcat(){ var pointsArray = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var templatesArray = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var result = dollarPRecognizer.greadyCloudMatch(pointsArray, template: templatesArray, samplingRate: 32) XCTAssertEqualWithAccuracy(Float(0.0), result, 0.0001) } func testGreadyCloudMatchDifferent(){ var pointsArray = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var templatesArray = [GesturePoint(x:600, y:20, strokeId:1), GesturePoint(x:800, y:20, strokeId:1), GesturePoint(x:700, y:20, strokeId:2), GesturePoint(x:700, y:90, strokeId:2)] var result = dollarPRecognizer.greadyCloudMatch(pointsArray, template: templatesArray, samplingRate: 32) XCTAssertEqualWithAccuracy(Float(2535.412598), result, 0.00001) } func testRecognizer() { var inputPoints: [GesturePoint] = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var templatePoints: [GesturePoint] = [GesturePoint(x:30, y:7, strokeId:1), GesturePoint(x:103, y:7, strokeId:1), GesturePoint(x:66, y:7, strokeId:2), GesturePoint(x:66, y:87, strokeId:2)] var result = dollarPRecognizer.recoginzer(inputPoints, templates: templatePoints) println(result.score) } }
46.876221
248
0.607046
f5bc6cfb6a0e2f90e935360b250730a4931b46bb
2,336
// // SceneDelegate.swift // test2 // // Created by Jerry Ye on 1/31/20. // Copyright © 2020 Jerry Ye. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.259259
147
0.711901
79ab503754a496bf44fa9624a68e8aef48634ca3
2,327
// // SceneDelegate.swift // App // // Created by LL on 2020/4/13. // Copyright © 2020 hxxxs. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.092593
147
0.711646
38f9f32bf79ec89b6a5513baa4894d9ff4f120a6
2,892
import Foundation /** flash.events.IEventDispatcher for Swift */ public protocol IEventDispatcher: class { func addEventListener(_ type: String, selector: Selector, observer: AnyObject?, useCapture: Bool) func removeEventListener(_ type: String, selector: Selector, observer: AnyObject?, useCapture: Bool) func dispatch(event: Event) func dispatch(_ type: String, bubbles: Bool, data: Any?) } public enum EventPhase: UInt8 { case capturing = 0 case atTarget = 1 case bubbling = 2 case dispose = 3 } // MARK: - /** flash.events.Event for Swift */ open class Event: NSObject { public static let SYNC: String = "sync" public static let EVENT: String = "event" public static let IO_ERROR: String = "ioError" public static let RTMP_STATUS: String = "rtmpStatus" public static func from(_ notification: Notification) -> Event { guard let userInfo: [AnyHashable: Any] = notification.userInfo, let event: Event = userInfo["event"] as? Event else { return Event(type: Event.EVENT) } return event } open fileprivate(set) var type: String open fileprivate(set) var bubbles: Bool open fileprivate(set) var data: Any? open fileprivate(set) var target: AnyObject? public init(type: String, bubbles: Bool = false, data: Any? = nil) { self.type = type self.bubbles = bubbles self.data = data } } // MARK: - /** flash.events.EventDispatcher for Swift */ open class EventDispatcher: NSObject, IEventDispatcher { private weak var target: AnyObject? override public init() { super.init() } public init(target: AnyObject) { self.target = target } deinit { target = nil } public final func addEventListener(_ type: String, selector: Selector, observer: AnyObject? = nil, useCapture: Bool = false) { NotificationCenter.default.addObserver( observer ?? target ?? self, selector: selector, name: Notification.Name(rawValue: "\(type)/\(useCapture)"), object: target ?? self ) } public final func removeEventListener(_ type: String, selector: Selector, observer: AnyObject? = nil, useCapture: Bool = false) { NotificationCenter.default.removeObserver( observer ?? target ?? self, name: Notification.Name(rawValue: "\(type)/\(useCapture)"), object: target ?? self ) } open func dispatch(event: Event) { event.target = target ?? self NotificationCenter.default.post( name: Notification.Name(rawValue: "\(event.type)/false"), object: target ?? self, userInfo: ["event": event] ) event.target = nil } public final func dispatch(_ type: String, bubbles: Bool, data: Any?) { dispatch(event: Event(type: type, bubbles: bubbles, data: data)) } }
30.442105
142
0.644882
ac46d4d0992b1beed0e37087255a60675719f97d
948
// // EmotionFinderControlTests.swift // EmotionFinderControlTests // // Created by Daniel Asher on 11/04/2015. // Copyright (c) 2015 AsherEnterprises. All rights reserved. // import UIKit import XCTest class EmotionFinderControlTests: 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. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
25.621622
111
0.633966
8a01b3d48557e7ebcc1c9a48b493f0b4ca9183d7
5,778
// StatusIndicator.swift // CometChatUIKit // Created by CometChat Inc. on 20/09/19. // Copyright © 2020 CometChat Inc. All rights reserved. /* >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> StatusIndicator: This component will be the class of UImageView which is customizable to display the status of the user. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> */ // MARK: - Importing Frameworks. import Foundation import UIKit import CometChatPro /* ----------------------------------------------------------------------------------------- */ @objc @IBDesignable public class StatusIndicator: UIView { // MARK: - Declaration of IBInspectable @IBInspectable var cornerRadius: CGFloat = 0.0 // @IBInspectable var borderColor: UIColor = UIColor.black // @IBInspectable var borderWidth: CGFloat = 0.5 private var customBackgroundColor = UIColor.white override public var backgroundColor: UIColor? { didSet { customBackgroundColor = backgroundColor! super.backgroundColor = UIColor.clear } } /// Inspectable var to enable runtime defined user attribute hide @IBInspectable var hide: Bool { get { return isHidden } set { isHidden = newValue } } @IBInspectable var setBackgroundColor: UIColor? { didSet { backgroundColor = setBackgroundColor } } // MARK: - Initialization of required Methods func setup() { super.backgroundColor = UIColor.clear } override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override public func draw(_ rect: CGRect) { customBackgroundColor.setFill() UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).fill() let borderRect = bounds.insetBy(dx: borderWidth/2, dy: borderWidth/2) let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: cornerRadius - borderWidth/2) borderColor?.setStroke() borderPath.lineWidth = borderWidth borderPath.stroke() } // MARK: - Public instance methods /** This method used to set the cornerRadius for StatusIndicator class - Parameter cornerRadius: This specifies a float value which sets corner radius. - Author: CometChat Team - Copyright: © 2020 CometChat Inc. - See Also: [StatusIndicator Documentation](https://prodocs.cometchat.com/docs/ios-ui-components#section-2-status-indicator) */ @objc public func set(cornerRadius: CGFloat) -> StatusIndicator { self.cornerRadius = cornerRadius return self } /** This method used to set the borderColor for StatusIndicator class - Parameter borderColor: This specifies a `UIColor` for border of the StatusIndicator. - Author: CometChat Team - Copyright: © 2020 CometChat Inc. - See Also: [StatusIndicator Documentation](https://prodocs.cometchat.com/docs/ios-ui-components#section-2-status-indicator) */ @objc public func set(borderColor: UIColor) -> StatusIndicator { self.borderColor = borderColor return self } /** This method used to set the borderWidth for StatusIndicator class - Parameter borderWidth: This specifies a `CGFloat` for border width of the StatusIndicator. - Author: CometChat Team - Copyright: © 2020 CometChat Inc. - See Also: [StatusIndicator Documentation](https://prodocs.cometchat.com/docs/ios-ui-components#section-2-status-indicator) */ @objc public func set(borderWidth: CGFloat) -> StatusIndicator { self.borderWidth = borderWidth return self } /** This method used to set the Color for StatusIndicator class - Parameter color: This specifies a `UIColor` for of the StatusIndicator. - Author: CometChat Team - Copyright: © 2020 CometChat Inc. - See Also: [StatusIndicator Documentation](https://prodocs.cometchat.com/docs/ios-ui-components#section-2-status-indicator) */ @objc public func set(color: UIColor) -> StatusIndicator { self.backgroundColor = color return self } /** This method used to set the Color according to the status of the user for StatusIndicator class - - Parameter status: This specifies a `UserStatus` such as `.online` or `.offline`. - Author: CometChat Team - Copyright: © 2020 CometChat Inc. - See Also: [StatusIndicator Documentation](https://prodocs.cometchat.com/docs/ios-ui-components#section-2-status-indicator) */ @objc public func set(status: CometChatPro.CometChat.UserStatus) -> StatusIndicator { switch status { case .online: self.backgroundColor = #colorLiteral(red: 0.6039215686, green: 0.8039215686, blue: 0.1960784314, alpha: 1) case .offline: self.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1) case .available: print("ignoring UI update for status: .available") @unknown default: // this should fatal error so we can catch // any unhandled updates to UserStatus in development vs // silencing them. fatalError("unimplemented status uption introduced. update all status switch statements.") } return self } } /* ----------------------------------------------------------------------------------------- */
37.519481
121
0.615092
bbd0c1581e1b9d923a99e36c2f79056f5d58a756
1,616
// // TestListView.swift // JXPagingView // // Created by jiaxin on 2018/5/28. // Copyright © 2018年 jiaxin. All rights reserved. // import UIKit import JXSegmentedView class TestListBaseView: UIView { var tableView: UITableView! override init(frame: CGRect) { super.init(frame: frame) tableView = UITableView(frame: frame, style: .plain) tableView.backgroundColor = UIColor.white tableView.tableFooterView = UIView() tableView.dataSource = self tableView.delegate = self tableView.register(PagingListBaseCell.self, forCellReuseIdentifier: "cell") addSubview(tableView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() tableView.frame = bounds } } extension TestListBaseView: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PagingListBaseCell cell.titleLabel.text = "row:\(indexPath.row)" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } } extension TestListBaseView: JXSegmentedListContainerViewListDelegate { func listView() -> UIView { return self } }
26.933333
111
0.685025
bfa6eebe7c31aa476366b0fa57fb72205dc01db7
2,401
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 UIKit public typealias MaterialDepthType = (offset: CGSize, opacity: Float, radius: CGFloat) public enum MaterialDepth { case None case Depth1 case Depth2 case Depth3 case Depth4 case Depth5 } /// Converts the MaterialDepth enum to a MaterialDepthType value. public func MaterialDepthToValue(depth: MaterialDepth) -> MaterialDepthType { switch depth { case .None: return (offset: CGSizeZero, opacity: 0, radius: 0) case .Depth1: return (offset: CGSizeMake(0, 1), opacity: 0.3, radius: 1) case .Depth2: return (offset: CGSizeMake(0, 2), opacity: 0.3, radius: 2) case .Depth3: return (offset: CGSizeMake(0, 3), opacity: 0.3, radius: 3) case .Depth4: return (offset: CGSizeMake(0, 4), opacity: 0.3, radius: 4) case .Depth5: return (offset: CGSizeMake(0, 5), opacity: 0.3, radius: 5) } }
39.360656
86
0.758017