repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ahoppen/swift | test/SILGen/writeback.swift | 18 | 5764 | // RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle %s | %FileCheck %s
struct Foo {
mutating // used to test writeback.
func foo() {}
subscript(x: Int) -> Foo {
get {
return Foo()
}
set {}
}
}
var x: Foo {
get {
return Foo()
}
set {}
}
var y: Foo {
get {
return Foo()
}
set {}
}
var z: Foo {
get {
return Foo()
}
set {}
}
var readonly: Foo {
get {
return Foo()
}
}
func bar(x x: inout Foo) {}
// Writeback to value type 'self' argument
x.foo()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]]
// CHECK: [[FOO:%.*]] = function_ref @$s9writeback3FooV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout Foo) -> ()
// CHECK: apply [[FOO]]([[X_TEMP]]) : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
// Writeback to inout argument
bar(x: &x)
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[BAR:%.*]] = function_ref @$s9writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: apply [[BAR]]([[X_TEMP]]) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
func zang(x x: Foo) {}
// No writeback for pass-by-value argument
zang(x: x)
// CHECK: function_ref @$s9writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @$s9writeback1xAA3FooVvs
zang(x: readonly)
// CHECK: function_ref @$s9writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @$s9writeback8readonlyAA3FooVvs
func zung() -> Int { return 0 }
// Ensure that subscripts are only evaluated once.
bar(x: &x[zung()])
// CHECK: [[ZUNG:%.*]] = function_ref @$s9writeback4zungSiyF : $@convention(thin) () -> Int
// CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int
// CHECK: [[GET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @$s9writeback3FooV{{[_0-9a-zA-Z]*}}ig : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo
// CHECK: [[BAR:%.*]] = function_ref @$s9writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @$s9writeback3FooV{{[_0-9a-zA-Z]*}}is : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: function_ref @$s9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
protocol Fungible {}
extension Foo : Fungible {}
var addressOnly: Fungible {
get {
return Foo()
}
set {}
}
func funge(x x: inout Fungible) {}
funge(x: &addressOnly)
// CHECK: [[TEMP:%.*]] = alloc_stack $Fungible
// CHECK: [[GET:%.*]] = function_ref @$s9writeback11addressOnlyAA8Fungible_pvg : $@convention(thin) () -> @out Fungible
// CHECK: apply [[GET]]([[TEMP]]) : $@convention(thin) () -> @out Fungible
// CHECK: [[FUNGE:%.*]] = function_ref @$s9writeback5funge1xyAA8Fungible_pz_tF : $@convention(thin) (@inout Fungible) -> ()
// CHECK: apply [[FUNGE]]([[TEMP]]) : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[SET:%.*]] = function_ref @$s9writeback11addressOnlyAA8Fungible_pvs : $@convention(thin) (@in Fungible) -> ()
// CHECK: apply [[SET]]([[TEMP]]) : $@convention(thin) (@in Fungible) -> ()
// CHECK: dealloc_stack [[TEMP]] : $*Fungible
// Test that writeback occurs with generic properties.
// <rdar://problem/16525257>
protocol Runcible {
associatedtype Frob: Frobable
var frob: Frob { get set }
}
protocol Frobable {
associatedtype Anse
var anse: Anse { get set }
}
// CHECK-LABEL: sil hidden [ossa] @$s9writeback12test_generic{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!modify
// CHECK: witness_method $Runce.Frob, #Frobable.anse!setter
func test_generic<Runce: Runcible>(runce runce: inout Runce, anse: Runce.Frob.Anse) {
runce.frob.anse = anse
}
// We should *not* write back when referencing decls or members as rvalues.
// <rdar://problem/16530235>
// CHECK-LABEL: sil hidden [ossa] @$s9writeback15loadAddressOnlyAA8Fungible_pyF : $@convention(thin) () -> @out Fungible {
func loadAddressOnly() -> Fungible {
// CHECK: function_ref writeback.addressOnly.getter
// CHECK-NOT: function_ref writeback.addressOnly.setter
return addressOnly
}
// CHECK-LABEL: sil hidden [ossa] @$s9writeback10loadMember{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!getter
// CHECK: witness_method $Runce.Frob, #Frobable.anse!getter
// CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter
// CHECK-NOT: witness_method $Runce, #Runcible.frob!setter
func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse {
return runce.frob.anse
}
| apache-2.0 | 57cef1bf171efa5315a19e347e590525 | 35.948718 | 136 | 0.613116 | 3.182772 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatMessageThrottledProcessingManager.swift | 1 | 4765 | //
// ChatMessageThrottledProcessingManager.swift
// Telegram
//
// Created by keepcoder on 07/03/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import Postbox
import SwiftSignalKit
import TGUIKit
final class ChatMessageThrottledProcessingManager {
private let queue = Queue()
private let delay: Double
private let submitInterval: Double?
var process: ((Set<MessageId>) -> Void)?
private var timer: SwiftSignalKit.Timer?
private var processedList: [MessageId] = []
private var processed: [MessageId: Double] = [:]
private var buffer = Set<MessageId>()
private let disposable = MetaDisposable()
init(delay: Double = 1.0, submitInterval: Double? = nil) {
self.delay = delay
self.submitInterval = submitInterval
}
func setProcess(process: @escaping (Set<MessageId>) -> Void) {
self.queue.async {
self.process = process
}
}
func add(_ messageIds: [MessageId]) {
self.queue.async {
let timestamp = CFAbsoluteTimeGetCurrent()
for id in messageIds {
if let processedTimestamp = self.processed[id] {
if let submitInterval = self.submitInterval, (timestamp - processedTimestamp) >= submitInterval {
self.processed[id] = timestamp
self.processedList.append(id)
self.buffer.insert(id)
}
} else {
self.processed[id] = timestamp
self.processedList.append(id)
self.buffer.insert(id)
}
}
if self.processedList.count > 1000 {
for i in 0 ..< 200 {
self.processed.removeValue(forKey: self.processedList[i])
}
self.processedList.removeSubrange(0 ..< 200)
}
if self.timer == nil {
var completionImpl: (() -> Void)?
let timer = SwiftSignalKit.Timer(timeout: self.delay, repeat: false, completion: {
completionImpl?()
}, queue: self.queue)
completionImpl = { [weak self, weak timer] in
if let strongSelf = self {
if let timer = timer, strongSelf.timer === timer {
strongSelf.timer = nil
}
let buffer = strongSelf.buffer
strongSelf.buffer.removeAll()
if let submitInterval = strongSelf.submitInterval {
strongSelf.disposable.set(delaySignal(submitInterval).start(completed: { [weak strongSelf]in
strongSelf?.add(Array(buffer))
}))
} else {
strongSelf.disposable.set(nil)
}
DispatchQueue.main.async {
strongSelf.process?(buffer)
}
}
}
self.timer = timer
timer.start()
}
}
}
}
final class ChatMessageVisibleThrottledProcessingManager {
private let queue = Queue()
private let delay: Double
private var currentIds = Set<MessageId>()
var process: ((Set<MessageId>) -> Void)?
private var timer: SwiftSignalKit.Timer?
init(delay: Double = 1.0) {
self.delay = delay
}
func setProcess(process: @escaping (Set<MessageId>) -> Void) {
self.queue.async {
self.process = process
}
}
func update(_ ids: Set<MessageId>) {
self.queue.async {
if self.currentIds != ids {
self.currentIds = ids
if self.timer == nil {
var completionImpl: (() -> Void)?
let timer = SwiftSignalKit.Timer(timeout: self.delay, repeat: false, completion: {
completionImpl?()
}, queue: self.queue)
completionImpl = { [weak self, weak timer] in
if let strongSelf = self {
if let timer = timer, strongSelf.timer === timer {
strongSelf.timer = nil
}
strongSelf.process?(strongSelf.currentIds)
}
}
self.timer = timer
timer.start()
}
}
}
}
}
| gpl-2.0 | 047b007829880c84f2f4b6f886937a83 | 32.549296 | 120 | 0.482578 | 5.469575 | false | false | false | false |
ymkim50/MFImageSlider | MFImageSlider/Classes/ImageSlider.swift | 1 | 8856 | //
// ImageSlider.swift
// Pods
//
// Created by Youngmin Kim on 2016. 12. 19..
//
//
import UIKit
public protocol FImageSliderDelegate: class {
func sliderValueChanged(slider: FImageSlider) // call when user is swiping slider
func sliderValueChangeEnded(slider: FImageSlider) // calls when user touchUpInside or touchUpOutside slider
}
let handleWidth: CGFloat = 14.0
let borderWidth: CGFloat = 2.0
let viewCornerRadius: CGFloat = 5.0
let animationDuration: TimeInterval = 0.1// speed when slider change position on tap
public class FImageSlider: UIView {
public enum Orientation {
case vertical
case horizontal
}
public weak var delegate: FImageSliderDelegate? = nil
lazy var imageView: UIImageView = {
var imageView = UIImageView()
imageView.backgroundColor = .red
imageView.frame = self.bounds
imageView.isHidden = true
return imageView
}()
public var backgroundImage: UIImage? {
get {
return imageView.image
}
set {
if let image = newValue {
imageView.image = image
imageView.isHidden = false
} else {
imageView.image = nil
imageView.isHidden = true
}
}
}
lazy var foregroundView: UIView = {
var view = UIView()
return view
}()
lazy var handleView: UIView = {
var view = UIView()
view.layer.cornerRadius = viewCornerRadius
view.layer.masksToBounds = true
return view
}()
lazy var label: UILabel = {
var label = UILabel()
switch self.orientation {
case .vertical:
label.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI / 2.0))
label.frame = self.bounds
case .horizontal:
label.frame = self.bounds
}
label.textAlignment = .center
label.font = UIFont(name: "Helvetica", size: 24)
return label
}()
var _value: Float = 0.0
public var value: Float {
get {
return _value
}
set {
_value = newValue
self.setValue(value: _value, animated: false, completion: nil)
}
}
var orientation: Orientation = .vertical
public var isCornersHidden: Bool = false {
didSet {
if isCornersHidden {
self.layer.cornerRadius = 0.0
self.layer.masksToBounds = true
} else {
self.layer.cornerRadius = viewCornerRadius
self.layer.masksToBounds = true
}
}
}
public var isBordersHidden: Bool = false {
didSet {
if isBordersHidden {
self.layer.borderWidth = 0.0
} else {
self.layer.borderWidth = borderWidth
}
}
}
public var isHandleHidden: Bool = false {
didSet {
if isHandleHidden {
handleView.isHidden = true
handleView.removeFromSuperview()
} else {
insertSubview(handleView, aboveSubview: label)
handleView.isHidden = false
}
}
}
public var foregroundColor: UIColor? {
get {
return foregroundView.backgroundColor
}
set {
foregroundView.backgroundColor = newValue
}
}
public var handleColor: UIColor? {
get {
return handleView.backgroundColor
}
set {
handleView.backgroundColor = newValue
}
}
public var borderColor: UIColor? {
get {
if let cgColor = self.layer.borderColor {
return UIColor(cgColor: cgColor)
} else {
return nil
}
}
set {
return self.layer.borderColor = newValue?.cgColor
}
}
public var text: String? {
get {
return self.label.text
}
set {
self.label.text = newValue
}
}
public var font: UIFont! {
get {
return self.label.font
}
set {
self.label.font = newValue
}
}
public var textColor: UIColor! {
get {
return self.label.textColor
}
set {
self.label.textColor = newValue
}
}
public init(frame: CGRect, orientation: Orientation) {
super.init(frame: frame)
self.orientation = orientation
initSlider()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if self.frame.width > self.frame.height {
orientation = .horizontal
} else {
orientation = .vertical
}
initSlider()
}
}
extension FImageSlider {
func initSlider() {
addSubview(imageView)
addSubview(foregroundView)
addSubview(label)
addSubview(handleView)
self.layer.cornerRadius = viewCornerRadius
self.layer.masksToBounds = true
self.layer.borderWidth = borderWidth
// set default value for slider. Value should be between 0 and 1
self.setValue(value: 0.0, animated: false, completion: nil)
}
func setValue(value: Float, animated: Bool, completion: ((Bool) -> Void)? = nil) {
assert(value >= 0.0 && value <= 1.0, "Value must between 0 and 1")
let calcValue = max(0, min(value, 1))
var point: CGPoint = .zero
switch orientation {
case .vertical:
point = CGPoint(x: 0, y: CGFloat(1 - calcValue) * self.frame.height)
case .horizontal:
point = CGPoint(x: CGFloat(calcValue) * self.frame.width, y: 0)
}
if animated {
UIView.animate(withDuration: animationDuration, animations: {
self.changeStartForegroundView(withPoint: point)
}, completion: { (completed) in
if completed {
completion?(completed)
}
})
} else {
changeStartForegroundView(withPoint: point)
}
}
}
// MARK: - Change slider forground with point
extension FImageSlider {
func changeStartForegroundView(withPoint point: CGPoint) {
var calcPoint = point
switch orientation {
case .vertical:
calcPoint.y = max(0, min(calcPoint.y, self.frame.height))
self._value = Float(1.0 - (calcPoint.y / self.frame.height))
self.foregroundView.frame = CGRect(x: 0.0, y: self.frame.height, width: self.frame.width, height: calcPoint.y - self.frame.height)
if !isHandleHidden {
if foregroundView.frame.origin.y <= 0 {
handleView.frame = CGRect(x: borderWidth,
y: 0.0,
width: self.frame.width - borderWidth * 2,
height: handleWidth)
} else if foregroundView.frame.origin.y >= self.frame.height {
handleView.frame = CGRect(x: borderWidth,
y: self.frame.height - handleWidth,
width: self.frame.width - borderWidth * 2,
height: handleWidth)
} else {
handleView.frame = CGRect(x: borderWidth,
y: foregroundView.frame.origin.y - handleWidth / 2,
width: self.frame.width - borderWidth * 2,
height: handleWidth)
}
}
case .horizontal:
calcPoint.x = max(0, min(calcPoint.x, self.frame.width))
self._value = Float(calcPoint.x / self.frame.width)
self.foregroundView.frame = CGRect(x: 0, y: 0, width: calcPoint.x, height: self.frame.height)
if !isHandleHidden {
if foregroundView.frame.width <= 0 {
handleView.frame = CGRect(x: 0,
y: borderWidth,
width: handleWidth,
height: foregroundView.frame.height - borderWidth)
self.delegate?.sliderValueChanged(slider: self) // or use sliderValueChangeEnded method
} else if foregroundView.frame.width >= self.frame.width {
handleView.frame = CGRect(x: foregroundView.frame.width - handleWidth,
y: borderWidth,
width: handleWidth,
height: foregroundView.frame.height - borderWidth * 2)
self.delegate?.sliderValueChanged(slider: self) // or use sliderValueChangeEnded method
} else {
handleView.frame = CGRect(x: foregroundView.frame.width - handleWidth / 2,
y: borderWidth,
width: handleWidth,
height: foregroundView.frame.height - borderWidth * 2)
}
}
}
}
}
// MARK: - Touch events
extension FImageSlider {
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let point = touch.location(in: self)
switch orientation {
case .vertical:
if !(point.y < 0) && !(point.y > self.frame.height) {
changeStartForegroundView(withPoint: point)
}
case .horizontal:
if !(point.x < 0) && !(point.x > self.frame.width) {
changeStartForegroundView(withPoint: point)
}
}
if point.x > 0 && point.x <= self.frame.width - handleWidth {
delegate?.sliderValueChanged(slider: self)
}
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let point = touch.location(in: self)
UIView.animate(withDuration: animationDuration, animations: {
self.changeStartForegroundView(withPoint: point)
}) { (completed) in
self.delegate?.sliderValueChangeEnded(slider: self)
}
}
}
| mit | 26756bea65a27d3b7fff933291ad13ae | 23.396694 | 133 | 0.630759 | 3.625051 | false | false | false | false |
codepath-volunteer-app/VolunteerMe | VolunteerMe/Pods/DateToolsSwift/DateToolsSwift/DateTools/TimePeriodCollection.swift | 11 | 9066 | //
// TimePeriodCollection.swift
// DateTools
//
// Created by Grayson Webster on 8/17/16.
// Copyright © 2016 Grayson Webster. All rights reserved.
//
import Foundation
/**
* Time period collections serve as loose sets of time periods. They are
* unorganized unless you decide to sort them, and have their own characteristics
* like a `beginning` and `end` that are extrapolated from the time periods within. Time
* period collections allow overlaps within their set of time periods.
*
* [Visit our github page](https://github.com/MatthewYork/DateTools#time-period-collections) for more information.
*/
open class TimePeriodCollection: TimePeriodGroup {
// MARK: - Collection Manipulation
/**
* Append a TimePeriodProtocol to the periods array and check if the Collection's
* beginning and end should change.
*
* - parameter period: TimePeriodProtocol to add to the collection
*/
public func append(_ period: TimePeriodProtocol) {
periods.append(period)
updateExtremes(period: period)
}
/**
* Append a TimePeriodProtocol array to the periods array and check if the Collection's
* beginning and end should change.
*
* - parameter periodArray: TimePeriodProtocol list to add to the collection
*/
public func append(_ periodArray: [TimePeriodProtocol]) {
for period in periodArray {
periods.append(period)
updateExtremes(period: period)
}
}
/**
* Append a TimePeriodGroup's periods array to the periods array of self and check if the Collection's
* beginning and end should change.
*
* - parameter newPeriods: TimePeriodGroup to merge periods arrays with
*/
public func append<C: TimePeriodGroup>(contentsOf newPeriods: C) {
for period in newPeriods as TimePeriodGroup {
periods.append(period)
updateExtremes(period: period)
}
}
/**
* Insert period into periods array at given index.
*
* - parameter newElement: The period to insert
* - parameter index: Index to insert period at
*/
public func insert(_ newElement: TimePeriodProtocol, at index: Int) {
periods.insert(newElement, at: index)
updateExtremes(period: newElement)
}
/**
* Remove from period array at the given index.
*
* - parameter at: The index in the collection to remove
*/
public func remove(at: Int) {
periods.remove(at: at)
updateExtremes()
}
/**
* Remove all periods from period array.
*/
public func removeAll() {
periods.removeAll()
updateExtremes()
}
// MARK: - Sorting
// In place
/**
* Sort periods array in place by beginning
*/
public func sortByBeginning() {
self.sort { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in
if period1.beginning == nil && period2.beginning == nil {
return false
} else if (period1.beginning == nil) {
return true
} else if (period2.beginning == nil) {
return false
} else {
return period2.beginning! < period1.beginning!
}
}
}
/**
* Sort periods array in place
*/
public func sort(by areInIncreasingOrder: (TimePeriodProtocol, TimePeriodProtocol) -> Bool) {
self.periods.sort(by: areInIncreasingOrder)
}
// New collection
/**
* Return collection with sorted periods array by beginning
*
* - returns: Collection with sorted periods
*/
public func sortedByBeginning() -> TimePeriodCollection {
let array = self.periods.sorted { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in
if period1.beginning == nil && period2.beginning == nil {
return false
} else if (period1.beginning == nil) {
return true
} else if (period2.beginning == nil) {
return false
} else {
return period2.beginning! < period1.beginning!
}
}
let collection = TimePeriodCollection()
collection.append(array)
return collection
}
/**
* Return collection with sorted periods array
*
* - returns: Collection with sorted periods
*/
public func sorted(by areInIncreasingOrder: (TimePeriodProtocol, TimePeriodProtocol) -> Bool) -> TimePeriodCollection {
let collection = TimePeriodCollection()
collection.append(self.periods.sorted(by: areInIncreasingOrder))
return collection
}
// MARK: - Collection Relationship
// Potentially use .reduce() instead of these functions
/**
* Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s
* whose start and end dates fall completely inside the interval of the given `TimePeriod`.
*
* - parameter period: The period to compare each other period against
*
* - returns: Collection of periods inside the given period
*/
public func allInside(in period: TimePeriodProtocol) -> TimePeriodCollection {
let collection = TimePeriodCollection()
// Filter by period
collection.periods = self.periods.filter({ (timePeriod: TimePeriodProtocol) -> Bool in
return timePeriod.isInside(of: period)
})
return collection
}
/**
* Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s containing
* the given date.
*
* - parameter date: The date to compare each period to
*
* - returns: Collection of periods intersected by the given date
*/
public func periodsIntersected(by date: Date) -> TimePeriodCollection {
let collection = TimePeriodCollection()
// Filter by period
collection.periods = self.periods.filter({ (timePeriod: TimePeriodProtocol) -> Bool in
return timePeriod.contains(date, interval: .closed)
})
return collection
}
/**
* Returns from the `TimePeriodCollection` a sub-collection of `TimePeriod`s
* containing either the start date or the end date--or both--of the given `TimePeriod`.
*
* - parameter period: The period to compare each other period to
*
* - returns: Collection of periods intersected by the given period
*/
public func periodsIntersected(by period: TimePeriodProtocol) -> TimePeriodCollection {
let collection = TimePeriodCollection()
//Filter by periop
collection.periods = self.periods.filter({ (timePeriod: TimePeriodProtocol) -> Bool in
return timePeriod.intersects(with: period)
})
return collection
}
// MARK: - Map
public func map(_ transform: (TimePeriodProtocol) throws -> TimePeriodProtocol) rethrows -> TimePeriodCollection {
var mappedArray = [TimePeriodProtocol]()
mappedArray = try periods.map(transform)
let mappedCollection = TimePeriodCollection()
for period in mappedArray {
mappedCollection.periods.append(period)
mappedCollection.updateExtremes(period: period)
}
return mappedCollection
}
// MARK: - Operator Overloads
/**
* Operator overload for comparing `TimePeriodCollection`s to each other
*/
public static func ==(left: TimePeriodCollection, right: TimePeriodCollection) -> Bool {
return left.equals(right)
}
//MARK: - Helpers
internal func updateExtremes(period: TimePeriodProtocol) {
//Check incoming period against previous beginning and end date
if self.count == 1 {
_beginning = period.beginning
_end = period.end
} else {
_beginning = nilOrEarlier(date1: _beginning, date2: period.beginning)
_end = nilOrLater(date1: _end, date2: period.end)
}
}
internal func updateExtremes() {
if periods.count == 0 {
_beginning = nil
_end = nil
} else {
_beginning = periods[0].beginning
_end = periods[0].end
for i in 1..<periods.count {
_beginning = nilOrEarlier(date1: _beginning, date2: periods[i].beginning)
_end = nilOrEarlier(date1: _end, date2: periods[i].end)
}
}
}
internal func nilOrEarlier(date1: Date?, date2: Date?) -> Date? {
if date1 == nil || date2 == nil {
return nil
} else {
return date1!.earlierDate(date2!)
}
}
internal func nilOrLater(date1: Date?, date2: Date?) -> Date? {
if date1 == nil || date2 == nil {
return nil
} else {
return date1!.laterDate(date2!)
}
}
}
| mit | c31bf78c321ab01b311e18adb5fe48a6 | 32.450185 | 123 | 0.609708 | 4.606199 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/ViewModels/Amount.swift | 1 | 12493 | //
// Amount.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-01-15.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import Foundation
import WalletKit
typealias CryptoAmount = WalletKit.Amount
/// View model for representing the WalletKit.Amount model
/// with extended currency, fiat conversion and formatting information
public struct Amount {
static let normalPrecisionDigits = 5
static let highPrecisionDigits = 8
let currency: Currency
let cryptoAmount: CryptoAmount
var rate: Rate?
var minimumFractionDigits: Int?
var maximumFractionDigits: Int
var negative: Bool { return cryptoAmount.isNegative }
var isZero: Bool { return self == Amount.zero(currency, rate: rate) }
internal var locale = Locale.current // for testing
// MARK: - Init
init(cryptoAmount: CryptoAmount,
currency: Currency,
rate: Rate? = nil,
minimumFractionDigits: Int? = nil,
maximumFractionDigits: Int = Amount.normalPrecisionDigits) {
assert(currency.uid == cryptoAmount.currency.uid)
self.currency = currency
// make a new instance of CryptoAmount
self.cryptoAmount = CryptoAmount.create(string: cryptoAmount.string(),
negative: cryptoAmount.isNegative,
unit: cryptoAmount.unit.base)
?? WalletKit.Amount.create(integer: 0, unit: cryptoAmount.unit.base)
self.rate = rate
self.minimumFractionDigits = minimumFractionDigits
self.maximumFractionDigits = maximumFractionDigits
}
init(amount: Amount,
rate: Rate? = nil,
minimumFractionDigits: Int? = nil,
maximumFractionDigits: Int? = nil,
negative: Bool = false) {
self.currency = amount.currency
// make a new instance of CryptoAmount
self.cryptoAmount = CryptoAmount.create(string: amount.cryptoAmount.string(),
negative: negative,
unit: amount.currency.baseUnit)
?? WalletKit.Amount.create(integer: 0, unit: amount.currency.baseUnit)
self.rate = rate ?? amount.rate
self.minimumFractionDigits = minimumFractionDigits ?? amount.minimumFractionDigits
self.maximumFractionDigits = maximumFractionDigits ?? amount.maximumFractionDigits
}
init(tokenString: String,
currency: Currency,
locale: Locale = Locale.current,
unit: CurrencyUnit? = nil,
rate: Rate? = nil,
minimumFractionDigits: Int? = nil,
maximumFractionDigits: Int = Amount.normalPrecisionDigits,
negative: Bool = false) {
let unit = (unit ?? currency.defaultUnit)
self.cryptoAmount = CryptoAmount.create(string: tokenString.usDecimalString(fromLocale: locale),
negative: negative,
unit: unit)
?? WalletKit.Amount.create(integer: 0, unit: currency.baseUnit)
self.currency = currency
self.rate = rate
self.minimumFractionDigits = minimumFractionDigits
self.maximumFractionDigits = maximumFractionDigits
}
init?(fiatString: String,
currency: Currency,
rate: Rate,
minimumFractionDigits: Int? = nil,
maximumFractionDigits: Int = Amount.normalPrecisionDigits,
negative: Bool = false) {
self.currency = currency
//TODO:CRYPTO use BRCrypto CurrencyPair for conversion
guard let fiatAmount = NumberFormatter().number(from: fiatString)?.decimalValue else { return nil }
var decimal = fiatAmount / Decimal(rate.rate)
if negative {
decimal *= -1.0
}
self.cryptoAmount = WalletKit.Amount.create(double: decimal.doubleValue, unit: currency.defaultUnit)
self.rate = rate
self.minimumFractionDigits = minimumFractionDigits
self.maximumFractionDigits = maximumFractionDigits
}
static func zero(_ currency: Currency, rate: Rate? = nil) -> Amount {
return Amount(cryptoAmount: CryptoAmount.create(integer: 0, unit: currency.baseUnit),
currency: currency,
rate: rate)
}
// MARK: - Convenience Accessors
var description: String {
return rate != nil ? fiatDescription : tokenDescription
}
var combinedDescription: String {
return Store.state.showFiatAmounts ? "\(fiatDescription) (\(tokenDescription))" : "\(tokenDescription) (\(fiatDescription))"
}
// MARK: Token
/// Token value in default units as Decimal number
/// NB: Decimal can only represent maximum 38 digits wheras UInt256 can represent up to 78 digits -- it is assumed the units represented will be multiple orders of magnitude smaller than the base unit value and precision loss is acceptable.
var tokenValue: Decimal {
return rawTokenFormat.number(from: tokenUnformattedString(in: currency.defaultUnit))?.decimalValue ?? Decimal.zero
}
/// Token value in default units as formatted string with currency ticker symbol suffix
var tokenDescription: String {
return tokenDescription(in: currency.defaultUnit)
}
/// Token value in default units as formatted string without symbol
var tokenFormattedString: String {
return tokenFormattedString(in: currency.defaultUnit)
}
/// Token value in specified units as formatted string without symbol (for user display)
func tokenFormattedString(in unit: CurrencyUnit) -> String {
guard var formattedValue = cryptoAmount.string(as: unit, formatter: tokenFormat) else {
assertionFailure()
return ""
}
// override precision digits if the value is too small to show
if !isZero && tokenFormat.number(from: formattedValue) == 0.0 {
guard let formatter = tokenFormat.copy() as? NumberFormatter else { assertionFailure(); return "" }
formatter.maximumFractionDigits = Int(unit.decimals)
formattedValue = cryptoAmount.string(as: unit, formatter: formatter) ?? formattedValue
}
return formattedValue
}
/// Token value in specified units as unformatted string without symbol (used API/internal use)
func tokenUnformattedString(in unit: CurrencyUnit) -> String {
if unit == currency.baseUnit {
return cryptoAmount.string(base: 10, preface: "")
}
guard let str = cryptoAmount.string(as: unit, formatter: rawTokenFormat) else {
assertionFailure(); return ""
}
return str
}
/// Token value in specified units as formatted string with currency ticker symbol suffix
func tokenDescription(in unit: CurrencyUnit) -> String {
return "\(tokenFormattedString(in: unit)) \(currency.name(forUnit: unit))"
}
var tokenFormat: NumberFormatter {
let format = NumberFormatter()
format.locale = locale
format.isLenient = true
format.numberStyle = .currency
format.generatesDecimalNumbers = true
format.negativeFormat = "-\(format.positiveFormat!)"
format.currencyCode = currency.code
format.currencySymbol = ""
format.maximumFractionDigits = min(Int(currency.defaultUnit.decimals), maximumFractionDigits)
format.minimumFractionDigits = minimumFractionDigits ?? 0
return format
}
/// formatter for raw value with maximum precision and no symbols or separators
private var rawTokenFormat: NumberFormatter {
let format = NumberFormatter()
format.locale = locale
format.isLenient = true
format.numberStyle = .currency
format.generatesDecimalNumbers = true
format.usesGroupingSeparator = false
format.currencyCode = ""
format.currencySymbol = ""
format.maximumFractionDigits = 99
format.minimumFractionDigits = 0
return format
}
// MARK: - Fiat
var fiatValue: Decimal {
guard let rate = rate ?? currency.state?.currentRate,
let value = commonUnitValue else { return 0.0 }
return value * Decimal(rate.rate)
}
var fiatDescription: String {
return fiatDescription()
}
func fiatDescription(forLocale locale: Locale? = nil) -> String {
let formatter = localFormat
if let locale = locale {
formatter.locale = locale
}
guard var fiatString = formatter.string(from: fiatValue as NSDecimalNumber) else { return "" }
if let stringValue = formatter.number(from: fiatString), abs(fiatValue) > 0.0, stringValue == 0 {
// if non-zero values show as 0, show minimum fractional value for fiat
let minimumValue = pow(10.0, Double(-formatter.minimumFractionDigits)) * (negative ? -1.0 : 1.0)
fiatString = formatter.string(from: NSDecimalNumber(value: minimumValue)) ?? fiatString
}
return fiatString
}
var localFormat: NumberFormatter {
let format = NumberFormatter()
format.locale = locale
format.isLenient = true
format.numberStyle = .currency
format.generatesDecimalNumbers = true
format.negativeFormat = "-\(format.positiveFormat!)"
if let rate = rate {
format.currencySymbol = rate.currencySymbol
format.maximumFractionDigits = rate.maxFractionalDigits
} else if let rate = currency.state?.currentRate {
format.currencySymbol = rate.currencySymbol
format.maximumFractionDigits = rate.maxFractionalDigits
}
format.minimumFractionDigits = minimumFractionDigits ?? format.minimumFractionDigits
return format
}
// MARK: - Private
private var commonUnitValue: Decimal? {
let commonUnitString = cryptoAmount.string(as: currency.defaultUnit, formatter: rawTokenFormat) ?? ""
return rawTokenFormat.number(from: commonUnitString)?.decimalValue
}
}
extension Amount: Equatable, Comparable {
public static func == (lhs: Amount, rhs: Amount) -> Bool {
return lhs.cryptoAmount == rhs.cryptoAmount
}
public static func > (lhs: Amount, rhs: Amount) -> Bool {
return lhs.cryptoAmount > rhs.cryptoAmount
}
public static func < (lhs: Amount, rhs: Amount) -> Bool {
return lhs.cryptoAmount < rhs.cryptoAmount
}
static func - (lhs: Amount, rhs: Amount) -> Amount {
return Amount(cryptoAmount: (lhs.cryptoAmount - rhs.cryptoAmount) ?? lhs.cryptoAmount,
currency: lhs.currency,
rate: lhs.rate,
minimumFractionDigits: lhs.minimumFractionDigits,
maximumFractionDigits: lhs.maximumFractionDigits)
}
static func + (lhs: Amount, rhs: Amount) -> Amount {
return Amount(cryptoAmount: (lhs.cryptoAmount + rhs.cryptoAmount) ?? lhs.cryptoAmount,
currency: lhs.currency,
rate: lhs.rate,
minimumFractionDigits: lhs.minimumFractionDigits,
maximumFractionDigits: lhs.maximumFractionDigits)
}
}
extension Decimal {
var doubleValue: Double {
return NSDecimalNumber(decimal: self).doubleValue
}
}
extension String {
func usDecimalString(fromLocale inputLocale: Locale) -> String {
let expectedFormat = NumberFormatter()
expectedFormat.numberStyle = .decimal
expectedFormat.locale = Locale(identifier: "en_US")
// createUInt256ParseDecimal expects en_us formatted string
let inputFormat = NumberFormatter()
inputFormat.locale = inputLocale
// remove grouping separators
var sanitized = self.replacingOccurrences(of: inputFormat.currencyGroupingSeparator, with: "")
sanitized = sanitized.replacingOccurrences(of: inputFormat.groupingSeparator, with: "")
// replace decimal separators
sanitized = sanitized.replacingOccurrences(of: inputFormat.currencyDecimalSeparator, with: expectedFormat.decimalSeparator)
sanitized = sanitized.replacingOccurrences(of: inputFormat.decimalSeparator, with: expectedFormat.decimalSeparator)
return sanitized
}
}
| mit | a3d28819dec7ee5542838cd3b75b3a39 | 39.957377 | 244 | 0.647294 | 5.164117 | false | false | false | false |
ysnrkdm/Graphene | Sources/Graphene/Think.swift | 1 | 830 | //
// Think.swift
// FlatReversi
//
// Created by KodamaYoshinori on 2016/10/16.
// Copyright © 2016 Yoshinori Kodama. All rights reserved.
//
import Foundation
public struct Hand : Hashable, Equatable {
public var row: Int
public var col: Int
public var color: Pieces
public init(row: Int, col: Int, color: Pieces) {
self.row = row
self.col = col
self.color = color
}
public var hashValue: Int {
get {
let hash = row + col * 10 + color.toInt() * 6
return hash
}
}
public static func ==(lhs: Hand, rhs: Hand) -> Bool {
return lhs.row == rhs.row && lhs.col == rhs.col && lhs.color == rhs.color
}
}
public protocol Think {
func think(_ color: Pieces, board: BoardRepresentation, info: Info) -> Hand
}
| mit | ad24ade1b8b446d23413125a7611d285 | 22.027778 | 81 | 0.580217 | 3.620087 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Utilities/Libs/CAPSPageMenu.swift | 1 | 55876 | // CAPSPageMenu.swift
//
// Niklas Fahl
//
// Copyright (c) 2014 The Board of Trustees of The University of Alabama 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 the University nor the names of the 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
@objc public protocol CAPSPageMenuDelegate {
// MARK: - Delegate functions
@objc optional func willMoveToPage(_ controller: UIViewController, index: Int)
@objc optional func didMoveToPage(_ controller: UIViewController, index: Int)
}
private var DefaultMargin : CGFloat = 42.0
class MenuItemView: UIView {
// MARK: - Menu item view
var titleLabel : UILabel?
var btn : UIButton?
var menuItemSeparator : UIView?
func setUpMenuItemView(_ menuItemWidth: CGFloat, menuScrollViewHeight: CGFloat, indicatorHeight: CGFloat, separatorPercentageHeight: CGFloat, separatorWidth: CGFloat, separatorRoundEdges: Bool, menuItemSeparatorColor: UIColor) {
titleLabel = UILabel(frame: CGRect(x: 0.0, y: menuScrollViewHeight - indicatorHeight - 20, width: menuItemWidth, height: 20))
/**
* 版本适配
*/
if iPhone6plus {
DefaultMargin = 56.0
}else if iPhone6{
DefaultMargin = 48.0
}
btn = UIButton(frame: CGRect(x: 0,y: 0,width: 28,height: 28))
btn?.center = CGPoint(x: menuItemWidth/2.0, y: (menuScrollViewHeight-20)/2.0)
btn?.isUserInteractionEnabled = false
menuItemSeparator = UIView(frame: CGRect(x: menuItemWidth - (separatorWidth / 2), y: floor(menuScrollViewHeight * ((1.0 - separatorPercentageHeight) / 2.0)), width: separatorWidth, height: floor(menuScrollViewHeight * separatorPercentageHeight)))
menuItemSeparator!.backgroundColor = menuItemSeparatorColor
if separatorRoundEdges {
menuItemSeparator!.layer.cornerRadius = menuItemSeparator!.frame.width / 2
}
menuItemSeparator!.isHidden = true
self.addSubview(menuItemSeparator!)
self.addSubview(titleLabel!)
self.addSubview(btn!)
}
func setTitleText(_ text: NSString) {
if titleLabel != nil {
titleLabel!.text = text as String
titleLabel!.numberOfLines = 0
titleLabel!.sizeToFit()
}
}
func clickEvent() {
}
}
public enum CAPSPageMenuOption {
case selectionIndicatorHeight(CGFloat)
case menuItemSeparatorWidth(CGFloat)
case menuMargin(CGFloat)
case menuItemMargin(CGFloat)
case menuHeight(CGFloat)
case menuItemSeparatorPercentageHeight(CGFloat)
case menuItemWidth(CGFloat)
case scrollAnimationDurationOnMenuItemTap(Int)
case scrollMenuBackgroundColor(UIColor)
case viewBackgroundColor(UIColor)
case bottomMenuHairlineColor(UIColor)
case selectionIndicatorColor(UIColor)
case menuItemSeparatorColor(UIColor)
case selectedMenuItemLabelColor(UIColor)
case unselectedMenuItemLabelColor(UIColor)
case menuItemFont(UIFont)
case useMenuLikeSegmentedControl(Bool)
case menuItemSeparatorRoundEdges(Bool)
case enableHorizontalBounce(Bool)
case addBottomMenuHairline(Bool)
case menuItemWidthBasedOnTitleTextWidth(Bool)
case titleTextSizeBasedOnMenuItemWidth(Bool)
case centerMenuItems(Bool)
case hideTopMenuBar(Bool)
}
open class CAPSPageMenu: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
// MARK: - Properties
let menuScrollView = UIScrollView()
let controllerScrollView = UIScrollView()
var controllerArray : [UIViewController] = []
var menuItems : [MenuItemView] = []
var menuItemWidths : [CGFloat] = []
var menuItemImages : [String] = []
open var menuHeight : CGFloat = 34.0
open var menuMargin : CGFloat = 0.0
open var menuItemWidth : CGFloat = 111.0
open var selectionIndicatorHeight : CGFloat = 3.0
var totalMenuItemWidthIfDifferentWidths : CGFloat = 0.0
open var scrollAnimationDurationOnMenuItemTap : Int = 500 // Millisecons
var startingMenuMargin : CGFloat = 0.0
var menuItemMargin : CGFloat = 0.0
var selectionIndicatorView : UIView = UIView()
var currentPageIndex : Int = 0
var lastPageIndex : Int = 0
open var selectionIndicatorColor : UIColor = UIColor.white
open var selectedMenuItemLabelColor : UIColor = UIColor.white
open var unselectedMenuItemLabelColor : UIColor = UIColor.lightGray
open var scrollMenuBackgroundColor : UIColor = UIColor.black
open var viewBackgroundColor : UIColor = UIColor.white
open var bottomMenuHairlineColor : UIColor = UIColor.white
open var menuItemSeparatorColor : UIColor = UIColor.lightGray
open var menuItemFont : UIFont = UIFont.systemFont(ofSize: 15.0)
open var menuItemSeparatorPercentageHeight : CGFloat = 0.2
open var menuItemSeparatorWidth : CGFloat = 0.5
open var menuItemSeparatorRoundEdges : Bool = false
open var addBottomMenuHairline : Bool = true
open var menuItemWidthBasedOnTitleTextWidth : Bool = false
open var titleTextSizeBasedOnMenuItemWidth : Bool = false
open var useMenuLikeSegmentedControl : Bool = false
open var centerMenuItems : Bool = false
open var enableHorizontalBounce : Bool = false
open var hideTopMenuBar : Bool = false
open var enableScroll :Bool = true
var currentOrientationIsPortrait : Bool = true
var pageIndexForOrientationChange : Int = 0
var didLayoutSubviewsAfterRotation : Bool = false
var didScrollAlready : Bool = false
var lastControllerScrollViewContentOffset : CGFloat = 0.0
var lastScrollDirection : CAPSPageMenuScrollDirection = .other
var startingPageForScroll : Int = 0
var didTapMenuItemToScroll : Bool = false
var pagesAddedDictionary : [Int : Int] = [:]
open weak var delegate : CAPSPageMenuDelegate?
var tapTimer : Timer?
enum CAPSPageMenuScrollDirection : Int {
case left
case right
case other
}
// MARK: - View life cycle
/**
Initialize PageMenu with view controllers
:param: viewControllers List of view controllers that must be subclasses of UIViewController
:param: frame Frame for page menu view
:param: options Dictionary holding any customization options user might want to set
*/
public init(viewControllers: [UIViewController], frame: CGRect, options: [String: AnyObject]?,Images:[String]) {
super.init(nibName: nil, bundle: nil)
controllerArray = viewControllers
menuItemImages = Images
self.view.frame = frame
}
public convenience init(viewControllers: [UIViewController], frame: CGRect, pageMenuOptions: [CAPSPageMenuOption]?,menuItemImages:[String]) {
self.init(viewControllers:viewControllers, frame:frame, options:nil,Images: menuItemImages)
if let options = pageMenuOptions {
for option in options {
switch (option) {
case let .selectionIndicatorHeight(value):
selectionIndicatorHeight = value
case let .menuItemSeparatorWidth(value):
menuItemSeparatorWidth = value
case let .scrollMenuBackgroundColor(value):
scrollMenuBackgroundColor = value
case let .viewBackgroundColor(value):
viewBackgroundColor = value
case let .bottomMenuHairlineColor(value):
bottomMenuHairlineColor = value
case let .selectionIndicatorColor(value):
selectionIndicatorColor = value
case let .menuItemSeparatorColor(value):
menuItemSeparatorColor = value
case let .menuMargin(value):
menuMargin = value
case let .menuItemMargin(value):
menuItemMargin = value
case let .menuHeight(value):
menuHeight = value
case let .selectedMenuItemLabelColor(value):
selectedMenuItemLabelColor = value
case let .unselectedMenuItemLabelColor(value):
unselectedMenuItemLabelColor = value
case let .useMenuLikeSegmentedControl(value):
useMenuLikeSegmentedControl = value
case let .menuItemSeparatorRoundEdges(value):
menuItemSeparatorRoundEdges = value
case let .menuItemFont(value):
menuItemFont = value
case let .menuItemSeparatorPercentageHeight(value):
menuItemSeparatorPercentageHeight = value
case let .menuItemWidth(value):
menuItemWidth = value
case let .enableHorizontalBounce(value):
enableHorizontalBounce = value
case let .addBottomMenuHairline(value):
addBottomMenuHairline = value
case let .menuItemWidthBasedOnTitleTextWidth(value):
menuItemWidthBasedOnTitleTextWidth = value
case let .titleTextSizeBasedOnMenuItemWidth(value):
titleTextSizeBasedOnMenuItemWidth = value
case let .scrollAnimationDurationOnMenuItemTap(value):
scrollAnimationDurationOnMenuItemTap = value
case let .centerMenuItems(value):
centerMenuItems = value
case let .hideTopMenuBar(value):
hideTopMenuBar = value
}
}
if hideTopMenuBar {
addBottomMenuHairline = false
menuHeight = 0.0
}
}
setUpUserInterface()
if menuScrollView.subviews.count == 0 {
configureUserInterface()
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Container View Controller
open override var shouldAutomaticallyForwardAppearanceMethods : Bool {
return true
}
open override func shouldAutomaticallyForwardRotationMethods() -> Bool {
return true
}
// MARK: - UI Setup
func setUpUserInterface() {
let viewsDictionary = ["menuScrollView":menuScrollView, "controllerScrollView":controllerScrollView]
// Set up controller scroll view
controllerScrollView.isPagingEnabled = true
controllerScrollView.translatesAutoresizingMaskIntoConstraints = false
controllerScrollView.alwaysBounceHorizontal = enableHorizontalBounce
controllerScrollView.bounces = enableHorizontalBounce
controllerScrollView.isScrollEnabled = false
controllerScrollView.frame = CGRect(x: 0.0, y: menuHeight, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(controllerScrollView)
let controllerScrollView_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let controllerScrollView_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:|[controllerScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(controllerScrollView_constraint_H)
self.view.addConstraints(controllerScrollView_constraint_V)
// Set up menu scroll view
menuScrollView.translatesAutoresizingMaskIntoConstraints = false
menuScrollView.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: menuHeight)
self.view.addSubview(menuScrollView)
let menuScrollView_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[menuScrollView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let menuScrollView_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:[menuScrollView(\(menuHeight))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(menuScrollView_constraint_H)
self.view.addConstraints(menuScrollView_constraint_V)
// Add hairline to menu scroll view
if addBottomMenuHairline {
let menuBottomHairline : UIView = UIView()
menuBottomHairline.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(menuBottomHairline)
let menuBottomHairline_constraint_H:Array = NSLayoutConstraint.constraints(withVisualFormat: "H:|[menuBottomHairline]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
let menuBottomHairline_constraint_V:Array = NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(menuHeight)-[menuBottomHairline(0.5)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["menuBottomHairline":menuBottomHairline])
self.view.addConstraints(menuBottomHairline_constraint_H)
self.view.addConstraints(menuBottomHairline_constraint_V)
menuBottomHairline.backgroundColor = bottomMenuHairlineColor
}
// Disable scroll bars
menuScrollView.showsHorizontalScrollIndicator = false
menuScrollView.showsVerticalScrollIndicator = false
controllerScrollView.showsHorizontalScrollIndicator = false
controllerScrollView.showsVerticalScrollIndicator = false
// Set background color behind scroll views and for menu scroll view
self.view.backgroundColor = viewBackgroundColor
menuScrollView.backgroundColor = scrollMenuBackgroundColor
}
func configureUserInterface() {
// Add tap gesture recognizer to controller scroll view to recognize menu item selection
let menuItemTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(CAPSPageMenu.handleMenuItemTap(_:)))
menuItemTapGestureRecognizer.numberOfTapsRequired = 1
menuItemTapGestureRecognizer.numberOfTouchesRequired = 1
menuItemTapGestureRecognizer.delegate = self
menuScrollView.addGestureRecognizer(menuItemTapGestureRecognizer)
// Set delegate for controller scroll view
controllerScrollView.delegate = self
// When the user taps the status bar, the scroll view beneath the touch which is closest to the status bar will be scrolled to top,
// but only if its `scrollsToTop` property is YES, its delegate does not return NO from `shouldScrollViewScrollToTop`, and it is not already at the top.
// If more than one scroll view is found, none will be scrolled.
// Disable scrollsToTop for menu and controller scroll views so that iOS finds scroll views within our pages on status bar tap gesture.
menuScrollView.scrollsToTop = false;
controllerScrollView.scrollsToTop = false;
// Configure menu scroll view
if useMenuLikeSegmentedControl {
menuScrollView.isScrollEnabled = false
menuScrollView.contentSize = CGSize(width: kScreenWidth, height: menuHeight)
menuMargin = 0.0
} else {
menuScrollView.contentSize = CGSize(width: (menuItemWidth + menuMargin) * CGFloat(controllerArray.count) + menuMargin, height: menuHeight)
}
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSize(width: self.view.frame.width * CGFloat(controllerArray.count), height: 0.0)
var index : CGFloat = 0.0
for controller in controllerArray {
if index == 0.0 {
// Add first two controllers to scrollview and as child view controller
addPageAtIndex(0)
}
// Set up menu item for menu scroll view
var menuItemFrame : CGRect = CGRect()
if useMenuLikeSegmentedControl {
//**************************拡張*************************************
if menuItemMargin > 0 {
let marginSum = menuItemMargin * CGFloat(controllerArray.count + 1)
let menuItemWidth = (self.view.frame.width - marginSum) / CGFloat(controllerArray.count)
menuItemFrame = CGRect(x: CGFloat(menuItemMargin * (index + 1)) + menuItemWidth * CGFloat(index), y: 0.0, width: CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), height: menuHeight)
} else {
menuItemFrame = CGRect(x: self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), y: 0.0, width: CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), height: menuHeight)
}
//**************************拡張ここまで*************************************
} else if menuItemWidthBasedOnTitleTextWidth {
let controllerTitle : String? = controller.title
let titleText : String = controllerTitle != nil ? controllerTitle! : "Menu \(Int(index) + 1)"
let itemWidthRect : CGRect = (titleText as NSString).boundingRect(with: CGSize(width: 1000, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
menuItemFrame = CGRect(x: totalMenuItemWidthIfDifferentWidths + menuMargin + (menuMargin * index), y: 0.0, width: menuItemWidth, height: menuHeight)
totalMenuItemWidthIfDifferentWidths += itemWidthRect.width
menuItemWidths.append(itemWidthRect.width)
} else {
if centerMenuItems && index == 0.0 {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
menuItemFrame = CGRect(x: startingMenuMargin + menuMargin, y: 0.0, width: menuItemWidth, height: menuHeight)
} else {
menuItemFrame = CGRect(x: menuItemWidth * index + menuMargin * (index + 1) + startingMenuMargin, y: 0.0, width: menuItemWidth, height: menuHeight)
}
}
let menuItemView : MenuItemView = MenuItemView(frame: menuItemFrame)
if useMenuLikeSegmentedControl {
//**************************拡張*************************************
if menuItemMargin > 0 {
let marginSum = menuItemMargin * CGFloat(controllerArray.count + 1)
let menuItemWidth = (self.view.frame.width - marginSum) / CGFloat(controllerArray.count)
menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
} else {
menuItemView.setUpMenuItemView(CGFloat(self.view.frame.width) / CGFloat(controllerArray.count), menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
}
//**************************拡張ここまで*************************************
} else {
menuItemView.setUpMenuItemView(menuItemWidth, menuScrollViewHeight: menuHeight, indicatorHeight: selectionIndicatorHeight, separatorPercentageHeight: menuItemSeparatorPercentageHeight, separatorWidth: menuItemSeparatorWidth, separatorRoundEdges: menuItemSeparatorRoundEdges, menuItemSeparatorColor: menuItemSeparatorColor)
}
// Configure menu item label font if font is set by user
menuItemView.titleLabel!.font = menuItemFont
menuItemView.titleLabel!.textAlignment = NSTextAlignment.center
menuItemView.titleLabel!.textColor = unselectedMenuItemLabelColor
//**************************拡張*************************************
menuItemView.titleLabel!.adjustsFontSizeToFitWidth = titleTextSizeBasedOnMenuItemWidth
//**************************拡張ここまで*************************************
// Set title depending on if controller has a title set
if controller.title != nil {
menuItemView.titleLabel!.text = controller.title!
if menuItemImages.count > 0{
menuItemView.btn?.setImage(UIImage(named: menuItemImages[Int(index)]), for: UIControlState())
}
} else {
menuItemView.titleLabel!.text = "Menu \(Int(index) + 1)"
}
// Add separator between menu items when using as segmented control
if useMenuLikeSegmentedControl {
if Int(index) < controllerArray.count - 1 {
menuItemView.menuItemSeparator!.isHidden = false
}
}
// Add menu item view to menu scroll view
menuScrollView.addSubview(menuItemView)
menuItems.append(menuItemView)
index += 1
}
// Set new content size for menu scroll view if needed
if menuItemWidthBasedOnTitleTextWidth {
menuScrollView.contentSize = CGSize(width: (totalMenuItemWidthIfDifferentWidths + menuMargin) + CGFloat(controllerArray.count) * menuMargin, height: menuHeight)
}
// Set selected color for title label of selected menu item
if menuItems.count > 0 {
if menuItems[currentPageIndex].titleLabel != nil {
menuItems[currentPageIndex].titleLabel!.textColor = selectedMenuItemLabelColor
/**
默认选中时的图片
*/
if menuItemImages.count > 0 {
menuItems[currentPageIndex].btn?.setImage(UIImage(named: menuItemImages[currentPageIndex]+"_selected"), for: UIControlState())
}
}
}
// Configure selection indicator view
var selectionIndicatorFrame : CGRect = CGRect()
if useMenuLikeSegmentedControl {
selectionIndicatorFrame = CGRect(x: 0.0, y: menuHeight - selectionIndicatorHeight, width: self.view.frame.width / CGFloat(controllerArray.count), height: selectionIndicatorHeight)
} else if menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorFrame = CGRect(x: menuMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[0], height: selectionIndicatorHeight)
} else {
if centerMenuItems {
selectionIndicatorFrame = CGRect(x: startingMenuMargin + menuMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidth, height: selectionIndicatorHeight)
} else {
selectionIndicatorFrame = CGRect(x: menuMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidth, height: selectionIndicatorHeight)
}
}
selectionIndicatorView = UIView(frame: selectionIndicatorFrame)
selectionIndicatorView.backgroundColor = selectionIndicatorColor
menuScrollView.addSubview(selectionIndicatorView)
if menuItemWidthBasedOnTitleTextWidth && centerMenuItems {
self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
selectionIndicatorView.frame = CGRect(x: leadingAndTrailingMargin, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[0], height: selectionIndicatorHeight)
}
}
// Adjusts the menu item frames to size item width based on title text width and center all menu items in the center
// if the menuItems all fit in the width of the view. Otherwise, it will adjust the frames so that the menu items
// appear as if only menuItemWidthBasedOnTitleTextWidth is true.
fileprivate func configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() {
// only center items if the combined width is less than the width of the entire view's bounds
if menuScrollView.contentSize.width < self.view.bounds.width {
// compute the margin required to center the menu items
let leadingAndTrailingMargin = self.getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
// adjust the margin of each menu item to make them centered
for (index, menuItem) in menuItems.enumerated() {
let controllerTitle = controllerArray[index].title!
let itemWidthRect = controllerTitle.boundingRect(with: CGSize(width: 1000, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font:menuItemFont], context: nil)
menuItemWidth = itemWidthRect.width
var margin: CGFloat
if index == 0 {
// the first menu item should use the calculated margin
margin = leadingAndTrailingMargin
} else {
// the other menu items should use the menuMargin
let previousMenuItem = menuItems[index-1]
let previousX = previousMenuItem.frame.maxX
margin = previousX + menuMargin
}
menuItem.frame = CGRect(x: margin, y: 0.0, width: menuItemWidth, height: menuHeight)
}
} else {
// the menuScrollView.contentSize.width exceeds the view's width, so layout the menu items normally (menuItemWidthBasedOnTitleTextWidth)
for (index, menuItem) in menuItems.enumerated() {
var menuItemX: CGFloat
if index == 0 {
menuItemX = menuMargin
} else {
menuItemX = menuItems[index-1].frame.maxX + menuMargin
}
menuItem.frame = CGRect(x: menuItemX, y: 0.0, width: menuItem.bounds.width, height: menuItem.bounds.height)
}
}
}
// Returns the size of the left and right margins that are neccessary to layout the menuItems in the center.
fileprivate func getMarginForMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems() -> CGFloat {
let menuItemsTotalWidth = menuScrollView.contentSize.width - menuMargin * 2
let leadingAndTrailingMargin = (self.view.bounds.width - menuItemsTotalWidth) / 2
return leadingAndTrailingMargin
}
// MARK: - Scroll view delegate
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !didLayoutSubviewsAfterRotation {
if scrollView.isEqual(controllerScrollView) {
if scrollView.contentOffset.x >= 0.0 && scrollView.contentOffset.x <= (CGFloat(controllerArray.count - 1) * self.view.frame.width) {
if (currentOrientationIsPortrait && UIApplication.shared.statusBarOrientation.isPortrait) || (!currentOrientationIsPortrait && UIApplication.shared.statusBarOrientation.isLandscape) {
// Check if scroll direction changed
if !didTapMenuItemToScroll {
if didScrollAlready {
var newScrollDirection : CAPSPageMenuScrollDirection = .other
if (CGFloat(startingPageForScroll) * scrollView.frame.width > scrollView.contentOffset.x) {
newScrollDirection = .right
} else if (CGFloat(startingPageForScroll) * scrollView.frame.width < scrollView.contentOffset.x) {
newScrollDirection = .left
}
if newScrollDirection != .other {
if lastScrollDirection != newScrollDirection {
let index : Int = newScrollDirection == .left ? currentPageIndex + 1 : currentPageIndex - 1
if index >= 0 && index < controllerArray.count {
// Check dictionary if page was already added
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
}
lastScrollDirection = newScrollDirection
}
if !didScrollAlready {
if (lastControllerScrollViewContentOffset > scrollView.contentOffset.x) {
if currentPageIndex != controllerArray.count - 1 {
// Add page to the left of current page
let index : Int = currentPageIndex - 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .right
}
} else if (lastControllerScrollViewContentOffset < scrollView.contentOffset.x) {
if currentPageIndex != 0 {
// Add page to the right of current page
let index : Int = currentPageIndex + 1
if pagesAddedDictionary[index] != index && index < controllerArray.count && index >= 0 {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
lastScrollDirection = .left
}
}
didScrollAlready = true
}
lastControllerScrollViewContentOffset = scrollView.contentOffset.x
}
var ratio : CGFloat = 1.0
// Calculate ratio between scroll views
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
// Calculate current page
let width : CGFloat = controllerScrollView.frame.size.width;
let page : Int = Int((controllerScrollView.contentOffset.x + (0.5 * width)) / width)
// Update page if changed
if page != currentPageIndex {
lastPageIndex = currentPageIndex
currentPageIndex = page
if pagesAddedDictionary[page] != page && page < controllerArray.count && page >= 0 {
addPageAtIndex(page)
pagesAddedDictionary[page] = page
}
if !didTapMenuItemToScroll {
// Add last page to pages dictionary to make sure it gets removed after scrolling
if pagesAddedDictionary[lastPageIndex] != lastPageIndex {
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Make sure only up to 3 page views are in memory when fast scrolling, otherwise there should only be one in memory
let indexLeftTwo : Int = page - 2
if pagesAddedDictionary[indexLeftTwo] == indexLeftTwo {
pagesAddedDictionary.removeValue(forKey: indexLeftTwo)
removePageAtIndex(indexLeftTwo)
}
let indexRightTwo : Int = page + 2
if pagesAddedDictionary[indexRightTwo] == indexRightTwo {
pagesAddedDictionary.removeValue(forKey: indexRightTwo)
removePageAtIndex(indexRightTwo)
}
}
}
// Move selection indicator view when swiping
moveSelectionIndicator(page)
}
} else {
var ratio : CGFloat = 1.0
ratio = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
}
} else {
didLayoutSubviewsAfterRotation = false
// Move selection indicator view when swiping
moveSelectionIndicator(currentPageIndex)
}
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.isEqual(controllerScrollView) {
// Call didMoveToPage delegate function
let currentController = controllerArray[currentPageIndex]
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
didScrollAlready = false
startingPageForScroll = currentPageIndex
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepingCapacity: false)
}
}
@objc func scrollViewDidEndTapScrollingAnimation() {
// Call didMoveToPage delegate function
let currentController = controllerArray[currentPageIndex]
delegate?.didMoveToPage?(currentController, index: currentPageIndex)
// Remove all but current page after decelerating
for key in pagesAddedDictionary.keys {
if key != currentPageIndex {
removePageAtIndex(key)
}
}
startingPageForScroll = currentPageIndex
didTapMenuItemToScroll = false
// Empty out pages in dictionary
pagesAddedDictionary.removeAll(keepingCapacity: false)
}
// MARK: - Handle Selection Indicator
func moveSelectionIndicator(_ pageIndex: Int) {
if pageIndex >= 0 && pageIndex < controllerArray.count {
UIView.animate(withDuration: 0.15, animations: { () -> Void in
var selectionIndicatorWidth : CGFloat = self.selectionIndicatorView.frame.width
var selectionIndicatorX : CGFloat = 0.0
if self.useMenuLikeSegmentedControl {
selectionIndicatorX = CGFloat(pageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
selectionIndicatorWidth = self.view.frame.width / CGFloat(self.controllerArray.count)
} else if self.menuItemWidthBasedOnTitleTextWidth {
selectionIndicatorWidth = self.menuItemWidths[pageIndex]
selectionIndicatorX = self.menuItems[pageIndex].frame.minX
} else {
if self.centerMenuItems && pageIndex == 0 {
selectionIndicatorX = self.startingMenuMargin + self.menuMargin
} else {
selectionIndicatorX = self.menuItemWidth * CGFloat(pageIndex) + self.menuMargin * CGFloat(pageIndex + 1) + self.startingMenuMargin
}
}
self.selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: selectionIndicatorWidth, height: self.selectionIndicatorView.frame.height)
// Switch newly selected menu item title label to selected color and old one to unselected color
if self.menuItems.count > 0 {
if self.menuItems[self.lastPageIndex].titleLabel != nil && self.menuItems[self.currentPageIndex].titleLabel != nil {
self.menuItems[self.lastPageIndex].titleLabel!.textColor = self.unselectedMenuItemLabelColor
self.menuItems[self.currentPageIndex].titleLabel!.textColor = self.selectedMenuItemLabelColor
/**
选中时的图片
*/
self.menuItems[self.currentPageIndex].btn?.setImage(UIImage(named: self.menuItemImages[self.currentPageIndex]+"_selected"), for: UIControlState())
self.menuItems[self.lastPageIndex].btn?.setImage(UIImage(named: self.menuItemImages[self.lastPageIndex]), for: UIControlState())
}
}
})
}
}
// MARK: - Tap gesture recognizer selector
@objc func handleMenuItemTap(_ gestureRecognizer : UITapGestureRecognizer) {
let tappedPoint : CGPoint = gestureRecognizer.location(in: menuScrollView)
if tappedPoint.y < menuScrollView.frame.height {
// Calculate tapped page
var itemIndex : Int = 0
if useMenuLikeSegmentedControl {
itemIndex = Int(tappedPoint.x / (self.view.frame.width / CGFloat(controllerArray.count)))
} else if menuItemWidthBasedOnTitleTextWidth {
var menuItemLeftBound: CGFloat
var menuItemRightBound: CGFloat
if centerMenuItems {
menuItemLeftBound = menuItems[0].frame.minX
menuItemRightBound = menuItems[menuItems.count-1].frame.maxX
if (tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) {
for (index, _) in controllerArray.enumerated() {
menuItemLeftBound = menuItems[index].frame.minX
menuItemRightBound = menuItems[index].frame.maxX
if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound {
itemIndex = index
break
}
}
}
} else {
// Base case being first item
menuItemLeftBound = 0.0
menuItemRightBound = menuItemWidths[0] + menuMargin + (menuMargin / 2)
if !(tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound) {
for i in 1...controllerArray.count - 1 {
menuItemLeftBound = menuItemRightBound + 1.0
menuItemRightBound = menuItemLeftBound + menuItemWidths[i] + menuMargin
if tappedPoint.x >= menuItemLeftBound && tappedPoint.x <= menuItemRightBound {
itemIndex = i
break
}
}
}
}
} else {
let rawItemIndex : CGFloat = ((tappedPoint.x - startingMenuMargin) - menuMargin / 2) / (menuMargin + menuItemWidth)
// Prevent moving to first item when tapping left to first item
if rawItemIndex < 0 {
itemIndex = -1
} else {
itemIndex = Int(rawItemIndex)
}
}
if itemIndex >= 0 && itemIndex < controllerArray.count {
// Update page if changed
if itemIndex != currentPageIndex {
startingPageForScroll = itemIndex
lastPageIndex = currentPageIndex
currentPageIndex = itemIndex
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for index in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[index] != index {
addPageAtIndex(index)
pagesAddedDictionary[index] = index
}
}
}
addPageAtIndex(itemIndex)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animate(withDuration: duration, animations: { () -> Void in
let xOffset : CGFloat = CGFloat(itemIndex) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
if tapTimer != nil {
tapTimer!.invalidate()
}
let timerInterval : TimeInterval = Double(scrollAnimationDurationOnMenuItemTap) * 0.001
tapTimer = Timer.scheduledTimer(timeInterval: timerInterval, target: self, selector: #selector(CAPSPageMenu.scrollViewDidEndTapScrollingAnimation), userInfo: nil, repeats: false)
}
}
}
// MARK: - Remove/Add Page
func addPageAtIndex(_ index : Int) {
// Call didMoveToPage delegate function
let currentController = controllerArray[index]
delegate?.willMoveToPage?(currentController, index: index)
let newVC = controllerArray[index]
newVC.willMove(toParentViewController: self)
newVC.view.frame = CGRect(x: self.view.frame.width * CGFloat(index), y: menuHeight, width: self.view.frame.width, height: self.view.frame.height - menuHeight)
self.addChildViewController(newVC)
self.controllerScrollView.addSubview(newVC.view)
newVC.didMove(toParentViewController: self)
}
func removePageAtIndex(_ index : Int) {
let oldVC = controllerArray[index]
oldVC.willMove(toParentViewController: nil)
oldVC.view.removeFromSuperview()
oldVC.removeFromParentViewController()
}
// MARK: - Orientation Change
override open func viewDidLayoutSubviews() {
// Configure controller scroll view content size
controllerScrollView.contentSize = CGSize(width: self.view.frame.width * CGFloat(controllerArray.count), height: self.view.frame.height - menuHeight)
let oldCurrentOrientationIsPortrait : Bool = currentOrientationIsPortrait
currentOrientationIsPortrait = UIApplication.shared.statusBarOrientation.isPortrait
if (oldCurrentOrientationIsPortrait && UIDevice.current.orientation.isLandscape) || (!oldCurrentOrientationIsPortrait && UIDevice.current.orientation.isPortrait) {
didLayoutSubviewsAfterRotation = true
//Resize menu items if using as segmented control
if useMenuLikeSegmentedControl {
menuScrollView.contentSize = CGSize(width: self.view.frame.width, height: menuHeight)
// Resize selectionIndicator bar
let selectionIndicatorX : CGFloat = CGFloat(currentPageIndex) * (self.view.frame.width / CGFloat(self.controllerArray.count))
let selectionIndicatorWidth : CGFloat = self.view.frame.width / CGFloat(self.controllerArray.count)
selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: selectionIndicatorWidth, height: self.selectionIndicatorView.frame.height)
// Resize menu items
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
item.frame = CGRect(x: self.view.frame.width / CGFloat(controllerArray.count) * CGFloat(index), y: 0.0, width: self.view.frame.width / CGFloat(controllerArray.count), height: menuHeight)
item.titleLabel!.frame = CGRect(x: 0.0, y: 28, width: kScreenWidth / CGFloat(controllerArray.count), height: 22)
item.menuItemSeparator!.frame = CGRect(x: item.frame.width - (menuItemSeparatorWidth / 2), y: item.menuItemSeparator!.frame.origin.y, width: item.menuItemSeparator!.frame.width, height: item.menuItemSeparator!.frame.height)
index += 1
}
} else if menuItemWidthBasedOnTitleTextWidth && centerMenuItems {
self.configureMenuItemWidthBasedOnTitleTextWidthAndCenterMenuItems()
let selectionIndicatorX = menuItems[currentPageIndex].frame.minX
selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: menuHeight - selectionIndicatorHeight, width: menuItemWidths[currentPageIndex], height: selectionIndicatorHeight)
} else if centerMenuItems {
startingMenuMargin = ((self.view.frame.width - ((CGFloat(controllerArray.count) * menuItemWidth) + (CGFloat(controllerArray.count - 1) * menuMargin))) / 2.0) - menuMargin
if startingMenuMargin < 0.0 {
startingMenuMargin = 0.0
}
let selectionIndicatorX : CGFloat = self.menuItemWidth * CGFloat(currentPageIndex) + self.menuMargin * CGFloat(currentPageIndex + 1) + self.startingMenuMargin
selectionIndicatorView.frame = CGRect(x: selectionIndicatorX, y: self.selectionIndicatorView.frame.origin.y, width: self.selectionIndicatorView.frame.width, height: self.selectionIndicatorView.frame.height)
// Recalculate frame for menu items if centered
var index : Int = 0
for item : MenuItemView in menuItems as [MenuItemView] {
if index == 0 {
item.frame = CGRect(x: startingMenuMargin + menuMargin, y: 0.0, width: menuItemWidth, height: menuHeight)
} else {
item.frame = CGRect(x: menuItemWidth * CGFloat(index) + menuMargin * CGFloat(index + 1) + startingMenuMargin, y: 0.0, width: menuItemWidth, height: menuHeight)
}
index += 1
}
}
for view : UIView in controllerScrollView.subviews {
view.frame = CGRect(x: self.view.frame.width * CGFloat(currentPageIndex), y: menuHeight, width: controllerScrollView.frame.width, height: self.view.frame.height - menuHeight)
}
let xOffset : CGFloat = CGFloat(self.currentPageIndex) * controllerScrollView.frame.width
controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: controllerScrollView.contentOffset.y), animated: false)
let ratio : CGFloat = (menuScrollView.contentSize.width - self.view.frame.width) / (controllerScrollView.contentSize.width - self.view.frame.width)
if menuScrollView.contentSize.width > self.view.frame.width {
var offset : CGPoint = menuScrollView.contentOffset
offset.x = controllerScrollView.contentOffset.x * ratio
menuScrollView.setContentOffset(offset, animated: false)
}
}
// Hsoi 2015-02-05 - Running on iOS 7.1 complained: "'NSInternalInconsistencyException', reason: 'Auto Layout
// still required after sending -viewDidLayoutSubviews to the view controller. ViewController's implementation
// needs to send -layoutSubviews to the view to invoke auto layout.'"
//
// http://stackoverflow.com/questions/15490140/auto-layout-error
//
// Given the SO answer and caveats presented there, we'll call layoutIfNeeded() instead.
self.view.layoutIfNeeded()
}
// MARK: - Move to page index
/**
Move to page at index
:param: index Index of the page to move to
*/
open func moveToPage(_ index: Int) {
if index >= 0 && index < controllerArray.count {
// Update page if changed
if index != currentPageIndex {
startingPageForScroll = index
lastPageIndex = currentPageIndex
currentPageIndex = index
didTapMenuItemToScroll = true
// Add pages in between current and tapped page if necessary
let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex
if smallerIndex + 1 != largerIndex {
for i in (smallerIndex + 1)...(largerIndex - 1) {
if pagesAddedDictionary[i] != i {
addPageAtIndex(i)
pagesAddedDictionary[i] = i
}
}
}
addPageAtIndex(index)
// Add page from which tap is initiated so it can be removed after tap is done
pagesAddedDictionary[lastPageIndex] = lastPageIndex
}
// Move controller scroll view when tapping menu item
let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)
UIView.animate(withDuration: duration, animations: { () -> Void in
let xOffset : CGFloat = CGFloat(index) * self.controllerScrollView.frame.width
self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
})
}
}
}
| mit | bb07db5d4d6e11262635266a175e1162 | 51.883412 | 392 | 0.590067 | 6.533021 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/DeliveryGoods/Controller/DeliveryGoodsViewController.swift | 1 | 8035 | //
// DeliveryGoodsViewController.swift
// OMS-WH
//
// Created by ___Gwy on 2017/8/21.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class DeliveryGoodsViewController: UIViewController,StatusController {
var viewModel = DeliveryGoodsViewModel()
fileprivate var filterArray = [OrderListModel]()
fileprivate var chooseData = [
["dictValueName":"分秒医配","dictValueCode":"FMYP"],
["dictValueName":"直送发货","dictValueCode":"ZSFH"],
["dictValueName":"快递发货","dictValueCode":"KDFH"],
["dictValueName":"大巴发货","dictValueCode":"DBFH"],
["dictValueName":"航空发货","dictValueCode":"HKFH"],
["dictValueName":"自提发货","dictValueCode":"ZTFH"]
]
// 当前页码
fileprivate var currentPage : Int = 1
// 是否加载更多
fileprivate var toLoadMore :Bool = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
title = "发货"
view.addSubview(table)
// requstData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
requstData()
}
//列表
fileprivate lazy var table:UITableView = {
let table = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: self.view.height-64), style: .plain)
table.separatorStyle = .none
table.dataSource = self
table.delegate = self
table.register(OrderListTableViewCell.self)
return table
}()
/// 请求发货列表数据
fileprivate func requstData(){
XCHRefershUI.show()
moyaNetWork.request(.commonRequst(paramters: ["sOType":"","pageNum":"\(currentPage)","pageSize":"60"], api: "oms-api-v3/order/waitingDeliveryList")) { result in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
self.dealWithData(result: data)
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
// self.table.endHeaderRefreshing()
break
}
}
}
//发货按钮请求出库单列表
fileprivate func requstOutBoundList(model:OrderListModel){
viewModel.requstOutBoundList(model.sONo) { (data, error) in
if data.count > 0{
SVProgressHUD.showError("此订单有多个出库单,请选择出库单发货")
}else{
let chooseVC = PickViewController(frame: self.view.bounds, dataSource: self.chooseData as [[String : AnyObject]], title: "请选择发货方式", modeBehaviour: ChooseBehaviour.chooseDictValue)
chooseVC.GetCode = {(indexpath:Int) in
if data.count <= 0 {return}
if self.chooseData[indexpath]["dictValueCode"] == "FMYP"{
let sendVC = SendByFMYPViewController()
sendVC.orderModel = model
sendVC.outboundModel = data[0]
self.navigationController?.pushViewController(sendVC, animated: true)
}else{
let sendVC = SendByOtherViewController()
sendVC.outboundModel = data[0]
sendVC.orderModel = model
if self.chooseData[indexpath]["dictValueCode"] == "ZSFH"{
sendVC.modeBehaviour = .byZSFH
}else if self.chooseData[indexpath]["dictValueCode"] == "KDFH"{
sendVC.modeBehaviour = .byKDFH
}else if self.chooseData[indexpath]["dictValueCode"] == "DBFH"{
sendVC.modeBehaviour = .byDBFH
}else if self.chooseData[indexpath]["dictValueCode"] == "HKFH"{
sendVC.modeBehaviour = .byHKFH
}else if self.chooseData[indexpath]["dictValueCode"] == "ZTFH"{
sendVC.modeBehaviour = .byZTFH
}
self.navigationController?.pushViewController(sendVC, animated: true)
}
}
self.view.addSubview(chooseVC.view)
self.addChildViewController(chooseVC)
}
}
}
private func dealWithData(result:[String:AnyObject]){
self.table.endHeaderRefreshing()
guard result["code"] as! Int == 0 else
{
SVProgressHUD.showError(result["msg"]! as! String)
self.toLoadMore = false
return
}
let info = result["info"] as! [String:AnyObject]
if let list = info["list"] as? [[String:AnyObject]]{
if list.count > 0{
var child = [OrderListModel]()
for item in list{
child.append(OrderListModel.init(dict: item))
}
self.filterArray = child
}else{
SVProgressHUD.showError("暂无订单")
}
self.table.reloadData()
}
}
}
extension DeliveryGoodsViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OrderListTableViewCell") as! OrderListTableViewCell
let model = filterArray[indexPath.section]
cell.orderListModel = model
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return filterArray.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let orderModel = filterArray[indexPath.section]
if orderModel.sOType == SoTypeName.OPER{
let detailVC = OrderDetailViewController()
detailVC.sONo = orderModel.sONo
navigationController?.pushViewController(detailVC, animated: true)
}else if orderModel.sOType == SoTypeName.INSTK{
let detailVC = StockOrderDetailViewController()
detailVC.sONo = orderModel.sONo
navigationController?.pushViewController(detailVC, animated: true)
}
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let orderModel = filterArray[indexPath.section]
let sendBtn = UITableViewRowAction(style: .normal, title: "发货") { (action, index) in
self.requstOutBoundList(model: orderModel)
}
sendBtn.backgroundColor = kAppearanceColor
let sendOrderBtn = UITableViewRowAction(style: .normal, title: "出库单发货") { (action, index) in
let outBoundSendListVC = OutBoundSendListViewController()
outBoundSendListVC.orderListModel = orderModel
self.navigationController?.pushViewController(outBoundSendListVC, animated: true)
}
return [sendOrderBtn,sendBtn]
// if orderModel.sOType == SoTypeName.OPER{
// return[sendOrderBtn,sendBtn]
// }else if orderModel.sOType == SoTypeName.INSTK{
// return[sendBtn]
// }
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 126
}
}
| mit | 471576cbf704dc0e99959f3b1c38419c | 38.565657 | 195 | 0.584631 | 5.041184 | false | false | false | false |
ansinlee/meteorology | meteorology/ProfViewController.swift | 1 | 1487 | //
// ProfViewController.swift
// meteorology
//
// Created by LeeAnsin on 15/3/21.
// Copyright (c) 2015年 LeeAnsin. All rights reserved.
//
import UIKit
class ProfViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "个人信息"
// 设置导航字体为白色
self.navigationController?.navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(),
forKey:NSForegroundColorAttributeName) as [NSObject : AnyObject]
self.navigationController?.navigationBar.barStyle = UIBarStyle.Default
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = NavBarBackgroudColor
// 设置背景色
self.view.backgroundColor = MainBackgroudColor
}
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | dc5179334a036d96608bf4ec78501c11 | 30.5 | 113 | 0.688751 | 5.231047 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Network/ErrorHandlePlugin.swift | 1 | 1865 | //
// ErrorHandlePlungin.swift
// HiPDA
//
// Created by leizh007 on 2017/6/5.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import Moya
import Result
enum NetworkError:Int, Swift.Error {
case timeOut = -1001 // NSURLErrorTimedOut
case offline = -1009 // NSURLErrorNotConnectedToInternet
case forbidden = 403
}
extension NetworkError: CustomStringConvertible {
var description: String {
switch self {
case .timeOut:
return "请求超时"
case .offline:
return "网络不给力"
case .forbidden:
return "拒绝访问"
}
}
}
extension NetworkError: LocalizedError {
var errorDescription: String? {
return description
}
}
public final class ErrorHandlePlugin: PluginType {
public func process(_ result: Result<Moya.Response, MoyaError>, target: Moya.TargetType) -> Result<Moya.Response, MoyaError> {
if case let .failure(requestError) = result,
case let .underlying(underlyingError) = requestError,
let networkError = NetworkError(rawValue: (underlyingError as NSError).code) {
let error = underlyingError as NSError
let domain = error.domain
let code = error.code
var userInfo = error.userInfo
userInfo[NSLocalizedDescriptionKey] = networkError.description
return Result.failure(.underlying(NSError(domain: domain, code: code, userInfo: userInfo)))
} else if case let .success(response) = result, response.statusCode == NetworkError.forbidden.rawValue {
return Result.failure(.underlying(NSError(domain: "HiPDA", code: NetworkError.forbidden.rawValue, userInfo: [NSLocalizedDescriptionKey : NetworkError.forbidden.description])))
} else {
return result
}
}
}
| mit | bdf3d725d3eff126b058264451043dca | 32.381818 | 187 | 0.660131 | 4.831579 | false | false | false | false |
jianweihehe/JWDouYuZB | JWDouYuZB/JWDouYuZB/Classes/Main/Controller/BaseAnchorViewController.swift | 1 | 4906 | //
// BaseAnchorViewController.swift
// JWDouYuZB
//
// Created by [email protected] on 2017/1/13.
// Copyright © 2017年 简伟. All rights reserved.
//
import UIKit
fileprivate let itemMargin:CGFloat = 10
fileprivate let itemWidth = (JWScreenWidth - 3 * itemMargin) * 0.5
fileprivate let normalItemHeight = itemWidth * 3 / 4
fileprivate let prettyItemHeight = itemWidth * 4 / 3
fileprivate let headerViewHeight:CGFloat = 50
fileprivate let normalCellID = "normalCellID"
fileprivate let prettyCellID = "prettyCellID"
fileprivate let headerViewID = "headerViewID"
class BaseAnchorViewController: BaseViewController {
//定义属性
var baseVM: BaseViewModel!
lazy var collectionView: UICollectionView = {[weak self] in
//创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: itemWidth, height: normalItemHeight)
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = itemMargin
layout.headerReferenceSize = CGSize(width: (self?.view.bounds.size.width)!, height: headerViewHeight)
layout.sectionInset = UIEdgeInsets(top: 0, left: itemMargin, bottom: 0, right: itemMargin)
//创建UICollectionView
let collectionView = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self as UICollectionViewDataSource?
collectionView.delegate = self
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: normalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: prettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadDataSource()
}
}
// MARK: - 设置UI
extension BaseAnchorViewController{
override func setupUI() {
baseContentView = collectionView
view.addSubview(collectionView)
super.setupUI()
}
}
// MARK: - 数据请求
extension BaseAnchorViewController{
func loadDataSource() {
}
}
// MARK: - UICollectionViewDataSource
extension BaseAnchorViewController: UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.anchorGropus.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGropus[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: normalCellID, for: indexPath) as! CollectionNormalCell
let group = baseVM.anchorGropus[indexPath.section]
cell.anchor = group.anchors[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerViewID, for: indexPath) as! CollectionHeaderView
//取出模型
headerView.group = baseVM.anchorGropus[indexPath.section]
return headerView
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension BaseAnchorViewController: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
return CGSize(width: itemWidth, height: normalItemHeight)
}
}
// MARK: - UICollectionViewDelegate
extension BaseAnchorViewController: UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let anchor = baseVM.anchorGropus[indexPath.section].anchors[indexPath.item]
anchor.isVertical == 1 ? presentShowRoomVC() : pushNormalRoomVC()
}
private func presentShowRoomVC() {
let showRoomVC = RoomShowViewController()
self.present(showRoomVC, animated: true, completion: nil)
}
private func pushNormalRoomVC() {
let normalRoomVC = RoomNormalViewController()
self.navigationController?.pushViewController(normalRoomVC, animated: true)
}
}
| mit | e2f60140b965dc5e43739ce8f8c1eabf | 34.727941 | 185 | 0.71949 | 5.636891 | false | false | false | false |
rc2server/appserver | Sources/appcore/RepeatingTimer.swift | 2 | 1563 | // from https://medium.com/@danielgalasko/a-background-repeating-timer-in-swift-412cecfd2ef9
import Foundation
/// RepeatingTimer mimics the API of DispatchSourceTimer but in a way that prevents
/// crashes that occur from calling resume multiple times on a timer that is
/// already resumed (noted by https://github.com/SiftScience/sift-ios/issues/52
class RepeatingTimer {
let timeInterval: TimeInterval
init(timeInterval: TimeInterval) {
self.timeInterval = timeInterval
}
private lazy var timer: DispatchSourceTimer = {
let t = DispatchSource.makeTimerSource()
t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
t.setEventHandler(handler: { [weak self] in
self?.eventHandler?()
})
return t
}()
var eventHandler: (() -> Void)?
private enum State {
case suspended
case resumed
}
private var state: State = .suspended
deinit {
timer.setEventHandler {}
timer.cancel()
/*
If the timer is suspended, calling cancel without resuming
triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
*/
resume()
eventHandler = nil
}
func resume() {
if state == .resumed {
return
}
state = .resumed
timer.resume()
}
func suspend() {
if state == .suspended {
return
}
state = .suspended
timer.suspend()
}
}
| isc | 9a80173e6e85ff28ef7cb219b088404d | 25.05 | 98 | 0.607806 | 4.722054 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/BuySellKit/Core/CheckoutData.swift | 1 | 5666 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import FeatureCardPaymentDomain
import MoneyKit
public struct CandidateOrderDetails {
/// The quote ID
public let quoteId: String?
/// The payment method
public let paymentMethod: PaymentMethodType?
/// Fiat value
public let fiatValue: FiatValue
/// Crypto value
public let cryptoValue: CryptoValue
/// The Crypto Currency that is being traded
public let cryptoCurrency: CryptoCurrency
/// The Fiat Currency that is being traded
/// This may be different from the fiat currency used to input the desired amount.
public let fiatCurrency: FiatCurrency
/// Whether the order is a `Buy` or a `Sell`
public let action: Order.Action
public let paymentMethodId: String?
private init(
quoteId: String?,
paymentMethod: PaymentMethodType?,
action: Order.Action,
fiatValue: FiatValue,
fiatCurrency: FiatCurrency,
cryptoValue: CryptoValue,
cryptoCurrency: CryptoCurrency,
paymentMethodId: String?
) {
self.quoteId = quoteId
self.action = action
self.paymentMethod = paymentMethod
self.fiatValue = fiatValue
self.fiatCurrency = fiatCurrency
self.cryptoValue = cryptoValue
self.cryptoCurrency = cryptoCurrency
self.paymentMethodId = paymentMethodId
}
public static func buy(
quoteId: String? = nil,
paymentMethod: PaymentMethodType? = nil,
fiatValue: FiatValue,
cryptoValue: CryptoValue,
paymentMethodId: String? = nil
) -> CandidateOrderDetails {
CandidateOrderDetails(
quoteId: quoteId,
paymentMethod: paymentMethod,
action: .buy,
fiatValue: fiatValue,
fiatCurrency: fiatValue.currency,
cryptoValue: cryptoValue,
cryptoCurrency: cryptoValue.currency,
paymentMethodId: paymentMethodId
)
}
public static func sell(
quoteId: String? = nil,
paymentMethod: PaymentMethodType? = nil,
fiatValue: FiatValue,
destinationFiatCurrency: FiatCurrency,
cryptoValue: CryptoValue,
paymentMethodId: String? = nil
) -> CandidateOrderDetails {
CandidateOrderDetails(
quoteId: quoteId,
paymentMethod: paymentMethod,
action: .sell,
fiatValue: fiatValue,
fiatCurrency: destinationFiatCurrency,
cryptoValue: cryptoValue,
cryptoCurrency: cryptoValue.currency,
paymentMethodId: paymentMethodId
)
}
}
public struct CheckoutData {
public let order: OrderDetails
public let paymentAccount: PaymentAccountDescribing!
public let isPaymentMethodFinalized: Bool
public let linkedBankData: LinkedBankData?
// MARK: - Properties
public var hasCardCheckoutMade: Bool {
order.is3DSConfirmedCardOrder || order.isPending3DSCardOrder
}
public var isPendingDepositBankWire: Bool {
order.isPendingDepositBankWire
}
public var isPendingDeposit: Bool {
order.isPendingDeposit
}
public var isPending3DS: Bool {
order.isPending3DSCardOrder
}
public var outputCurrency: CurrencyType {
order.outputValue.currency
}
public var inputCurrency: CurrencyType {
order.inputValue.currency
}
public var fiatValue: FiatValue? {
if let fiat = order.inputValue.fiatValue {
return fiat
}
if let fiat = order.outputValue.fiatValue {
return fiat
}
return nil
}
public var cryptoValue: CryptoValue? {
if let crypto = order.inputValue.cryptoValue {
return crypto
}
if let crypto = order.outputValue.cryptoValue {
return crypto
}
return nil
}
/// `true` if the order is card but is undetermined
public var isUnknownCardType: Bool {
order.paymentMethod.isCard && order.paymentMethodId == nil
}
/// `true` if the order is bank transfer but is undetermined
public var isUnknownBankTransfer: Bool {
order.paymentMethod.isBankTransfer && order.paymentMethodId == nil
}
public var isPendingConfirmationFunds: Bool {
order.isPendingConfirmation && order.paymentMethod.isFunds
}
public init(
order: OrderDetails,
paymentAccount: PaymentAccountDescribing? = nil,
linkedBankData: LinkedBankData? = nil
) {
self.order = order
self.paymentAccount = paymentAccount
self.linkedBankData = linkedBankData
isPaymentMethodFinalized = (paymentAccount != nil || order.paymentMethodId != nil)
}
public func checkoutData(byAppending cardData: CardData) -> CheckoutData {
var order = order
order.paymentMethodId = cardData.identifier
return CheckoutData(order: order)
}
public func checkoutData(byAppending bankAccount: LinkedBankData) -> CheckoutData {
var order = order
order.paymentMethodId = bankAccount.identifier
return CheckoutData(order: order, linkedBankData: bankAccount)
}
func checkoutData(byAppending paymentAccount: PaymentAccountDescribing) -> CheckoutData {
CheckoutData(
order: order,
paymentAccount: paymentAccount
)
}
func checkoutData(byAppending orderDetails: OrderDetails) -> CheckoutData {
CheckoutData(
order: orderDetails,
paymentAccount: paymentAccount
)
}
}
| lgpl-3.0 | 983d7095d17428e5ce343972138ffd21 | 28.051282 | 93 | 0.648897 | 5.206801 | false | false | false | false |
brentsimmons/Evergreen | Account/Sources/Account/Feedly/Operations/FeedlyAddFeedToCollectionOperation.swift | 1 | 1960 | //
// FeedlyAddFeedToCollectionOperation.swift
// Account
//
// Created by Kiel Gillard on 11/10/19.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import Foundation
protocol FeedlyAddFeedToCollectionService {
func addFeed(with feedId: FeedlyFeedResourceId, title: String?, toCollectionWith collectionId: String, completion: @escaping (Result<[FeedlyFeed], Error>) -> ())
}
final class FeedlyAddFeedToCollectionOperation: FeedlyOperation, FeedlyFeedsAndFoldersProviding, FeedlyResourceProviding {
let feedName: String?
let collectionId: String
let service: FeedlyAddFeedToCollectionService
let account: Account
let folder: Folder
let feedResource: FeedlyFeedResourceId
init(account: Account, folder: Folder, feedResource: FeedlyFeedResourceId, feedName: String? = nil, collectionId: String, service: FeedlyAddFeedToCollectionService) {
self.account = account
self.folder = folder
self.feedResource = feedResource
self.feedName = feedName
self.collectionId = collectionId
self.service = service
}
private(set) var feedsAndFolders = [([FeedlyFeed], Folder)]()
var resource: FeedlyResourceId {
return feedResource
}
override func run() {
service.addFeed(with: feedResource, title: feedName, toCollectionWith: collectionId) { [weak self] result in
guard let self = self else {
return
}
if self.isCanceled {
self.didFinish()
return
}
self.didCompleteRequest(result)
}
}
}
private extension FeedlyAddFeedToCollectionOperation {
func didCompleteRequest(_ result: Result<[FeedlyFeed], Error>) {
switch result {
case .success(let feedlyFeeds):
feedsAndFolders = [(feedlyFeeds, folder)]
let feedsWithCreatedFeedId = feedlyFeeds.filter { $0.id == resource.id }
if feedsWithCreatedFeedId.isEmpty {
didFinish(with: AccountError.createErrorNotFound)
} else {
didFinish()
}
case .failure(let error):
didFinish(with: error)
}
}
}
| mit | fdf964f2f52fc86f1ac877efe2e7f613 | 26.208333 | 167 | 0.742726 | 3.696226 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Home/Model/GYZShopGoodsModel.swift | 1 | 5515 | //
// GYZShopGoodsModel.swift
// baking
// 商家详情model
// Created by gouyz on 2017/4/9.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
class GYZShopGoodsModel: NSObject {
var goods : [GoodsModel]?
var member_info : ShopInfoModel?
var activity: [ActivityModel]?
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "goods" {
goods = Array()
guard let datas = value as? [[String : Any]] else { return }
for dict in datas {
let foodModel = GoodsModel(dict: dict)
goods?.append(foodModel)
}
}else if key == "member_info" {
guard let datas = value as? [String : Any] else { return }
member_info = ShopInfoModel(dict: datas)
}else if key == "activity"{
activity = [ActivityModel]()
guard let datas = value as? [[String : Any]] else { return }
for dict in datas {
let model = ActivityModel(dict: dict)
activity?.append(model)
}
}else {
super.setValue(value, forKey: key)
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
/// 所有商品model
class GoodsModel: NSObject {
var goods_class : GoodsCategoryModel?
var goods_list : [GoodInfoModel]?
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "goods_list" {
goods_list = Array()
guard let datas = value as? [[String : Any]] else { return }
for dict in datas {
let foodModel = GoodInfoModel(dict: dict)
goods_list?.append(foodModel)
}
}else if key == "goods_class" {
guard let datas = value as? [String : Any] else { return }
goods_class = GoodsCategoryModel(dict: datas)
}else {
super.setValue(value, forKey: key)
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
/// 商品信息model
class GoodInfoModel: NSObject {
var id : String?
var cn_name : String?
var goods_img : String?
var goods_thumb_img : String?
///立减价格,或者打几折
var preferential_price : String?
///0无优惠 1立减 2打折
var preferential_type : String?
var is_collect : String?
var month_num : String?
var attr: [GoodsAttrModel]?
///优惠价购买数量 0无限制
var preferential_buy_num : String?
///普通价格购买数量 0无限制
var buy_num : String?
///父类ID
var class_member_id : String?
///子类ID
var class_child_member_id : String?
///父类名称
var class_member_name : String?
//子类名称
var class_child_member_name : String?
/// 店铺ID
var member_id: String?
override init() {
}
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "attr" {
attr = [GoodsAttrModel]()
guard let datas = value as? [[String : Any]] else { return }
for dict in datas {
let attrModel = GoodsAttrModel(dict: dict)
attr?.append(attrModel)
}
} else {
super.setValue(value, forKey: key)
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
/// 商品分类model
class GoodsCategoryModel: NSObject {
///分类ID
var class_member_id : String?
///分类名
var class_member_name : String?
///父级分类ID,-1时为热销商品(固定)
var parent_class_id : String?
///父分类名称
var parent_class_name : String?
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
/// 商家信息model
class ShopInfoModel: NSObject {
///商店ID
var member_id : String?
///商店名
var company_name : String?
var logo : String?
///月销售
var month_num : String?
///起送价
var send_price : String?
///店主留言
var features : String?
///电话
var tel : String?
///地址
var address : String?
///商店图片,分号隔开
var shop_img : String?
///证件照,分号隔开
var cert_img : String?
///商店是否收藏
var is_collect : String?
///经度
var lng : String?
///纬度
var lat : String?
//配送距离(行驶距离),单位是千米
var distance: String?
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit | f3e95bf85edd084edd05482f78dc75de | 23.28972 | 72 | 0.534436 | 3.928949 | false | false | false | false |
Arty-Maly/Volna | Volna/StationCollectionViewCell.swift | 1 | 1857 | //
// StationCollectionViewCell.swift
// Volna
//
// Created by Artem Malyshev on 1/14/17.
// Copyright © 2017 Artem Malyshev. All rights reserved.
//
import UIKit
class StationCollectionViewCell: UICollectionViewCell {
var stationUrl: String?
private var placeholderImage: UIImage
@IBOutlet weak var stationName: UILabel!
@IBOutlet weak var imageView: UIImageView!
var radioStation: RadioStation!
required init(coder aDecoder: NSCoder) {
placeholderImage = UIImage(named: "placeholder.png")!
placeholderImage = placeholderImage.resizeImage(newWidth: CGFloat(90))
super.init(coder: aDecoder)!
// self.layer.cornerRadius = 20
// self.layer.masksToBounds = false
}
override init(frame: CGRect) {
placeholderImage = UIImage(named: "placeholder.png")!
placeholderImage = placeholderImage.resizeImage(newWidth: CGFloat(90))
super.init(frame: frame)
}
func prepareCellForDisplay(_ station: RadioStation) {
imageView.image = placeholderImage
isHidden = false
radioStation = station
stationName.text = parseName(station.name)
stationName.layer.zPosition = 1
backgroundColor = UIColor.white
stationUrl = station.url
setImage(station.image)
}
private func setImage(_ url: String) {
// DispatchQueue.global(qos: .userInitiated).async { [weak self] in
if let image = ImageCache.shared[url] {
// DispatchQueue.main.async {
imageView.image = image
return
}
// }
}
private func parseName(_ name: String) -> String {
if name.characters.count >= 17 {
return name.replace(target: " ", withString: "\n")
}
return name
}
}
| gpl-3.0 | 4121aceca2f2a1e60812b175346f6b81 | 29.933333 | 78 | 0.622845 | 4.746803 | false | false | false | false |
yarshure/Surf | Surf/SFInterfaceTraffic.swift | 1 | 6565 | //
// SFInterfaceTraffic.swift
// Surf
//
// Created by networkextension on 7/7/16.
// Copyright © 2016 yarshure. All rights reserved.
//
import Foundation
import CFNetwork
import Darwin
import SFSocket
import XRuler
//if let p = ipaddr where p == "240.7.1.9" {
//}
struct SFInterfaceTraffic {
var WiFiSent:UInt = 0;
var WiFiReceived:UInt = 0;
var WWANSent:UInt = 0;
var WWANReceived:UInt = 0;
var TunSent:UInt = 0;
var TunReceived:UInt = 0;
}
func getIFAddresses() -> [NetInfo] {
var addresses = [NetInfo]()
//let d0 = NSDate()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
// For each interface ...
var ptr = ifaddr
while( ptr != nil) {
let flags = Int32((ptr?.pointee.ifa_flags)!)
var addr = ptr?.pointee.ifa_addr.pointee
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr?.sa_family == UInt8(AF_INET) || addr?.sa_family == UInt8(AF_INET6) {
// Convert interface address to a human readable string:
var hostname = [CChar](repeating: 0, count: Int(256))//NI_MAXHOST
if (getnameinfo(&addr!, socklen_t((addr?.sa_len)!), &hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0) {
if let address = String.init(cString: hostname, encoding: .utf8) {
let name = ptr?.pointee.ifa_name
let ifname = String.init(cString: name!, encoding: .utf8)
// var x = NSMutableData.init(length: Int(strlen(name)))
// let p = UnsafeMutablePointer<Void>.init((x?.bytes)!)
// memcpy(p, name, Int(strlen(name)))
//print(ifname)
var net = ptr?.pointee.ifa_netmask.pointee
var netmaskName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(&net!, socklen_t((net?.sa_len)!), &netmaskName, socklen_t(netmaskName.count),
nil, socklen_t(0), NI_NUMERICHOST)
if let netmask = String.init(cString: netmaskName, encoding: .utf8) {
if address.count > 15 {
let net = NetInfo(ip: "2001:470:4a34:ee00:d80a:882c:100:0", netmask: netmask,ifName:ifname!)
addresses.append(net)
}else {
let net = NetInfo(ip: address, netmask: netmask,ifName:ifname!)
addresses.append(net)
}
//addresses[ifname!] = address
}
}
}
}
}
ptr = ptr?.pointee.ifa_next
}
freeifaddrs(ifaddr)
}
//let d1 = NSDate()
//print("\(d1.timeIntervalSinceDate(d0))")
return addresses
}
func showStart() ->Bool{
let x = getIFAddresses()
for xx in x {
if xx.ip == "240.7.1.9" {
return true
}
}
return false
}
func abigtTunIP() ->String?{
let x = getIFAddresses()
for xx in x {
if xx.ip == "240.7.1.9" {
return xx.ifName
}
}
return nil
}
//last:SFInterfaceTraffic
func getInterfaceTraffic() -> SFInterfaceTraffic {
var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
var t = SFInterfaceTraffic()
guard let tunName = abigtTunIP() else {return t}
if getifaddrs(&ifaddr) == 0 {
// For each interface ...
var ptr = ifaddr
while( ptr != nil) {
let flags = Int32((ptr?.pointee.ifa_flags)!)
let addr = ptr?.pointee.ifa_addr.pointee
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr?.sa_family == UInt8(AF_LINK) {
// Convert interface address to a human readable string:
let name = ptr?.pointee.ifa_name
let ifname = String.init(cString: name!)
let networkData: UnsafeMutablePointer<if_data> = unsafeBitCast(ptr!.pointee.ifa_data,to: UnsafeMutablePointer<if_data>.self)
//var ipaddr:String?
// var hostname = [CChar](count: Int(256), repeatedValue: 0)//NI_MAXHOST
// if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
// nil, socklen_t(0), NI_NUMERICHOST) == 0) {
// if let address = String.fromCString(hostname){
// ipaddr = address
// }
// }
if ifname.hasPrefix("en") {
t.WiFiReceived = UInt(networkData.pointee.ifi_ibytes)
t.WiFiSent = UInt(networkData.pointee.ifi_obytes)
}else if ifname.hasPrefix("pdp_ip") {
t.WWANReceived = UInt(networkData.pointee.ifi_ibytes)
t.WWANSent = UInt(networkData.pointee.ifi_obytes)
}else if ifname == tunName {//hasPrefix("utun")
t.TunReceived = UInt(networkData.pointee.ifi_ibytes)
t.TunSent = UInt(networkData.pointee.ifi_obytes)
}
}
}
ptr = ptr?.pointee.ifa_next
}
freeifaddrs(ifaddr)
}
//let d1 = NSDate()
//print("\(d1.timeIntervalSinceDate(d0))")
return t
}
| bsd-3-clause | f612f176c2ff677ec4c329c90227bca7 | 39.02439 | 144 | 0.460999 | 4.523777 | false | false | false | false |
cheyongzi/MGTV-Swift | MGTV-Swift/Search/View/CustomSearchBar.swift | 1 | 6277 | //
// CustomSearchBar.swift
// MGTV-Swift
//
// Created by Che Yongzi on 16/10/17.
// Copyright © 2016年 Che Yongzi. All rights reserved.
//
import UIKit
import SnapKit
let defaultPlaceholder = "搜索视频、明星"
protocol CustomSearchBarDelegate: class {
func search(text: String?)
func clear()
func auto(text: String?)
func beginEdit()
func touchAction(text: String?)
}
extension CustomSearchBarDelegate {
func search(text: String?) { }
func clear() { }
func auto(text: String?) { }
func beginEdit() { }
func touchAction(text: String?) { }
}
class CustomSearchBar: UIView, UITextFieldDelegate {
weak var delegate: CustomSearchBarDelegate?
/// placeholder网络请求进行展示,默认为false
var requestPlaceholder: Bool = false {
didSet {
if requestPlaceholder {
SearchRecommendDataSource.fetchSearchRecommend(nil, complete: { [weak self] (response, error) in
guard let searchRecommendResponse = response as? SearchRecommendResponse else {
return
}
guard let searchRecommendItem = searchRecommendResponse.data?.first else {
return
}
guard let recommendPlaceholder = searchRecommendItem.name else {
return
}
if let strongSelf = self {
strongSelf.placeholder = recommendPlaceholder
}
})
}
}
}
//text field is can edit
var isCanEdit: Bool = true {
didSet {
if isCanEdit {
textField.isUserInteractionEnabled = true
} else {
textField.isUserInteractionEnabled = false
}
}
}
//搜索框
lazy private var textField: UITextField = { [unowned self] in
let field = UITextField()
field.font = UIFont.systemFont(ofSize: 13)
field.clearButtonMode = .always
field.returnKeyType = .search
field.delegate = self
field.addTarget(self, action: #selector(textFieldObserver(_:)), for: .editingChanged)
return field
}()
//搜索图标
lazy private var searchIcon: UIImageView = {
let icon = UIImageView.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
icon.image = UIImage(named: "TabBar_SearchBox_icon")
return icon
}()
//placeholder
var placeholder: String {
get {
return textField.placeholder!
}
set {
textField.attributedPlaceholder = NSAttributedString.init(string: newValue, attributes: [NSForegroundColorAttributeName : UIColor(red: 102.0/255, green: 102.0/255, blue: 102.0/255, alpha: 1.0)])
}
}
//text
var text: String? {
get {
return textField.text
}
set {
textField.text = newValue
}
}
//MARK: - Init method
override init(frame: CGRect) {
super.init(frame: frame)
self.initSearchBar()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
self.initSearchBar()
}
//MARK: - UITextField Delegate
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if !isCanEdit {
return false
}
delegate?.beginEdit()
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
delegate?.clear()
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.text != nil && textField.text != "" {
delegate?.search(text: textField.text)
} else {
if textField.placeholder != nil && textField.placeholder != defaultPlaceholder {
delegate?.search(text: textField.placeholder)
}
}
return true
}
//MARK: - Touch action
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if !isCanEdit {
delegate?.touchAction(text: textField.placeholder)
}
}
//MARK: - Init search bar
private func initSearchBar() {
self.backgroundColor = UIColor.white
self.layer.cornerRadius = 4
self.clipsToBounds = true
self.addSubview(textField)
self.addSubview(searchIcon)
textField.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
searchIcon.snp.makeConstraints { (make) in
make.trailing.equalTo(textField.snp.leading).offset(-5)
make.width.height.equalTo(10)
make.centerY.equalTo(self)
}
placeholder = defaultPlaceholder
}
//MARK: - Text filed status observer
@objc private func textFieldObserver(_ textField: UITextField) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(autoChange), object: nil)
self.perform(#selector(autoChange), with: nil, afterDelay: 0.2)
}
@objc private func autoChange() {
delegate?.auto(text: textField.text)
}
//MARK: - Update constraints
override func updateConstraints() {
if isCanEdit {
textField.snp.removeConstraints()
textField.snp.makeConstraints({ (make) in
make.edges.equalTo(self).inset(UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0))
})
textField.textAlignment = .left
} else {
textField.snp.removeConstraints()
textField.snp.makeConstraints({ (make) in
make.center.equalTo(self)
})
textField.textAlignment = .center
}
super.updateConstraints()
}
//MARK: - Become First Responder
override func becomeFirstResponder() -> Bool {
textField.becomeFirstResponder()
return true
}
}
| mit | a15be847cbefdb6eea9543511591deda | 28.628571 | 206 | 0.567824 | 5.001608 | false | false | false | false |
noppoMan/Hexaville | Sources/HexavilleCore/Filesystem/FileManager.swift | 1 | 1734 | //
// FileManager.swift
// Hexaville
//
// Created by Yuki Takei on 2017/05/19.
//
//
import Foundation
enum FileManagerError: Error {
case couldNotMakeDirectory(String)
}
extension FileManager {
public func copyFiles(from: String, to dest: String, excludes: [String] = []) throws {
guard let enumerator = FileManager.default.enumerator(atPath: from) else { return }
let r = Process.exec("mkdir", ["-p", dest])
if r.terminationStatus != 0 {
throw FileManagerError.couldNotMakeDirectory(dest)
}
for item in enumerator {
guard let item = item as? String else { continue }
let fullTargetPath = from+"/"+item
let attributes = try FileManager.default.attributesOfItem(atPath: fullTargetPath)
if let fileType = attributes[FileAttributeKey.type] as? Foundation.FileAttributeType {
let fullDestinationPath = dest+"/"+item
switch fileType {
case FileAttributeType.typeDirectory:
_ = try FileManager.default.createDirectory(
atPath: fullDestinationPath,
withIntermediateDirectories: true,
attributes: [:]
)
print("created \(fullDestinationPath)")
case FileAttributeType.typeRegular:
try Data(contentsOf: URL(string: "file://\(fullTargetPath)")!)
.write(to: URL(string: "file://\(fullDestinationPath)")!)
print("created \(fullDestinationPath)")
default:
break
}
}
}
}
}
| mit | f162fea8fc26d7ef27a5a6c3ad4accf0 | 33 | 98 | 0.55075 | 5.504762 | false | false | false | false |
padawan/smartphone-app | MT_iOS/MT_iOS/Classes/ViewController/BaseDraftTableViewController.swift | 1 | 5104 | //
// BaseDraftTableViewController.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/11.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class BaseDraftTableViewController: BaseTableViewController {
var files = [String]()
var blog: Blog!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.registerNib(UINib(nibName: "EntryTableViewCell", bundle: nil), forCellReuseIdentifier: "EntryTableViewCell")
}
func dataDir()-> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var dir = blog.dataDirPath()
var path = paths[0].stringByAppendingPathComponent(dir)
path = path.stringByAppendingPathComponent(self is EntryDraftTableViewController ? "draft_entry" : "draft_page")
let manager = NSFileManager.defaultManager()
manager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil, error: nil)
return path
}
func fetch() {
let manager = NSFileManager.defaultManager()
var paths = manager.contentsOfDirectoryAtPath(self.dataDir(), error: nil)!
files = [String]()
for path in paths {
if !path.hasPrefix(".") {
files.append(path as! String)
}
}
files = files.reverse()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.fetch()
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return files.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("EntryTableViewCell", forIndexPath: indexPath) as! EntryTableViewCell
self.adjustCellLayoutMargins(cell)
// Configure the cell...
let filename = self.files[indexPath.row]
let dir = self.dataDir()
let path = dir.stringByAppendingPathComponent(filename)
let item = EntryItemList.loadFromFile(path, filename: filename)
cell.object = item.object
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Table view delegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 130.0
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 8c6eb56aea6fa233d164bf1a115139c9 | 35.184397 | 157 | 0.669737 | 5.445037 | false | false | false | false |
lanjing99/RxSwiftDemo | 03-subjects-and-variable/challenge/Challenge1-Starter/RxSwift.playground/Contents.swift | 1 | 1698 | //: Please build the scheme 'RxSwiftPlayground' first
import RxSwift
example(of: "PublishSubject") {
let disposeBag = DisposeBag()
let dealtHand = PublishSubject<[(String, Int)]>()
func deal(_ cardCount: UInt) {
var deck = cards
var cardsRemaining: UInt32 = 52
var hand = [(String, Int)]()
for _ in 0..<cardCount {
let randomIndex = Int(arc4random_uniform(cardsRemaining))
hand.append(deck[randomIndex])
deck.remove(at: randomIndex)
cardsRemaining -= 1
}
// Add code to update dealtHand here
}
// Add subscription to dealtHand here
deal(3)
}
/*:
Copyright (c) 2014-2016 Razeware LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
| mit | 566bf760300a0961822f3eedd67c47e6 | 31.653846 | 78 | 0.738516 | 4.564516 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/Game/Animation.swift | 1 | 1224 | //
// Animation.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
/**
This object represents an animation file to be displayed in a Telegram message containing a game, used for additional visual flair and to better preview what your game is to
*/
public struct Animation: Codable {
/// A unique file identifier for the animation.
public var fileID: String
/// Animation thumbnail as defined by the sender.
public var thumb: Photo?
/// Original animation filename as defined by the sender.
public var fileName: String?
/// MIME type of the file as defined by sender.
public var mimeType: String?
/// File size.
public var fileSize: Int?
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case fileID = "file_id"
case thumb
case fileName = "file_name"
case mimeType = "mime_type"
case fileSize = "file_size"
}
public init(fileID: String,
thumb: Photo? = nil,
fileName: String? = nil,
mimeType: String? = nil,
fileSize: Int? = nil) {
self.fileID = fileID
self.thumb = thumb
self.fileName = fileName
self.mimeType = mimeType
self.fileSize = fileSize
}
}
| mit | 1ae431f32d324e59ebecf72756ddd9e1 | 20.857143 | 174 | 0.684641 | 3.731707 | false | false | false | false |
Kofktu/KofktuSDK | KofktuSDK/Classes/Components/LateInit.swift | 1 | 1690 | //
// LateInit.swift
// KofktuSDK
//
// Created by USER on 2021/01/08.
// Copyright © 2021 Kofktu. All rights reserved.
//
import Foundation
@propertyWrapper
public struct LateInit<T> {
private var value: T?
public init() {
value = nil
}
public var wrappedValue: T {
get {
guard let value = value else {
fatalError("Trying to access LateInit.value before setting it.")
}
return value
}
set { value = newValue }
}
}
@propertyWrapper
public struct LazyInit<T> {
private(set) var value: T?
private let constructor: () -> T
public var wrappedValue: T {
mutating get {
if let value = value {
return value
}
let newValue = constructor()
value = newValue
return newValue
}
set { value = newValue }
}
public init(_ constructor: @escaping () -> T) {
self.constructor = constructor
self.value = nil
}
}
@propertyWrapper
public struct LazyInitOnce<T> {
private(set) var value: T?
private let constructor: () -> T
public var wrappedValue: T {
mutating get {
if let value = value {
return value
}
let newValue = constructor()
value = newValue
return newValue
}
}
public init(_ constructor: @escaping () -> T) {
self.constructor = constructor
self.value = nil
}
public func `do`(sideEffectTask: (T) -> Void) {
guard let value = value else { return }
sideEffectTask(value)
}
}
| mit | c1c3d3bf9f313384e2897bfbeddcdb8c | 20.653846 | 80 | 0.531083 | 4.492021 | false | false | false | false |
RadioBear/CalmKit | CalmKit/Animators/BRBCalmKitFadingCircleAnimator.swift | 1 | 2811 | //
// BRBCalmKitFadingCircleAnimator.swift
// CalmKit
//
// Copyright (c) 2016 RadioBear
//
// 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
class BRBCalmKitFadingCircleAnimator: BRBCalmKitAnimator {
func setupAnimation(inLayer layer : CALayer, withSize size : CGSize, withColor color : UIColor) {
let beginTime = CACurrentMediaTime()
let squareSize: CGFloat = size.width / 6
let radius: CGFloat = (size.width / 2) - (squareSize * 0.5)
for i in 0..<12 {
let square = CALayer()
let angle: Double = Double(i) * (M_PI_2/3.0)
let x: CGFloat = radius + CGFloat(sin(angle)) * radius
let y: CGFloat = radius - CGFloat(cos(angle)) * radius
square.frame = CGRectMake(x, y, squareSize, squareSize)
square.backgroundColor = color.CGColor
square.anchorPoint = CGPointMake(0.5, 0.5)
square.opacity = 0.0
square.transform = CATransform3DRotate(CATransform3DIdentity, CGFloat(angle), 0, 0, 1.0)
let anim = CAKeyframeAnimation(keyPath: "opacity")
anim.removedOnCompletion = false
anim.repeatCount = HUGE
anim.duration = 1.0
anim.beginTime = beginTime + (0.084 * Double(i))
anim.keyTimes = [0.0, 0.5, 1.0]
anim.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
]
anim.values = [1.0, 0.0, 0.0]
layer.addSublayer(square)
square.addAnimation(anim, forKey: "calmkit-anim")
}
}
}
| mit | d8c852cd4c362515daf3108d37c3a3b4 | 41.590909 | 101 | 0.647101 | 4.630972 | false | false | false | false |
machelix/iOS9_Contacts | iOS9_Contacts/MasterViewController.swift | 2 | 3787 | //
// MasterViewController.swift
// iOS9_Contacts
//
// Created by WataruSuzuki on 2015/08/14.
// Copyright © 2015年 Wataru Suzuki. All rights reserved.
//
import UIKit
import Contacts
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
var myContactStore = CNContactStore()
override func viewDidLoad() {
super.viewDidLoad()
let status = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
switch status {
case CNAuthorizationStatus.NotDetermined:
myContactStore.requestAccessForEntityType(CNEntityType.Contacts) { (success, error) -> Void in
if !success {
print(error?.description)
}
}
default:
break
}
// Do any additional setup after loading the view, typically from a nib.
//self.navigationItem.leftBarButtonItem = self.editButtonItem()
//let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
//self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case SampleMenu.SHOW_ALL_LIST.segueId():
//TODO
break
default:
break
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return SampleMenu.MENU_MAX.rawValue
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel!.text = SampleMenu(rawValue: indexPath.row)?.toString()
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let segueId = SampleMenu(rawValue: indexPath.row)?.segueId()
self.performSegueWithIdentifier(segueId!, sender: self)
}
enum SampleMenu : Int {
case SHOW_ALL_LIST = 0,
MENU_MAX
func toString() -> String {
switch self {
case .SHOW_ALL_LIST: return "Show all contacts list"
default: return ""
}
}
func segueId() -> String {
switch self {
case .SHOW_ALL_LIST: return "ShowAllContactsList"
default: return ""
}
}
}
}
| mit | 2856868d5e5f72d6cc6c85961dbbc8d4 | 31.34188 | 144 | 0.642178 | 5.405714 | false | false | false | false |
lukemetz/Paranormal | Paranormal/ParanormalTests/Matchers.swift | 3 | 1137 | import Foundation
import Nimble
import Cocoa
public func beColor(expectR : UInt, expectG : UInt, expectB : UInt, expectA : UInt)
-> MatcherFunc<NSColor?> {
return beNearColor(expectR, expectG, expectB, expectA, tolerance: 0)
}
public func beNearColor(expectR : UInt, expectG : UInt, expectB : UInt, expectA : UInt,
#tolerance: Int)
-> MatcherFunc<NSColor?> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(expectR, expectG, expectB, expectA)>"
if let color = actualExpression.evaluate() {
if let colorUnwrap = color {
let (gotR, gotG, gotB, gotA) =
(UInt(colorUnwrap.redComponent), UInt(colorUnwrap.greenComponent),
UInt(colorUnwrap.blueComponent), UInt(colorUnwrap.alphaComponent))
return abs(gotR - expectR) <= tolerance &&
abs(gotG - expectG) <= tolerance &&
abs(gotB - expectB) <= tolerance &&
abs(gotA - expectA) <= tolerance
}
}
return false
}
}
| mit | 28249ee1c48d72ac8b77ea2fc89ddb3d | 36.9 | 87 | 0.592788 | 4.373077 | false | false | false | false |
SunLiner/Floral | Floral/Floral/AppDelegate.swift | 1 | 3692 | //
// AppDelegate.swift
// Floral
//
// Created by ALin on 16/4/25.
// Copyright © 2016年 ALin. All rights reserved.
// github : https://github.com/SunLiner/Floral
// blog : http://www.jianshu.com/p/2893be49c50e
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 方便测试: 每次登录的时候, 都把登录状态设置false
// LoginHelper.sharedInstance.setLoginStatus(false)
// 设置全局的UINavigationBar属性
let bar = UINavigationBar.appearance()
bar.tintColor = UIColor.blackColor()
bar.titleTextAttributes = [NSFontAttributeName : UIFont.systemFontOfSize(15), NSForegroundColorAttributeName : UIColor.blackColor()]
// 设置window
window = UIWindow(frame: UIScreen.mainScreen().bounds)
// 根据版本号, 判断显示哪个控制器
if toNewFeature() {
window?.rootViewController = NewFeatureViewController()
}else{
window?.rootViewController = MainViewController()
}
// 设置相关的appkey
setAppKey()
window?.makeKeyAndVisible()
return true
}
private let SLBundleShortVersionString = "SLBundleShortVersionString"
// MARK: - 判断版本号
private func toNewFeature() -> Bool
{
// 根据版本号来确定是否进入新特性界面
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
let oldVersion = NSUserDefaults.standardUserDefaults().objectForKey(SLBundleShortVersionString) ?? ""
// 如果当前的版本号和本地保存的版本比较是降序, 则需要显示新特性
if (currentVersion.compare(oldVersion as! String)) == .OrderedDescending{
// 保存当前的版本
NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: SLBundleShortVersionString)
return true
}
return false
}
// MARK: - 设置相关的APPkey
private func setAppKey()
{
// 设置友盟的appkey
UMSocialData.setAppKey("574e565fe0f55a1b7c002d43")
// 如果碰到"NSConcreteMutableData wbsdk_base64EncodedString]: ..."这个错误, 说明新版的新浪SDK不支持armv7s, 需要在在other linker flags增加-ObjC 选项,并添加ImageIO 系统framework
// 如果需要使用SSO授权, 需要在info里面添加白名单, 具体可以直接拷贝我的info.plist里面的LSApplicationQueriesSchemes
UMSocialSinaSSOHandler.openNewSinaSSOWithAppKey("3433284356", secret: "a4708df245b826da73511ad268a85c3c", redirectURL: "http://sns.whalecloud.com/sina2/callback")
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
let result = UMSocialSnsService.handleOpenURL(url)
if result == false {
}
return result
}
}
// 首先要明确一点: swift里面是没有宏定义的概念
// 自定义内容输入格式: 文件名[行号]函数名: 输入内容
// 需要在info.plist的other swift flag的Debug中添加DEBUG
func ALinLog<T>(message: T, fileName: String = #file, lineNum: Int = #line, funcName: String = #function)
{
#if DEBUG
print("\((fileName as NSString).lastPathComponent)[\(lineNum)] \(funcName): \(message)")
#endif
}
| mit | 0e2b3deab90e572b180d880d69380d0b | 32.05102 | 170 | 0.660698 | 4.290066 | false | false | false | false |
rajkhatri/RKBarcodeScanner | BarcodeScanner/CameraPermissions.swift | 1 | 2407 | //
// CameraPermissions.swift
// BarcodeScanner
//
// Created by Raj Khatri on 2016-01-02.
// Copyright © 2016 Raj Khatri. All rights reserved.
//
import UIKit
import AVFoundation
class CameraPermissions : NSObject {
static let sharedInstance = CameraPermissions()
// Should be set to top most VC before checkCameraPermissions are called. Used only for Alert display.
var cameraViewController:UIViewController?
private var cameraPermissionsClosure:(()->())?
func checkCameraPermissions(completion:(()->())) {
cameraPermissionsClosure = completion
let authStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
switch authStatus {
case .Authorized:
cameraPermissionsClosure!()
break
case .Denied:
showAlert("Denied")
break
case .Restricted:
showAlert("Restricted")
break
case .NotDetermined:
askForPermissions()
break
}
}
private func askForPermissions() {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo) { (granted) -> Void in
if (granted) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
guard self.cameraPermissionsClosure != nil else { return }
self.cameraPermissionsClosure!()
})
}
else {
let error = "Camera Permissions Denied. Please enable in settings."
print(error)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.showAlert(error)
})
}
}
}
private func showAlert(type:String? = "") {
let vc = UIAlertController(title: "Error: Cannot display camera because of issue:", message: type, preferredStyle: .Alert)
let okButton = UIAlertAction(title: "Ok", style: .Default) { (action) -> Void in
self.cameraViewController?.dismissViewControllerAnimated(true, completion: nil)
}
vc.addAction(okButton)
guard cameraViewController != nil else { return }
cameraViewController?.presentViewController(vc, animated: true, completion: nil)
}
} | mit | 8371f34a5e0dc169df13194a766c60ca | 32.430556 | 130 | 0.57606 | 5.595349 | false | false | false | false |
russelhampton05/MenMew | App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/MenuItemManager.swift | 1 | 1814 | //
// MenuItemManager.swift
// App_Prototype_Alpha_001
//
// Created by Guest User on 10/10/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import Foundation
import Firebase
class MenuItemManager{
static let ref = FIRDatabase.database().reference().child("MenuItems")
static func GetMenuItem(id: String, completionHandler: @escaping (_ item: MenuItem) -> ()) {
let item = MenuItem()
ref.child(id).observeSingleEvent(of: .value, with:{(FIRDataSnapshot) in
let value = FIRDataSnapshot.value as? NSDictionary
item.item_ID = id
item.title = value?["name"] as? String
item.image = value?["image"] as? String
item.desc = value?["desc"] as? String
item.price = value?["price"] as? Double
}){(error) in
print(error.localizedDescription)
}
completionHandler(item)
}
static func GetMenuItem(ids: [String], completionHandler: @escaping (_ items: [MenuItem]) -> ()) {
var items :[MenuItem] = []
let sem1 = DispatchGroup.init()
for id in ids{
print("Initiating request for item id " + id)
var newItem: MenuItem?
sem1.enter()
GetMenuItem(id: id) {
item in
print("Finished request for item id " + id)
newItem = item
items.append(newItem!)
sem1.leave()
}
}
sem1.notify(queue: DispatchQueue.main, execute: {
print("Finished all requests for menu items")
completionHandler(items) })
}
}
| mit | d30b4bbe720ad35325a593a06feec768 | 27.328125 | 102 | 0.51241 | 4.967123 | false | false | false | false |
thegreatmichael/Tasks-iOS8-Swift | Tasks/NewTaskViewController.swift | 1 | 1859 | //
// NewTaskViewController.swift
// Tasks
//
// Created by Michael Stewart on 10/27/14.
// Copyright (c) 2014 iOS in Action. All rights reserved.
//
import UIKit
class NewTaskViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.textField.becomeFirstResponder()
self.textField.delegate = self
}
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBOutlet weak var delegate: AnyObject!
@IBOutlet weak var textField: UITextField!
@IBAction func saveTask(sender: AnyObject) {
if (self.textField.text.utf16Count == 0) {
return;
} else {
var tasksListView = self.delegate as ViewController
tasksListView.tasks.addObject(self.textField.text)
self.close(sender)
}
}
@IBAction func close(sender: AnyObject) {
println("trying to close")
self.dismissViewControllerAnimated(true, completion: {})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (textField == self.textField) {
self.saveTask(self)
return true
}// if there were another textfield, instead of returning, we could focus the next textbox
return true
}
}
| mit | 6cdfeb297baf96236135a6349a93b2f5 | 28.046875 | 106 | 0.645508 | 4.983914 | false | false | false | false |
sarvex/SwiftRecepies | Camera/Taking Photos with the Camera/Taking Photos with the Camera/ViewController.swift | 1 | 4371 | //
// ViewController.swift
// Taking Photos with the Camera
//
// Created by Vandad Nahavandipoor on 7/10/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import MobileCoreServices
class ViewController: UIViewController,
UINavigationControllerDelegate, UIImagePickerControllerDelegate {
/* We will use this variable to determine if the viewDidAppear:
method of our view controller is already called or not. If not, we will
display the camera view */
var beenHereBefore = false
var controller: UIImagePickerController?
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
println("Picker returned successfully")
let mediaType:AnyObject? = info[UIImagePickerControllerMediaType]
if let type:AnyObject = mediaType{
if type is String{
let stringType = type as! String
if stringType == kUTTypeMovie as! String{
let urlOfVideo = info[UIImagePickerControllerMediaURL] as? NSURL
if let url = urlOfVideo{
println("Video URL = \(url)")
}
}
else if stringType == kUTTypeImage as! String{
/* Let's get the metadata. This is only for images. Not videos */
let metadata = info[UIImagePickerControllerMediaMetadata]
as? NSDictionary
if let theMetaData = metadata{
let image = info[UIImagePickerControllerOriginalImage]
as? UIImage
if let theImage = image{
println("Image Metadata = \(theMetaData)")
println("Image = \(theImage)")
}
}
}
}
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
println("Picker was cancelled")
picker.dismissViewControllerAnimated(true, completion: nil)
}
func isCameraAvailable() -> Bool{
return UIImagePickerController.isSourceTypeAvailable(.Camera)
}
func cameraSupportsMedia(mediaType: String,
sourceType: UIImagePickerControllerSourceType) -> Bool{
let availableMediaTypes =
UIImagePickerController.availableMediaTypesForSourceType(sourceType) as!
[String]?
if let types = availableMediaTypes{
for type in types{
if type == mediaType{
return true
}
}
}
return false
}
func doesCameraSupportTakingPhotos() -> Bool{
return cameraSupportsMedia(kUTTypeImage as! String, sourceType: .Camera)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if beenHereBefore{
/* Only display the picker once as the viewDidAppear: method gets
called whenever the view of our view controller gets displayed */
return;
} else {
beenHereBefore = true
}
if isCameraAvailable() && doesCameraSupportTakingPhotos(){
controller = UIImagePickerController()
if let theController = controller{
theController.sourceType = .Camera
theController.mediaTypes = [kUTTypeImage as! String]
theController.allowsEditing = true
theController.delegate = self
presentViewController(theController, animated: true, completion: nil)
}
} else {
println("Camera is not available")
}
}
}
| isc | 2d6f090b7ed665a15ed1a26470852743 | 30.446043 | 83 | 0.653169 | 5.209774 | false | false | false | false |
mozilla-mobile/firefox-ios | Shared/KeychainStore.swift | 2 | 2034 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import SwiftyJSON
import MozillaAppServices
public class KeychainStore {
public static let shared = KeychainStore()
private let keychainWrapper: MZKeychainWrapper
private init() {
self.keychainWrapper = MZKeychainWrapper.sharedClientAppContainerKeychain
}
public func setDictionary(_ value: [String: Any]?, forKey key: String, withAccessibility accessibility: MZKeychainItemAccessibility = .afterFirstUnlock) {
guard let value = value else {
setString(nil, forKey: key, withAccessibility: accessibility)
return
}
let stringValue = JSON(value).stringify()
setString(stringValue, forKey: key, withAccessibility: accessibility)
}
public func setString(_ value: String?, forKey key: String, withAccessibility accessibility: MZKeychainItemAccessibility = .afterFirstUnlock) {
guard let value = value else {
keychainWrapper.removeObject(forKey: key, withAccessibility: accessibility)
return
}
keychainWrapper.set(value, forKey: key, withAccessibility: accessibility)
}
public func dictionary(forKey key: String, withAccessibility accessibility: MZKeychainItemAccessibility = .afterFirstUnlock) -> [String: Any]? {
guard let stringValue = string(forKey: key, withAccessibility: accessibility) else { return nil }
let json = JSON(parseJSON: stringValue)
let dictionary = json.dictionaryObject
return dictionary
}
public func string(forKey key: String, withAccessibility accessibility: MZKeychainItemAccessibility = .afterFirstUnlock) -> String? {
keychainWrapper.ensureStringItemAccessibility(accessibility, forKey: key)
return keychainWrapper.string(forKey: key, withAccessibility: accessibility)
}
}
| mpl-2.0 | d888ab1e5e7d840fadfc848bbc76d13a | 38.115385 | 158 | 0.720256 | 5.149367 | false | false | false | false |
ChristianKienle/Bold | Bold/ResultSet.swift | 1 | 4474 | import Foundation
/**
Represents a result set. You usually do not interact with the result set directly but you can.
*/
final public class ResultSet {
fileprivate let statement: Statement
// MARK: Creating
public init(statement: Statement) {
self.statement = statement
}
// MARK: General
/**
Moves the cursor to the next row in the result set. Before you can access anything in the result set you have to call next at least once.
:returns: true if there is another row, false if there isn't or if an error occurred.
*/
public func next() -> Bool {
return step() == SQLITE_ROW
}
/**
Closes the result set.
:returns: true if the result set could be closed, otherwise false.
*/
public func close() -> Bool {
return statement.close()
}
/**
Returns the number of columns in the result set.
*/
public var columnCount:Int32 {
return sqlite3_column_count(statement.statementHandle)
}
internal func step() -> Int32 {
return sqlite3_step(statement.statementHandle)
}
}
// MARK: Get a row representation
public extension ResultSet {
/**
Gets the current row.
*/
public var row: Row {
var items = Array<Row.Item>()
let columnIndexes = (0..<columnCount)
columnIndexes.forEach { index in
guard let rawColumnName = sqlite3_column_name(statement.statementHandle, index) else {
return
}
let columnName = String(cString: rawColumnName)
let value = self.value(forColumn: index)
items.append(Row.Item(columnIndex: index, columnName: columnName, value: value))
}
return Row(items: items)
}
}
// MARK: Getting values
extension ResultSet {
/**
Used to get the string value of the column at a specific column in the current row.
:param: columnIndex The index of the column.
:returns: The string value of the column at the specified column in the current row.
*/
private func stringValue(forColumn columnIndex:Int32) -> String {
guard let text = sqlite3_column_text(statement.statementHandle, columnIndex) else {
return ""
}
return String(cString: text)
}
/**
Used to get the32 string value of the column at a specific column in the current row.
:param: columnIndex The index of the column.
:returns: The int32 value of the column at the specified column in the current row.
*/
private func int32Value(forColumn columnIndex:Int32) -> Int32 {
let value:Int32 = sqlite3_column_int(statement.statementHandle, columnIndex)
return value
}
/**
Used to get the int value of the column at a specific column in the current row.
:param: columnIndex The index of the column.
:returns: The int value of the column at the specified column in the current row.
*/
private func intValue(forColumn columnIndex:Int32) -> Int {
let value = int32Value(forColumn: columnIndex)
return Int(value)
}
/**
Used to get the double value of the column at a specific column in the current row.
:param: columnIndex The index of the column.
:returns: The double value of the column at the specified column in the current row.
*/
private func doubleValue(forColumn columnIndex:Int32) -> Double {
let value = sqlite3_column_double(statement.statementHandle, columnIndex)
return value
}
/**
Used to get the data value of the column at a specific column in the current row.
:param: columnIndex The index of the column.
:returns: The data value of the column at the specified column in the current row.
*/
private func dataValue(forColumn columnIndex:Int32) -> Data {
let rawData:UnsafeRawPointer = sqlite3_column_blob(statement.statementHandle, columnIndex)
let size:Int = Int(sqlite3_column_bytes(statement.statementHandle, columnIndex))
let value = Data(bytes: rawData, count: size)
return value
}
internal func value(forColumn columnIndex:Int32) -> Bindable? {
let columnType = sqlite3_column_type(statement.statementHandle, columnIndex)
if columnType == SQLITE_TEXT {
return stringValue(forColumn: columnIndex)
}
if columnType == SQLITE_INTEGER {
return intValue(forColumn: columnIndex)
}
if columnType == SQLITE_FLOAT {
return doubleValue(forColumn: columnIndex)
}
if columnType == SQLITE_NULL {
return nil
}
if columnType == SQLITE_BLOB {
return dataValue(forColumn: columnIndex)
}
return nil
}
}
| mit | 4048a47135d32817418c28a8428bc4c7 | 30.730496 | 141 | 0.691775 | 4.326886 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk | Sources/CoreAPI/Models/CoreAPI_Person.swift | 1 | 2010 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2018 ShopGun. All rights reserved.
import Foundation
extension CoreAPI {
public struct Person: Equatable, Codable {
public typealias Identifier = GenericIdentifier<Person>
public enum Gender: String, Codable {
case male
case female
}
public var id: Identifier
public var name: String
public var email: String
public var gender: Gender?
public var birthYear: Int?
// MARK: - Codable
enum CodingKeys: String, CodingKey {
case id
case name
case email
case gender
case birthYear = "birth_year"
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
// In the infinite wisdom of the CoreAPI, id is sent from the endpoint (for now) as an Int
// it is encoded to disk as a string (and could/should be a string in the future), so also decode from String
if let intId = try? values.decode(Int.self, forKey: .id) {
self.id = Identifier(rawValue: String(intId))
} else {
self.id = try values.decode(Identifier.self, forKey: .id)
}
self.name = try values.decode(String.self, forKey: .name)
self.email = try values.decode(String.self, forKey: .email)
self.gender = try? values.decode(Gender.self, forKey: .gender)
self.birthYear = try? values.decode(Int.self, forKey: .birthYear)
}
}
}
| mit | eb796a848059d833218d328a3c9ac1b5 | 32.236364 | 121 | 0.511488 | 4.362768 | false | false | false | false |
xmartlabs/Opera | Example/Example/Controllers/RepositoryPullRequestsController.swift | 1 | 4323 | // RepositoryPullRequestsController.swift
// Example-iOS ( https://github.com/xmartlabs/Example-iOS )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import OperaSwift
import RxSwift
import RxCocoa
private enum SortFilter: Int, CustomStringConvertible, FilterType {
case open = 0
case closed
case all
var description: String {
switch self {
case .open: return "open"
case .closed: return "closed"
case .all: return "all"
}
}
var parameters: [String: AnyObject]? {
return ["state": "\(self)" as AnyObject]
}
}
class RepositoryPullRequestsController: RepositoryBaseController {
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var filterSegmentControl: UISegmentedControl!
let refreshControl = UIRefreshControl()
var disposeBag = DisposeBag()
fileprivate var filter = SortFilter.open
lazy var viewModel: PaginationViewModel<PaginationRequest<PullRequest>> = { [unowned self] in
return PaginationViewModel(paginationRequest: PaginationRequest(route: GithubAPI.Repository.GetPullRequests(owner: self.owner, repo: self.name), filter: self.filter))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.keyboardDismissMode = .onDrag
tableView.addSubview(self.refreshControl)
emptyStateLabel.text = "No pull requests found"
let refreshControl = self.refreshControl
rx.sentMessage(#selector(RepositoryForksController.viewWillAppear(_:)))
.map { _ in false }
.bind(to: viewModel.refreshTrigger)
.disposed(by: disposeBag)
tableView.rx.reachedBottom
.bind(to: viewModel.loadNextPageTrigger)
.disposed(by: disposeBag)
viewModel.loading
.drive(activityIndicatorView.rx.isAnimating)
.disposed(by: disposeBag)
Driver.combineLatest(viewModel.elements.asDriver(), viewModel.firstPageLoading) { elements, loading in return loading ? [] : elements }
.asDriver()
.drive(tableView.rx.items(cellIdentifier:"Cell")) { _, pullRequest, cell in
cell.textLabel?.text = pullRequest.user
cell.detailTextLabel?.text = pullRequest.state
}
.disposed(by: disposeBag)
refreshControl.rx.valueChanged
.filter { refreshControl.isRefreshing }
.map { true }
.bind(to: viewModel.refreshTrigger)
.disposed(by: disposeBag)
viewModel.loading
.filter { !$0 && refreshControl.isRefreshing }
.drive(onNext: { _ in refreshControl.endRefreshing() })
.disposed(by: disposeBag)
filterSegmentControl.rx.valueChanged
.map { [weak self] in return SortFilter(rawValue: self?.filterSegmentControl.selectedSegmentIndex ?? 0) ?? SortFilter.open }
.bind(to: viewModel.filterTrigger)
.disposed(by: disposeBag)
viewModel.emptyState
.drive(onNext: { [weak self] emptyState in self?.emptyStateLabel.isHidden = !emptyState })
.disposed(by: disposeBag)
}
}
| mit | faf23dc3a53f1d420c7504f180bdc7f2 | 36.267241 | 174 | 0.681471 | 4.890271 | false | false | false | false |
vivekvpandya/GetSwifter | GetSwifter/ChallengeDetailsVC.swift | 2 | 7001 | //
// RealWorldChallengeDetailsVC.swift
// GetSwifter
//
//
import UIKit
import Alamofire
import Social
import MessageUI
class ChallengeDetailsVC: UIViewController, UIAlertViewDelegate, UIWebViewDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var registerButton: UIButton!
@IBOutlet weak var postButton: UIButton!
@IBOutlet weak var detailsWebView: UIWebView!
@IBOutlet weak var tweetButton: UIButton!
@IBOutlet weak var firstPlacePrize: UILabel!
@IBOutlet weak var secondPlacePrize: UILabel!
@IBOutlet weak var thirdPlacePrize: UILabel!
@IBOutlet weak var fourthPlacePrize: UILabel!
@IBOutlet weak var fifthPlacePrize: UILabel!
var serviceEndPoint : String = "http://api.topcoder.com/v2/develop/challenges/" // here challenge id will be appended at the end
var challengeID : NSString = "" // This value will be set by prepareForSegue method of RealWorldChallengesTVC
var directURL : NSString = "" // this will be used to open topcoder challenge page in Safari
override func viewDidLoad() {
super.viewDidLoad()
registerButton.enabled = false
postButton.enabled = false
tweetButton.enabled = false
detailsWebView.delegate = self
getChallengeDetails()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getChallengeDetails(){
activityIndicator.startAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
var apiURLString = "\(serviceEndPoint)\(challengeID)"
Alamofire.request(.GET,apiURLString, encoding : .JSON).responseJSON
{ (request,response,JSON,error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if (error == nil){
if response?.statusCode == 200{
self.activityIndicator.stopAnimating()
var challengeDetails : NSDictionary = JSON as NSDictionary
if let directURL = challengeDetails.objectForKey("directUrl") as? NSString {
self.directURL = directURL
self.registerButton.enabled = true
self.tweetButton.enabled = true
self.postButton.enabled = true
}
if let detailedReq = challengeDetails.objectForKey("detailedRequirements") as? NSString{
self.detailsWebView.loadHTMLString(detailedReq, baseURL:nil)
self.detailsWebView.layer.borderColor = UIColor.blueColor().CGColor
self.detailsWebView.layer.borderWidth = 0.3
}
if let prize = challengeDetails.objectForKey("prize") as? NSArray {
if 1 <= prize.count{
if let firstPrize = prize[0] as? Int{
self.firstPlacePrize.text = "$ \(firstPrize)"
}
}
if 2 <= prize.count {
if let secondPrize = prize[1] as? Int{
self.secondPlacePrize.text = "$ \(secondPrize)"
}
}
if 3 <= prize.count {
if let thirdPrize = prize[2] as? Int{
self.thirdPlacePrize.text = "$ \(thirdPrize)"
}
}
if 4 <= prize.count {
if let fourthPrize = prize[3] as? Int{
self.fourthPlacePrize.text = "$ \(fourthPrize)"
}
}
if 5 <= prize.count {
if let fifthPrize = prize[4] as? Int{
self.fifthPlacePrize.text = "$ \(fifthPrize)"
}
}
}
}
else{
self.activityIndicator.stopAnimating()
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
}
}
else{
self.activityIndicator.stopAnimating()
var alert = UIAlertView(title:"Error" , message:"Sorry! error in details loading. " , delegate:self, cancelButtonTitle:"Dismiss")
alert.show()
}
}
}
@IBAction func registerForChallenge(sender: AnyObject) {
if self.directURL != ""{
var url = NSURL(string: self.directURL)
UIApplication.sharedApplication().openURL(url)
}
}
@IBAction func postToFaceBook(sender: AnyObject) {
if self.directURL != "" {
var socialVC :SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
socialVC.setInitialText("Hey check out this cool swift challenge \(self.directURL)")
self.presentViewController(socialVC, animated:true, completion:nil)
}
}
@IBAction func tweetChallengeDetails(sender: AnyObject) {
if self.directURL != "" {
var socialVC :SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
socialVC.setInitialText("Hey check out this cool swift challenge \(self.directURL)")
self.presentViewController(socialVC, animated:true, completion:nil)
}
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
self.navigationController?.popViewControllerAnimated(true)
}
// UIWebView will open links in safari
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked {
UIApplication.sharedApplication().openURL(request.URL)
return false
}
return true
}
}
| mit | da36e2dbdee80c39440f62932a54e25b | 30.394619 | 150 | 0.515212 | 6.17917 | false | false | false | false |
iWeslie/Ant | Ant/Ant/Tools/ImageScrollview.swift | 2 | 4817 | //
// File.swift
// AntDemo
//
// Created by LiuXinQiang on 2017/6/22.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
import Foundation
import SDWebImage
//定义传值闭包
typealias pageClosureType = (_ number : CGFloat?) -> Void
class ImageScrollview: UIScrollView ,UIScrollViewDelegate{
lazy var imageArray = Array<UIImage>()
var imageScrollview = UIScrollView()
var imageCount : Int?
//定义定时器对象
var timer : Timer?
//将申明闭包设置成属性
var pageNumBlock : pageClosureType?
convenience init(imageArray : NSArray) {
self.init()
self.imageScrollview = self
imageScrollview.frame = CGRect.init(x: 0, y: 0, width:screenWidth, height: 160)
imageScrollview.contentSize = CGSize(width: screenWidth * CGFloat(imageArray.count), height: 160)
imageScrollview.bounces = false
imageScrollview.delegate = self
imageScrollview.isPagingEnabled = true
imageScrollview.showsVerticalScrollIndicator = false
imageScrollview.showsHorizontalScrollIndicator = false
self.imageCount = imageArray.count
//取出数组中的相册图片
for i in 0..<imageArray.count {
let imageName = imageArray[i] as? String
let imageURL = NSURL.init(string: imageName!)
let cycleImageView = UIImageView()
//网络请求图片
cycleImageView.sd_setImage(with: imageURL as URL!, placeholderImage: UIImage.init(named: "moren"), options: [.continueInBackground , .lowPriority]){ (image, error, type, url) in
if(error == nil){
self.imageArray.append(image!)
}else{
print(error as Any)
}
}
cycleImageView.frame = CGRect.init(x: screenWidth * CGFloat(i), y: 0, width: screenWidth, height: 160)
imageScrollview.addSubview(cycleImageView)
//图片标题
let titleView = UIView(frame: CGRect.init(x: screenWidth * CGFloat(i), y: 125, width: screenWidth, height: 35))
titleView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3)
let textLable = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 35))
textLable.text = " \(i)"
textLable.textAlignment = .left
textLable.textColor = UIColor.white
titleView.addSubview(textLable)
imageScrollview.addSubview(titleView)
}
addTimer()
}
deinit {
self.removeTimer()
}
}
//MARK: - imageScrollView定时器
extension ImageScrollview {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.removeTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.addTimer()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let x = scrollView.contentOffset.x
let width = self.frame.width
if x >= 2*width {
// currentPage = (currentPage!+1) % self.images!.count
// pageControl!.currentPage = currentPage!
// refreshImages()
}
if x <= 0 {
// currentPage = (currentPage!+self.images!.count-1) % self.images!.count
// pageControl!.currentPage = currentPage!
// refreshImages()
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.setContentOffset(CGPoint(x: self.frame.width, y: 0), animated: true)
let pageNumber = scrollView.contentOffset.x / screenWidth
if (pageNumBlock != nil) {
pageNumBlock!(pageNumber)
}
}
//开启定时器
func addTimer(){
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ImageScrollview.nextImage), userInfo: nil, repeats: true)
}
//关闭定时器
func removeTimer(){
self.timer?.invalidate()
}
func nextImage(){
let page = Int(self.imageScrollview.contentOffset.x / screenWidth)
if (page == self.imageCount! - 1){
self.imageScrollview.contentOffset.x = 0
if (pageNumBlock != nil) {
pageNumBlock!(self.imageScrollview.contentOffset.x / screenWidth)
}
}else{
self.imageScrollview.contentOffset.x += screenWidth
if (pageNumBlock != nil) {
pageNumBlock!(self.imageScrollview.contentOffset.x / screenWidth)
}
}
}
}
| apache-2.0 | a6f9d2438bb4bdaa3738ea74dc794dd1 | 30.77027 | 189 | 0.588686 | 4.627953 | false | false | false | false |
aliceatlas/daybreak | Classes/SBHistory.swift | 1 | 2878 | /*
SBHistory.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
private func swindle<T, U>(fn: T -> U) (_ arg: AnyObject) -> U {
return fn(arg as! T)
}
class SBHistory: NSObject {
static let sharedHistory = SBHistory()
var history = WebHistory()
override init() {
super.init()
WebHistory.setOptionalSharedHistory(history)
readFromFile()
}
var URL: NSURL {
return NSURL(fileURLWithPath: SBHistoryFilePath)
}
var items: [WebHistoryItem] {
return history.orderedLastVisitedDays.flatMap{swindle(history.orderedItemsLastVisitedOnDay)($0) as! [WebHistoryItem]}
}
func itemsAtIndexes(indexes: NSIndexSet) -> [WebHistoryItem] {
return items.objectsAtIndexes(indexes)
}
func addNewItem(URLString URLString: String, title: String) {
let item = WebHistoryItem(URLString: URLString, title: title, lastVisitedTimeInterval: NSDate().timeIntervalSince1970)
history.addItems([item])
writeToFile()
}
func removeItems(inItems: [WebHistoryItem]) {
if !inItems.isEmpty {
history.removeItems(inItems)
writeToFile()
}
}
func removeAtIndexes(indexes: NSIndexSet) {
removeItems(itemsAtIndexes(indexes))
}
func removeAllItems() {
history.removeAllItems()
writeToFile()
}
func readFromFile() -> Bool {
return (try? history.loadFromURL(URL)) != nil
}
func writeToFile() -> Bool {
return (try? history.saveToURL(URL)) != nil
}
} | bsd-2-clause | d505b4f7f12c820926b9d4807feaa11b | 32.870588 | 126 | 0.707436 | 4.597444 | false | false | false | false |
taewan0530/TWKit | Pod/getConstraint/UIView+GetConstraint.swift | 1 | 3202 | //
// UIView+GetConstraint.swift
// EasyKit
//
// IBOulet로 Constraint를 참조 시키는게 개취가 아니라 만든 extension
//
//
// Created by kimtaewan on 2016. 4. 27..
// Copyright © 2016년 taewan. All rights reserved.
//
import UIKit
public extension UIView {
public func getConstraint(identifier: String) -> NSLayoutConstraint? {
if let superview = self.superview {
for constraint in superview.constraints where constraint.identifier == identifier {
return constraint
}
}
for constraint in self.constraints where constraint.identifier == identifier {
return constraint
}
return nil
}
public func getConstraint(attribute attr: NSLayoutAttribute) -> NSLayoutConstraint? {
let constrinsts = getConstraints(attribute: attr)
if constrinsts.count == 1 {
return constrinsts.first
}
//active deactive도 확인한번 해줄까.
return constrinsts.max {
$0.0.priority < $0.1.priority
}
}
public func getConstraints(attribute attr: NSLayoutAttribute) -> [NSLayoutConstraint] {
return getConstraints(item: self, attribute: attr)
}
public func getConstraints(item view: AnyObject, attribute attr1: NSLayoutAttribute) -> [NSLayoutConstraint] {
var results: [NSLayoutConstraint] = []
if let superview = self.superview {
results += UIView.targetFromConstraints(target: superview, item: view, attribute: attr1)
}
results += UIView.targetFromConstraints(target: self, item: view, attribute: attr1)
return results
}
private class func targetFromConstraints(target: AnyObject, item view: AnyObject?, attribute attr: NSLayoutAttribute) -> [NSLayoutConstraint] {
var results: [NSLayoutConstraint] = []
for constraint in target.constraints {
if "NSContentSizeLayoutConstraint" == classNameAsString(obj: constraint) {
continue
}
let targetAttribute: NSLayoutAttribute
if "_UILayoutGuide" == classNameAsString(obj: constraint.firstItem) {
targetAttribute = constraint.secondAttribute
} else {
targetAttribute = constraint.firstAttribute
}
let firstItemEqual: Bool
let secondItemEqual: Bool
if view == nil {
firstItemEqual = constraint.secondItem === target
secondItemEqual = constraint.firstItem === target
} else {
firstItemEqual = constraint.firstItem === view
secondItemEqual = constraint.secondItem === view
}
guard targetAttribute == attr && (firstItemEqual || secondItemEqual) else {
continue
}
results.append(constraint)
}
return results
}
static func classNameAsString(obj: AnyObject) -> String {
return type(of: obj).description().components(separatedBy:"__").last!
}
}
| mit | be0da055e721950cc1ae29c0f2ff5394 | 32.168421 | 147 | 0.596319 | 5.082258 | false | false | false | false |
Fenrikur/ef-app_ios | EurofurenceTests/Presenter Tests/Event Detail/Test Doubles/FakeEventsService.swift | 1 | 2598 | import EurofurenceModel
import EurofurenceModelTestDoubles
import Foundation
class FakeEventsService: EventsService {
var runningEvents: [Event] = []
var upcomingEvents: [Event] = []
var allEvents: [Event] = []
var favourites: [EventIdentifier] = []
init(favourites: [EventIdentifier] = []) {
self.favourites = favourites
}
var events = [Event]()
func fetchEvent(identifier: EventIdentifier) -> Event? {
return events.first(where: { $0.identifier == identifier })
}
private var observers = [EventsServiceObserver]()
func add(_ observer: EventsServiceObserver) {
observers.append(observer)
observer.eventsDidChange(to: allEvents)
observer.runningEventsDidChange(to: runningEvents)
observer.upcomingEventsDidChange(to: upcomingEvents)
observer.favouriteEventsDidChange(favourites)
}
private(set) var lastProducedSchedule: FakeEventsSchedule?
func makeEventsSchedule() -> EventsSchedule {
let schedule = FakeEventsSchedule(events: allEvents)
lastProducedSchedule = schedule
return schedule
}
private(set) var lastProducedSearchController: FakeEventsSearchController?
func makeEventsSearchController() -> EventsSearchController {
let searchController = FakeEventsSearchController()
lastProducedSearchController = searchController
return searchController
}
}
extension FakeEventsService {
func stubSomeFavouriteEvents() {
allEvents = [FakeEvent].random(minimum: 3)
favourites = Array(allEvents.dropFirst()).map({ $0.identifier })
}
func simulateEventFavourited(identifier: EventIdentifier) {
favourites.append(identifier)
observers.forEach { $0.favouriteEventsDidChange(favourites) }
}
func simulateEventFavouritesChanged(to identifiers: [EventIdentifier]) {
favourites = identifiers
observers.forEach { $0.favouriteEventsDidChange(favourites) }
}
func simulateEventUnfavourited(identifier: EventIdentifier) {
if let idx = favourites.firstIndex(of: identifier) {
favourites.remove(at: idx)
}
observers.forEach { $0.favouriteEventsDidChange(favourites) }
}
func simulateEventsChanged(_ events: [Event]) {
lastProducedSchedule?.simulateEventsChanged(events)
}
func simulateDaysChanged(_ days: [Day]) {
lastProducedSchedule?.simulateDaysChanged(days)
}
func simulateDayChanged(to day: Day?) {
lastProducedSchedule?.simulateDayChanged(to: day)
}
}
| mit | a9244aba8777e9fb004c8c2a75078d20 | 29.928571 | 78 | 0.69592 | 5.084149 | false | false | false | false |
DianQK/rx-sample-code | CustomRefresh/Support/NumberSection.swift | 2 | 1790 | //
// NumberSection.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 1/7/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxDataSources
// MARK: Data
struct NumberSection {
var header: String
var numbers: [IntItem]
var updated: Date
init(header: String, numbers: [Item], updated: Date) {
self.header = header
self.numbers = numbers
self.updated = updated
}
}
struct IntItem {
let number: Int
let date: Date
}
// MARK: Just extensions to say how to determine identity and how to determine is entity updated
extension NumberSection
: AnimatableSectionModelType {
typealias Item = IntItem
typealias Identity = String
var identity: String {
return header
}
var items: [IntItem] {
return numbers
}
init(original: NumberSection, items: [Item]) {
self = original
self.numbers = items
}
}
extension NumberSection
: CustomDebugStringConvertible {
var debugDescription: String {
return "NumberSection(header: \"\(self.header)\", numbers: \(numbers.debugDescription), updated: date)"
}
}
extension IntItem
: IdentifiableType
, Equatable {
typealias Identity = Int
var identity: Int {
return number
}
}
// equatable, this is needed to detect changes
func == (lhs: IntItem, rhs: IntItem) -> Bool {
return lhs.number == rhs.number && lhs.date == rhs.date
}
// MARK: Some nice extensions
extension IntItem
: CustomDebugStringConvertible {
var debugDescription: String {
return "IntItem(number: \(number), date: date)"
}
}
extension IntItem
: CustomStringConvertible {
var description: String {
return "\(number)"
}
}
| mit | 2a669243c5c704579c4ca8057ad65736 | 18.659341 | 111 | 0.648407 | 4.4725 | false | false | false | false |
DarlingXIe/WeiBoProject | WeiBo/WeiBo/Classes/ViewModel/XDLHomeViewModel.swift | 1 | 5254 | //
// XDLStatusViewModel.swift
// WeiBo
//
// Created by DalinXie on 16/9/18.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
import SDWebImage
class XDLHomeViewModel: NSObject {
// var statusArray: [XDLStatus]?
var statusArray: [XDLStatusViewModel]?
static let shareModel:XDLHomeViewModel = XDLHomeViewModel()
func loadData(pullUp: Bool, completion:@escaping (Bool,Int)->()){
//let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
var max_id: Int64 = 0
var sinceId: Int64 = 0
//if pullUp is true, set the value of max_id for the last datemodel, the function request will load the pullUpDate with this max_id
if pullUp{
if let id = statusArray?.last?.status?.id{
max_id = id - 1
}
}else{
if let id = statusArray?.first?.status?.id{
sinceId = id
}
}
XDLStatusDAL.loadData(maxId:max_id, sinceId:sinceId) { (result) in
guard let dictArray = result else{
print("request error")
completion(false,0)
return
}
// let parameters = [
//
// "access_token" : XDLUserAccountViewModel.shareModel.access_token ?? " ",
// "max_id": "\(max_id)",
//
// "since_id": "\(sinceId)"
// ]
// XDLNetWorkTools.sharedTools.request(method: .Get, urlSting: urlString, parameters: parameters) { (response, error) in
// if response == nil && error != nil{
// print("-------\(error)")
// return
// }
// print("******\(response)")
// // the array of statuses with dict of array
// guard let dictArray = (response! as! [String : Any])["statuses"] as? [[String : Any]] else{
//
// return
// }
//print("*&*&*&*&*&*&*&*\(dictArray)")
// change the array of stauses with dict to the model of XDLStatus array
// XDLStatusDAL.loadData(status: dictArray)
let modelArray = NSArray.yy_modelArray(with: XDLStatus.self, json: dictArray) as! [XDLStatus]
//dataSaveTocache
//print("*&*&*&*\(modelArray)")
var tempArray = [XDLStatusViewModel]()
for status in modelArray{
//print---oriPictureWithText..
if let pic_urls = status.pic_urls, pic_urls.count > 0 {
print(status.pic_urls?.first?.thumbnail_pic)
}
let viewModel = XDLStatusViewModel()
viewModel.status = status
tempArray.append(viewModel)
}
//self.statusArray = modelArray
// if the first load data, the self.status would be nill and save the first load modelData
// if(self.statusArray == nil){
//
// self.statusArray = tempArray
// }
if self.statusArray == nil {
self.statusArray = [XDLStatusViewModel]()
}
if pullUp{
self.statusArray = self.statusArray! + tempArray
}else{
// if next load pullDown......
self.statusArray = tempArray + self.statusArray!
}
//completion(true)
// self.tableView.reloadData()
//download the singlePic for origView
self.cacheSingleImage(status: tempArray, completion: completion)
}
}
private func cacheSingleImage(status:[XDLStatusViewModel], completion:@escaping (Bool,Int)->()){
// group to download images when it's completed, recall the block for inform controller
let group = DispatchGroup.init()
for piValue in status{
guard let pic_urls = (piValue.status?.pic_urls?.count == 1) ? piValue.status?.pic_urls : piValue.status?.retweeted_status?.pic_urls, pic_urls.count == 1 else{
continue
}
let photoInfo = pic_urls.first!
let urlString = photoInfo.thumbnail_pic
let url = URL(string: urlString ?? "")
group.enter()
SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, error, _, _, _) in
photoInfo.size = image?.size
print("download completed:")
group.leave()
})
group.notify(queue: DispatchQueue.main, execute: {
print("download all pics")
completion(true,status.count)
})
}
}
}
| mit | c6382326a2328ddb51330d76ce0c21cc | 31.214724 | 170 | 0.477052 | 4.884651 | false | false | false | false |
RoverPlatform/rover-ios-beta | Example/Example/AppDelegate.swift | 1 | 10175 | //
// AppDelegate.swift
// Example
//
// Created by Andrew Clunis on 2019-04-26.
// Copyright © 2019 Rover Labs Inc. All rights reserved.
//
import os.log
import Rover
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Pass your account token from the Rover Settings app to the Rover SDK.
Rover.accountToken = "<YOUR_SDK_TOKEN>"
// This method demonstrates how to observe the Rover events mentioned above in your own app.
observeRoverNotifications()
return true
}
// This app delegate method is called when any app (your own included) calls the
// `open(_:options:completionHandler:)` method on `UIApplication` with a URL that matches one of the schemes setup
// in your `Info.plist` file. These custom URL schemes are commonly referred to as "deep links". This Example app
// uses a custom URL scheme `example` which is configured in Example/Example/Info.plist.
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
// You will need to setup a specific URL structure to be used for presenting Rover experiences in your app. The
// simplest approach is to use a specific URL path/host and include the experience ID and (optional) campaign
// ID as query parameters. The below example demonstrates how to route URLs in the format
// `example://experience?id=<EXPERIENCE_ID>&campaignID=<CAMPAIGN_ID>` to a Rover experience.
if url.host == "experience" {
guard let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else {
return false
}
guard let id = queryItems.first(where: { $0.name == "id" })?.value else {
return false
}
let campaignID = queryItems.first(where: { $0.name == "campaignID" })?.value
// you can optionally pass in a screen ID to navigate to immediately rather than starting at the home screen.
let screenID = queryItems.first(where: { $0.name == "screenID" })?.value
// Instantiate a `RoverViewController` and call the `loadExperience(id:campaignID)` method to load the
// experience whose id matches the value passed in the query parameter.
let roverViewController = RoverViewController()
roverViewController.loadExperience(id: id, campaignID: campaignID, initialScreenID: screenID)
// Use Rover's UIApplication.present() helper extension method to find the currently active view controller,
// and present the RoverViewController on top.
app.present(roverViewController, animated: true)
return true
}
// If the standard approach above does not meet your needs you can setup any arbitrary URL to launch a Rover
// experience as long as you can extract the experience ID from it. For example you could use a path based
// approach which includes the experience ID and optional campaign ID as path components instead of query
// string parameters. The below example demonstrates how to route URLs in the format
// `example://experience/<EXPERIENCE_ID>/<CAMPAIGN_ID>` to a Rover experience.
if let host = url.host, host.starts(with: "experience") {
let components = host.components(separatedBy: "/")
guard components.indices.contains(1) else {
return false
}
let id = components[1]
let campaignID = components.indices.contains(2) ? components[2] : nil
let roverViewController = RoverViewController()
roverViewController.loadExperience(id: id, campaignID: campaignID)
app.present(roverViewController, animated: true)
return true
}
return false
}
// This app delegate method is called in response to the user opening a Universal Link, amongst other things such
// as Handoff.
func application(_ app: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
// Check `activityType` to see if this method was called in response to a Universal Link.
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL else {
return false
}
// Check the URL to see if the domain matches the one assigned to your Rover account. The `example.rover.io`
// domain used below needs to be set in your App Links configuration and entitlements. See the documentation
// for further details.
if url.host == "example.rover.io" {
// Instantiate a `RoverViewController` and call the `loadExperience(universalLink:campaignID)` method to
// load the experience whose associated universal link matches the url in the user activity.
let roverViewController = RoverViewController()
roverViewController.loadExperience(universalLink: url)
app.present(roverViewController, animated: true)
return true
}
return false
}
// This method demonstrates how to observe various Rover "events" such as when an experience is viewed or a
// button in a Rover experience is tapped. This is particularly useful for integrating with your mobile analytics
// or marketing auotmation provider. The Rover documentation provides specific examples for many of the popular
// providers.
func observeRoverNotifications() {
NotificationCenter.default.addObserver(forName: ExperienceViewController.experiencePresentedNotification, object: nil, queue: nil) { notification in
let campaignID = notification.userInfo?[ExperienceViewController.campaignIDUserInfoKey] as? String
let experience = notification.userInfo?[ExperienceViewController.experienceUserInfoKey] as! Experience
os_log("Experience Presented: \"%@\" (campaignID=%@)", experience.name, campaignID ?? "none")
}
NotificationCenter.default.addObserver(forName: ExperienceViewController.experienceDismissedNotification, object: nil, queue: nil) { notification in
let campaignID = notification.userInfo?[ExperienceViewController.campaignIDUserInfoKey] as? String
let experience = notification.userInfo?[ExperienceViewController.experienceUserInfoKey] as! Experience
os_log("Experience Dismissed: \"%@\" (campaignID=%@)", experience.name, campaignID ?? "none")
}
NotificationCenter.default.addObserver(forName: ExperienceViewController.experienceViewedNotification, object: nil, queue: nil) { notification in
let campaignID = notification.userInfo?[ExperienceViewController.campaignIDUserInfoKey] as? String
let experience = notification.userInfo?[ExperienceViewController.experienceUserInfoKey] as! Experience
let duration = notification.userInfo?[ExperienceViewController.durationUserInfoKey] as! Double
os_log("Experience Viewed: \"%@\" (campaignID=%@), for %f seconds", experience.name, campaignID ?? "none", duration)
}
NotificationCenter.default.addObserver(forName: ScreenViewController.screenPresentedNotification, object: nil, queue: nil) { notification in
let screen = notification.userInfo?[ScreenViewController.screenUserInfoKey] as! Screen
os_log("Screen Presented: \"%@\"", screen.name)
}
NotificationCenter.default.addObserver(forName: ScreenViewController.screenDismissedNotification, object: nil, queue: nil) { notification in
let screen = notification.userInfo?[ScreenViewController.screenUserInfoKey] as! Screen
os_log("Screen Dismissed: \"%@\"", screen.name)
}
NotificationCenter.default.addObserver(forName: ScreenViewController.screenViewedNotification, object: nil, queue: nil) { notification in
let screen = notification.userInfo?[ScreenViewController.screenUserInfoKey] as! Screen
let duration = notification.userInfo?[ScreenViewController.durationUserInfoKey] as! Double
os_log("Screen Viewed: \"%@\", for %f seconds", screen.name, duration)
}
NotificationCenter.default.addObserver(forName: ScreenViewController.blockTappedNotification, object: nil, queue: nil) { notification in
let block = notification.userInfo?[ScreenViewController.blockUserInfoKey] as! Block
os_log("Block Tapped: \"%@\"", block.name)
}
NotificationCenter.default.addObserver(forName: ScreenViewController.pollAnsweredNotification, object: nil, queue:nil) { notification in
let experience = notification.userInfo?[ExperienceViewController.experienceUserInfoKey] as! Experience
let campaignID = notification.userInfo?[ExperienceViewController.campaignIDUserInfoKey] as? String
let screen = notification.userInfo?[ScreenViewController.screenUserInfoKey] as! Screen
let block = notification.userInfo?[ScreenViewController.blockUserInfoKey] as! PollBlock
let option = notification.userInfo?[ScreenViewController.optionUserInfoKey] as! PollOption
os_log(
"Poll Answered: \"%@\" (campaignID=%@,experienceID=%@,screenID=%@,pollID=%@) answered with option \"%@\" (optionID=%@)",
block.poll.question.rawValue,
campaignID ?? "none",
experience.id,
screen.id,
block.pollID(containedBy: experience.id),
option.text.rawValue,
option.id
)
}
}
}
| mit | 743cb6690095861f61f8b49eec89f675 | 58.847059 | 159 | 0.675349 | 5.2606 | false | false | false | false |
youngsoft/TangramKit | TangramKitDemo/linerLayoutDemo/LLTest4ViewController.swift | 1 | 6523 | //
// LLTest4ViewController.swift
// TangramKit
//
// Created by yant on 10/5/16.
// Copyright © 2016年 youngsoft. All rights reserved.
//
import UIKit
/**
*4.LinearLayout - Wrap content
*/
class LLTest4ViewController: UIViewController {
weak var rootLayout :TGLinearLayout!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func loadView() {
/*
这个例子详细说明tg_width, tg_height设置为.wrap的意义、以及边界线性的设定、以及布局中可局部缩放背景图片的设定方法。
*/
self.edgesForExtendedLayout = UIRectEdge(rawValue:0) //设置视图控制器中的视图尺寸不延伸到导航条或者工具条下面。您可以注释这句代码看看效果。
super.loadView()
let contentView = UIView()
contentView.backgroundColor = CFTool.color(5)
self.view.addSubview(contentView)
contentView.tg_width.equal(.wrap)
contentView.tg_height.equal(.wrap) //如果一个非布局父视图里面有布局子视图,那么这个非布局父视图也是可以将高度和宽度设置为.wrap的,他表示的意义是这个非布局父视图的尺寸由里面的布局子视图的尺寸来决定的。还有一个场景是非布局父视图是一个UIScrollView。他是左右滚动的,但是滚动视图的高度是由里面的布局子视图确定的,而宽度则是和窗口保持一致。这样只需要将滚动视图的宽度设置为和屏幕保持一致,高度设置为.wrap,并且把一个水平线性布局添加到滚动视图即可。
let rootLayout = TGLinearLayout(.vert)
rootLayout.layer.borderWidth = 1
rootLayout.layer.borderColor = UIColor.lightGray.cgColor
rootLayout.tg_height.equal(.wrap)
rootLayout.tg_width.equal(.wrap)
rootLayout.tg_padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
rootLayout.tg_zeroPadding = false //这个属性设置为false时表示当布局视图的尺寸是wrap也就是由子视图决定时并且在没有任何子视图是不会参与布局视图高度的计算的。您可以在这个DEMO的测试中将所有子视图都删除掉,看看效果,然后注释掉这句代码看看效果。
rootLayout.tg_vspace = 5
contentView.addSubview(rootLayout)
self.rootLayout = rootLayout
self.rootLayout.addSubview(self.addWrapContentLayout())
}
}
//MARK: - Layout Construction
extension LLTest4ViewController
{
internal func addWrapContentLayout() -> TGLinearLayout
{
let wrapContentLayout = TGLinearLayout(.horz)
wrapContentLayout.tg_height.equal(.wrap)
wrapContentLayout.tg_width.equal(.wrap)
wrapContentLayout.tg_padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
wrapContentLayout.tg_hspace = 5
/*
布局视图的tg_backgroundImage的属性的内部实现是通过设置视图的layer的content属性来实现的。因此如果我们希望实现具有拉升效果的
背景图片的话。则可以设置布局视图的layer.contentCenter属性。这个属性的意义请参考CALayer方面的介绍。
*/
wrapContentLayout.tg_backgroundImage = UIImage(named: "bk2")
wrapContentLayout.layer.contentsCenter = CGRect(x: 0.1, y: 0.1, width: 0.5, height: 0.5)
//四周的边线
wrapContentLayout.tg_boundBorderline = TGBorderline(color: .red, headIndent:10, tailIndent:30)
let actionLayout = TGLinearLayout(.vert)
actionLayout.layer.borderWidth = 1
actionLayout.layer.borderColor = CFTool.color(9).cgColor
actionLayout.tg_padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
actionLayout.tg_vspace = 5
actionLayout.tg_width.equal(.wrap)
actionLayout.tg_height.equal(.wrap)
wrapContentLayout.addSubview(actionLayout)
actionLayout.addSubview(self.addActionButton(NSLocalizedString("add vert layout", comment:"") ,tag:100))
actionLayout.addSubview(self.addActionButton(NSLocalizedString("add vert button", comment:""), tag:500))
wrapContentLayout.addSubview(self.addActionButton(NSLocalizedString("add horz button", comment:""), tag:200))
wrapContentLayout.addSubview(self.addActionButton(NSLocalizedString("remove layout", comment:""), tag:300))
return wrapContentLayout
}
internal func addActionButton(_ title: String , tag :NSInteger) -> UIButton
{
let button = UIButton(type:.system)
button.addTarget(self ,action:#selector(handleAction), for:.touchUpInside)
button.setTitle(title ,for:.normal)
button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.font = CFTool.font(14)
button.backgroundColor = CFTool.color(14)
button.layer.cornerRadius = 10
button.layer.borderColor = UIColor.lightGray.cgColor
button.layer.borderWidth = 0.5
button.tag = tag
button.tg_height.equal(50)
button.tg_width.equal(80)
return button
}
}
//MARK: - Handle Method
extension LLTest4ViewController
{
@objc internal func handleAction(_ sender :UIButton)
{
if (sender.tag == 100)
{
self.rootLayout.addSubview(self.addWrapContentLayout())
}
else if (sender.tag == 200)
{
let actionLayout = sender.superview as! TGLinearLayout
actionLayout.addSubview(self.addActionButton(NSLocalizedString("remove self", comment:""), tag:400))
}
else if (sender.tag == 300)
{
let actionLayout = sender.superview as! TGLinearLayout
actionLayout.removeFromSuperview()
}
else if (sender.tag == 400)
{
sender.removeFromSuperview()
}
else if (sender.tag == 500)
{
let addLayout = sender.superview as! TGLinearLayout
addLayout.addSubview(self.addActionButton(NSLocalizedString("remove self", comment:""), tag:400))
}
}
}
| mit | 38545a7733001029f52d011ff876f6ca | 32.73494 | 260 | 0.6525 | 3.963199 | false | false | false | false |
eoger/firefox-ios | Storage/SyncQueue.swift | 4 | 2009 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Deferred
import SwiftyJSON
public struct SyncCommand: Equatable {
public let value: String
public var commandID: Int?
public var clientGUID: GUID?
let version: String?
public init(value: String) {
self.value = value
self.version = nil
self.commandID = nil
self.clientGUID = nil
}
public init(id: Int, value: String) {
self.value = value
self.version = nil
self.commandID = id
self.clientGUID = nil
}
public init(id: Int?, value: String, clientGUID: GUID?) {
self.value = value
self.version = nil
self.clientGUID = clientGUID
self.commandID = id
}
/**
* Sent displayURI commands include the sender client GUID.
*/
public static func displayURIFromShareItem(_ shareItem: ShareItem, asClient sender: GUID) -> SyncCommand {
let jsonObj: [String: Any] = [
"command": "displayURI",
"args": [shareItem.url, sender, shareItem.title ?? ""]
]
return SyncCommand(value: JSON(jsonObj).stringValue()!)
}
public func withClientGUID(_ clientGUID: String?) -> SyncCommand {
return SyncCommand(id: self.commandID, value: self.value, clientGUID: clientGUID)
}
}
public func ==(lhs: SyncCommand, rhs: SyncCommand) -> Bool {
return lhs.value == rhs.value
}
public protocol SyncCommands {
func deleteCommands() -> Success
func deleteCommands(_ clientGUID: GUID) -> Success
func getCommands() -> Deferred<Maybe<[GUID: [SyncCommand]]>>
func insertCommand(_ command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>>
func insertCommands(_ commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Maybe<Int>>
}
| mpl-2.0 | ca3cb74640e5d2e776a4e65d1af7ddfe | 29.907692 | 110 | 0.647088 | 4.386463 | false | false | false | false |
velvetroom/columbus | Source/View/CreateSearch/VCreateSearchBaseListCell+Factory.swift | 1 | 1984 | import MapKit
extension VCreateSearchBaseListCell
{
//MARK: private
private func factoryTitle(model:MKLocalSearchCompletion) -> NSAttributedString
{
let highlightRanges:[NSValue] = model.titleHighlightRanges
let string:NSMutableAttributedString = NSMutableAttributedString(
string:model.title,
attributes:attributesTitle)
for highlightRange:NSValue in highlightRanges
{
let range:NSRange = highlightRange.rangeValue
string.addAttributes(
attributesTitleHighlighted,
range:range)
}
return string
}
private func factorySubtitle(model:MKLocalSearchCompletion) -> NSAttributedString?
{
let subtitle:String = model.subtitle
guard
subtitle.count > 0
else
{
return nil
}
let highlightRanges:[NSValue] = model.subtitleHighlightRanges
let string:NSMutableAttributedString = NSMutableAttributedString(
string:subtitle,
attributes:attributesSubtitle)
for highlightRange:NSValue in highlightRanges
{
let range:NSRange = highlightRange.rangeValue
string.addAttributes(
attributesSubtitleHighlighted,
range:range)
}
return string
}
//MARK: internal
func factoryText(model:MKLocalSearchCompletion) -> NSAttributedString
{
let title:NSAttributedString = factoryTitle(model:model)
let string:NSMutableAttributedString = NSMutableAttributedString()
string.append(title)
if let subtitle:NSAttributedString = factorySubtitle(model:model)
{
string.append(breakLine)
string.append(subtitle)
}
return string
}
}
| mit | bd354534c4f5817faed4040d8b32842a | 25.810811 | 86 | 0.588206 | 6.338658 | false | false | false | false |
djfink-carglass/analytics-ios | AnalyticsTests/ContextTest.swift | 1 | 2200 | //
// ContextTest.swift
// Analytics
//
// Created by Tony Xiao on 9/20/16.
// Copyright © 2016 Segment. All rights reserved.
//
import Quick
import Nimble
import SwiftTryCatch
import Analytics
class ContextTests: QuickSpec {
override func spec() {
var analytics: SEGAnalytics!
beforeEach {
let config = SEGAnalyticsConfiguration(writeKey: "foobar")
analytics = SEGAnalytics(configuration: config)
}
it("throws when used incorrectly") {
var context: SEGContext?
var exception: NSException?
SwiftTryCatch.tryRun({
context = SEGContext()
}, catchRun: { e in
exception = e
}, finallyRun: nil)
expect(context).to(beNil())
expect(exception).toNot(beNil())
}
it("initialized correctly") {
let context = SEGContext(analytics: analytics)
expect(context._analytics) == analytics
expect(context.eventType) == SEGEventType.undefined
}
it("accepts modifications") {
let context = SEGContext(analytics: analytics)
let newContext = context.modify { context in
context.userId = "sloth"
context.eventType = .track;
}
expect(newContext.userId) == "sloth"
expect(newContext.eventType) == SEGEventType.track;
}
it("modifies copy in debug mode to catch bugs") {
let context = SEGContext(analytics: analytics).modify { context in
context.debug = true
}
expect(context.debug) == true
let newContext = context.modify { context in
context.userId = "123"
}
expect(context) !== newContext
expect(newContext.userId) == "123"
expect(context.userId).to(beNil())
}
it("modifies self in non-debug mode to optimize perf.") {
let context = SEGContext(analytics: analytics).modify { context in
context.debug = false
}
expect(context.debug) == false
let newContext = context.modify { context in
context.userId = "123"
}
expect(context) === newContext
expect(newContext.userId) == "123"
expect(context.userId) == "123"
}
}
}
| mit | bea6c65a441ced89d205b9e9c61d346c | 24.275862 | 72 | 0.608004 | 4.398 | false | false | false | false |
instacrate/tapcrate-api | Sources/api/Library/Contexts/Contexts.swift | 1 | 1134 | //
// Contexts.swift
// tapcrate-api
//
// Created by Hakon Hanesand on 6/30/17.
//
import Vapor
import HTTP
import Fluent
import FluentProvider
public struct ParentContext<Parent: Entity>: Context {
public let parent_id: Identifier
init(_ parent: Identifier?) throws {
guard let identifier = parent else {
throw Abort.custom(status: .internalServerError, message: "Parent context does not have id")
}
parent_id = identifier
}
}
public struct SecondaryParentContext<Parent: Entity, Secondary: Entity>: Context {
public let parent_id: Identifier
public let secondary_id: Identifier
init(_ _parent: Identifier?, _ _secondary: Identifier?) throws {
guard let parent = _parent else {
throw Abort.custom(status: .internalServerError, message: "Parent context does not have parent id")
}
guard let secondary = _secondary else {
throw Abort.custom(status: .internalServerError, message: "Parent context does not have secondary id")
}
self.parent_id = parent
self.secondary_id = secondary
}
}
| mit | 5649c36148306b032f97025856e84ed0 | 25.372093 | 114 | 0.663139 | 4.464567 | false | false | false | false |
gokselkoksal/GKValidator | Pod/Classes/Core/Validators/FieldValidationDelegate.swift | 1 | 3634 | //
// FieldModel.swift
// EruValidator
//
// Created by Göksel Köksal on 28/06/15.
// Copyright © 2015 Eru. All rights reserved.
//
import Foundation
/// Name of notification which is fired upon a field change.
public let FieldDidChangeNotification: String = "FieldDidChangeNotification"
/**
Protocol to be adapted by validatable fields.
*/
@objc public protocol ValidatableField {
/// Value in the field. For example `self.text` for a `UITextField`.
var fieldValue: Any? { get set }
/**
Adds a target-action for field change event.
- Parameters:
- target: Target object.
- action: Selector to look for.
*/
func addFieldValueChangedEvent(forTarget target: AnyObject?, action: Selector)
/**
Removes a target-action for field change event.
- Parameters:
- target: Target object.
- action: Selector to look for.
*/
func removeFieldValueChangedEvent(fromTarget target: AnyObject?, action: Selector)
}
/**
`FieldValidationDelegate` binds a validator to a field to take care of validation with no effort.
*/
open class FieldValidationDelegate<ValidatableType> : NSObject {
/// Field to be validated.
open weak var field: ValidatableField?
/// Validator to validate field with.
open var validator: FieldValidator<ValidatableType>
fileprivate var storedFieldValue: ValidatableType?
/**
Creates an instance of this class with given field and validator.
- Parameters:
- field: Field to be validated.
- validator: Validator to validate field with.
*/
public init(field: ValidatableField?, validator: FieldValidator<ValidatableType>) {
self.validator = validator
self.field = field
super.init()
self.field?.addFieldValueChangedEvent(forTarget: self, action: #selector(FieldValidationDelegate.fieldValueDidChange(_:)))
}
// MARK: Public methods
/**
Validates the field with its current value.
- Parameter type: Type of the validation.
- Returns: Result of the validation.
*/
@discardableResult
open func validateForType(_ type: ValidationType) -> ValidationResult {
let valueToValidate = valueToValidateForField(field)
return validator.validateValue(valueToValidate, forType: type)
}
// MARK: Actions
@objc func fieldValueDidChange(_ field: ValidatableField!) {
let valueToValidate = valueToValidateForField(field)
switch validator.validateInput(valueToValidate) {
case .success:
storedFieldValue = valueToValidate
validateForType(.eligibility)
validateForType(.completeness)
postFieldModelDidChangeNotification()
default:
field.fieldValue = storedFieldValue
}
}
// MARK: Private
fileprivate func valueToValidateForField(_ field: ValidatableField?) -> ValidatableType? {
let value = field?.fieldValue as? ValidatableType
let valueToValidate: ValidatableType?
// Empty string should not be validated. Pass nil instead.
if let string = value as? String, string.count == 0 {
valueToValidate = nil
}
else {
valueToValidate = value
}
return valueToValidate
}
fileprivate func postFieldModelDidChangeNotification() {
NotificationCenter.default.post(name: Notification.Name(rawValue: FieldDidChangeNotification), object: self)
}
}
| mit | d9fc8cec4731f846d7937a9f6b0ab105 | 29.512605 | 130 | 0.651887 | 5.02213 | false | false | false | false |
XSega/Words | Words/Scenes/Trainings/EngRuTraining/EngRuTrainingViewController.swift | 1 | 6600 | //
// EngRuTrainingViewController.swift
// Words
//
// Created by Sergey Ilyushin on 30/07/2017.
// Copyright (c) 2017 Sergey Ilyushin. All rights reserved.
//
import UIKit
protocol IEngRuTrainingView: class {
func display(word: String)
func display(translations: [String])
func display(imageData: Data?)
func displayCorrectAlert()
func displayWrongAlert()
func displaySkipAlert()
func displayCorrectVariant(index: Int)
func displayWrongVariant(index: Int)
func resetAlerts()
func displayFinish()
}
class EngRuTrainingViewController: TrainingViewController, IEngRuTrainingView {
// MARK:- Outlets
@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var alertLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var speakerContainer: UIView!
@IBOutlet weak var meaningContainer: UIView!
@IBOutlet weak var speakerButton: UIButton!
@IBOutlet weak var variant1Button: UIButton!
@IBOutlet weak var variant2Button: UIButton!
@IBOutlet weak var variant3Button: UIButton!
@IBOutlet weak var variant4Button: UIButton!
// MARK: Scene vars
var interactor: ITrainingInteractor!
var router: (NSObjectProtocol & ITrainingRouter & ITrainingDataPassing)!
// MARK: Object lifecycle
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: Setup
private func setup() {
let viewController = self
let interactor = TrainingInteractor()
let presenter = EngRuTrainingPresenter()
let router = TrainingRouter()
viewController.interactor = interactor
viewController.router = router
interactor.presenter = presenter
presenter.view = viewController
router.viewController = viewController
router.dataStore = interactor
}
// MARK: Routing
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let scene = segue.identifier {
let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
if let router = router, router.responds(to: selector) {
router.perform(selector, with: segue)
}
}
}
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
start()
}
// MARK: Do something
func start() {
interactor?.start()
}
func finish() {
performSegue(withIdentifier: "FinishTraining", sender: self)
}
func checkVariant(index: Int) {
interactor.checkVariantIndex(index)
view.isUserInteractionEnabled = false
}
// MARK: IEngRuTrainingView
func display(word: String) {
resetAlerts()
wordLabel.text = word
alertLabel.text = "Remember the translation"
alertLabel.textColor = UIColor.hintTextColor
view.isUserInteractionEnabled = true
speakerContainer.isHidden = false
imageView.isHidden = true
}
func display(translations: [String]) {
self.variant1Button.setTitle(translations[0], for: .normal)
self.variant2Button.setTitle(translations[1], for: .normal)
self.variant3Button.setTitle(translations[2], for: .normal)
self.variant4Button.setTitle(translations[3], for: .normal)
}
func display(imageData: Data?){
speakerContainer.isHidden = true
imageView.isHidden = false
if let imageData = imageData {
self.imageView.image = UIImage(data: imageData)
}
}
func displayCorrectAlert() {
meaningContainer.backgroundColor = UIColor.correct
alertLabel.text = "Your answered correctly"
alertLabel.textColor = UIColor.white
}
func displayWrongAlert() {
meaningContainer.backgroundColor = UIColor.wrong
alertLabel.text = "Your answer is incorrect"
alertLabel.textColor = UIColor.white
}
func displaySkipAlert() {
meaningContainer.backgroundColor = UIColor.skip
alertLabel.text = "Let's learn, remember!"
alertLabel.textColor = UIColor.white
}
func displayCorrectVariant(index: Int) {
let correctButton = variantButtonAtIndex(index)
correctButton.backgroundColor = UIColor.correct
correctButton.setTitleColor(UIColor.white, for: .normal)
}
func displayWrongVariant(index: Int) {
let wrongButton = variantButtonAtIndex(index)
wrongButton.backgroundColor = UIColor.wrong
wrongButton.setTitleColor(UIColor.white, for: .normal)
}
func resetAlerts() {
meaningContainer.backgroundColor = UIColor.blueBackground
variant1Button.backgroundColor = UIColor.white
variant2Button.backgroundColor = UIColor.white
variant3Button.backgroundColor = UIColor.white
variant4Button.backgroundColor = UIColor.white
variant1Button.setTitleColor(UIColor.varianTextColor, for: .normal)
variant2Button.setTitleColor(UIColor.varianTextColor, for: .normal)
variant3Button.setTitleColor(UIColor.varianTextColor, for: .normal)
variant4Button.setTitleColor(UIColor.varianTextColor, for: .normal)
}
func displayFinish() {
finish()
}
// MARK: IBActions
@IBAction func skipAction(_ button: UIButton) {
interactor.skipMeaning()
}
@IBAction func checkVariant1(_ button: UIButton) {
checkVariant(index: 0)
}
@IBAction func checkVariant2(_ button: UIButton) {
checkVariant(index: 1)
}
@IBAction func checkVariant3(_ button: UIButton) {
checkVariant(index: 2)
}
@IBAction func checkVariant4(_ button: UIButton) {
checkVariant(index: 3)
}
@IBAction func listenAgain(_ button: UIButton) {
interactor.listenAgain()
}
@IBAction func closeAction(_ button: UIButton) {
finish()
}
// MARK: Utils
func variantButtonAtIndex(_ index: Int) -> UIButton {
switch index {
case 0:
return variant1Button
case 1:
return variant2Button
case 2:
return variant3Button
default:
return variant4Button
}
}
}
| mit | e7267df77aee3667d4bcc92a5c2c0f82 | 27.947368 | 82 | 0.641364 | 4.849375 | false | false | false | false |
adly-holler/SwiftBox | SwiftBox/Node.swift | 1 | 3842 | //
// Node.swift
// SwiftBox
//
// Created by Josh Abernathy on 2/6/15.
// Copyright (c) 2015 Josh Abernathy. All rights reserved.
//
import Foundation
public struct Edges {
public let left: CGFloat
public let right: CGFloat
public let bottom: CGFloat
public let top: CGFloat
private var asTuple: (Float, Float, Float, Float) {
return (Float(left), Float(top), Float(right), Float(bottom))
}
public init(left: CGFloat = 0, right: CGFloat = 0, bottom: CGFloat = 0, top: CGFloat = 0) {
self.left = left
self.right = right
self.bottom = bottom
self.top = top
}
public init(uniform: CGFloat) {
self.left = uniform
self.right = uniform
self.bottom = uniform
self.top = uniform
}
}
public enum Direction: UInt32 {
case Column = 0
case Row = 1
}
public enum Justification: UInt32 {
case FlexStart = 0
case Center = 1
case FlexEnd = 2
case SpaceBetween = 3
case SpaceAround = 4
}
public enum ChildAlignment: UInt32 {
case FlexStart = 1
case Center = 2
case FlexEnd = 3
case Stretch = 4
}
public enum SelfAlignment: UInt32 {
case Auto = 0
case FlexStart = 1
case Center = 2
case FlexEnd = 3
case Stretch = 4
}
/// A node in a layout hierarchy.
public struct Node {
/// Indicates that the value is undefined, for the flexbox algorithm to
/// fill in.
public static let Undefined: CGFloat = nan("SwiftBox.Node.Undefined")
public let size: CGSize
public let children: [Node]
public let direction: Direction
public let margin: Edges
public let padding: Edges
public let wrap: Bool
public let justification: Justification
public let selfAlignment: SelfAlignment
public let childAlignment: ChildAlignment
public let flex: CGFloat
public let measure: (CGFloat -> CGSize)?
public init(size: CGSize = CGSize(width: Undefined, height: Undefined), children: [Node] = [], direction: Direction = .Column, margin: Edges = Edges(), padding: Edges = Edges(), wrap: Bool = false, justification: Justification = .FlexStart, selfAlignment: SelfAlignment = .Auto, childAlignment: ChildAlignment = .Stretch, flex: CGFloat = 0, measure: (CGFloat -> CGSize)? = nil) {
self.size = size
self.children = children
self.direction = direction
self.margin = margin
self.padding = padding
self.wrap = wrap
self.justification = justification
self.selfAlignment = selfAlignment
self.childAlignment = childAlignment
self.flex = flex
self.measure = measure
}
private func createUnderlyingNode() -> NodeImpl {
let node = NodeImpl()
node.node.memory.style.dimensions = (Float(size.width), Float(size.height))
node.node.memory.style.margin = margin.asTuple
node.node.memory.style.padding = padding.asTuple
node.node.memory.style.flex = Float(flex)
node.node.memory.style.flex_direction = css_flex_direction_t(direction.rawValue)
node.node.memory.style.flex_wrap = css_wrap_type_t(wrap ? 1 : 0)
node.node.memory.style.justify_content = css_justify_t(justification.rawValue)
node.node.memory.style.align_self = css_align_t(selfAlignment.rawValue)
node.node.memory.style.align_items = css_align_t(childAlignment.rawValue)
if let measure = measure {
node.measure = measure
}
node.children = children.map { $0.createUnderlyingNode() }
return node
}
/// Lay out the receiver and all its children with an optional max width.
public func layout(maxWidth: CGFloat? = nil) -> Layout {
let node = createUnderlyingNode()
if let maxWidth = maxWidth {
node.layoutWithMaxWidth(maxWidth)
} else {
node.layout()
}
let children = createLayoutsFromChildren(node)
return Layout(frame: node.frame, children: children)
}
}
private func createLayoutsFromChildren(node: NodeImpl) -> [Layout] {
return node.children.map {
let child = $0 as! NodeImpl
let frame = child.frame
return Layout(frame: frame, children: createLayoutsFromChildren(child))
}
}
| bsd-3-clause | 73a2bb74d796520a016e34353848ffc9 | 27.671642 | 380 | 0.721499 | 3.337967 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/ComOperation/Model/SAMForSaleModel.swift | 1 | 1124 | //
// SAMForSaleModel.swift
// SaleManager
//
// Created by apple on 16/12/26.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
class SAMForSaleModel: NSObject {
///产品编号ID
var productID = "" {
didSet{
productID = ((productID == "") ? "---" : productID)
}
}
///客户名称
var CGUnitName = "" {
didSet{
CGUnitName = ((CGUnitName == "") ? "---" : CGUnitName)
}
}
///产品编号名称
var productIDName = "" {
didSet{
productIDName = ((productIDName == "") ? "---" : productIDName)
}
}
///订单单号
var orderBillNumber = "" {
didSet{
orderBillNumber = ((orderBillNumber == "") ? "---" : orderBillNumber)
}
}
///产品编号单位
var unit = ""
///数量
var meter = 0.0
///扫码人
var employeeName = "" {
didSet{
employeeName = ((employeeName == "") ? "---" : employeeName)
}
}
//MARK: - 辅助属性
let orderStateImageName = "indicater_forSale_selected"
}
| apache-2.0 | 09fcaf6f7763c368c3f9cfc24cad4842 | 19.686275 | 81 | 0.482464 | 3.650519 | false | false | false | false |
indexsky/ShiftPoint | ShiftPoint/ShiftPoint/Bullet.swift | 2 | 2001 | //
// Bullet.swift
// ShiftPoint
//
// Created by Ashton Wai on 3/4/16.
// Copyright © 2016 Ashton Wai & Zachary Bebel. All rights reserved.
//
import SpriteKit
class Bullet : SKShapeNode {
let bulletSpeed: CGFloat = CGFloat(Config.Player.BULLET_SPEED)
let bulletMaxPower: Int = Config.Player.BULLET_POWER_MAX
var bulletPower: Int = Config.Player.BULLET_POWER
// MARK: - Initialization -
init(circleOfRadius: CGFloat) {
super.init()
let diameter = circleOfRadius * 2
let center = CGPoint(x: -circleOfRadius, y: -circleOfRadius)
let size = CGSize(width: diameter, height: diameter)
self.name = "bullet"
self.path = CGPath(ellipseIn: CGRect(origin: center, size: size), transform: nil)
self.fillColor = SKColor.red
self.lineWidth = 0
self.physicsBody = SKPhysicsBody(circleOfRadius: 10)
self.physicsBody?.isDynamic = true
self.physicsBody?.categoryBitMask = PhysicsCategory.Bullet
self.physicsBody?.contactTestBitMask = PhysicsCategory.Enemy
self.physicsBody?.collisionBitMask = PhysicsCategory.None
self.physicsBody?.usesPreciseCollisionDetection = true
self.physicsBody?.angularDamping = 0
self.physicsBody?.linearDamping = 0
self.physicsBody?.restitution = 0
self.physicsBody?.friction = 0
self.physicsBody?.allowsRotation = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Movement Controls -
func move(_ dx: CGFloat, dy: CGFloat) {
self.physicsBody?.applyImpulse(CGVector(dx: dx * bulletSpeed, dy: dy * bulletSpeed))
}
// MARK: - Event Handlers -
func onHit(_ damage: Int) {
bulletPower -= damage
if bulletPower <= 0 {
onDestroy()
}
}
func onDestroy() {
self.removeFromParent()
}
}
| mit | cf5925e83a94a25d9824fe02e6afc648 | 29.769231 | 92 | 0.6275 | 4.524887 | false | false | false | false |
nearfri/Strix | Tests/StrixTests/Parsers/PrimitiveParsersTests.swift | 1 | 21066 | import XCTest
@testable import Strix
final class PrimitiveParsersTests: XCTestCase {
// MARK: - just
func test_just() throws {
let p: Parser<String> = .just("hello")
let text = try p.run("Input")
XCTAssertEqual(text, "hello")
}
// MARK: - fail
func test_fail() {
let p: Parser<String> = .fail(message: "Invalid input")
let reply = p.parse(ParserState(stream: "Input string"))
XCTAssert(reply.result.isFailure)
XCTAssertEqual(reply.errors, [.generic(message: "Invalid input")])
}
// MARK: - discard
func test_discardFirst() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("hello")
// When
let p: Parser<String> = .discardFirst(p1, p2)
let text = try p.run("Input")
// Then
XCTAssertEqual(text, "hello")
}
func test_discardSecond() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("hello")
// When
let p: Parser<Int> = .discardSecond(p1, p2)
let number = try p.run("Input")
// Then
XCTAssertEqual(number, 1)
}
// MARK: - tuple
func test_tuple2() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("2")
// When
let p = Parser.tuple(p1, p2)
let value = try p.run("Input")
// Then
XCTAssertEqual(value.0, 1)
XCTAssertEqual(value.1, "2")
}
func test_tuple3() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("2")
let p3: Parser<Double> = .just(3.0)
// When
let p = Parser.tuple(p1, p2, p3)
let value = try p.run("Input")
// Then
XCTAssertEqual(value.0, 1)
XCTAssertEqual(value.1, "2")
XCTAssertEqual(value.2, 3.0)
}
func test_tuple4() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("2")
let p3: Parser<Double> = .just(3.0)
let p4: Parser<Bool> = .just(true)
// When
let p = Parser.tuple(p1, p2, p3, p4)
let value = try p.run("Input")
// Then
XCTAssertEqual(value.0, 1)
XCTAssertEqual(value.1, "2")
XCTAssertEqual(value.2, 3.0)
XCTAssertEqual(value.3, true)
}
func test_tuple5() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("2")
let p3: Parser<Double> = .just(3.0)
let p4: Parser<Bool> = .just(true)
let p5: Parser<Character> = .just("c")
// When
let p = Parser.tuple(p1, p2, p3, p4, p5)
let value = try p.run("Input")
// Then
XCTAssertEqual(value.0, 1)
XCTAssertEqual(value.1, "2")
XCTAssertEqual(value.2, 3.0)
XCTAssertEqual(value.3, true)
XCTAssertEqual(value.4, "c")
}
func test_tuple6() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("2")
let p3: Parser<Double> = .just(3.0)
let p4: Parser<Bool> = .just(true)
let p5: Parser<Character> = .just("c")
let p6: Parser<Int> = .just(6)
// When
let p = Parser.tuple(p1, p2, p3, p4, p5, p6)
let value = try p.run("Input")
// Then
XCTAssertEqual(value.0, 1)
XCTAssertEqual(value.1, "2")
XCTAssertEqual(value.2, 3.0)
XCTAssertEqual(value.3, true)
XCTAssertEqual(value.4, "c")
XCTAssertEqual(value.5, 6)
}
func test_tuple7() throws {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .just("2")
let p3: Parser<Double> = .just(3.0)
let p4: Parser<Bool> = .just(true)
let p5: Parser<Character> = .just("c")
let p6: Parser<Int> = .just(6)
let p7: Parser<String> = .just("7")
// When
let p = Parser.tuple(p1, p2, p3, p4, p5, p6, p7)
let value = try p.run("Input")
// Then
XCTAssertEqual(value.0, 1)
XCTAssertEqual(value.1, "2")
XCTAssertEqual(value.2, 3.0)
XCTAssertEqual(value.3, true)
XCTAssertEqual(value.4, "c")
XCTAssertEqual(value.5, 6)
XCTAssertEqual(value.6, "7")
}
func test_tuple3_failure() {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<String> = .fail(message: "invalid input")
let p3: Parser<Double> = .just(3.0)
// When
let p = Parser.tuple(p1, p2, p3)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertFalse(reply.result.isSuccess)
XCTAssertFalse(reply.errors.isEmpty)
}
// MARK: - alternative
func test_alternative_leftSuccess_returnLeftReply() {
// Given
let p1: Parser<Int> = .just(1)
let p2: Parser<Int> = .just(2)
// When
let p: Parser<Int> = .alternative(p1, p2)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, 1)
}
func test_alternative_leftFailWithoutChange_returnRightReply() {
// Given
let p1: Parser<Int> = .fail(message: "Invalid input")
let p2: Parser<Int> = .just(2)
// When
let p: Parser<Int> = .alternative(p1, p2)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, 2)
}
func test_alternative_leftFailWithChange_returnLeftReply() {
// Given
let p1: Parser<Int> = Parser { state in
return .failure([.generic(message: "Invalid input")],
state.withStream(state.stream.dropFirst()))
}
let p2: Parser<Int> = .just(2)
// When
let p: Parser<Int> = .alternative(p1, p2)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isFailure)
XCTAssertEqual(reply.errors, [.generic(message: "Invalid input")])
}
// MARK: - anyOf
func test_anyOf_returnFirstSuccess() {
// Given
let p1: Parser<Int> = .fail(message: "Fail 1")
let p2: Parser<Int> = .just(2)
let p3: Parser<Int> = .just(3)
// When
let p: Parser<Int> = .any(of: [p1, p2, p3])
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, 2)
}
func test_anyOf_failWithChange_returnFailure() {
// Given
let p1: Parser<Int> = .fail(message: "Fail 1")
let p2: Parser<Int> = Parser { state in
return .failure([.generic(message: "Fail 3")],
state.withStream(state.stream.dropFirst()))
}
let p3: Parser<Int> = .just(3)
// When
let p: Parser<Int> = .any(of: [p1, p2, p3])
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isFailure)
}
func test_anyOf_failWithoutChange_mergeErrors() {
// Given
let p1: Parser<Int> = .fail(message: "Fail 1")
let p2: Parser<Int> = .fail(message: "Fail 2")
let p3: Parser<Int> = .fail(message: "Fail 3")
// When
let p: Parser<Int> = .any(of: [p1, p2, p3])
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.errors, [.generic(message: "Fail 1"),
.generic(message: "Fail 2"),
.generic(message: "Fail 3")])
}
// MARK: - optional
func test_optional_succeed_returnValue() throws {
// Given
let p1: Parser<String> = .just("hello")
// When
let p: Parser<String?> = .optional(p1)
let reply = p.parse(ParserState(stream: "Input"))
let value: String? = try XCTUnwrap(reply.result.value)
// Then
XCTAssert(reply.result.isSuccess)
XCTAssertEqual(value, "hello")
}
func test_optional_fail_returnNil() throws {
// Given
let p1: Parser<String> = .fail(message: "Fail")
// When
let p: Parser<String?> = .optional(p1)
let reply = p.parse(ParserState(stream: "Input"))
let value: String? = try XCTUnwrap(reply.result.value)
// Then
XCTAssert(reply.result.isSuccess)
XCTAssertNil(value)
}
// MARK: - notEmpty
func test_notEmpty_succeedWithChange_succeed() {
// Given
let p1: Parser<String> = Parser { state in
return .success("hello", state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<String> = .notEmpty(p1)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, "hello")
}
func test_notEmpty_succeedWithoutChange_fail() {
// Given
let p1: Parser<String> = .just("hello")
// When
let p: Parser<String> = .notEmpty(p1)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isFailure)
}
// MARK: - one
func test_oneWithSatisfying_succeed_returnValue() {
// Given
let p1: Parser<String> = Parser { state in
return .success("Hello", [], state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<String> = .one(p1, label: "Greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, "Hello")
XCTAssertEqual(reply.errors, [])
}
func test_oneWithSatisfying_failWithoutChange_returnFailureWithLabel() {
// Given
let p1: Parser<String> = .fail(message: "Fail")
// When
let p: Parser<String> = .one(p1, label: "Greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.errors, [.expected(label: "Greeting")])
}
func test_oneWithSatisfying_predicateSucceded_returnValue() throws {
// Given
let p1: Parser<Int> = Parser { state in
return .success(1, state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<Int> = .one(p1, satisfying: { $0 > 0 }, label: "positive integer")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.state.stream, "nput")
XCTAssertEqual(reply.result.value, 1)
}
func test_oneWithSatisfying_predicateFailed_backtrackAndReturnFailure() throws {
// Given
let p1: Parser<Int> = Parser { state in
return .success(0, state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<Int> = .one(p1, satisfying: { $0 > 0 }, label: "positive integer")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.state.stream, "Input")
XCTAssert(reply.result.isFailure)
}
// MARK: - attempt
func test_attempt_succeed_consumeInput() {
// Given
let p1: Parser<String> = Parser { state in
return .success("hello", state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<String> = .attempt(p1)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, "hello")
XCTAssertEqual(reply.state.stream, "nput")
}
func test_attempt_fail_backtrack() {
// Given
let p1: Parser<String> = Parser { state in
return .failure([], state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<String> = .attempt(p1)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.state.stream, "Input")
}
func test_attemptWithLabel_succeed_consumeInput() {
// Given
let p1: Parser<String> = Parser { state in
return .success("hello", state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<String> = .attempt(p1, label: "greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, "hello")
XCTAssertEqual(reply.state.stream, "nput")
}
func test_attemptWithLabel_failWithoutChange_returnExpectedError() {
// Given
let p1: Parser<String> = .fail(message: "invalid input")
// When
let p: Parser<String> = .attempt(p1, label: "greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.errors, [.expected(label: "greeting")])
}
func test_attemptWithLabel_failWithChange_backtrackAndReturnCompoundError() {
// Given
let input: Substring = "Input"
let secondIndex = input.index(after: input.startIndex)
let p1Errors = [ParseError.generic(message: "invalid input")]
let p1: Parser<String> = Parser { state in
return .failure(p1Errors, state.withStream(input[secondIndex...]))
}
// When
let p: Parser<String> = .attempt(p1, label: "greeting")
let reply = p.parse(ParserState(stream: input))
// Then
XCTAssertEqual(reply.state.stream, input)
XCTAssertEqual(reply.errors,
[.compound(label: "greeting", position: secondIndex, errors: p1Errors)])
}
// MARK: - lookAhead
func test_lookAhead_succeed_backtrackAndReturnValue() {
// Given
let p1: Parser<String> = Parser { state in
return .success("hello", state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<String> = .lookAhead(p1)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.result.value, "hello")
XCTAssertEqual(reply.state.stream, "Input")
}
func test_lookAhead_failWithoutChange_backtrack() {
// Given
let p1Errors = [ParseError.generic(message: "invalid input")]
let p1: Parser<String> = Parser { state in
return .failure(p1Errors, state)
}
// When
let p: Parser<String> = .lookAhead(p1)
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.state.stream, "Input")
XCTAssertEqual(reply.errors, p1Errors)
}
func test_lookAhead_failWithChange_backtrackAndReturnNestedError() {
// Given
let input: Substring = "Input"
let secondIndex = input.index(after: input.startIndex)
let p1Errors = [ParseError.generic(message: "invalid input")]
let p1: Parser<String> = Parser { state in
return .failure(p1Errors, state.withStream(input[secondIndex...]))
}
// When
let p: Parser<String> = .lookAhead(p1)
let reply = p.parse(ParserState(stream: input))
// Then
XCTAssertEqual(reply.state.stream, input)
XCTAssertEqual(reply.errors, [.nested(position: secondIndex, errors: p1Errors)])
}
// MARK: - recursive
func test_recursive() throws {
enum Container: Equatable {
indirect case wrapper(Container)
case value(Int)
}
let containerParser: Parser<Container> = .recursive { placeholder in
let wrapperParser: Parser<Container> =
(.character("(") *> placeholder <* .character(")")).map({ .wrapper($0) })
let valueParser: Parser<Container> = Parser.int().map({ .value($0) })
return wrapperParser <|> valueParser
}
let parsedContainer: Container = try containerParser.run("((5))")
let expectedContainer: Container = .wrapper(.wrapper(.value(5)))
XCTAssertEqual(parsedContainer, expectedContainer)
}
// MARK: - endOfStream
func test_endOfStream_atEOS_returnSuccess() {
// Given
let input = "Input"
let endState = ParserState(stream: input[input.endIndex...])
// When
let p: Parser<Void> = .endOfStream
let reply = p.parse(endState)
// Then
XCTAssert(reply.result.isSuccess)
}
func test_endOfStream_beforeEOS_returnFailure() {
// Given
let input = "Input"
let endState = ParserState(stream: input[input.index(before: input.endIndex)...])
// When
let p: Parser<Void> = .endOfStream
let reply = p.parse(endState)
// Then
XCTAssert(reply.result.isFailure)
}
// MARK: - follow
func test_follow_succeed_backtrackAndSucceed() {
// Given
let p1: Parser<String> = Parser { state in
return .success("hello", state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<Void> = .follow(p1, label: "greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isSuccess)
XCTAssertEqual(reply.state.stream, "Input")
}
func test_follow_fail_backtrackAndReturnExpectedError() {
// Given
let p1: Parser<String> = Parser { state in
return .failure([], state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<Void> = .follow(p1, label: "greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isFailure)
XCTAssertEqual(reply.state.stream, "Input")
XCTAssertEqual(reply.errors, [.expected(label: "greeting")])
}
// MARK: - not
func test_not_succeed_backtrackAndReturnUnexpectedError() {
// Given
let p1: Parser<String> = Parser { state in
return .success("hello", state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<Void> = .not(p1, label: "greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isFailure)
XCTAssertEqual(reply.state.stream, "Input")
XCTAssertEqual(reply.errors, [.unexpected(label: "greeting")])
}
func test_not_fail_backtrackAndSucceed() {
// Given
let p1: Parser<String> = Parser { state in
return .failure([], state.withStream(state.stream.dropFirst()))
}
// When
let p: Parser<Void> = .not(p1, label: "greeting")
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isSuccess)
XCTAssertEqual(reply.state.stream, "Input")
}
func test_updateUserState() {
// Given
var expectedUserState = UserState()
expectedUserState["greeting"] = "hello"
let p: Parser<Void> = .updateUserState { userState in
userState["greeting"] = "hello"
}
// When
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssertEqual(reply.state.userState, expectedUserState)
}
func test_satisfyUserState_succeed_returnSuccess() {
// Given
let message = "Nested tags are not allowed."
let p: Parser<Void> = .satisfyUserState({ _ in true }, message: message)
// When
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isSuccess)
}
func test_satisfyUserState_failed_returnFailure() {
// Given
let message = "Nested tags are not allowed."
let p: Parser<Void> = .satisfyUserState({ _ in false }, message: message)
// When
let reply = p.parse(ParserState(stream: "Input"))
// Then
XCTAssert(reply.result.isFailure)
XCTAssertEqual(reply.state.stream, "Input")
XCTAssertEqual(reply.errors, [.generic(message: message)])
}
}
| mit | 53b841ec0aab89f78e6cb36a6f94fc0f | 30.025037 | 95 | 0.53864 | 4.045708 | false | true | false | false |
khizkhiz/swift | stdlib/public/SDK/UIKit/UIKit.swift | 2 | 6496 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
@_exported import UIKit
//===----------------------------------------------------------------------===//
// Equatable types.
//===----------------------------------------------------------------------===//
@_transparent // @fragile
@warn_unused_result
public func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool {
return lhs.top == rhs.top &&
lhs.left == rhs.left &&
lhs.bottom == rhs.bottom &&
lhs.right == rhs.right
}
extension UIEdgeInsets : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: UIOffset, rhs: UIOffset) -> Bool {
return lhs.horizontal == rhs.horizontal &&
lhs.vertical == rhs.vertical
}
extension UIOffset : Equatable {}
// These are un-imported macros in UIKit.
//===----------------------------------------------------------------------===//
// UIDeviceOrientation
//===----------------------------------------------------------------------===//
#if !os(watchOS) && !os(tvOS)
public extension UIDeviceOrientation {
var isLandscape: Bool {
return self == .landscapeLeft || self == .landscapeRight
}
var isPortrait: Bool {
return self == .portrait || self == .portraitUpsideDown
}
var isFlat: Bool {
return self == .faceUp || self == .faceDown
}
var isValidInterfaceOrientation: Bool {
switch (self) {
case .portrait, .portraitUpsideDown, .landscapeLeft, .landscapeRight:
return true
default:
return false
}
}
}
@warn_unused_result
public func UIDeviceOrientationIsLandscape(
orientation: UIDeviceOrientation
) -> Bool {
return orientation.isLandscape
}
@warn_unused_result
public func UIDeviceOrientationIsPortrait(
orientation: UIDeviceOrientation
) -> Bool {
return orientation.isPortrait
}
@warn_unused_result
public func UIDeviceOrientationIsValidInterfaceOrientation(
orientation: UIDeviceOrientation) -> Bool
{
return orientation.isValidInterfaceOrientation
}
#endif
//===----------------------------------------------------------------------===//
// UIInterfaceOrientation
//===----------------------------------------------------------------------===//
#if !os(watchOS) && !os(tvOS)
public extension UIInterfaceOrientation {
var isLandscape: Bool {
return self == .landscapeLeft || self == .landscapeRight
}
var isPortrait: Bool {
return self == .portrait || self == .portraitUpsideDown
}
}
@warn_unused_result
public func UIInterfaceOrientationIsPortrait(
orientation: UIInterfaceOrientation) -> Bool {
return orientation.isPortrait
}
@warn_unused_result
public func UIInterfaceOrientationIsLandscape(
orientation: UIInterfaceOrientation
) -> Bool {
return orientation.isLandscape
}
#endif
// Overlays for variadic initializers.
#if !os(watchOS) && !os(tvOS)
public extension UIActionSheet {
convenience init(title: String?,
delegate: UIActionSheetDelegate?,
cancelButtonTitle: String?,
destructiveButtonTitle: String?,
// Hack around overload ambiguity with non-variadic constructor.
// <rdar://problem/16704770>
otherButtonTitles firstButtonTitle: String,
_ moreButtonTitles: String...) {
self.init(title: title,
delegate: delegate,
cancelButtonTitle: cancelButtonTitle,
destructiveButtonTitle: destructiveButtonTitle)
self.addButton(withTitle: firstButtonTitle)
for buttonTitle in moreButtonTitles {
self.addButton(withTitle: buttonTitle)
}
}
}
#endif
#if !os(watchOS) && !os(tvOS)
public extension UIAlertView {
convenience init(title: String,
message: String,
delegate: UIAlertViewDelegate?,
cancelButtonTitle: String?,
// Hack around overload ambiguity with non-variadic constructor.
// <rdar://problem/16704770>
otherButtonTitles firstButtonTitle: String,
_ moreButtonTitles: String...) {
self.init(title: title,
message: message,
delegate: delegate,
cancelButtonTitle: cancelButtonTitle)
self.addButton(withTitle: firstButtonTitle)
for buttonTitle in moreButtonTitles {
self.addButton(withTitle: buttonTitle)
}
}
}
#endif
#if !os(watchOS)
internal struct _UIViewQuickLookState {
static var views = Set<UIView>()
}
extension UIView : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
if _UIViewQuickLookState.views.contains(self) {
return .view(UIImage())
} else {
_UIViewQuickLookState.views.insert(self)
// in case of an empty rectangle abort the logging
if (bounds.size.width == 0) || (bounds.size.height == 0) {
return .view(UIImage())
}
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
// UIKit is about to update this to be optional, so make it work
// with both older and newer SDKs. (In this context it should always
// be present.)
let ctx: CGContext! = UIGraphicsGetCurrentContext()
UIColor(white:1.0, alpha:0.0).set()
CGContextFillRect(ctx, bounds)
layer.render(in: ctx)
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
_UIViewQuickLookState.views.remove(self)
return .view(image)
}
}
}
#endif
extension UIColor : _ColorLiteralConvertible {
public required convenience init(colorLiteralRed red: Float, green: Float,
blue: Float, alpha: Float) {
self.init(red: CGFloat(red), green: CGFloat(green),
blue: CGFloat(blue), alpha: CGFloat(alpha))
}
}
public typealias _ColorLiteralType = UIColor
extension UIImage : _ImageLiteralConvertible {
private convenience init!(failableImageLiteral name: String) {
self.init(named: name)
}
public required convenience init(imageLiteral name: String) {
self.init(failableImageLiteral: name)
}
}
public typealias _ImageLiteralType = UIImage
| apache-2.0 | 17056fbba6a3695583334c88b78e1869 | 28 | 80 | 0.625308 | 5.082942 | false | false | false | false |
IxD-WowHack/spotify-swift-jonas | 0.2 Auth and playing a song/SpotifySwiftHack/SpotifySwiftHack/AppDelegate.swift | 1 | 4282 | //
// AppDelegate.swift
// SpotifySwiftHack
//
// Created by Jonas Berglund on 17/07/15.
// Copyright © 2015 Jonas Berglund. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var session: SPTSession?
var player: SPTAudioStreamingController?
let kClientId = "9921258e4129458da3bd81ca20ca0751"
let kCallbackURL = "spotify-swift-hack://callback"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let auth = SPTAuth.defaultInstance()
auth.clientID = kClientId
auth.redirectURL = NSURL(string: kCallbackURL)
auth.requestedScopes = [SPTAuthPlaylistModifyPublicScope,SPTAuthUserReadPrivateScope, SPTAuthPlaylistReadPrivateScope, SPTAuthStreamingScope]
let loginURL = auth.loginURL
delay(0.1) {
application.openURL(loginURL)
return
}
return true
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if SPTAuth.defaultInstance().canHandleURL(url) {
SPTAuth.defaultInstance().handleAuthCallbackWithTriggeredAuthURL(url, callback: { (error, session) -> Void in
if error != nil {
print(error.localizedDescription)
return
}
self.playUsingSession(session)
})
}
return false
}
func playUsingSession(session:SPTSession) {
// Create a new player if needed
if (self.player == nil) {
self.player = SPTAudioStreamingController(clientId: kClientId)
}
self.player?.loginWithSession(session, callback: { (error) -> Void in
if (error != nil) {
print("*** Enabling playback got error: \(error)")
return
} else {
var trackURIs: [NSURL] = []
trackURIs.append(NSURL(string: "spotify:track:3j9uGwbiRJrsOzOYloTE1b")!)
self.player?.playURIs(trackURIs, fromIndex: 0, callback: nil)
}
})
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 1082b2e06e7d49b4706698502bc77125 | 39.771429 | 285 | 0.651717 | 5.126946 | false | false | false | false |
m-schmidt/Refracto | Refracto/Computations.swift | 1 | 3872 | // Computations.swift - Refractometer Computations
//
// Refractometer formula "Standard" is according Louis K. Bonham:
// "The Use of Handheld Refractometers by Homebrewers" in the Zymurgy January/February 2001
//
// Refractometer formulas of Petr Novotný:
// http://www.diversity.beer/2017/01/pocitame-nova-korekce-refraktometru.html
//
// Refractometer formulas of Sean Terrill:
// http://seanterrill.com
import Foundation
// MARK: - Plato/SG Conversion
func plato(forSpecificGravity SG: Double) -> Double {
return 668.72 * SG - 463.37 - 205.347 * pow(SG, 2)
}
func specificGravity(forPlato plato: Double) -> Double {
return 1 + plato / (258.6 - plato * 227.1 / 258.2)
}
// MARK: - Refractometer Computation
func apparentSpecificGravity(forInitialRefraction initial: Double, finalRefraction final: Double, wortCorrection: Double, formula: RefractometerFormula) -> Double {
guard initial >= final else { return .nan }
let initialAdjusted = initial / wortCorrection
let finalAdjusted = final / wortCorrection
let result: Double
switch(formula) {
case .Standard:
result = 1.001843
- 0.002318474 * initialAdjusted
- 0.000007775 * pow(initialAdjusted, 2)
- 0.000000034 * pow(initialAdjusted, 3)
+ 0.00574 * final
+ 0.00003344 * pow(final, 2)
+ 0.000000086 * pow(final, 3)
case .NovotnyLinear:
result = 1.0
- 0.002349 * initialAdjusted
+ 0.006276 * finalAdjusted
case .NovotnyQuadratic:
result = 1.0
+ 0.00001335 * pow(initialAdjusted, 2)
- 0.00003239 * initialAdjusted * finalAdjusted
+ 0.00002916 * pow(finalAdjusted, 2)
- 0.002421 * initialAdjusted
+ 0.006219 * finalAdjusted
case .TerrillLinear:
result = 1.0
- 0.000856829 * initialAdjusted
+ 0.00349412 * finalAdjusted
case .TerrillCubic:
result = 1.0
- 0.0044993 * initialAdjusted
+ 0.000275806 * pow(initialAdjusted, 2)
- 0.00000727999 * pow(initialAdjusted, 3)
+ 0.0117741 * finalAdjusted
- 0.00127169 * pow(finalAdjusted, 2)
+ 0.0000632929 * pow(finalAdjusted, 3)
}
return result >= 1.0 ? result : .nan
}
func actualSpecificGravity(forApparentSpecificGravity gravity: Double, initialRefraction initial: Double, wortCorrection: Double) -> Double {
guard gravity.isNormal else { return .nan }
let initialAdjusted = initial / wortCorrection
let actual = 0.1808 * initialAdjusted + 0.8192 * plato(forSpecificGravity: gravity)
return specificGravity(forPlato: actual)
}
// MARK: - Attenuation Computation
func attenuation(forSpecificGravity gravity: Double, initialRefraction initial: Double, wortCorrection: Double) -> Double {
guard gravity.isNormal else { return .nan }
let initialAdjusted = initial / wortCorrection
let attenuation = (1.0 - plato(forSpecificGravity: gravity) / initialAdjusted) * 100.0
return max(0, min(100, attenuation))
}
// MARK: - Alcohol Computation
func alcoholContent(forSpecificGravity gravity: Double, initialRefraction initial: Double, wortCorrection: Double) -> Double {
guard gravity.isNormal else { return .nan }
let initialAdjusted = initial / wortCorrection
let actualExtract = 0.1808 * initialAdjusted + 0.8192 * plato(forSpecificGravity: gravity)
let actualDensity = specificGravity(forPlato: actualExtract)
let alcoholByWeight = (initialAdjusted - actualExtract) / (2.0665 - 0.010665 * initialAdjusted)
let alcoholByVolume = alcoholByWeight * actualDensity / 0.7893
return max(0, min(100, alcoholByVolume))
}
| bsd-3-clause | 1a54bf2b8da276617d523e3dd0b5bbb4 | 35.17757 | 164 | 0.649961 | 3.783969 | false | false | false | false |
sinoru/STwitter | Sources/OAuth.swift | 1 | 17257 | //
// OAuth.swift
// STwitter
//
// Created by Sinoru on 2016. 12. 2..
// Copyright © 2016 Sinoru. 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
import Cryptor
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Accounts
import Social
#endif
/// A class for OAuth-ing with Twitter.
///
/// - note:
/// You can obtain Twitter OAuth Acess Token like this:
///
/// let session = Session(consumerKey: <#consumerKey#>, consumerSecret: <#consumerSecret#>)
/// OAuth.requestRequestToken(session: session, completionHandler: { (<#requestToken#>, <#requestTokenSecret#>, <#error#>) in
/// var urlComponents = URLComponents(url: OAuth.authorizeURL)
/// urlComponents.query = "oauth_token=\(<#requestToken#>)"
///
/// let authorizeURL = urlComponents.url
///
/// // Open authorizeURL on WebView or anything. and get OAuth verifier
///
/// OAuth.requestAccessToken(session: session, requestToken: <#requestToken#>, requestTokenSecret: <#requestTokenSecret#>, oauthVerifier: <#oauthVerifier#>, completionHandler: { (<#accessToken#>, <#accessTokenSecret#>, <#userID#>, <#screenName#>, <#error#>) in
/// // Implementation
/// })
/// })
@objc(STWOAuth)
public class OAuth: NSObject {
/// XAuth mode for OAuth requests.
@objc(STWxAuthMode)
public enum XAuthMode: UInt {
/// None.
case None = 0
/// Client authentication based on Username, Password.
case ClientAuth = 1
}
/// A URL for *authorize* endpoint. Desktop applications must use this endpoint.
///
/// - seealso:
/// [Twitter Developer Documentation](https://dev.twitter.com/oauth/reference/get/oauth/authorize)
public static var authorizeURL: URL {
return URL.twitterOAuthURL(endpoint: "authorize")!
}
/// A URL for *authenticate* endpoint.
///
/// - seealso:
/// [Twitter Developer Documentation](https://dev.twitter.com/oauth/reference/get/oauth/authenticate)
public static var authenticateURL: URL {
return URL.twitterOAuthURL(endpoint: "authenticate")!
}
/// Request Request-Token from Twitter OAuth 1.0a
///
/// - Parameters:
/// - session: A session for request.
/// - callback: OAuth callback string. The value you specify here will be used as the URL a user is redirected to should they approve your application’s access to their account. Set this to `oob` for out-of-band pin mode. This is also how you specify custom callbacks for use in desktop/mobile applications.
/// - completionHandler: A handler that will be called after completion.
/// - requestToken: A request token that returned
/// - requestTokenSecret: A request secret token that returned
/// - error: A error that returned
@objc public class func requestRequestToken(session: Session, callback: String = "oob", completionHandler: @escaping (_ requestToken: String?, _ requestTokenSecret: String?, _ error: Swift.Error?) -> Void) {
let url = URL.twitterOAuthURL(endpoint: "request_token")!
let httpMethod = "POST"
do {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = httpMethod
let oauthItems = ["oauth_callback": callback]
let authorizationHeader = try self.authorizationHeader(oauthItems: oauthItems, HTTPMethod: httpMethod, url: url, consumerKey: session.consumerKey, consumerSecret: session.consumerSecret, token: nil, tokenSecret: nil)
urlRequest.setValue(authorizationHeader, forHTTPHeaderField: "Authorization")
let task = session.urlSession.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
if let error = error {
completionHandler(nil, nil, error)
return
}
do {
let (token, tokenSecret, userInfo) = try self.processOAuth(response: response, data: data)
guard let callbackConfirmed = Bool((userInfo["oauth_callback_confirmed"] ?? nil) ?? "false"), callbackConfirmed == true else {
completionHandler(nil, nil, Error.Unknown)
return
}
completionHandler(token, tokenSecret, nil)
} catch let error {
completionHandler(nil, nil, error)
}
})
task.resume()
} catch let error {
completionHandler(nil, nil, error)
}
}
/// Request Request-Token from Twitter OAuth 1.0a for Reverse Auth
///
/// - Parameters:
/// - session: A session for request.
/// - completionHandler: A handler that will be called after completion.
/// - response: A string that returned for access token
/// - error: A error that returned
@objc public class func requestRequestTokenForxAuthReverse(session: Session, completionHandler: @escaping (_ response: String?, _ error: Swift.Error?) -> Void) {
let url = URL.twitterOAuthURL(endpoint: "request_token")!
let httpMethod = "POST"
do {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = httpMethod
let queryItems = [ URLQueryItem(name: "x_auth_mode", value: "reverse_auth") ]
let authorizationHeader = try self.authorizationHeader(queryItems: queryItems, HTTPMethod: httpMethod, url: url, consumerKey: session.consumerKey, consumerSecret: session.consumerSecret, token: nil, tokenSecret: nil)
urlRequest.setValue(authorizationHeader, forHTTPHeaderField: "Authorization")
var urlComponents = URLComponents()
urlComponents.queryItems = queryItems
urlRequest.httpBody = urlComponents.percentEncodedQuery?.addingPercentEncoding(withAllowedCharacters: CharacterSet.twitterAllowedCharacters)?.data(using: .utf8)
let task = session.urlSession.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
if let error = error {
completionHandler(nil, error)
return
}
guard let data = data else {
completionHandler(nil, error)
return
}
guard let responseString = String(data: data, encoding: .utf8) else {
completionHandler(nil, error)
return
}
do {
try TwitterError.checkTwitterError(onJsonObject: try? JSONSerialization.jsonObject(with: data, options: []))
completionHandler(responseString, nil)
} catch let error {
completionHandler(nil, error)
}
})
task.resume()
} catch let error {
completionHandler(nil, error)
}
}
/// Request Access-Token Completion Handler
///
/// - Parameters:
/// - accessToken: A access token that returned
/// - accessTokenSecret: A access secret token that returned
/// - userID: A user ID that returned
/// - screenName: A screen name that returned
/// - error: A error that returned
public typealias RequestAccessTokenCompletionHandler = (_ accessToken: String?, _ accessTokenSecret: String?, _ userID: Int64, _ screenName: String?, _ error: Swift.Error?) -> Void
/// Request Access-Token from Twitter OAuth 1.0a
///
/// - Parameters:
/// - session: A session for request.
/// - requestToken: A request token.
/// - requestTokenSecret: A request token secret.
/// - xAuthMode: xAuth mode. For possible values, see xAuthMode.
/// - xAuthUsername: A username for xAuth ClientAuth.
/// - xAuthPassword: A password for xAuth ClientAuth.
/// - oauthVerifier: A verifier from oauth/authentication.
/// - completionHandler: A handler that will be called after completion.
@objc public class func requestAccessToken(session: Session, requestToken: String, requestTokenSecret: String, xAuthMode: XAuthMode = .None, xAuthUsername: String? = nil, xAuthPassword: String? = nil, oauthVerifier: String? = nil, completionHandler: @escaping RequestAccessTokenCompletionHandler) {
let url = URL.twitterOAuthURL(endpoint: "access_token")!
let httpMethod = "POST"
do {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = httpMethod
var oauthItems = [String:String]()
if let oauthVerifier = oauthVerifier {
oauthItems["oauth_verifier"] = oauthVerifier
}
// TODO: xAuth
let authorizationHeader = try self.authorizationHeader(oauthItems: oauthItems, HTTPMethod: httpMethod, url: url, consumerKey: session.consumerKey, consumerSecret: session.consumerSecret, token: requestToken, tokenSecret: requestTokenSecret)
urlRequest.setValue(authorizationHeader, forHTTPHeaderField: "Authorization")
let task = session.urlSession.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
if let error = error {
completionHandler(nil, nil, -1, nil, error)
return
}
do {
let (token, tokenSecret, userInfo) = try self.processOAuth(response: response, data: data)
let userID: Int64 = Int64((userInfo["user_id"] ?? "") ?? "") ?? -1
let screenName = userInfo["screen_name"] ?? nil
completionHandler(token, tokenSecret, userID, screenName, nil)
} catch let error {
completionHandler(nil, nil, -1, nil, error)
}
})
task.resume()
} catch let error {
completionHandler(nil, nil, -1, nil, error)
}
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
/// Request Access-Token from Twitter OAuth 1.0a
///
/// - Parameters:
/// - session: A session for request.
/// - account: A account from ACAccountStore for request
/// - requestResponse: A request response.
/// - completionHandler: A handler that will be called after completion.
@objc public class func requestAccessToken(session: Session, accountForxAuthReverse account: ACAccount, requestResponse: String, completionHandler: @escaping RequestAccessTokenCompletionHandler) {
let url = URL.twitterOAuthURL(endpoint: "access_token")!
let parameters = ["x_reverse_auth_target": session.consumerKey, "x_reverse_auth_parameters": requestResponse]
guard let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: url, parameters: parameters) else {
completionHandler(nil, nil, -1, nil, Error.Unknown)
return
}
request.account = account
let task = session.urlSession.dataTask(with: request.preparedURLRequest(), completionHandler: { (data, response, error) in
if let error = error {
completionHandler(nil, nil, -1, nil, error)
return
}
do {
let (token, tokenSecret, userInfo) = try self.processOAuth(response: response, data: data)
let userID: Int64 = Int64((userInfo["user_id"] ?? "") ?? "") ?? -1
let screenName = userInfo["screen_name"] ?? nil
completionHandler(token, tokenSecret, userID, screenName, nil)
} catch let error {
completionHandler(nil, nil, -1, nil, error)
}
})
task.resume()
}
#endif
internal class func processOAuth(response: URLResponse?, data: Data?) throws -> (token: String, tokenSecret: String, userInfo: [String:String?]) {
try TwitterError.checkTwitterError(onJsonObject: try? JSONSerialization.jsonObject(with: data ?? Data(), options: []))
guard let response = response as? HTTPURLResponse, 200 <= response.statusCode && response.statusCode < 300 else {
throw Error.Unknown
}
guard let data = data else {
throw Error.Unknown
}
guard let queryString = String(data: data, encoding: .utf8) else {
throw Error.Unknown
}
var urlComponents = URLComponents()
urlComponents.query = queryString.removingPercentEncoding
guard let queryItems = urlComponents.queryItems else {
throw Error.Unknown
}
var items = [String:String?]()
for queryItem in queryItems {
items[queryItem.name] = queryItem.value
}
guard let token = items["oauth_token"] ?? nil, let tokenSecret = items["oauth_token_secret"] ?? nil else {
throw Error.Unknown
}
items.removeValue(forKey: "oauth_token")
items.removeValue(forKey: "oauth_token_secret")
return (token, tokenSecret, items)
}
internal class func authorizationHeader(queryItems: [URLQueryItem] = [], oauthItems: [String:String] = [:], HTTPMethod: String, url: URL, consumerKey: String, consumerSecret: String, token: String?, tokenSecret: String?) throws -> String {
var authorizationHeaderQueryItems = [
URLQueryItem(name: "oauth_consumer_key", value: consumerKey),
URLQueryItem(name: "oauth_signature_method", value: "HMAC-SHA1"),
URLQueryItem(name: "oauth_version", value: "1.0")
]
if let token = token {
authorizationHeaderQueryItems.append(URLQueryItem(name: "oauth_token", value: token))
}
for (key, value) in oauthItems {
authorizationHeaderQueryItems.append(URLQueryItem(name: key, value: value))
}
let nonce = UUID().uuidString
authorizationHeaderQueryItems.append(URLQueryItem(name: "oauth_nonce", value: nonce))
let timestamp = String(Int(Date().timeIntervalSince1970))
authorizationHeaderQueryItems.append(URLQueryItem(name: "oauth_timestamp", value: timestamp))
let signature = try self.signature(queryItems: authorizationHeaderQueryItems + queryItems, HTTPMethod: HTTPMethod, url: url, consumerSecret: consumerSecret, tokenSecret: tokenSecret)
authorizationHeaderQueryItems.append(URLQueryItem(name: "oauth_signature", value: signature))
authorizationHeaderQueryItems.sort(by: {$0.name.compare($1.name) == .orderedAscending})
var authorizationHeaderStringItems = [String]()
for item in authorizationHeaderQueryItems {
guard var authorizationHeaderString = item.name.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlUnreservedCharacters) else {
break
}
if let value = item.value?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlUnreservedCharacters) {
authorizationHeaderString += "=\"\(value)\""
}
authorizationHeaderStringItems.append(authorizationHeaderString)
}
return "OAuth " + authorizationHeaderStringItems.joined(separator: ", ")
}
internal class func signature(queryItems: [URLQueryItem], HTTPMethod: String, url: URL, consumerSecret: String, tokenSecret: String?) throws -> String {
let queryItems = queryItems.sorted(by: {$0.name.compare($1.name) == .orderedAscending})
let signatureKey = "\(consumerSecret)&\(tokenSecret ?? "")"
var signatureValue = "\(HTTPMethod)"
if let path = url.absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlUnreservedCharacters) {
signatureValue += "&\(path)"
} else {
throw Error.Unknown
}
var urlComponents = URLComponents()
urlComponents.queryItems = queryItems
if let percentEncodedQuery = urlComponents.percentEncodedQuery?.addingPercentEncoding(withAllowedCharacters: CharacterSet.twitterAllowedCharacters)?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlUnreservedCharacters) {
signatureValue += "&\(percentEncodedQuery)"
}
let key = CryptoUtils.byteArray(from: signatureKey)
let data: [UInt8] = CryptoUtils.byteArray(from: signatureValue)
guard let hmac = HMAC(using: HMAC.Algorithm.sha1, key: key).update(byteArray: data)?.final() else {
throw Error.Unknown
}
return (CryptoUtils.data(from: hmac) as Data).base64EncodedString()
}
}
| apache-2.0 | a1f89a1cc347fab6342d5f4b961408a3 | 43.583979 | 313 | 0.632375 | 4.959471 | false | false | false | false |
XiaHaozheJose/WB | WB/WB/Classes/Main/PreviousView/JS_PreviousView.swift | 1 | 1360 | //
// JS_PreviousView.swift
// WB
//
// Created by 浩哲 夏 on 2017/1/6.
// Copyright © 2017年 浩哲 夏. All rights reserved.
//
import UIKit
class JS_PreviousView: UIView {
// MARK:- 属性
@IBOutlet weak var backgoundImage: UIImageView!
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var registerBtn: UIButton!
@IBOutlet weak var LogInBtn: UIButton!
// MARK:- 快速构造方法
class func initWithXibView() ->JS_PreviousView {
return Bundle.main.loadNibNamed("JS_PreviousView", owner: nil, options: nil)?.first as! JS_PreviousView
}
}
// MARK: - 供外届调用接口
extension JS_PreviousView{
func getPreviousProperty(imageName: String, descripText: String){
iconImage.image = UIImage.init(named: imageName)
descLabel.text = descripText
backgoundImage.isHidden = true
}
func starAnimation(){
let imageAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
imageAnimation.fromValue = 0
imageAnimation.toValue = M_PI * 2
imageAnimation.repeatDuration = CFTimeInterval(MAXFLOAT)
imageAnimation.duration = 10
imageAnimation.isRemovedOnCompletion = false
backgoundImage.layer.add(imageAnimation, forKey: nil)
}
}
| apache-2.0 | 6136c499bde9b0282e485527e71d7edd | 26.395833 | 111 | 0.670722 | 4.13522 | false | false | false | false |
xwu/swift | test/stdlib/Diffing.swift | 1 | 25942 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import Swift
import StdlibUnittest
let suite = TestSuite("Diffing")
// This availability test has to be this awkward because of
// rdar://problem/48450376 - Availability checks don't apply to top-level code
if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {
suite.test("Diffing empty collections") {
let a = [Int]()
let b = [Int]()
let diff = b.difference(from: a)
expectEqual(diff, a.difference(from: a))
expectTrue(diff.isEmpty)
}
suite.test("Basic diffing algorithm validators") {
let expectedChanges: [(
source: [String],
target: [String],
changes: [CollectionDifference<String>.Change],
line: UInt
)] = [
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
changes: [],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Presents",
"New Years", "Champagne"],
changes: [
.remove(offset: 5, element: "Lights", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel", "Gelt",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
changes: [
.insert(offset: 3, element: "Gelt", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Presents", "Tree", "Lights",
"New Years", "Champagne"],
changes: [
.remove(offset: 6, element: "Presents", associatedWith: 4),
.insert(offset: 4, element: "Presents", associatedWith: 6)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Lights", "Presents", "Tree",
"New Years", "Champagne"],
changes: [
.remove(offset: 4, element: "Tree", associatedWith: 6),
.insert(offset: 6, element: "Tree", associatedWith: 4)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel", "Presents",
"Xmas", "Tree", "Lights",
"New Years", "Champagne"],
changes: [
.remove(offset: 6, element: "Presents", associatedWith: 3),
.insert(offset: 3, element: "Presents", associatedWith: 6)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights",
"New Years", "Champagne", "Presents"],
changes: [
.remove(offset: 6, element: "Presents", associatedWith: 8),
.insert(offset: 8, element: "Presents", associatedWith: 6)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
changes: [
.remove(offset: 2, element: "Dreidel", associatedWith: nil),
.remove(offset: 1, element: "Menorah", associatedWith: nil),
.remove(offset: 0, element: "Hannukah", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
changes: [
.insert(offset: 7, element: "New Years", associatedWith: nil),
.insert(offset: 8, element: "Champagne", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["New Years", "Champagne",
"Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents"],
changes: [
.remove(offset: 8, element: "Champagne", associatedWith: 1),
.remove(offset: 7, element: "New Years", associatedWith: 0),
.insert(offset: 0, element: "New Years", associatedWith: 7),
.insert(offset: 1, element: "Champagne", associatedWith: 8)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne",
"Hannukah", "Menorah", "Dreidel"],
changes: [
.remove(offset: 2, element: "Dreidel", associatedWith: 8),
.remove(offset: 1, element: "Menorah", associatedWith: 7),
.remove(offset: 0, element: "Hannukah", associatedWith: 6),
.insert(offset: 6, element: "Hannukah", associatedWith: 0),
.insert(offset: 7, element: "Menorah", associatedWith: 1),
.insert(offset: 8, element: "Dreidel", associatedWith: 2)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel", "Presents",
"Xmas", "Tree", "Lights",
"New Years", "Champagne"],
target:
["Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
changes: [
.remove(offset: 3, element: "Presents", associatedWith: 3),
.remove(offset: 2, element: "Dreidel", associatedWith: nil),
.remove(offset: 1, element: "Menorah", associatedWith: nil),
.remove(offset: 0, element: "Hannukah", associatedWith: nil),
.insert(offset: 3, element: "Presents", associatedWith: 3)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Presents",
"New Years", "Champagne", "Lights"],
changes: [
.remove(offset: 5, element: "Lights", associatedWith: 8),
.insert(offset: 6, element: "New Years", associatedWith: nil),
.insert(offset: 7, element: "Champagne", associatedWith: nil),
.insert(offset: 8, element: "Lights", associatedWith: 5)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years"],
changes: [
.remove(offset: 8, element: "Champagne", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel", "Presents",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne", "Presents"],
target:
["Hannukah", "Menorah", "Dreidel", "Presents",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne", "Presents"],
changes: [],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel", "Presents",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne", "Presents"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights",
"New Years", "Champagne", "Presents"],
changes: [
.remove(offset: 7, element: "Presents", associatedWith: nil),
.remove(offset: 3, element: "Presents", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights",
"New Years", "Champagne", "Presents"],
target:
["Hannukah", "Menorah", "Dreidel", "Presents",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne", "Presents"],
changes: [
.insert(offset: 3, element: "Presents", associatedWith: nil),
.insert(offset: 7, element: "Presents", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah", "Dreidel", "Presents",
"Xmas", "Tree", "Lights",
"New Years", "Champagne", "Presents"],
target:
["Hannukah", "Menorah", "Dreidel",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne", "Presents"],
changes: [
.remove(offset: 3, element: "Presents", associatedWith: 6),
.insert(offset: 6, element: "Presents", associatedWith: 3)
],
line: #line),
(source:
["Hannukah", "Menorah",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne",
"Hannukah", "Dreidel"],
target:
["Hannukah", "Menorah",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne",
"Hannukah", "Dreidel"],
changes: [],
line: #line),
(source:
["Hannukah", "Menorah",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne",
"Hannukah", "Dreidel"],
target:
["Hannukah", "Menorah",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
changes: [
.remove(offset: 9, element: "Dreidel", associatedWith: nil),
.remove(offset: 8, element: "Hannukah", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne"],
target:
["Hannukah", "Menorah",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne",
"Hannukah", "Dreidel"],
changes: [
.insert(offset: 8, element: "Hannukah", associatedWith: nil),
.insert(offset: 9, element: "Dreidel", associatedWith: nil)
],
line: #line),
(source:
["Hannukah", "Menorah",
"Xmas", "Tree", "Lights", "Presents",
"New Years", "Champagne",
"Hannukah", "Dreidel"],
target:
["Xmas", "Tree", "Lights", "Presents",
"Hannukah", "Menorah",
"New Years", "Champagne",
"Hannukah", "Dreidel"],
changes: [
.remove(offset: 1, element: "Menorah", associatedWith: 5),
.remove(offset: 0, element: "Hannukah", associatedWith: 4),
.insert(offset: 4, element: "Hannukah", associatedWith: 0),
.insert(offset: 5, element: "Menorah", associatedWith: 1)
],
line: #line),
]
for (source, target, expected, line) in expectedChanges {
let actual = target.difference(from: source).inferringMoves()
expectEqual(CollectionDifference(expected), actual, "failed test at line \(line)")
}
}
suite.test("Empty diffs have sane behaviour") {
guard let diff = CollectionDifference<String>([]) else {
expectUnreachable()
return
}
expectEqual(0, diff.insertions.count)
expectEqual(0, diff.removals.count)
expectEqual(true, diff.isEmpty)
var c = 0
diff.forEach({ _ in c += 1 })
expectEqual(0, c)
}
suite.test("Happy path tests for the change validator") {
// Base case: one insert and one remove with legal offsets
expectNotNil(CollectionDifference<Int>.init([
.insert(offset: 0, element: 0, associatedWith: nil),
.remove(offset: 0, element: 0, associatedWith: nil)
]))
// Code coverage:
// • non-first change .remove has legal associated offset
// • non-first change .insert has legal associated offset
expectNotNil(CollectionDifference<Int>.init([
.remove(offset: 1, element: 0, associatedWith: 0),
.remove(offset: 0, element: 0, associatedWith: 1),
.insert(offset: 0, element: 0, associatedWith: 1),
.insert(offset: 1, element: 0, associatedWith: 0)
]))
}
suite.test("Exhaustive edge case tests for the change validator") {
// Base case: two inserts sharing the same offset
expectNil(CollectionDifference<Int>.init([
.insert(offset: 0, element: 0, associatedWith: nil),
.insert(offset: 0, element: 0, associatedWith: nil)
]))
// Base case: two removes sharing the same offset
expectNil(CollectionDifference<Int>.init([
.remove(offset: 0, element: 0, associatedWith: nil),
.remove(offset: 0, element: 0, associatedWith: nil)
]))
// Base case: illegal insertion offset
expectNil(CollectionDifference<Int>.init([
.insert(offset: -1, element: 0, associatedWith: nil)
]))
// Base case: illegal remove offset
expectNil(CollectionDifference<Int>.init([
.remove(offset: -1, element: 0, associatedWith: nil)
]))
// Base case: two inserts sharing same associated offset
expectNil(CollectionDifference<Int>.init([
.insert(offset: 0, element: 0, associatedWith: 0),
.insert(offset: 1, element: 0, associatedWith: 0)
]))
// Base case: two removes sharing same associated offset
expectNil(CollectionDifference<Int>.init([
.remove(offset: 0, element: 0, associatedWith: 0),
.remove(offset: 1, element: 0, associatedWith: 0)
]))
// Base case: insert with illegal associated offset
expectNil(CollectionDifference<Int>.init([
.insert(offset: 0, element: 0, associatedWith: -1)
]))
// Base case: remove with illegal associated offset
expectNil(CollectionDifference<Int>.init([
.remove(offset: 1, element: 0, associatedWith: -1)
]))
// Code coverage: non-first change has illegal offset
expectNil(CollectionDifference<Int>.init([
.remove(offset: 0, element: 0, associatedWith: nil),
.insert(offset: -1, element: 0, associatedWith: nil)
]))
// Code coverage: non-first change has illegal associated offset
expectNil(CollectionDifference<Int>.init([
.remove(offset: 0, element: 0, associatedWith: nil),
.insert(offset: 0, element: 0, associatedWith: -1)
]))
}
suite.test("Enumeration order is safe") {
let safelyOrderedChanges: [CollectionDifference<Int>.Change] = [
.remove(offset: 2, element: 0, associatedWith: nil),
.remove(offset: 1, element: 0, associatedWith: 0),
.remove(offset: 0, element: 0, associatedWith: 1),
.insert(offset: 0, element: 0, associatedWith: 1),
.insert(offset: 1, element: 0, associatedWith: 0),
.insert(offset: 2, element: 0, associatedWith: nil),
]
let diff = CollectionDifference<Int>.init(safelyOrderedChanges)!
var enumerationOrderedChanges = [CollectionDifference<Int>.Change]()
diff.forEach { c in
enumerationOrderedChanges.append(c)
}
expectEqual(enumerationOrderedChanges, safelyOrderedChanges)
}
suite.test("Change validator rejects bad associations") {
// .remove(1) → .insert(1)
// ↑ ↓
// .insert(0) ← .remove(0)
expectNil(CollectionDifference<Int>.init([
.remove(offset: 1, element: 0, associatedWith: 1),
.remove(offset: 0, element: 0, associatedWith: 0),
.insert(offset: 0, element: 0, associatedWith: 1),
.insert(offset: 1, element: 0, associatedWith: 0)
]))
// Coverage: duplicate remove offsets both with assocs
expectNil(CollectionDifference<Int>.init([
.remove(offset: 0, element: 0, associatedWith: 1),
.remove(offset: 0, element: 0, associatedWith: 0),
]))
// Coverage: duplicate insert assocs
expectNil(CollectionDifference<Int>.init([
.insert(offset: 0, element: 0, associatedWith: 1),
.insert(offset: 1, element: 0, associatedWith: 1),
]))
}
// Full-coverage test for CollectionDifference.Change.==()
suite.test("Exhaustive testing for equatable conformance") {
// Differs by type:
expectNotEqual(
CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0)
)
// Differs by type in the other direction:
expectNotEqual(
CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0)
)
// Insert differs by offset
expectNotEqual(
CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.insert(offset: 1, element: 0, associatedWith: 0)
)
// Insert differs by element
expectNotEqual(
CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.insert(offset: 0, element: 1, associatedWith: 0)
)
// Insert differs by association
expectNotEqual(
CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.insert(offset: 0, element: 0, associatedWith: 1)
)
// Remove differs by offset
expectNotEqual(
CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.remove(offset: 1, element: 0, associatedWith: 0)
)
// Remove differs by element
expectNotEqual(
CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.remove(offset: 0, element: 1, associatedWith: 0)
)
// Remove differs by association
expectNotEqual(
CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 0),
CollectionDifference<Int>.Change.remove(offset: 0, element: 0, associatedWith: 1)
)
}
suite.test("Compile-time test of hashable conformance") {
let _ = Set<CollectionDifference<String>>();
}
suite.test("Move inference") {
let n = CollectionDifference<String>.init([
.insert(offset: 3, element: "Sike", associatedWith: nil),
.insert(offset: 4, element: "Sike", associatedWith: nil),
.insert(offset: 2, element: "Hello", associatedWith: nil),
.remove(offset: 6, element: "Hello", associatedWith: nil),
.remove(offset: 8, element: "Goodbye", associatedWith: nil),
.remove(offset: 9, element: "Sike", associatedWith: nil),
])
let w = CollectionDifference<String>.init([
.insert(offset: 3, element: "Sike", associatedWith: nil),
.insert(offset: 4, element: "Sike", associatedWith: nil),
.insert(offset: 2, element: "Hello", associatedWith: 6),
.remove(offset: 6, element: "Hello", associatedWith: 2),
.remove(offset: 8, element: "Goodbye", associatedWith: nil),
.remove(offset: 9, element: "Sike", associatedWith: nil),
])
expectEqual(w, n?.inferringMoves())
}
suite.test("Three way merge") {
let baseLines = ["Is", "it", "time", "already?"]
let theirLines = ["Hi", "there", "is", "it", "time", "already?"]
let myLines = ["Is", "it", "review", "time", "already?"]
// Create a difference from base to theirs
let diff = theirLines.difference(from: baseLines)
// Apply it to mine, if possible
guard let patchedLines = myLines.applying(diff) else {
print("Merge conflict applying patch, manual merge required")
return
}
// Reassemble the result
expectEqual(patchedLines, ["Hi", "there", "is", "it", "review", "time", "already?"])
// print(patched)
}
suite.test("Diff reversal demo code") {
let diff = CollectionDifference<Int>([])!
let _ = CollectionDifference<Int>(
diff.map({(change) -> CollectionDifference<Int>.Change in
switch change {
case .insert(offset: let o, element: let e, associatedWith: let a):
return .remove(offset: o, element: e, associatedWith: a)
case .remove(offset: let o, element: let e, associatedWith: let a):
return .insert(offset: o, element: e, associatedWith: a)
}
})
)!
}
suite.test("Naive application by enumeration") {
var arr = ["Is", "it", "time", "already?"]
let theirLines = ["Hi", "there", "is", "it", "time", "already?"]
// Create a difference from base to theirs
let diff = theirLines.difference(from: arr)
for c in diff {
switch c {
case .remove(offset: let o, element: _, associatedWith: _):
arr.remove(at: o)
case .insert(offset: let o, element: let e, associatedWith: _):
arr.insert(e, at: o)
}
}
expectEqual(theirLines, arr)
}
suite.test("Fast applicator boundary conditions") {
let a = [1, 2, 3, 4, 5, 6, 7, 8]
for removeMiddle in [false, true] {
for insertMiddle in [false, true] {
for removeLast in [false, true] {
for insertLast in [false, true] {
for removeFirst in [false, true] {
for insertFirst in [false, true] {
var b = a
// Prepare b
if removeMiddle { b.remove(at: 4) }
if insertMiddle { b.insert(10, at: 4) }
if removeLast { b.removeLast() }
if insertLast { b.append(11) }
if removeFirst { b.removeFirst() }
if insertFirst { b.insert(12, at: 0) }
// Generate diff
let diff = b.difference(from: a)
// Validate application
expectEqual(b, a.applying(diff)!)
expectEqual(a, b.applying(diff.inverse())!)
}}}}}}
}
}
if #available(macOS 10.15.4, iOS 13.4, tvOS 13.4, watchOS 6.2, *) {
suite.test("Fast applicator error condition") {
let bear = "bear"
let bird = "bird"
let bat = "bat"
let diff = bird.difference(from: bear)
expectEqual(nil, bat.applying(diff))
}
suite.test("Fast applicator boundary condition remove last element") {
let base = [1, 2, 3]
expectEqual([1, 2], base.applying(CollectionDifference<Int>([.remove(offset: base.count - 1, element: 3, associatedWith: nil)])!))
}
suite.test("Fast applicator boundary condition append element") {
let base = [1, 2, 3]
expectEqual([1, 2, 3, 4], base.applying(CollectionDifference<Int>([.insert(offset: base.count, element: 4, associatedWith: nil)])!))
}
suite.test("Fast applicator error boundary condition remove at endIndex") {
let base = [1, 2, 3]
expectEqual(nil, base.applying(CollectionDifference<Int>([.remove(offset: base.count, element: 4, associatedWith: nil)])!))
}
suite.test("Fast applicator error boundary condition insert beyond end") {
let base = [1, 2, 3]
expectEqual(nil, base.applying(CollectionDifference<Int>([.insert(offset: base.count + 1, element: 5, associatedWith: nil)])!))
}
suite.test("Fast applicator boundary condition replace tail") {
let base = [1, 2, 3]
expectEqual([1, 2, 4], base.applying(CollectionDifference<Int>([
.remove(offset: base.count - 1, element: 3, associatedWith: nil),
.insert(offset: base.count - 1, element: 4, associatedWith: nil)
])!))
}
suite.test("Fast applicator error boundary condition insert beyond end after tail removal") {
let base = [1, 2, 3]
expectEqual(nil, base.applying(CollectionDifference<Int>([
.remove(offset: base.count - 1, element: 3, associatedWith: nil),
.insert(offset: base.count, element: 4, associatedWith: nil)
])!))
}
suite.test("Fast applicator error boundary condition insert beyond end after non-tail removal") {
let base = [1, 2, 3]
expectEqual(nil, base.applying(CollectionDifference<Int>([
.remove(offset: base.count - 2, element: 2, associatedWith: nil),
.insert(offset: base.count, element: 4, associatedWith: nil)
])!))
}
}
if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {
suite.test("Fast applicator fuzzer") {
func makeArray() -> [Int] {
var arr = [Int]()
for _ in 0..<Int.random(in: 0..<10) {
arr.append(Int.random(in: 0..<20))
}
return arr
}
for _ in 0..<1000 {
let a = makeArray()
let b = makeArray()
let d = b.difference(from: a)
let applied = a.applying(d)
expectNotNil(applied)
if let applied = applied {
expectEqual(b, applied)
expectEqual(a, applied.applying(d.inverse()))
if (b != applied) {
print("""
// repro:
let a = \(a)
let b = \(b)
let d = b.difference(from: a)
expectEqual(b, a.applying(d))
expectEqual(a, applied.applying(d.inverse()))
""")
break
}
}
}
}
}
runAllTests()
| apache-2.0 | 6c7fa942257b0e4c7cecafc15366ccbd | 34.375171 | 136 | 0.570536 | 3.642366 | false | false | false | false |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/apiinteraction/connect/ConnectService.swift | 2 | 7022 | //
// ConnectService.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 07/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
enum CSError: Error {
case IllegalArgumentException(String)
case LowBridge
}
public class ConnectService {
public let JsonSerializer: IJsonSerializer
let logger: ILogger
let httpClient: IAsyncHttpClient
private let appName: String
private let appVersion: String
public init(jsonSerializer: IJsonSerializer, logger: ILogger, httpClient: IAsyncHttpClient, appName: String, appVersion: String) {
self.JsonSerializer = jsonSerializer
self.logger = logger
self.httpClient = httpClient
self.appName = appName
self.appVersion = appVersion
}
public func Authenticate(username: String, password: String, success: @escaping (ConnectAuthenticationResult) -> Void, failure: @escaping (EmbyError) -> Void) {
// UnsupportedEncodingException, NoSuchAlgorithmException {
let args = QueryStringDictionary()
args.Add("nameOrEmail", value: username)
args.Add("password", value: ConnectPassword.PerformPreHashFilter(password: password).md5())
let url = GetConnectUrl(handler: "user/authenticate")
let request = HttpRequest(url: url, method: .post, postData: args)
AddXApplicationName(request: request)
httpClient.sendRequest(request: request, success: success, failure: failure)
}
public func CreatePin(deviceId: String, success: @escaping (PinCreationResult) -> Void, failure: @escaping (EmbyError) -> Void)
{
let args = QueryStringDictionary()
args.Add("deviceId", value: deviceId)
let url = GetConnectUrl(handler: "pin") + "?" + args.GetQueryString()
let request = HttpRequest(url: url, method: .post, postData: args)
AddXApplicationName(request: request)
httpClient.sendRequest(request: request, success: success, failure: failure)
}
public func GetPinStatus(pin: PinCreationResult, success: @escaping (PinStatusResult) -> Void, failure: @escaping (EmbyError) -> Void)
{
let dict = QueryStringDictionary()
dict.Add("deviceId", value: pin.deviceId)
dict.Add("pin", value: pin.pin)
let url = GetConnectUrl(handler: "pin") + "?" + dict.GetQueryString()
let request = HttpRequest(url: url, method: .get)
AddXApplicationName(request: request)
httpClient.sendRequest(request: request, success: success, failure: failure)
}
public func ExchangePin(pin: PinCreationResult, success: @escaping (PinExchangeResult) -> Void, failure: @escaping (EmbyError) -> Void)
{
let args = QueryStringDictionary()
args.Add("deviceId", value: pin.deviceId)
args.Add("pin", value: pin.pin)
let url = GetConnectUrl(handler: "pin/authenticate")
let request = HttpRequest(url: url, method: .post, postData: args)
AddXApplicationName(request: request)
httpClient.sendRequest(request: request, success: success, failure: failure)
}
public func GetConnectUser(query: ConnectUserQuery, connectAccessToken: String?, success: @escaping (ConnectUser) -> Void, failure: @escaping (EmbyError) -> Void) throws
{
let dict = QueryStringDictionary()
if let id = query.id
{
dict.Add("id", value: id)
}
else if let name = query.name
{
dict.Add("name", value: name)
}
else if let email = query.email
{
dict.Add("email", value: email)
}
else if let nameOrEmail = query.nameOrEmail
{
dict.Add("nameOrEmail", value: nameOrEmail)
}
else
{
throw CSError.IllegalArgumentException("Empty ConnectUserQuery")
}
let url = GetConnectUrl(handler: "user") + "?" + dict.GetQueryString()
let request = HttpRequest(url: url, method: .get)
try AddUserAccessToken(request: request, accessToken: connectAccessToken)
AddXApplicationName(request: request)
httpClient.sendRequest(request: request, success: success, failure: failure)
}
public func GetServers(userId: String, connectAccessToken: String, success: @escaping ([ConnectUserServer]) -> Void, failure: @escaping (EmbyError) -> Void) throws
{
let dict = QueryStringDictionary()
dict.Add("userId", value: userId)
let url = GetConnectUrl(handler: "servers") + "?" + dict.GetQueryString()
let request = HttpRequest(url: url, method: .get)
try AddUserAccessToken(request: request, accessToken: connectAccessToken)
AddXApplicationName(request: request)
httpClient.sendCollectionRequest(request: request, success: success, failure: failure)
}
public func Logout(connectAccessToken: String, success: @escaping (EmptyResponse) -> Void, failure: @escaping (EmbyError) -> Void) throws
{
let url = GetConnectUrl(handler: "user/logout")
let request = HttpRequest(url: url, method: .post)
try AddUserAccessToken(request: request, accessToken: connectAccessToken)
AddXApplicationName(request: request)
httpClient.sendRequest(request: request, success: success, failure: failure)
}
private func GetConnectUrl(handler: String) -> String
{
return Configuration.mediaBrowserTV_APIServer + handler
}
private func AddUserAccessToken(request: HttpRequest, accessToken: String?) throws
{
if let accessToken = accessToken
{
request.headers["X-Connect-UserToken"] = accessToken
} else {
throw CSError.IllegalArgumentException("accessToken")
}
}
private func AddXApplicationName(request: HttpRequest)
{
request.headers["X-Application"] = appName + "/" + appVersion
}
public func GetRegistrationInfo(userId: String, feature: String, connectAccessToken: String, success: @escaping (RegistrationInfo) -> Void, failure: @escaping (EmbyError) -> Void) throws
{
let dict = QueryStringDictionary()
dict.Add("userId", value: userId)
dict.Add("feature", value: feature)
let url = GetConnectUrl(handler: "registrationInfo") + "?" + dict.GetQueryString()
let request = HttpRequest(url: url, method: .get)
try AddUserAccessToken(request: request, accessToken: connectAccessToken)
AddXApplicationName(request: request)
httpClient.sendRequest(request: request, success: success, failure: failure)
}
}
| mit | 21872d13cc863e7fd1db7cc5acefd23b | 34.639594 | 190 | 0.628543 | 4.70892 | false | false | false | false |
Finb/V2ex-Swift | View/UIButton+Extension.swift | 1 | 532 | //
// UIButton+Extension.swift
// V2ex-Swift
//
// Created by huangfeng on 1/29/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
extension UIButton {
class func roundedButton() -> UIButton {
let btn = UIButton(type: .custom)
btn.layer.masksToBounds = true
btn.layer.cornerRadius = 3
btn.backgroundColor = V2EXColor.colors.v2_ButtonBackgroundColor
btn.titleLabel!.font = v2Font(14)
btn.setTitleColor(UIColor.white, for: .normal)
return btn
}
}
| mit | 6c010e829a95d8fc1bf3d60d443dcc9d | 24.285714 | 72 | 0.647834 | 3.739437 | false | false | false | false |
wibosco/ASOS-Consumer | ASOSConsumer/ViewControllers/Product/ProductViewController.swift | 1 | 8029 | //
// ProductViewController.swift
// ASOSConsumer
//
// Created by William Boles on 03/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
import PureLayout
let kCollectionViewHeight: CGFloat = 268.0
class ProductViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
//MARK: - Accessors
var categoryProduct: CategoryProduct
private var product: Product?
private lazy var brandLabel: UILabel = {
let brandLabel = UILabel.newAutoLayoutView()
brandLabel.textAlignment = NSTextAlignment.Center
brandLabel.backgroundColor = UIColor.lightGrayColor()
return brandLabel
}()
private lazy var collectionView: UICollectionView = {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: self.view.frame.size.width, height: kCollectionViewHeight)
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
layout.minimumInteritemSpacing = 0.0
layout.minimumLineSpacing = 0.0
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.pagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(MediaCollectionViewCell.self, forCellWithReuseIdentifier: MediaCollectionViewCell.reuseIdentifier())
return collectionView
}()
private lazy var productDescriptionTextView: UITextView = {
let productDescriptionTextView = UITextView.newAutoLayoutView()
productDescriptionTextView.editable = false
let paddingInset: CGFloat = 10.0
productDescriptionTextView.textContainerInset = UIEdgeInsetsMake(0.0, paddingInset, 0.0, paddingInset);
return productDescriptionTextView
}()
private lazy var addToBasketButton: UIButton = {
let addToBasketButton = UIButton.newAutoLayoutView()
addToBasketButton.addTarget(self, action: "addToBasketButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
addToBasketButton.backgroundColor = UIColor.greenColor()
addToBasketButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
addToBasketButton.titleLabel!.font = UIFont.boldSystemFontOfSize(17.0)
return addToBasketButton
}()
private lazy var loadingView: LoadingView = {
let loadingView = LoadingView.init(frame: self.view.frame)
return loadingView
}()
//MARK: - Init
init(categoryProduct: CategoryProduct) {
self.categoryProduct = categoryProduct
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - ViewLifecycle
override func viewDidLoad() {
super.viewDidLoad()
/*-----------------*/
self.view.addSubview(self.brandLabel)
self.view.addSubview(self.collectionView)
self.view.addSubview(self.productDescriptionTextView)
self.view.addSubview(self.addToBasketButton)
/*-----------------*/
self.updateViewConstraints()
/*-----------------*/
self.refresh()
}
//MARK: - Constraints
override func updateViewConstraints() {
self.brandLabel.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view)
self.brandLabel.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Top, ofView: self.view, withOffset: 44.0)
self.brandLabel.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view)
self.brandLabel.autoSetDimension(ALDimension.Height, toSize: 20.0)
/*-----------------*/
self.collectionView.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view)
self.collectionView.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: self.brandLabel)
self.collectionView.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view)
self.collectionView.autoSetDimension(ALDimension.Height, toSize: kCollectionViewHeight)
/*-----------------*/
self.addToBasketButton.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view)
self.addToBasketButton.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view)
self.addToBasketButton.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Bottom, ofView: self.view)
self.addToBasketButton.autoSetDimension(ALDimension.Height, toSize: 44.0)
/*-----------------*/
self.productDescriptionTextView.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view)
self.productDescriptionTextView.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: self.collectionView)
self.productDescriptionTextView.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view)
self.productDescriptionTextView.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Top, ofView: self.addToBasketButton)
/*-----------------*/
super.updateViewConstraints()
}
//MARK: - DataRetrieval
private func refresh() {
self.view.addSubview(self.loadingView)
ProductAPIManager.retrieveProduct(self.categoryProduct) {[weak self] (product) -> Void in
if let strongSelf = self {
strongSelf.product = product
/*-----------------*/
let title = NSLocalizedString("Add To Basket", comment: "") + " (\(strongSelf.product!.displayPrice!))"
strongSelf.addToBasketButton.setTitle(title as String, forState: UIControlState.Normal)
/*-----------------*/
strongSelf.productDescriptionTextView.text = strongSelf.product!.displayDescription
/*-----------------*/
strongSelf.brandLabel.text = strongSelf.product!.brand
/*-----------------*/
strongSelf.collectionView.reloadData()
/*-----------------*/
strongSelf.loadingView.removeFromSuperview()
}
}
}
//MARK: - UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numberOfItemsInSection = 0
if (self.product != nil) {
numberOfItemsInSection = self.product!.medias.count
}
return numberOfItemsInSection
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MediaCollectionViewCell.reuseIdentifier(), forIndexPath: indexPath) as! MediaCollectionViewCell
let productMedia = self.product?.medias[indexPath.row]
MediaAPIManager.retrieveMediaAsset(productMedia!) { (media, mediaImage) -> Void in
if (productMedia!.isEqual(media)) {
cell.productImageView.image = mediaImage
}
}
return cell
}
//MARK: - ButtonActions
private func addToBasketButtonPressed(sender: UIButton) {
SessionManager.sharedInstance.basketProducts.append(self.product!)
}
}
| mit | b2176212cc03ce700aa58fcf11722a14 | 36.339535 | 168 | 0.627803 | 5.66549 | false | false | false | false |
petereddy/Alamofire | Tests/ResponseTests.swift | 7 | 20829 | // ResponseTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class ResponseDataTestCase: BaseTestCase {
func testThatResponseDataReturnsSuccessResultWithValidData() {
// Given
let URLString = "https://httpbin.org/get"
let expectation = expectationWithDescription("request should succeed")
var response: Response<NSData, NSError>?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseData { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isSuccess, "result should be success")
} else {
XCTFail("response should not be nil")
}
}
func testThatResponseDataReturnsFailureResultWithOptionalDataAndError() {
// Given
let URLString = "https://invalid-url-here.org/this/does/not/exist"
let expectation = expectationWithDescription("request should fail with 404")
var response: Response<NSData, NSError>?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseData { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNil(response.response, "response should be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isFailure, "result should be failure")
} else {
XCTFail("response should not be nil")
}
}
}
// MARK: -
class ResponseStringTestCase: BaseTestCase {
func testThatResponseStringReturnsSuccessResultWithValidString() {
// Given
let URLString = "https://httpbin.org/get"
let expectation = expectationWithDescription("request should succeed")
var response: Response<String, NSError>?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseString { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isSuccess, "result should be success")
} else {
XCTFail("response should not be nil")
}
}
func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() {
// Given
let URLString = "https://invalid-url-here.org/this/does/not/exist"
let expectation = expectationWithDescription("request should fail with 404")
var response: Response<String, NSError>?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseString { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNil(response.response, "response should be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isFailure, "result should be failure")
} else {
XCTFail("response should not be nil")
}
}
}
// MARK: -
class ResponseJSONTestCase: BaseTestCase {
func testThatResponseJSONReturnsSuccessResultWithValidJSON() {
// Given
let URLString = "https://httpbin.org/get"
let expectation = expectationWithDescription("request should succeed")
var response: Response<AnyObject, NSError>?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isSuccess, "result should be success")
} else {
XCTFail("response should not be nil")
}
}
func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() {
// Given
let URLString = "https://invalid-url-here.org/this/does/not/exist"
let expectation = expectationWithDescription("request should fail with 404")
var response: Response<AnyObject, NSError>?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNil(response.response, "response should be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isFailure, "result should be failure")
} else {
XCTFail("response should not be nil")
}
}
func testThatResponseJSONReturnsSuccessResultForGETRequest() {
// Given
let URLString = "https://httpbin.org/get"
let expectation = expectationWithDescription("request should succeed")
var response: Response<AnyObject, NSError>?
// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isSuccess, "result should be success")
// The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info.
// - https://openradar.appspot.com/radar?id=5517037090635776
if let args = response.result.value?["args" as NSString] as? [String: String] {
XCTAssertEqual(args, ["foo": "bar"], "args should match parameters")
} else {
XCTFail("args should not be nil")
}
} else {
XCTFail("response should not be nil")
}
}
func testThatResponseJSONReturnsSuccessResultForPOSTRequest() {
// Given
let URLString = "https://httpbin.org/post"
let expectation = expectationWithDescription("request should succeed")
var response: Response<AnyObject, NSError>?
// When
Alamofire.request(.POST, URLString, parameters: ["foo": "bar"])
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
if let response = response {
XCTAssertNotNil(response.request, "request should not be nil")
XCTAssertNotNil(response.response, "response should not be nil")
XCTAssertNotNil(response.data, "data should not be nil")
XCTAssertTrue(response.result.isSuccess, "result should be success")
// The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info.
// - https://openradar.appspot.com/radar?id=5517037090635776
if let form = response.result.value?["form" as NSString] as? [String: String] {
XCTAssertEqual(form, ["foo": "bar"], "form should match parameters")
} else {
XCTFail("form should not be nil")
}
} else {
XCTFail("response should not be nil")
}
}
}
// MARK: -
class RedirectResponseTestCase: BaseTestCase {
// MARK: Setup and Teardown
override func tearDown() {
super.tearDown()
Alamofire.Manager.sharedInstance.delegate.taskWillPerformHTTPRedirection = nil
}
// MARK: Tests
func testThatRequestWillPerformHTTPRedirectionByDefault() {
// Given
let redirectURLString = "https://www.apple.com"
let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)"
let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL")
XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code")
}
func testThatRequestWillPerformRedirectionMultipleTimesByDefault() {
// Given
let redirectURLString = "https://httpbin.org/get"
let URLString = "https://httpbin.org/redirect/5"
let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL")
XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code")
}
func testThatTaskOverrideClosureCanPerformHTTPRedirection() {
// Given
let redirectURLString = "https://www.apple.com"
let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)"
let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)")
let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate
delegate.taskWillPerformHTTPRedirection = { _, _, _, request in
return request
}
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL")
XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code")
}
func testThatTaskOverrideClosureCanCancelHTTPRedirection() {
// Given
let redirectURLString = "https://www.apple.com"
let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)"
let expectation = expectationWithDescription("Request should not redirect to \(redirectURLString)")
let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate
delegate.taskWillPerformHTTPRedirection = { _, _, _, _ in
return nil
}
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(response?.URL?.URLString ?? "", URLString, "response URL should match the origin URL")
XCTAssertEqual(response?.statusCode ?? -1, 302, "response should have a 302 status code")
}
func testThatTaskOverrideClosureIsCalledMultipleTimesForMultipleHTTPRedirects() {
// Given
let redirectURLString = "https://httpbin.org/get"
let URLString = "https://httpbin.org/redirect/5"
let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)")
let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate
var totalRedirectCount = 0
delegate.taskWillPerformHTTPRedirection = { _, _, _, request in
++totalRedirectCount
return request
}
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: NSData?
var error: NSError?
// When
Alamofire.request(.GET, URLString)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL")
XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code")
XCTAssertEqual(totalRedirectCount, 5, "total redirect count should be 5")
}
func testThatRedirectedRequestContainsAllHeadersFromOriginalRequest() {
// Given
let redirectURLString = "https://httpbin.org/get"
let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)"
let headers = [
"Authorization": "1234",
"Custom-Header": "foobar",
]
// NOTE: It appears that most headers are maintained during a redirect with the exception of the `Authorization`
// header. It appears that Apple's strips the `Authorization` header from the redirected URL request. If you
// need to maintain the `Authorization` header, you need to manually append it to the redirected request.
Alamofire.Manager.sharedInstance.delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
var redirectedRequest = request
if let
originalRequest = task.originalRequest,
headers = originalRequest.allHTTPHeaderFields,
authorizationHeaderValue = headers["Authorization"]
{
let mutableRequest = request.mutableCopy() as! NSMutableURLRequest
mutableRequest.setValue(authorizationHeaderValue, forHTTPHeaderField: "Authorization")
redirectedRequest = mutableRequest
}
return redirectedRequest
}
let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)")
var response: Response<AnyObject, NSError>?
// When
Alamofire.request(.GET, URLString, headers: headers)
.responseJSON { closureResponse in
response = closureResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(response?.request, "request should not be nil")
XCTAssertNotNil(response?.response, "response should not be nil")
XCTAssertNotNil(response?.data, "data should not be nil")
XCTAssertTrue(response?.result.isSuccess ?? false, "response result should be a success")
if let
JSON = response?.result.value as? [String: AnyObject],
headers = JSON["headers"] as? [String: String]
{
XCTAssertEqual(headers["Custom-Header"], "foobar", "Custom-Header should be equal to foobar")
XCTAssertEqual(headers["Authorization"], "1234", "Authorization header should be equal to 1234")
}
}
}
| mit | 7b295aa6ec29d87610758b3b5c2d2ad6 | 38.222222 | 120 | 0.641139 | 5.493801 | false | false | false | false |
githubError/KaraNotes | KaraNotes/KaraNotes/Other/View/CPFProgressView.swift | 1 | 7295 | //
// CPFProgressView.swift
// KaraNotes
//
// Created by 崔鹏飞 on 2017/4/11.
// Copyright © 2017年 崔鹏飞. All rights reserved.
//
import UIKit
class CPFProgressView: UIView {
static let instance:CPFProgressView = CPFProgressView()
var progressValue:CGFloat! = 0.0 {
didSet{
progressFrontgroundBezierPath = UIBezierPath(arcCenter: progressView.center, radius: (progressViewSize.width - progressStrokeWidth - progressCircleMargin) / 2.0, startAngle: -CGFloat(Double.pi / 2.0), endAngle: CGFloat(Double.pi * 2.0) * progressValue - CGFloat(Double.pi / 2.0), clockwise: true)
progressFrontgroundLayer.path = progressFrontgroundBezierPath.cgPath
}
}
var progressPromptText:String! = ""{
didSet{
progressPromptLabel.text = ""
progressPromptLabel.text = progressPromptText
}
}
var progressStrokeWidth:CGFloat = 5.0
var progressColor:UIColor = CPFRGBA(r: 0, g: 118, b: 255, a: 1.0)
var progressTrackColor:UIColor = CPFRGBA(r: 200, g: 200, b: 200, a: 0.8)
var progressViewColor:UIColor = UIColor.white
var dismissBtnTitleColor:UIColor = UIColor.black
var progressViewSize:CGSize = CGSize(width: 100, height: 100)
fileprivate var progressView:UIView!
fileprivate var progressPromptLabel:UILabel!
fileprivate var separateLineView:UIView!
fileprivate var dismissProgressViewBtn:UIButton!
fileprivate var progressBackgroundView:UIView!
fileprivate var progressBackgroundLayer: CAShapeLayer!
fileprivate var progressFrontgroundLayer: CAShapeLayer!
fileprivate var progressBackgroundBezierPath:UIBezierPath!
fileprivate var progressFrontgroundBezierPath:UIBezierPath!
fileprivate let progressCircleMargin:CGFloat = 10.0
fileprivate let separateLineViewHeight:CGFloat = 1.0
fileprivate var once:Bool = true
static func sharedInstance() -> CPFProgressView {
if instance.once {
let window = UIApplication.shared.keyWindow
instance.frame = (window?.bounds)!
instance.backgroundColor = CPFRGBA(r: 0, g: 0, b: 0, a: 0.2)
window?.addSubview(instance)
instance.setupSubviews()
instance.once = false
}
return instance
}
}
extension CPFProgressView {
func showProgressView(progress:CGFloat, promptMessage message:String) -> Void {
progressValue = progress
progressPromptText = message
}
func dismissProgressView(completionHandeler: () -> Void) -> Void {
//completionHandeler()
progressView.layer.sublayers?.forEach({ (layer) in
layer.removeFromSuperlayer()
})
subviews.forEach { (view) in
view.removeFromSuperview()
}
once = true
removeFromSuperview()
}
}
// MARK:- setup subviews
extension CPFProgressView {
func setupSubviews() -> Void {
setupProgressView()
setupProgressPromptLabel()
setupSeparateLine()
setupDismissProgressViewBtn()
setupProgressBackgroundView()
setupLayer()
}
func setupProgressView() -> Void {
let point = CGPoint(x: center.x - progressViewSize.width / 2.0 , y: center.y - progressViewSize.height / 2.0)
progressView = UIView(frame: CGRect(origin: point, size: progressViewSize))
addSubview(progressView)
}
func setupProgressPromptLabel() -> Void {
progressPromptLabel = UILabel()
let labelW = progressViewSize.width - 3.0 * progressCircleMargin
let labelH = CGFloat(50.0)
let labelX = (progressViewSize.width - labelW) / 2.0
let labelY = (progressViewSize.height - labelH) / 2.0
progressPromptLabel.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
progressPromptLabel.font = CPFPingFangSC(weight: .light, size: 12)
progressPromptLabel.textAlignment = .center
progressPromptLabel.numberOfLines = 0
progressView.addSubview(progressPromptLabel)
}
func setupSeparateLine() -> Void {
separateLineView = UIView()
let x = progressView.frame.origin.x
let y = progressView.frame.origin.y + progressViewSize.height
separateLineView.frame = CGRect(x: x, y: y, width: progressViewSize.width, height: separateLineViewHeight)
separateLineView.backgroundColor = CPFRGBA(r: 158, g: 158, b: 158, a: 0.8)
addSubview(separateLineView)
}
func setupDismissProgressViewBtn() -> Void {
dismissProgressViewBtn = UIButton(type: .custom)
let btnX = progressView.frame.origin.x
let btnY = progressView.frame.origin.y + progressViewSize.height + separateLineViewHeight
dismissProgressViewBtn.frame = CGRect(x: btnX, y: btnY, width: progressViewSize.width, height: 20)
dismissProgressViewBtn.setTitle(CPFLocalizableTitle("progressView_dismissBtn"), for: .normal)
dismissProgressViewBtn.titleLabel?.font = CPFPingFangSC(weight: .regular, size: 15)
dismissProgressViewBtn.setTitleColor(dismissBtnTitleColor, for: .normal)
dismissProgressViewBtn.addTarget(self, action: #selector(dismissProgressView(completionHandeler:)), for: .touchUpInside)
addSubview(dismissProgressViewBtn)
}
func setupProgressBackgroundView() -> Void {
progressBackgroundView = UIView()
let x = progressView.frame.origin.x
let y = progressView.frame.origin.y
progressBackgroundView.frame = CGRect(x: x, y: y, width: progressViewSize.width, height: progressViewSize.height + dismissProgressViewBtn.frame.size.height + separateLineViewHeight)
insertSubview(progressBackgroundView, at: 0)
progressBackgroundView.backgroundColor = progressViewColor
progressBackgroundView.makeRound(round: 10)
}
func setupLayer() -> Void {
let point = CGPoint(x: -(center.x - progressViewSize.width / 2.0) , y: -(center.y - progressViewSize.height / 2.0))
progressBackgroundLayer = CAShapeLayer()
progressBackgroundLayer.frame = CGRect(origin: point, size: progressViewSize)
progressView.layer.addSublayer(progressBackgroundLayer)
progressBackgroundLayer.fillColor = nil
progressBackgroundLayer.strokeColor = progressTrackColor.cgColor
progressBackgroundLayer.lineWidth = progressStrokeWidth
progressFrontgroundLayer = CAShapeLayer()
progressFrontgroundLayer.frame = CGRect(origin: point, size: progressViewSize)
progressView.layer.addSublayer(progressFrontgroundLayer)
progressFrontgroundLayer.fillColor = nil
progressFrontgroundLayer.strokeColor = progressColor.cgColor
progressFrontgroundLayer.lineWidth = progressStrokeWidth
progressFrontgroundLayer.lineCap = "round"
progressBackgroundBezierPath = UIBezierPath(arcCenter: progressView.center, radius: (progressViewSize.width - progressStrokeWidth - progressCircleMargin) / 2.0, startAngle: 0, endAngle: CGFloat(Double.pi * 2.0), clockwise: true)
progressBackgroundLayer.path = progressBackgroundBezierPath.cgPath
}
}
| apache-2.0 | 591d8de303f6be6786e3c2cd1309abde | 40.83908 | 308 | 0.686401 | 4.818001 | false | false | false | false |
timd/ProiOSTableCollectionViews | Ch16/endPoint/SwiftClock/SwiftClock/ClockLayout.swift | 1 | 7572 | //
// ClockLayout.swift
// SwiftClock
//
// Created by Tim on 23/04/15.
// Copyright (c) 2015 Tim Duckett. All rights reserved.
//
import UIKit
class ClockLayout: UICollectionViewLayout {
private var clockTime: NSDate!
private let dateFormatter = NSDateFormatter()
private var timeHours: Int!
private var timeMinutes: Int!
private var timeSeconds: Int!
var minuteHandSize: CGSize!
var secondHandSize: CGSize!
var hourHandSize: CGSize!
var hourLabelCellSize: CGSize!
private var clockFaceRadius: CGFloat!
private var cvCenter: CGPoint!
private var attributesArray = [UICollectionViewLayoutAttributes]()
// MARK:
// MARK: UICollectionViewLayout functions
override func prepareLayout() {
cvCenter = CGPointMake(collectionView!.frame.size.width/2, collectionView!.frame.size.height/2)
clockTime = NSDate()
dateFormatter.dateFormat = "HH"
let hourString = dateFormatter.stringFromDate(clockTime)
timeHours = Int(hourString)!
dateFormatter.dateFormat = "mm"
let minString = dateFormatter.stringFromDate(clockTime)
timeMinutes = Int(minString)!
dateFormatter.dateFormat = "ss"
let secString = dateFormatter.stringFromDate(clockTime)
timeSeconds = Int(secString)!
clockFaceRadius = min(cvCenter.x, cvCenter.y)
calculateAllAttributes()
}
override func collectionViewContentSize() -> CGSize {
return collectionView!.frame.size
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attributesArray
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
// return the item from attributesArray with the matching indexPath
return attributesArray.filter({ (theAttribute) -> Bool in
theAttribute.indexPath == indexPath
}).first
}
// MARK:
// MARK: Unused UICollectionViewLayout function
override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
// Will not get called by this layout, as there are no decoration views involved
return nil
}
override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
// Will not get called by this layout, as there are no supplementary views involved
return nil
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
// Default value is false
return false
}
// MARK:
// MARK: Custom clock layout functions
func calculateAllAttributes() {
for section in 0..<collectionView!.numberOfSections() {
for item in 0..<collectionView!.numberOfItemsInSection(section) {
// Create index path for this item
let indexPath = NSIndexPath(forItem: item, inSection: section)
// Calculate the attributes
let attributes = calculateAttributesForItemAt(indexPath)
// Update or insert the newAttributes into the attributesArray
if let matchingAttributeIndex = attributesArray.indexOf( { (attributes: UICollectionViewLayoutAttributes ) -> Bool in
attributes.indexPath.compare(indexPath) == NSComparisonResult.OrderedSame
}) {
// Attribute already existed, therefore replace it
attributesArray[matchingAttributeIndex] = attributes
} else {
// New set of attributes required
attributesArray.append(attributes)
}
}
}
}
func calculateAttributesForItemAt(itemPath: NSIndexPath) -> UICollectionViewLayoutAttributes {
var newAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: itemPath)
if itemPath.section == 0 {
newAttributes = calculateAttributesForHandCellAt(itemPath)
}
if itemPath.section == 1 {
newAttributes = calculateAttributesForHourLabelWith(itemPath)
}
return newAttributes
}
func calculateAttributesForHourLabelWith(hourPath: NSIndexPath) -> UICollectionViewLayoutAttributes {
// Create new instance of UICollectionViewLayoutAttributes
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: hourPath)
// Calculate overall size of hour label
attributes.size = hourLabelCellSize
// Calculate the rotation per hour around the clock face
let angularDisplacement: Double = (2 * M_PI) / 12
let theta = angularDisplacement * Double(hourPath.row)
let xDisplacement = sin(theta) * Double(clockFaceRadius - (attributes.size.width / 2))
let yDisplacement = cos(theta) * Double(clockFaceRadius - (attributes.size.height / 2))
let xPosition = cvCenter.x + CGFloat(xDisplacement)
let yPosition = cvCenter.y - CGFloat(yDisplacement)
let center: CGPoint = CGPointMake(xPosition, yPosition)
attributes.center = center
return attributes
}
func calculateAttributesForHandCellAt(handPath: NSIndexPath) -> UICollectionViewLayoutAttributes {
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: handPath)
let rotationPerHour: Double = (2 * M_PI) / 12
let rotationPerMinute: Double = (2 * M_PI) / 60.0
switch handPath.row {
case 0: // handle hour hands
attributes.size = hourHandSize
attributes.center = cvCenter
let intraHourRotationPerMinute: Double = rotationPerHour / 60
let currentIntraHourRotation: Double = intraHourRotationPerMinute * Double(timeMinutes)
let angularDisplacement = (rotationPerHour * Double(timeHours)) + currentIntraHourRotation
attributes.transform = CGAffineTransformMakeRotation(CGFloat(angularDisplacement))
case 1: // handle minute hands
attributes.size = minuteHandSize
attributes.center = cvCenter
let intraMinuteRotationPerSecond: Double = rotationPerMinute / 60
let currentIntraMinuteRotation: Double = intraMinuteRotationPerSecond * Double(timeSeconds)
let angularDisplacement = (rotationPerMinute * Double(timeMinutes)) + currentIntraMinuteRotation
attributes.transform = CGAffineTransformMakeRotation(CGFloat(angularDisplacement))
case 2: // handle second hands
attributes.size = secondHandSize
attributes.center = cvCenter
let angularDisplacement = rotationPerMinute * Double(timeSeconds)
attributes.transform = CGAffineTransformMakeRotation(CGFloat(angularDisplacement))
default:
break
}
return attributes
}
} | mit | 9e1f5ae3a1c4241a49ca446ba2327f22 | 31.363248 | 156 | 0.63616 | 6 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/perfect-squares.swift | 2 | 548 | /**
* https://leetcode.com/problems/perfect-squares/
*
*
*/
// Date: Sat Jun 27 11:19:12 PDT 2020
class Solution {
func numSquares(_ n: Int) -> Int {
var steps = Array(repeating: Int.max, count: n + 1)
steps[0] = 0
for x in 1 ... n {
var minStep = steps[x]
var dx = 1
while (x - dx * dx) >= 0 {
minStep = min(minStep, 1 + steps[x - dx * dx])
dx += 1
}
steps[x] = minStep
}
return steps[n]
}
} | mit | 97c3cbf25e9b6c9026147b8f58d3549b | 22.869565 | 62 | 0.430657 | 3.558442 | false | false | false | false |
IvanVorobei/RequestPermission | Example/SPPermission/SPPermission/Frameworks/SparrowKit/Social/Viber/SPViber.swift | 1 | 2299 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPViber {
static var isSetApp: Bool {
return UIApplication.shared.canOpenURL(URL(string: "viber://forward?text=test")!)
}
static func share(text: String, complection: @escaping (_ isOpened: Bool)->() = {_ in }) {
let urlStringEncoded = text.addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)
let urlOptional = URL(string: "viber://forward?text=\(urlStringEncoded ?? "")")
if let url = urlOptional {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: complection)
} else {
complection(false)
}
} else {
complection(false)
}
}
private init() {}
}
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
| mit | 65de230286a001013915c3630cf97df8 | 45.897959 | 151 | 0.714099 | 4.81761 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ColorModel/Model/CMYColorModel.swift | 1 | 8869 | //
// CMYColorModel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@frozen
public struct CMYColorModel: ColorModel {
public typealias Indices = Range<Int>
public typealias Scalar = Double
@inlinable
@inline(__always)
public static var numberOfComponents: Int {
return 3
}
@inlinable
@inline(__always)
public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> {
precondition(0..<numberOfComponents ~= i, "Index out of range.")
return 0...1
}
public var cyan: Double
public var magenta: Double
public var yellow: Double
@inlinable
@inline(__always)
public init(cyan: Double, magenta: Double, yellow: Double) {
self.cyan = cyan
self.magenta = magenta
self.yellow = yellow
}
@inlinable
public subscript(position: Int) -> Double {
get {
return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] }
}
set {
withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue }
}
}
}
extension CMYColorModel {
@inlinable
@inline(__always)
public init() {
self.cyan = 0
self.magenta = 0
self.yellow = 0
}
}
extension CMYColorModel {
@inlinable
public init(_ gray: GrayColorModel) {
self.cyan = 1 - gray.white
self.magenta = 1 - gray.white
self.yellow = 1 - gray.white
}
@inlinable
public init(_ rgb: RGBColorModel) {
self.cyan = 1 - rgb.red
self.magenta = 1 - rgb.green
self.yellow = 1 - rgb.blue
}
@inlinable
public init(_ cmyk: CMYKColorModel) {
let _k = 1 - cmyk.black
self.cyan = cmyk.cyan * _k + cmyk.black
self.magenta = cmyk.magenta * _k + cmyk.black
self.yellow = cmyk.yellow * _k + cmyk.black
}
}
extension CMYColorModel {
@inlinable
@inline(__always)
public static var black: CMYColorModel {
return CMYColorModel(cyan: 1, magenta: 1, yellow: 1)
}
@inlinable
@inline(__always)
public static var white: CMYColorModel {
return CMYColorModel(cyan: 0, magenta: 0, yellow: 0)
}
@inlinable
@inline(__always)
public static var red: CMYColorModel {
return CMYColorModel(cyan: 0, magenta: 1, yellow: 1)
}
@inlinable
@inline(__always)
public static var green: CMYColorModel {
return CMYColorModel(cyan: 1, magenta: 0, yellow: 1)
}
@inlinable
@inline(__always)
public static var blue: CMYColorModel {
return CMYColorModel(cyan: 1, magenta: 1, yellow: 0)
}
@inlinable
@inline(__always)
public static var cyan: CMYColorModel {
return CMYColorModel(cyan: 1, magenta: 0, yellow: 0)
}
@inlinable
@inline(__always)
public static var magenta: CMYColorModel {
return CMYColorModel(cyan: 0, magenta: 1, yellow: 0)
}
@inlinable
@inline(__always)
public static var yellow: CMYColorModel {
return CMYColorModel(cyan: 0, magenta: 0, yellow: 1)
}
}
extension CMYColorModel {
@inlinable
@inline(__always)
public func normalized() -> CMYColorModel {
return self
}
@inlinable
@inline(__always)
public func denormalized() -> CMYColorModel {
return self
}
}
extension CMYColorModel {
@inlinable
@inline(__always)
public func map(_ transform: (Double) -> Double) -> CMYColorModel {
return CMYColorModel(cyan: transform(cyan), magenta: transform(magenta), yellow: transform(yellow))
}
@inlinable
@inline(__always)
public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result {
var accumulator = initialResult
updateAccumulatingResult(&accumulator, cyan)
updateAccumulatingResult(&accumulator, magenta)
updateAccumulatingResult(&accumulator, yellow)
return accumulator
}
@inlinable
@inline(__always)
public func combined(_ other: CMYColorModel, _ transform: (Double, Double) -> Double) -> CMYColorModel {
return CMYColorModel(cyan: transform(self.cyan, other.cyan), magenta: transform(self.magenta, other.magenta), yellow: transform(self.yellow, other.yellow))
}
}
extension CMYColorModel {
public typealias Float16Components = FloatComponents<float16>
public typealias Float32Components = FloatComponents<Float>
@frozen
public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents {
public typealias Indices = Range<Int>
@inlinable
@inline(__always)
public static var numberOfComponents: Int {
return 3
}
public var cyan: Scalar
public var magenta: Scalar
public var yellow: Scalar
@inline(__always)
public init() {
self.cyan = 0
self.magenta = 0
self.yellow = 0
}
@inline(__always)
public init(cyan: Scalar, magenta: Scalar, yellow: Scalar) {
self.cyan = cyan
self.magenta = magenta
self.yellow = yellow
}
@inlinable
@inline(__always)
public init(_ color: CMYColorModel) {
self.cyan = Scalar(color.cyan)
self.magenta = Scalar(color.magenta)
self.yellow = Scalar(color.yellow)
}
@inlinable
@inline(__always)
public init<T>(_ components: FloatComponents<T>) {
self.cyan = Scalar(components.cyan)
self.magenta = Scalar(components.magenta)
self.yellow = Scalar(components.yellow)
}
@inlinable
public subscript(position: Int) -> Scalar {
get {
return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] }
}
set {
withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue }
}
}
@inlinable
@inline(__always)
public var model: CMYColorModel {
get {
return CMYColorModel(cyan: Double(cyan), magenta: Double(magenta), yellow: Double(yellow))
}
set {
self = FloatComponents(newValue)
}
}
}
}
extension CMYColorModel.FloatComponents {
@inlinable
@inline(__always)
public func map(_ transform: (Scalar) -> Scalar) -> CMYColorModel.FloatComponents<Scalar> {
return CMYColorModel.FloatComponents(cyan: transform(cyan), magenta: transform(magenta), yellow: transform(yellow))
}
@inlinable
@inline(__always)
public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result {
var accumulator = initialResult
updateAccumulatingResult(&accumulator, cyan)
updateAccumulatingResult(&accumulator, magenta)
updateAccumulatingResult(&accumulator, yellow)
return accumulator
}
@inlinable
@inline(__always)
public func combined(_ other: CMYColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> CMYColorModel.FloatComponents<Scalar> {
return CMYColorModel.FloatComponents(cyan: transform(self.cyan, other.cyan), magenta: transform(self.magenta, other.magenta), yellow: transform(self.yellow, other.yellow))
}
}
| mit | 45da291faaa58a1caedd47d78ee5f842 | 29.269625 | 179 | 0.618108 | 4.48836 | false | false | false | false |
lkzhao/Hero | Examples/MatchInCollectionExample.swift | 1 | 2842 | import UIKit
import CollectionKit
class MatchInCollectionExampleViewController1: ExampleBaseViewController {
let collectionView = CollectionView()
override func viewDidLoad() {
super.viewDidLoad()
view.insertSubview(collectionView, belowSubview: dismissButton)
setupCollection()
}
func setupCollection() {
let dataSource = ArrayDataSource<Int>(data: Array(0..<30))
let viewSource = ClosureViewSource { (view: UILabel, data: Int, index: Int) in
let color = UIColor(hue: CGFloat(data) / 30, saturation: 0.68,
brightness: 0.98, alpha: 1)
view.backgroundColor = color
view.textColor = .white
view.textAlignment = .center
view.layer.cornerRadius = 4
view.layer.masksToBounds = true
view.text = "\(data)"
}
let sizeSource = { (i: Int, data: Int, size: CGSize) -> CGSize in
let width: CGFloat = (size.width - 20) / 3
return CGSize(width: width, height: width)
}
let provider = BasicProvider<Int, UILabel>(
dataSource: dataSource,
viewSource: viewSource,
sizeSource: sizeSource,
layout: FlowLayout(spacing: 10).inset(by: UIEdgeInsets(top: 100, left: 10, bottom: 10, right: 10))
)
provider.tapHandler = { (context) in
self.cellTapped(cell: context.view, data: context.data)
}
collectionView.provider = provider
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
func cellTapped(cell: UIView, data: Int) {
// MARK: Hero configuration
// here we are using the data as the hero.id, we have to make sure that this id is
// unique for each cell. a random hero.id will also work.
let heroId = "cell\(data)"
cell.hero.id = heroId
let vc = MatchInCollectionExampleViewController2()
vc.hero.isEnabled = true
// copy over the backgroundColor and hero.id over to the next view
// controller. In a real app, we would be passing some data correspoding to the cell
// being tapped. then configure the next view controller according to the data.
// and make sure that views that need to be transitioned have the same hero.id
vc.contentView.backgroundColor = cell.backgroundColor
vc.contentView.hero.id = heroId
present(vc, animated: true, completion: nil)
}
}
class MatchInCollectionExampleViewController2: ExampleBaseViewController {
let contentView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
contentView.cornerRadius = 8
view.addSubview(contentView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
contentView.frame = CGRect(x: (view.bounds.width - 250) / 2, y: 140, width: 250, height: view.bounds.height - 280)
}
}
| mit | 6a35166d6ead3370b261e1fbe1a7b0b8 | 31.295455 | 118 | 0.674173 | 4.372308 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/Services/PushAuthenticationService.swift | 2 | 2245 | import Foundation
/// The purpose of this service is to encapsulate the Restful API that performs Mobile 2FA
/// Code Verification.
///
@objc open class PushAuthenticationService: LocalCoreDataService {
open var authenticationServiceRemote: PushAuthenticationServiceRemote?
/// Designated Initializer
///
/// - Parameter managedObjectContext: A Reference to the MOC that should be used to interact with
/// the Core Data Persistent Store.
///
public required override init(managedObjectContext: NSManagedObjectContext) {
super.init(managedObjectContext: managedObjectContext)
self.authenticationServiceRemote = PushAuthenticationServiceRemote(wordPressComRestApi: apiForRequest())
}
/// Authorizes a WordPress.com Login Attempt (2FA Protected Accounts)
///
/// - Parameters:
/// - token: The Token sent over by the backend, via Push Notifications.
/// - completion: The completion block to be executed when the remote call finishes.
///
open func authorizeLogin(_ token: String, completion: @escaping ((Bool) -> ())) {
if self.authenticationServiceRemote == nil {
return
}
self.authenticationServiceRemote!.authorizeLogin(token,
success: {
completion(true)
},
failure: {
completion(false)
})
}
/// Helper method to get the WordPress.com REST Api, if any
///
/// - Returns: WordPressComRestApi instance. It can be an anonymous API instance if there are no credentials.
///
fileprivate func apiForRequest() -> WordPressComRestApi {
var api: WordPressComRestApi? = nil
let accountService = AccountService(managedObjectContext: managedObjectContext)
if let unwrappedRestApi = accountService.defaultWordPressComAccount()?.wordPressComRestApi {
if unwrappedRestApi.hasCredentials() {
api = unwrappedRestApi
}
}
if api == nil {
api = WordPressComRestApi.anonymousApi(userAgent: WPUserAgent.wordPress())
}
return api!
}
}
| gpl-2.0 | 15bdcd4751975ceb8419bc7b48087ac9 | 34.634921 | 114 | 0.633408 | 5.907895 | false | false | false | false |
PauuloG/app-native-ios | film-quizz/Classes/Network/UrlBuilder.swift | 1 | 1585 | //
// UrlBuilder.swift
// film-quizz
//
// Created by Paul Gabriel on 07/06/16.
// Copyright © 2016 Paul Gabriel. All rights reserved.
//
import Foundation
class UrlBuilder {
static var apibase = "http://163.172.29.197:3000"
static func retrieveUserUrl(UUID: String) -> String {
let url = "\(apibase)/api/user/\(UUID)"
return url
}
static func createUserUrl() -> String {
let url = "\(apibase)/api/user"
return url
}
static func gameMoviesUrl() -> String {
let url = "\(apibase)/api/movies/state"
return url
}
static func successListUrl() -> String {
let url = "\(apibase)/api/movies/success"
return url
}
static func singleMovieUrl(id: String) -> String {
let url = "\(apibase)/api/movie/\(id)"
return url
}
static func detailMovieUrl(movieId: Int) -> String {
let url = "\(apibase)/api/movie/\(movieId)"
return url
}
static func postScoreUrl() -> String {
let url = "\(apibase)/api/score"
return url
}
static func getActorsUrl(movieId: String) -> String {
let url = "\(apibase)/api/movie/\(movieId)/cast"
return url
}
static func getActorPictureUrl(fileName: String) -> String {
let url = "http://image.tmdb.org/t/p/original/\(fileName)"
return url
}
static func getRelatedListUrl(movieId: String) -> String {
let url = "\(apibase)/api/movie/\(movieId)/related"
return url
}
}
| mit | ec7cf7d8c3bebd2478e6c93402b4ce8e | 23.75 | 66 | 0.566919 | 3.872861 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Extensions/UIView-Extensions.swift | 1 | 3908 | //
// UIView-Extensions.swift
// Habitica
//
// Created by Phillip Thelen on 01/03/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import Foundation
extension UIView {
class func fromNib<T: UIView>(nibName: String? = nil) -> T? {
guard let nibs = Bundle.main.loadNibNamed(nibName ?? String(describing: T.self), owner: nil, options: nil) else {
return nil
}
guard let view = nibs[0] as? T else {
return nil
}
return view
}
@objc
class func loadFromNib(nibName: String) -> UIView? {
guard let nibs = Bundle.main.loadNibNamed(nibName, owner: nil, options: nil) else {
return nil
}
return nibs[0] as? UIView
}
@objc
func viewFromNibForClass() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as? UIView
return view
}
@discardableResult
func addTopBorderWithColor(color: UIColor, width: CGFloat) -> CALayer {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: width)
layer.addSublayer(border)
return border
}
@discardableResult
func addRightBorderWithColor(color: UIColor, width: CGFloat) -> CALayer {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
layer.addSublayer(border)
return border
}
@discardableResult
func addBottomBorderWithColor(color: UIColor, width: CGFloat) -> CALayer {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
layer.addSublayer(border)
return border
}
@discardableResult
func addLeftBorderWithColor(color: UIColor, width: CGFloat) -> CALayer {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
layer.addSublayer(border)
return border
}
func addHeightConstraint(height: CGFloat, relatedBy: NSLayoutConstraint.Relation = NSLayoutConstraint.Relation.equal) {
self.addConstraint(NSLayoutConstraint(item: self,
attribute: NSLayoutConstraint.Attribute.height,
relatedBy: relatedBy,
toItem: nil,
attribute: NSLayoutConstraint.Attribute.notAnAttribute,
multiplier: 1,
constant: height))
}
func addWidthConstraint(width: CGFloat, relatedBy: NSLayoutConstraint.Relation = NSLayoutConstraint.Relation.equal) {
self.addConstraint(NSLayoutConstraint(item: self,
attribute: NSLayoutConstraint.Attribute.width,
relatedBy: relatedBy,
toItem: nil,
attribute: NSLayoutConstraint.Attribute.notAnAttribute,
multiplier: 1,
constant: width))
}
func addSizeConstraint(size: CGFloat, relatedBy: NSLayoutConstraint.Relation = NSLayoutConstraint.Relation.equal) {
addHeightConstraint(height: size)
addWidthConstraint(width: size)
}
func addCenterXConstraint() {
if let superview = superview {
centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
}
}
func addCenterYConstraint() {
if let superview = superview {
centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
}
}
}
| gpl-3.0 | d29d4c6376e83227dba638fbbb0ab098 | 33.883929 | 123 | 0.633222 | 4.712907 | false | false | false | false |
zefferus/BidirectionalMap | Sources/BidirectionalMap.swift | 1 | 14898 | //
// BidirectionalMap.swift
// Wing
//
// Created by Tom Wilkinson on 3/31/16.
// Copyright © 2016 Sparo, Inc. All rights reserved.
//
import Foundation
private extension Dictionary {
/**
Returns the element at the given optional index if index is not optional
- parameter index: Index?
- returns: Element?
*/
subscript (safe key: Key?) -> Value? {
get {
guard let key = key else {
return nil
}
return self[key]
}
set {
guard let key = key else {
return
}
self[key] = newValue
}
}
}
public struct BidirectionalMap<Key: Hashable, Value: Hashable>:
CollectionType, DictionaryLiteralConvertible {
public typealias Element = (Key, Value)
public typealias Index = BidirectionalMapIndex<Key, Value>
private var leftDictionary: [Key: Value]
private var rightDictionary: [Value: Key]
/**
Create an empty bidirectional map.
*/
public init() {
leftDictionary = [:]
rightDictionary = [:]
}
/**
Create a bidirectional map with a minimum capacity. The true capacity will be the smallest
power of 2 greater than `minimumCapacity`.
- parameter minimumCapacity:
*/
public init(minimumCapacity: Int) {
leftDictionary = [Key: Value](minimumCapacity: minimumCapacity)
rightDictionary = [Value: Key](minimumCapacity: minimumCapacity)
}
/**
Create a bidirectional map with the sequence.
If more than one key exists for a value, one of them will be nondeterministically chosen
- parameter sequence:
*/
public init<S: SequenceType where S.Generator.Element == (Key, Value)>(_ sequence: S) {
self.init(minimumCapacity: sequence.underestimateCount())
for (key, value) in sequence {
self[key] = value
}
}
/**
The position of the first element in a non-empty bidirectional map
Identical to `endIndex` in an empty bidirectional map
- Complexity: Amortized O(1) if `self` does not wrap a bridged
`NSDictionary`, O(N) otherwise
- returns: BidirectionalMapIndex
*/
public var startIndex: BidirectionalMapIndex<Key, Value> {
return BidirectionalMapIndex(dictionaryIndex: leftDictionary.startIndex)
}
/**
The position of the last element in a non-empty bidirectional map.
Identical to `endIndex` in an empty bidirectional map.
- Complexity: Amortized O(1) if `self` does not wrap a bridged
`NSDictionary`, O(N) otherwise
- returns: BidirectionalMapIndex
*/
public var endIndex: BidirectionalMapIndex<Key, Value> {
return BidirectionalMapIndex(dictionaryIndex: leftDictionary.endIndex)
}
/**
- parameter key:
- returns: `Index` for the given key, or `nil` if the key is not present
in the bidirectional map
*/
@warn_unused_result
public func indexForKey(key: Key) -> BidirectionalMapIndex<Key, Value>? {
return BidirectionalMapIndex(dictionaryIndex: leftDictionary.indexForKey(key))
}
/**
- parameter value:
- returns: `Index` for the given value, or `nil` if the value is not present
in the bidirectional map
*/
@warn_unused_result
public func indexForValue(value: Value) -> BidirectionalMapIndex<Key, Value>? {
guard let key = rightDictionary[value] else {
return nil
}
return BidirectionalMapIndex(dictionaryIndex: leftDictionary.indexForKey(key))
}
/**
- parameter position:
- returns: `(Key, Value)` pair for the `Index`
*/
public subscript (position: BidirectionalMapIndex<Key, Value>) -> (Key, Value) {
return leftDictionary[position.dictionaryIndex]
}
/**
This behaves exactly as does the normal `Dictionary` subscript, except that
here key is also an Optional, and if nil will always return nil (and won't do anything
for a set)
- parameter key:
- returns: Value?
*/
public subscript (key: Key?) -> Value? {
get {
guard let key = key else {
return nil
}
return leftDictionary[key]
}
set {
guard let key = key else {
return
}
setKeyAndValue(key, value: newValue)
}
}
/**
This will behave the same as subscript with key, except it
uses the value to do the lookup
- parameter value: Optional value of the bidirectional map
- returns: Key?
*/
public subscript (value value: Value?) -> Key? {
get {
guard let value = value else {
return nil
}
return rightDictionary[value]
}
set(newKey) {
guard let value = value else {
return
}
setKeyAndValue(newKey, value: value)
}
}
/**
Private helper to set both the key and the value.
- parameter key:
- parameter value:
*/
private mutating func setKeyAndValue(key: Key?, value: Value?) {
leftDictionary[safe: rightDictionary[safe: value]] = nil
rightDictionary[safe: leftDictionary[safe: key]] = nil
leftDictionary[safe: key] = value
rightDictionary[safe: value] = key
}
/**
Update the value stored in the dicationary for the given key, or, if the
key does not exist, add a new key-value pair to the bidirectional map.
- parameter value:
- parameter forKey:
- returns: The value that was replaced, or `nil` if a new key-value pair
was added.
*/
public mutating func updateValue(value: Value, forKey key: Key) -> Value? {
let oldValue = self[key]
self[key] = value
return oldValue
}
/**
Update the key stored in the dicationary for the given value, or, if the
value does not exist, add a new key-value pair to the bidirectional map.
- parameter key:
- parameter forValue:
- returns: The value that was replaced, or `nil` if a new key-value pair
was added.
*/
public mutating func updateKey(key: Key, forValue value: Value) -> Key? {
let oldKey = self[value: value]
self[value: value] = key
return oldKey
}
/**
Remove the key-value pair at `index`
Invalidates all indices with respect to `self`.
- Complexity: O(`self.count`)
- returns: The removed `Element`
*/
public mutating func removeAtIndex(index: BidirectionalMapIndex<Key, Value>) -> (Key, Value) {
let pair = leftDictionary.removeAtIndex(index.dictionaryIndex)
rightDictionary.removeValueForKey(pair.1)
return pair
}
/**
Removes a given key and its value from the bidirectional map.
- parameter key:
- returns: The value that was removed, or `nil` if the key was not present
in the bidirectional map
*/
public mutating func removeValueForKey(key: Key) -> Value? {
guard let value = leftDictionary.removeValueForKey(key) else {
return nil
}
rightDictionary.removeValueForKey(value)
return value
}
/**
Removes a given value and its key from the bidirectional map.
- parameter value:
- returns: The key that was removed, or `nil` if the value was not present
in the bidirectional map
*/
public mutating func removeKeyForValue(value: Value) -> Key? {
guard let key = rightDictionary.removeValueForKey(value) else {
return nil
}
leftDictionary.removeValueForKey(key)
return key
}
/**
Removes all elements.
- Postcondition: `capacity == 0` if `keepCapacity` is `false`, othwerise
the capacity will not be decreased.
Invalidates all indices with respect to `self`.
- parameter keepCapacty: If `true`, the operation preserves the storage capacity
that the collection has, otherwise the underlying storage is released. The default
is `false`.
- Complexity: O(`self.count`).
*/
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
leftDictionary.removeAll(keepCapacity: keepCapacity)
rightDictionary.removeAll(keepCapacity: keepCapacity)
}
/**
The number of entries in the dictionary.
- Complexity: O(1)
*/
public var count: Int {
return leftDictionary.count
}
/**
- returns: A generator over the (key, value) pairs.
- Complexity: O(1).
*/
public func generate() -> BidirectionalMapGenerator<Key, Value> {
return BidirectionalMapGenerator(dictionaryGenerator: leftDictionary.generate())
}
/**
Create an instance initialized with `elements`.
- parameter elements:
*/
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(minimumCapacity: elements.count)
for (key, value) in elements {
leftDictionary[key] = value
rightDictionary[value] = key
}
}
/**
A collection containing just the keys of `self`.
Keys appear in the same order as they occur in the `.0` member
of key-value pairs in `self`. Each key in the result has a
unique value.
*/
public var keys: LazyMapCollection<BidirectionalMap<Key, Value>, Key> {
return self.lazy.map { $0.0 }
}
/**
A collection containing just the values of `self`.
Values appear in the same order as they occur in the `.1` member
of key-value pairs in `self`. Each vaue in the result has a unique
value.
*/
public var values: LazyMapCollection<BidirectionalMap<Key, Value>, Value> {
return self.lazy.map { $0.1 }
}
/// `true` iff `count == 0`.
public var isEmpty: Bool {
return leftDictionary.isEmpty
}
}
extension BidirectionalMap : CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of `self`.
public var description: String {
return leftDictionary.description
}
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return leftDictionary.description
}
}
extension BidirectionalMap {
/**
If `!self.isEmpty`, return the first key-value pair in the sequence of
elements, otherwise return `nil`.
- Complexity: Amortized O(1)
*/
public mutating func popFirst() -> (Key, Value)? {
guard !isEmpty else {
return nil
}
return removeAtIndex(startIndex)
}
}
/// A generator over the members of a `BidirectionalMap<Key, Value>`.
public struct BidirectionalMapGenerator<Key: Hashable, Value: Hashable> : GeneratorType {
private var dictionaryGenerator: DictionaryGenerator<Key, Value>
/**
Create a new bidirectional map generate wrapper over the dictionary generator
- parameter dictionaryGenerator:
*/
private init?(dictionaryGenerator: DictionaryGenerator<Key, Value>?) {
guard let dictionaryGenerator = dictionaryGenerator else {
return nil
}
self.dictionaryGenerator = dictionaryGenerator
}
/**
Create a new bidirectional map generate wrapper over the dictionary generator
- parameter dictionaryGenerator:
*/
private init(dictionaryGenerator: DictionaryGenerator<Key, Value>) {
self.dictionaryGenerator = dictionaryGenerator
}
/**
Advance to the next element and return in, or `nil` if no next
element exists.
- Requires: No preceding call to `self.next()` has returned `nil`.
*/
public mutating func next() -> (Key, Value)? {
return dictionaryGenerator.next()
}
}
/**
Less than operator for bidirectional map index
- parameter lhs:
- parameter rhs:
- returns: Bool
*/
public func < <Key: Hashable, Value: Hashable>(
lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool
{
return lhs.dictionaryIndex < rhs.dictionaryIndex
}
/**
Less than or equal to operator for bidirectional map index
- parameter lhs:
- parameter rhs:
- returns: Bool
*/
public func <= <Key: Hashable, Value: Hashable>(
lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool
{
return lhs.dictionaryIndex <= rhs.dictionaryIndex
}
/**
Greater than operator for bidirectional map index
- parameter lhs:
- parameter rhs:
- returns: Bool
*/
public func > <Key: Hashable, Value: Hashable>(
lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool
{
return lhs.dictionaryIndex > rhs.dictionaryIndex
}
/**
Greater than or equal operator for bidirectional map index
- parameter lhs:
- parameter rhs:
- returns: Bool
*/
public func >= <Key: Hashable, Value: Hashable>(
lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool
{
return lhs.dictionaryIndex >= rhs.dictionaryIndex
}
/**
Equal operator for bidirectional map index
- parameter lhs:
- parameter rhs:
- returns: Bool
*/
public func == <Key: Hashable, Value: Hashable>(
lhs: BidirectionalMapIndex<Key, Value>, rhs: BidirectionalMapIndex<Key, Value>) -> Bool
{
return lhs.dictionaryIndex == rhs.dictionaryIndex
}
/**
Used to access the key-value pairs in an instance of `BidirectionalMap<Key, Value>`.
Bidirectional map has three subscripting interfaces:
1. Subscripting with an optional key, yielding an optional value:
v = d[k]!
2. Subscripting with an optional value, yielding an optional key:
k = d[k]!
3. Subscripting with an index, yielding a key-value pair:
(k, v) = d[i]
*/
public struct BidirectionalMapIndex<Key: Hashable, Value: Hashable> : ForwardIndexType, Comparable {
private let dictionaryIndex: DictionaryIndex<Key, Value>
/**
Create a new bidirectional map index from the underlying dictionary index
- parameter dictionaryIndex:
*/
private init?(dictionaryIndex: DictionaryIndex<Key, Value>?) {
guard let dictionaryIndex = dictionaryIndex else {
return nil
}
self.dictionaryIndex = dictionaryIndex
}
/**
Create a new bidirectional map index from the underlying dictionary index
- parameter dictionaryIndex:
*/
private init(dictionaryIndex: DictionaryIndex<Key, Value>) {
self.dictionaryIndex = dictionaryIndex
}
/**
- Requires: The next value is representable.
- returns: The next consecutive value after `self`.
*/
public func successor() -> BidirectionalMapIndex<Key, Value> {
return BidirectionalMapIndex(dictionaryIndex: dictionaryIndex.successor())
}
}
| mit | 00431a530326ffc1b4e5676cb82f3236 | 27.926214 | 100 | 0.64174 | 4.624961 | false | false | false | false |
yangyueguang/MyCocoaPods | tools/Stars/XPlayer.swift | 1 | 69790 | //
// XPlayer.swift
import UIKit
import SnapKit
import CoreMedia
import CoreGraphics
import QuartzCore
import MediaPlayer
import AVFoundation
let kOffset = "contentOffset"
let SliderFillColorAnim = "fillColor"
// playerLayer的填充模式
enum XPlayerFillMode : Int {
case resize
case aspect
case aspectFill
}
enum PanDirection: Int {
case horizontal = 0
case vertical = 1
}
// 播放器的几种状态
enum XPlayerState: Int {
case failed = 0 // 播放失败
case buffering // 缓冲中
case playing // 播放中
case stopped // 停止播放
case pause // 暂停播放
}
enum XPImage: String {
case play = "play"
case pause = "pause"
case back = "back_full"
case close = "close"
case lock = "lock-nor"
case unlock = "unlock-nor"
case full = "fullscreen"
case slider = "slider"
case download = "download"
case play_btn = "play_btn"
case loading = "loading_bgView"
case brightness = "brightness"
case management = "management_mask"
case not_download = "not_download"
case repeat_video = "repeat_video"
case shrinkscreen = "shrinkscreen"
case top_shadow = "top_shadow"
case bottom_shadow = "bottom_shadow"
var img: UIImage? {
return UIImage(named: rawValue)
}
}
extension CALayer {
func animateKey(_ animationName: String, fromValue: Any?, toValue: Any?, customize block: ((_ animation: CABasicAnimation?) -> Void)?) {
setValue(toValue, forKey: animationName)
let anim = CABasicAnimation(keyPath: animationName)
anim.fromValue = fromValue ?? presentation()?.value(forKey: animationName)
anim.toValue = toValue
block?(anim)
add(anim, forKey: animationName)
}
}
// 私有类
class ASValuePopUpView: UIView, CAAnimationDelegate {
var currentValueOffset: (() -> CGFloat)?
var colorDidUpdate:((UIColor) -> Void)?
var arrowLength: CGFloat = 8
var widthPaddingFactor: CGFloat = 1.15
var heightPaddingFactor: CGFloat = 1.1
private var shouldAnimate = false
private var animDuration: TimeInterval = 0
private var arrowCenterOffset: CGFloat = 0
var imageView = UIImageView()
var timeLabel = UILabel()
private var colorAnimLayer = CAShapeLayer()
private lazy var pathLayer = CAShapeLayer(layer: layer)
var cornerRadius: CGFloat = 0 {
didSet {
if oldValue != self.cornerRadius {
pathLayer.path = path(for: bounds, withArrowOffset: arrowCenterOffset)?.cgPath
}
}
}
var color: UIColor? {
get {
if let fill = pathLayer.presentation()?.fillColor {
return UIColor(cgColor: fill)
}
return nil
}
set(newValue) {
pathLayer.fillColor = newValue?.cgColor
colorAnimLayer.removeAnimation(forKey: SliderFillColorAnim)
}
}
var opaqueColor: UIColor? {
let a = colorAnimLayer.presentation()
let co = a?.fillColor ?? pathLayer.fillColor
if let components = co?.components {
if (components.count == 2) {
return UIColor(white: components[0], alpha: 1)
} else {
return UIColor(red: components[0], green: components[1], blue: components[2], alpha: 1)
}
} else {
return nil
}
}
override init(frame: CGRect) {
super.init(frame: frame)
cornerRadius = 4.0
shouldAnimate = false
self.layer.anchorPoint = CGPoint(x:0.5, y: 1)
self.isUserInteractionEnabled = false
layer.addSublayer(colorAnimLayer)
timeLabel.text = "10:00"
timeLabel.textAlignment = .center
timeLabel.textColor = UIColor.white
addSubview(timeLabel)
addSubview(imageView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func action(for layer: CALayer, forKey event: String) -> CAAction? {
if shouldAnimate {
let anim = CABasicAnimation(keyPath: event)
anim.beginTime = CACurrentMediaTime()
anim.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
anim.fromValue = layer.presentation()?.value(forKey: event)
anim.duration = animDuration
return anim
} else {
return nil
}
}
func setAnimatedColors(animatedColors: [UIColor], withKeyTimes keyTimes:[NSNumber]) {
var cgColors:[CGColor] = []
for col in animatedColors {
cgColors.append(col.cgColor)
}
let colorAnim = CAKeyframeAnimation(keyPath:SliderFillColorAnim)
colorAnim.keyTimes = keyTimes
colorAnim.values = cgColors
colorAnim.fillMode = .both
colorAnim.duration = 1.0
colorAnim.delegate = self
colorAnimLayer.speed = Float.leastNormalMagnitude
colorAnimLayer.timeOffset = 0.0
colorAnimLayer.add(colorAnim, forKey: SliderFillColorAnim)
}
func setAnimationOffset(animOffset: CGFloat, returnColor:((UIColor?) -> Void)) {
if (colorAnimLayer.animation(forKey: SliderFillColorAnim) != nil) {
colorAnimLayer.timeOffset = CFTimeInterval(animOffset)
pathLayer.fillColor = colorAnimLayer.presentation()?.fillColor
returnColor(opaqueColor)
}
}
func setFrame(frame:CGRect, arrowOffset:CGFloat) {
if arrowOffset != arrowCenterOffset || !frame.size.equalTo(self.frame.size) {
let a = path(for: frame, withArrowOffset: arrowOffset)
pathLayer.path = a?.cgPath
}
arrowCenterOffset = arrowOffset
let anchorX = 0.5+(arrowOffset/frame.size.width)
self.layer.anchorPoint = CGPoint(x:anchorX, y:1)
self.layer.position = CGPoint(x:frame.origin.x + frame.size.width*anchorX,y: 0)
self.layer.bounds = CGRect(origin: CGPoint.zero, size: frame.size)
}
func animateBlock(block:((TimeInterval) -> Void)) {
shouldAnimate = true
animDuration = 0.5
let anim = layer.animation(forKey: "position")
if let anim = anim {
let elapsedTime = min(CACurrentMediaTime() - anim.beginTime, anim.duration)
animDuration = animDuration * elapsedTime / anim.duration
}
block(animDuration)
shouldAnimate = false
}
func showAnimated(animated: Bool){
if (!animated) {
self.layer.opacity = 1.0
return
}
CATransaction.begin()
let anim = self.layer.animation(forKey: "transform")
let a = layer.presentation()?.value(forKey: "transform")
let b = NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1))
let fromValue = (anim == nil ? b : a)
layer.animateKey("transform", fromValue: fromValue, toValue: NSValue(caTransform3D: CATransform3DIdentity)) { (animation) in
animation?.duration = 0.4
animation?.timingFunction = CAMediaTimingFunction(controlPoints:0.8 ,2.5 ,0.35 ,0.5)
}
layer.animateKey("opacity", fromValue: nil, toValue: 1.0) { (animation) in
animation?.duration = 0.1
}
CATransaction.commit()
}
func hideAnimated(animated: Bool, completionBlock block:@escaping(() -> Void)) {
CATransaction.begin()
CATransaction.setCompletionBlock {[weak self] in
block()
self?.layer.transform = CATransform3DIdentity
}
if (animated) {
layer.animateKey("transform", fromValue: nil, toValue: NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1)), customize: { (animation) in
animation?.duration = 0.55
animation?.timingFunction = CAMediaTimingFunction(controlPoints: 0.1 ,-2 ,0.3 ,3)
})
layer.animateKey("opacity", fromValue: nil, toValue: 0, customize: { (animation) in
animation?.duration = 0.75
})
} else {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
self.layer.opacity = 0.0
})
}
CATransaction.commit()
}
func animationDidStart(_ anim: CAAnimation) {
colorAnimLayer.speed = 0.0
colorAnimLayer.timeOffset = CFTimeInterval(currentValueOffset?() ?? 0)
pathLayer.fillColor = colorAnimLayer.presentation()?.fillColor
colorDidUpdate?(opaqueColor ?? .red)
}
func path(for rect: CGRect, withArrowOffset arrowOffset: CGFloat) -> UIBezierPath? {
var rect = rect
if rect.equalTo(CGRect.zero) { return nil }
rect = CGRect(origin: CGPoint.zero, size: rect.size)
var roundedRect = rect
roundedRect.size.height -= arrowLength
let popUpPath = UIBezierPath(roundedRect: roundedRect, cornerRadius: cornerRadius)
let maxX = roundedRect.maxX
let arrowTipX = rect.midX + arrowOffset
let tip = CGPoint(x: arrowTipX, y: rect.maxY)
let arrowLength = roundedRect.height / 2.0
let x = arrowLength * tan(45.0 * .pi / 180)
let arrowPath = UIBezierPath()
arrowPath.move(to: tip)
arrowPath.addLine(to: CGPoint(x: max(arrowTipX - x, 0), y: roundedRect.maxY - arrowLength))
arrowPath.addLine(to: CGPoint(x: min(arrowTipX + x, maxX), y: roundedRect.maxY - arrowLength))
arrowPath.close()
popUpPath.append(arrowPath)
return popUpPath
}
override func layoutSubviews() {
super.layoutSubviews()
let textRect = CGRect(x:self.bounds.origin.x, y:0, width:self.bounds.size.width,height: 13)
timeLabel.frame = textRect
let imageReact = CGRect(x:self.bounds.origin.x+5, y:textRect.size.height+textRect.origin.y, width:self.bounds.size.width-10, height:56)
imageView.frame = imageReact
}
}
/// 亮度类 私有类
class XBrightnessView: UIView {
static let shared = XBrightnessView()
// 调用单例记录播放状态是否锁定屏幕方向
var isLockScreen = false
// cell上添加player时候,不允许横屏,只运行竖屏状态状态
var isAllowLandscape = false
var backImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 79, height: 76))
lazy var title = UILabel(frame: CGRect(x: 0, y: 5, width: bounds.size.width, height: 30))
lazy var longView = UIView(frame: CGRect(x: 13, y: 132, width: bounds.size.width - 26, height: 7))
var tipArray: [UIImageView] = []
var orientationDidChange = false
var timer: Timer?
override init(frame: CGRect) {
super.init(frame: frame)
backImage.image = XPImage.brightness.img
self.frame = CGRect(x: APPW * 0.5, y: APPH * 0.5, width: 155, height: 155)
layer.cornerRadius = 10
layer.masksToBounds = true
let toolbar = UIToolbar(frame: bounds)
toolbar.alpha = 0.97
addSubview(toolbar)
addSubview(backImage)
title.font = UIFont.boldSystemFont(ofSize: 16)
title.textColor = UIColor(red: 0.25, green: 0.22, blue: 0.21, alpha: 1.00)
title.textAlignment = .center
title.text = "亮度"
addSubview(title)
longView.backgroundColor = UIColor(red: 0.25, green: 0.22, blue: 0.21, alpha: 1.00)
addSubview(longView)
let tipW: CGFloat = (longView.bounds.size.width - 17) / 16
for i in 0..<16 {
let tipX = CGFloat(i) * (tipW + 1) + 1
let image = UIImageView()
image.backgroundColor = UIColor.white
image.frame = CGRect(x: tipX, y: 1, width: tipW, height: 5)
longView.addSubview(image)
tipArray.append(image)
}
updateLongView(sound: UIScreen.main.brightness)
NotificationCenter.default.addObserver(self, selector: #selector(updateLayer(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
UIScreen.main.addObserver(self, forKeyPath: "brightness", options: .new, context: nil)
alpha = 0.0
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let ab = change?[NSKeyValueChangeKey(rawValue: "new")] as? NSNumber
let sound = CGFloat(ab?.floatValue ?? 0)
if self.alpha == 0 {
self.alpha = 1.0
timer?.invalidate()
timer = Timer(timeInterval: 3, target: self, selector: #selector(disAppearSoundView), userInfo: nil, repeats: false)
RunLoop.main.add(timer!, forMode: .default)
}
updateLongView(sound: sound)
}
@objc func updateLayer(_ notify: Notification?) {
orientationDidChange = true
setNeedsLayout()
}
@objc func disAppearSoundView() {
if (self.alpha == 1.0) {
UIView.animate(withDuration: 0.8) {
self.alpha = 0
}
}
}
func updateLongView(sound: CGFloat) {
let stage = CGFloat( 1 / 15.0)
let level = Int(sound / stage)
for i in 0..<self.tipArray.count {
let img = tipArray[i]
img.isHidden = i > level
}
}
override func willMove(toSuperview newSuperview: UIView?) {
setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
let orien = UIDevice.current.orientation
if orientationDidChange {
UIView.animate(withDuration: 0.25, animations: {
if orien == .portrait || orien == .faceUp {
self.center = CGPoint(x: APPW * 0.5, y: (APPH - 10) * 0.5)
} else {
self.center = CGPoint(x: APPW * 0.5, y: APPH * 0.5)
}
}) { (finished) in
self.orientationDidChange = false
}
} else {
if orien == .portrait {
self.center = CGPoint(x: APPW * 0.5, y: (APPH - 10) * 0.5)
} else {
self.center = CGPoint(x: APPW * 0.5, y: APPH * 0.5)
}
}
backImage.center = CGPoint(x: 155 * 0.5, y: 155 * 0.5)
}
deinit {
UIScreen.main.removeObserver(self, forKeyPath: "brightness")
NotificationCenter.default.removeObserver(self)
}
}
/// 滑块 私有类
class ASValueTrackingSlider: UISlider {
var popUpView = ASValuePopUpView()
var popUpViewAlwaysOn = false
var keyTimes: [NSNumber] = []
var valueRange: Float {return maximumValue - minimumValue}
var popUpViewAnimatedColors: [UIColor] = []
var sliderWillDisplayPopUpView: (() -> Void)?
var sliderDidHidePopUpView: (() -> Void)?
var tempOffset: CGFloat {return CGFloat((self.value - self.minimumValue) / self.valueRange)}
override var value: Float {
didSet {
popUpView.setAnimationOffset(animOffset: tempOffset) { (color) in
super.minimumTrackTintColor = color
}
}
}
var autoAdjustTrackColor = true {
didSet {
if (autoAdjustTrackColor != oldValue) {
super.minimumTrackTintColor = oldValue ? popUpView.opaqueColor: nil
}
}
}
var popUpViewColor: UIColor? {
didSet {
popUpViewAnimatedColors = []
popUpView.color = self.popUpViewColor
if (autoAdjustTrackColor) {
super.minimumTrackTintColor = popUpView.opaqueColor
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
autoAdjustTrackColor = true
popUpViewAlwaysOn = false
self.popUpViewColor = UIColor(hue: 0.6, saturation: 0.6, brightness: 0.5, alpha: 0.8)
self.popUpView.alpha = 0.0
popUpView.colorDidUpdate = {[weak self] color in
guard let `self` = self else { return }
let temp = self.autoAdjustTrackColor
self.minimumTrackTintColor = color
self.autoAdjustTrackColor = temp
}
popUpView.currentValueOffset = { [weak self] in
return self?.tempOffset ?? 0
}
addSubview(self.popUpView)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func setPopUpViewAnimatedColors(colors: [UIColor], withPositions positions: [NSNumber] = []) {
if (positions.count <= 0) { return }
popUpViewAnimatedColors = colors
keyTimes = []
for num in positions.sorted(by: { (a, b) -> Bool in
return a.floatValue < b.floatValue
}) {
keyTimes.append(NSNumber(value: (num.floatValue - minimumValue) / valueRange))
}
if (colors.count >= 2) {
self.popUpView.setAnimatedColors(animatedColors: colors, withKeyTimes: keyTimes)
} else {
self.popUpViewColor = colors.last != nil ? nil : popUpView.color
}
}
@objc func didBecomeActiveNotification(note: NSNotification) {
if !self.popUpViewAnimatedColors.isEmpty {
self.popUpView.setAnimatedColors(animatedColors: popUpViewAnimatedColors, withKeyTimes: keyTimes)
}
}
func showPopUpViewAnimated(_ animated: Bool) {
sliderWillDisplayPopUpView?()
popUpView.showAnimated(animated: animated)
}
func hidePopUpViewAnimated(_ animated: Bool) {
sliderWillDisplayPopUpView?()
popUpView.hideAnimated(animated: animated) {
self.sliderDidHidePopUpView?()
}
}
override func layoutSubviews() {
super.layoutSubviews()
let popUpViewSize = CGSize(width: 100, height: 56 + self.popUpView.arrowLength + 18)
let thumbRect = self.thumbRect(forBounds: bounds, trackRect: trackRect(forBounds: bounds), value: value)
let thumbW = thumbRect.size.width
let thumbH = thumbRect.size.height
var popUpRect = CGRect(x: 0,
y: thumbRect.origin.y - popUpViewSize.height,
width: (thumbW - popUpViewSize.width)/2,
height: (thumbH - popUpViewSize.height)/2)
let minOffsetX = popUpRect.minX
let maxOffsetX = popUpRect.maxX - self.bounds.width
let offset = minOffsetX < 0.0 ? minOffsetX : (maxOffsetX > 0.0 ? maxOffsetX : 0.0)
popUpRect.origin.x -= offset
popUpView.setFrame(frame: popUpRect, arrowOffset: offset)
}
override func didMoveToWindow() {
if self.window == nil {
NotificationCenter.default.removeObserver(self)
} else {
if !popUpViewAnimatedColors.isEmpty {
popUpView.setAnimatedColors(animatedColors: popUpViewAnimatedColors, withKeyTimes: keyTimes)
}
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActiveNotification(note:)), name: UIApplication.didBecomeActiveNotification, object: nil)
}
}
override func setValue(_ value: Float, animated: Bool) {
if animated {
func anim() {
super.setValue(value, animated: animated)
self.popUpView.setAnimationOffset(animOffset: tempOffset) { (color) in
self.minimumTrackTintColor = color
}
self.layoutIfNeeded()
}
popUpView.animateBlock {(duration) in
UIView.animate(withDuration: duration) {
anim()
}
}
} else {
super.setValue(value, animated: animated)
}
}
override var minimumTrackTintColor: UIColor? {
willSet {
autoAdjustTrackColor = false
}
}
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let begin = super.beginTracking(touch, with: event)
if begin && !self.popUpViewAlwaysOn {
self.popUpViewAlwaysOn = true
self.showPopUpViewAnimated(false)
}
return begin
}
override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let conti = super.continueTracking(touch, with: event)
if conti {
popUpView.setAnimationOffset(animOffset: tempOffset) { (color) in
super.minimumTrackTintColor = color
}
}
return conti
}
override func cancelTracking(with event: UIEvent?) {
super.cancelTracking(with: event)
if !popUpViewAlwaysOn {
hidePopUpViewAnimated(false)
}
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
if !popUpViewAlwaysOn {
hidePopUpViewAnimated(false)
}
}
}
/// 播放控制类 私有类
class XPlayerControlView: UIView {
@IBOutlet weak var videoSlider: ASValueTrackingSlider! // 滑杆
@IBOutlet weak var titleLabel: UILabel! // 标题
@IBOutlet weak var startBtn: UIButton! // 开始播放按钮
@IBOutlet weak var currentTimeLabel: UILabel! // 当前播放时长label
@IBOutlet weak var totalTimeLabel: UILabel! // 视频总时长label
@IBOutlet weak var progressView: UIProgressView! // 缓冲进度条
@IBOutlet weak var fullScreenBtn: UIButton! // 全屏按钮
@IBOutlet weak var lockBtn: UIButton! // 锁定屏幕方向按钮
@IBOutlet weak var horizontalLabel: UILabel! // 快进快退label
@IBOutlet weak var activity: UIActivityIndicatorView! // 系统菊花
@IBOutlet weak var backBtn: UIButton! // 返回按钮
@IBOutlet weak var repeatBtn: UIButton! // 重播按钮
@IBOutlet weak var topView: UIView!
@IBOutlet weak var topImageView: UIImageView! // 顶部渐变
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var bottomImageView: UIImageView! // 底部渐变
@IBOutlet weak var downLoadBtn: UIButton! // 缓存按钮
@IBOutlet weak var resolutionBtn: UIButton! // 切换分辨率按钮
@IBOutlet weak var playeBtn: UIButton! // 播放按钮
// 切换分辨率的block
var resolutionBlock: ((UIButton?) -> Void)?
// slidertap事件Block
var tapBlock: ((CGFloat) -> Void)?
// 分辨率的View
var resolutionView = UIView()
// 分辨率的名称
var resolutionArray: [String] = [] {
didSet {
resolutionBtn.setTitle(resolutionArray.first, for: .normal)
resolutionView.isHidden = true
resolutionView.backgroundColor = UIColor(white: 0.7, alpha: 1)
addSubview(resolutionView)
resolutionView.snp.makeConstraints { (make) in
make.width.equalTo(40)
make.height.equalTo(CGFloat(resolutionArray.count * 30))
make.leading.equalTo(resolutionBtn.snp.leading)
make.top.equalTo(resolutionBtn.snp.bottom)
}
for i in 0..<resolutionArray.count {
let btn = UIButton(type: .custom)
btn.tag = 200 + i
resolutionView.addSubview(btn)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.frame = CGRect(x: 0, y: CGFloat(30 * i), width: 40, height: 30)
btn.setTitle(resolutionArray[i], for: .normal)
btn.addTarget(self, action: #selector(changeResolution(_:)), for: .touchUpInside)
}
}
}
class func xibView() -> XPlayerControlView {
let xib = UINib(nibName: "XPlayerControlView", bundle: nil)
let controlView = xib.instantiate(withOwner: nil, options: nil).first as! XPlayerControlView
return controlView
}
override func awakeFromNib() {
super.awakeFromNib()
initial()
}
override init(frame: CGRect) {
super.init(frame: frame)
initial()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func initial() {
videoSlider.popUpViewColor = .red
videoSlider.setThumbImage(XPImage.slider.img, for: .normal)
resolutionBtn.addTarget(self, action: #selector(resolutionAction(_:)), for: .touchUpInside)
let sliderTap = UITapGestureRecognizer(target: self, action: #selector(tapSliderAction(_:)))
videoSlider.addGestureRecognizer(sliderTap)
activity.stopAnimating()
resetControlView()
}
// 点击topView上的按钮
@objc func resolutionAction(_ sender: UIButton?) {
sender?.isSelected = !(sender?.isSelected ?? false)
resolutionView.isHidden = !(sender?.isSelected)!
}
// 点击切换分别率按钮
@objc func changeResolution(_ sender: UIButton?) {
resolutionView.isHidden = true
resolutionBtn.isSelected = false
resolutionBtn.setTitle(sender?.titleLabel?.text, for: .normal)
resolutionBlock?(sender)
}
// UISlider TapAction
@objc func tapSliderAction(_ tap: UITapGestureRecognizer?) {
if (tap?.view is UISlider) {
let slider = tap?.view as? UISlider
let point = tap?.location(in: slider)
let length = slider?.frame.size.width
// 视频跳转的value
let tapValue = (point?.x ?? 0.0) / (length ?? 0.0)
tapBlock?(tapValue)
}
}
// MARK: - Public Method
func resetControlView() {
videoSlider.value = 0
progressView.progress = 0
currentTimeLabel.text = "00:00"
totalTimeLabel.text = "00:00"
horizontalLabel.isHidden = true
repeatBtn.isHidden = true
playeBtn.isHidden = true
resolutionView.isHidden = true
backgroundColor = UIColor.clear
downLoadBtn.isEnabled = true
}
func resetControlViewForResolution() {
horizontalLabel.isHidden = true
repeatBtn.isHidden = true
resolutionView.isHidden = true
playeBtn.isHidden = true
downLoadBtn.isEnabled = true
backgroundColor = UIColor.clear
}
func showControlView() {
topView.alpha = 1
bottomView.alpha = 1
lockBtn.alpha = 1
}
func hideControlView() {
topView.alpha = 0
bottomView.alpha = 0
lockBtn.alpha = 0
resolutionBtn.isSelected = true
resolutionAction(resolutionBtn)
}
}
class XPlayer: UIView {
static let shared = XPlayer()
let nessView = XBrightnessView.shared
// 视频URL
var videoURL: URL? {
didSet {
if (self.placeholderImageName.isEmpty) {
let image = XPImage.loading.img
self.layer.contents = image?.cgImage
}
self.repeatToPlay = false
self.playDidEnd = false
self.addNotifications()
self.onDeviceOrientationChange()
self.isPauseByUser = true
self.controlView.playeBtn.isHidden = false
self.controlView.hideControlView()
}
}
// 视频标题
var title = "" {didSet {self.controlView.titleLabel.text = title}}
// 视频URL的数组
var videoURLArray: [String] = []
// 返回按钮Block
var goBackBlock: (() -> Void)?
var downloadBlock: ((String?) -> Void)?
// 从xx秒开始播放视频跳转
var seekTime = 0
// 是否自动播放
var isAutoPlay = false { didSet {if isAutoPlay {self.configZFPlayer()}}}
// 是否有下载功能(默认是关闭)
var hasDownload = false {didSet {self.controlView.downLoadBtn.isHidden = !hasDownload}}
// 是否被用户暂停
private(set) var isPauseByUser = false
// 播放属性
private var player: AVPlayer?
private lazy var urlAsset = AVURLAsset(url: videoURL!)
private lazy var imageGenerator = AVAssetImageGenerator(asset: self.urlAsset)
// playerLayer
private var playerLayer: AVPlayerLayer?
private var timeObserve: Any?
// 用来保存快进的总时长
private var sumTime: CGFloat = 0.0
// 定义一个实例变量,保存枚举值
private var panDirection: PanDirection = .horizontal
// 是否为全屏
private var isFullScreen = false
// 是否锁定屏幕方向
private var isLocked = false
// 是否在调节音量
private var isVolume = false
// 是否显示controlView
private var isMaskShowing = false
// 是否播放本地文件
private var isLocalVideo = false
// slider上次的值
private var sliderLastValue: Float = 0.0
// 是否再次设置URL播放视频
private var repeatToPlay = false
// 播放完了
private var playDidEnd = false
// 进入后台
private var didEnterBackground = false
private var tap: UITapGestureRecognizer?
private var doubleTap: UITapGestureRecognizer?
// player所在cell的indexPath
private var indexPath = IndexPath(row: 0, section: 0)
// cell上imageView的tag
private var cellImageViewTag = 0
// ViewController中页面是否消失
private var viewDisappear = false
// 是否在cell上播放video
private var isCellVideo = false
// 是否缩小视频在底部
private var isBottomVideo = false
// 是否切换分辨率
private var isChangeResolution = false
// 播发器的几种状态
private var state: XPlayerState = .failed {
didSet {
if (state == .playing) {
self.layer.contents = XPImage.management.img?.cgImage
} else if (state == .failed) {
self.controlView.downLoadBtn.isEnabled = false
}
// 控制菊花显示、隐藏
if state == .buffering {
controlView.activity.startAnimating()
} else {
controlView.activity.stopAnimating()
}
}
}
// 播放前占位图片的名称,不设置就显示默认占位图(需要在设置视频URL之前设置)
var placeholderImageName = "" {
didSet {
let image = UIImage(named:placeholderImageName) ?? XPImage.loading.img
self.layer.contents = image?.cgImage
}
}
// 设置playerLayer的填充模式
var playerLayerGravity: XPlayerFillMode = .aspectFill {
didSet {
switch (playerLayerGravity) {
case .resize: self.playerLayer?.videoGravity = .resizeAspect
case .aspect: self.playerLayer?.videoGravity = .resizeAspect
case .aspectFill: self.playerLayer?.videoGravity = .resizeAspectFill
}
}
}
// 切换分辨率传的字典(key:分辨率名称,value:分辨率url)
var resolutionDic: [String : String] = [:] {
didSet {
self.controlView.resolutionBtn.isHidden = false
self.videoURLArray = []
self.controlView.resolutionArray = []
resolutionDic.forEach {[weak self] (key,value) in
self?.videoURLArray.append(value)
self?.controlView.resolutionArray.append(key)
}
}
}
private var playerItem: AVPlayerItem? {
didSet {
if (oldValue == playerItem) {return}
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: oldValue)
oldValue?.removeObserver(self, forKeyPath: "status")
oldValue?.removeObserver(self, forKeyPath: "loadedTimeRanges")
oldValue?.removeObserver(self, forKeyPath: "playbackBufferEmpty")
oldValue?.removeObserver(self, forKeyPath: "playbackLikelyToKeepUp")
NotificationCenter.default.addObserver(self, selector: #selector(moviePlayDidEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
playerItem?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
playerItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions.new, context: nil)
// 缓冲区空了,需要等待数据
playerItem?.addObserver(self, forKeyPath: "playbackBufferEmpty", options: NSKeyValueObservingOptions.new, context: nil)
// 缓冲区有足够数据可以播放了
playerItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: NSKeyValueObservingOptions.new, context: nil)
}
}
// 滑杆
private var volumeViewSlider: UISlider?
// 控制层View
private var controlView = XPlayerControlView.xibView()
// palyer加到tableView
private var tableView: UITableView? {
didSet {
if oldValue == self.tableView { return }
oldValue?.removeObserver(self, forKeyPath: kOffset)
self.tableView?.addObserver(self, forKeyPath: kOffset, options: NSKeyValueObservingOptions.new, context: nil)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeThePlayer()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func awakeFromNib() {
super.awakeFromNib()
initializeThePlayer()
}
func initializeThePlayer() {
unLockTheScreen()
self.addSubview(controlView)
controlView.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.zero)
}
controlView.layoutSubviews()
}
deinit {
self.playerItem = nil
self.tableView = nil
NotificationCenter.default.removeObserver(self)
if let time = self.timeObserve {
player?.removeTimeObserver(time)
self.timeObserve = nil
}
}
// 重置player
public func resetPlayer() {
self.playDidEnd = false
self.playerItem = nil
self.didEnterBackground = false
self.seekTime = 0
self.isAutoPlay = false
player?.removeTimeObserver(timeObserve!)
self.timeObserve = nil
NotificationCenter.default.removeObserver(self)
pause()
playerLayer?.removeFromSuperlayer()
// self.imageGenerator = nil
self.player?.replaceCurrentItem(with: nil)
self.player = nil
if (self.isChangeResolution) {
self.controlView.resetControlViewForResolution()
self.isChangeResolution = false
}else {
self.controlView.resetControlView()
}
if (!self.repeatToPlay) { removeFromSuperview() }
self.isBottomVideo = false
if (self.isCellVideo && !self.repeatToPlay) {
self.viewDisappear = true
self.isCellVideo = false
self.tableView = nil
self.indexPath = IndexPath(row: 0, section: 0)
}
}
// 在当前页面,设置新的Player的URL调用此方法
public func resetToPlayNewURL() {
self.repeatToPlay = true
self.resetPlayer()
}
// 添加观察者、通知
func addNotifications() {
let not = NotificationCenter.default
// app退到后台
not.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.willResignActiveNotification, object: nil)
// app进入前台
not.addObserver(self, selector: #selector(appDidEnterPlayGround), name: UIApplication.didBecomeActiveNotification, object: nil)
// slider开始滑动事件
controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchBegan), for: .touchDown)
// slider滑动中事件
controlView.videoSlider.addTarget(self, action: #selector(progressSliderValueChanged), for: .valueChanged)
// slider结束滑动事件
controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchEnded), for: .touchUpInside)
controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchEnded), for: .touchCancel)
controlView.videoSlider.addTarget(self, action: #selector(progressSliderTouchEnded), for: .touchUpOutside)
// 播放按钮点击事件
controlView.startBtn.addTarget(self, action: #selector(startAction), for: .touchUpInside)
// cell上播放视频的话,该返回按钮为×
if (self.isCellVideo) {
controlView.backBtn.setImage(XPImage.close.img, for: .normal)
}else {
controlView.backBtn.setImage(XPImage.back.img, for: .normal)
}
// 返回按钮点击事件
controlView.backBtn.addTarget(self, action: #selector(backButtonAction), for: .touchUpInside)
// 全屏按钮点击事件
controlView.fullScreenBtn.addTarget(self, action: #selector(fullScreenAction), for: .touchUpInside)
// 锁定屏幕方向点击事件
controlView.lockBtn.addTarget(self, action: #selector(lockScreenAction), for: .touchUpInside)
// 重播
controlView.repeatBtn.addTarget(self, action: #selector(repeatPlay), for: .touchUpInside)
// 中间按钮播放
controlView.playeBtn.addTarget(self, action: #selector(configZFPlayer), for: .touchUpInside)
controlView.downLoadBtn.addTarget(self, action: #selector(downloadVideo), for: .touchUpInside)
controlView.resolutionBlock = {btn in
let currentTime = CMTimeGetSeconds(self.player!.currentTime())
let videoStr = self.videoURLArray[(btn?.tag ?? 0)-200]
let videoURL = URL(string: videoStr)
if videoStr == self.videoURL?.absoluteString { return }
self.isChangeResolution = true
self.resetToPlayNewURL()
self.videoURL = videoURL
self.seekTime = Int(currentTime)
self.isAutoPlay = true
}
controlView.tapBlock = { value in
self.pause()
let duration = self.playerItem!.duration
let total = Int32(duration.value) / duration.timescale
let dragedSeconds = floorf(Float(CGFloat(total) * value))
self.controlView.startBtn.isSelected = true
self.seekToTime(Int(dragedSeconds))
}
// 监测设备方向
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(onDeviceOrientationChange), name: UIDevice.orientationDidChangeNotification, object: nil)
}
//pragma mark - layoutSubviews
override func layoutSubviews() {
super.layoutSubviews()
self.playerLayer?.frame = self.bounds
UIApplication.shared.isStatusBarHidden = false
self.isMaskShowing = false
self.animateShow()
self.layoutIfNeeded()
}
//pragma mark - 设置视频URL
// 用于cell上播放player
public func setVideoURL(videoURL: URL, tableView: UITableView, indexPath: IndexPath, tag: Int) {
if (!self.viewDisappear && (self.playerItem != nil)) { self.resetPlayer() }
self.isCellVideo = true
self.viewDisappear = false
self.cellImageViewTag = tag
self.tableView = tableView
self.indexPath = indexPath
self.videoURL = videoURL
}
// 设置Player相关参数
@objc func configZFPlayer() {
self.playerItem = AVPlayerItem(asset: urlAsset)
self.player = AVPlayer(playerItem: playerItem)
self.playerLayer = AVPlayerLayer(player: player)
self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
self.layer.insertSublayer(playerLayer!, at: 0)
self.isMaskShowing = true
self.autoFadeOutControlBar()
self.createGesture()
self.createTimer()
self.configureVolume()
if self.videoURL?.scheme == "file" {
self.state = .playing
self.isLocalVideo = true
self.controlView.downLoadBtn.isEnabled = false
} else {
self.state = .buffering
self.isLocalVideo = false
}
self.play()
self.controlView.startBtn.isSelected = true
self.isPauseByUser = false
self.controlView.playeBtn.isHidden = true
self.setNeedsLayout()
self.layoutIfNeeded()
}
// 创建手势
func createGesture() {
self.tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
self.tap?.delegate = self
self.addGestureRecognizer(self.tap!)
self.doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapAction))
self.doubleTap?.numberOfTapsRequired = 2
self.addGestureRecognizer(self.doubleTap!)
self.tap?.delaysTouchesBegan = true
self.tap?.require(toFail: self.doubleTap!)
}
func createTimer() {
self.timeObserve = self.player?.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 1), queue: nil, using: { (time) in
let currentItem = self.playerItem
if let item = currentItem, item.seekableTimeRanges.count > 0, item.duration.timescale != 0 {
let currentTime = Int(CMTimeGetSeconds(item.currentTime()))
let proMin = currentTime / 60
let proSec = currentTime % 60
let totalTime = Int(item.duration.value) / Int(item.duration.timescale)
let durMin = totalTime / 60
let durSec = totalTime % 60
self.controlView.videoSlider.value = Float(currentTime) / Float(totalTime)
self.controlView.currentTimeLabel.text = String(format: "%02zd:%02zd", proMin, proSec)
self.controlView.totalTimeLabel.text = String(format:"%02zd:%02zd", durMin, durSec)
}
})
}
// 获取系统音量
func configureVolume() {
let volumeView = MPVolumeView()
volumeViewSlider = nil
for view in volumeView.subviews {
if view.description == "MPVolumeSlider"{
volumeViewSlider = view as? UISlider
break
}
}
// 使用这个category的应用不会随着手机静音键打开而静音,可在手机静音下播放声音
let se = AVAudioSession.sharedInstance()
try? se.setCategory(.playback)
// 监听耳机插入和拔掉通知
NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListenerCallback(notification:)), name: NSNotification.Name(rawValue: AVAudioSessionRouteChangeReasonKey), object: nil)
}
// 耳机插入、拔出事件
@objc func audioRouteChangeListenerCallback(notification: NSNotification) {
let interuptionDict = notification.userInfo
let routeChangeReason = interuptionDict?[AVAudioSessionRouteChangeReasonKey] as! AVAudioSession.RouteChangeReason
switch (routeChangeReason) {
case .newDeviceAvailable: break
case .oldDeviceUnavailable: self.play()
case .categoryChange:
print("AVAudioSessionRouteChangeReasonCategoryChange")
default: break
}
}
//pragma mark - ShowOrHideControlView
func autoFadeOutControlBar() {
if (!self.isMaskShowing) { return }
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hideControlView), object: nil)
self.perform(#selector(hideControlView), with: nil, afterDelay: TimeInterval(7))
}
// 取消延时隐藏controlView的方法
public func cancelAutoFadeOutControlBar() {
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
// 隐藏控制层
@objc func hideControlView() {
if (!self.isMaskShowing) { return }
UIView.animate(withDuration: TimeInterval(0.35), animations: {
self.controlView.hideControlView()
if (self.isFullScreen) {
self.controlView.backBtn.alpha = 0
UIApplication.shared.setStatusBarHidden(true, with: UIStatusBarAnimation.fade)
}else if (self.isBottomVideo && !self.isFullScreen) {
self.controlView.backBtn.alpha = 1
}else {
self.controlView.backBtn.alpha = 0
}
}) { finished in
self.isMaskShowing = false
}
}
// 显示控制层
func animateShow() {
if (self.isMaskShowing) { return }
UIView.animate(withDuration: TimeInterval(0.35), animations: {
self.controlView.backBtn.alpha = 1
if (self.isBottomVideo && !self.isFullScreen) { self.controlView.hideControlView()
}else if (self.playDidEnd) {
self.controlView.hideControlView()
}else {
self.controlView.showControlView()
}
UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.fade)
}) { (finished) in
self.isMaskShowing = true
self.autoFadeOutControlBar()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object as? AVPlayerItem == player?.currentItem {
if keyPath == "status" {
if player?.currentItem?.status == AVPlayerItem.Status.readyToPlay {
self.state = .playing
let pan = UIPanGestureRecognizer(target: self, action: #selector(panDirection(_:)))
pan.delegate = self
self.addGestureRecognizer(pan)
self.seekToTime(seekTime)
} else if player?.currentItem?.status == AVPlayerItem.Status.failed {
self.state = .failed
self.controlView.horizontalLabel.isHidden = false
self.controlView.horizontalLabel.text = "视频加载失败"
}
} else if keyPath == "loadedTimeRanges" {
let totalDuration = CMTimeGetSeconds(self.playerItem!.duration)
let progres = self.availableDuration() / totalDuration
let progressView = controlView.progressView
progressView?.setProgress(Float(progres), animated: false)
let tiaojian = ((progressView?.progress ?? 0) - controlView.videoSlider.value > 0.05)
if !self.isPauseByUser && !self.didEnterBackground && tiaojian {
self.play()
}
} else if keyPath == "playbackBufferEmpty" {
if (self.playerItem?.isPlaybackBufferEmpty ?? false) {
self.state = .buffering
self.bufferingSomeSecond()
}
} else if keyPath == "playbackLikelyToKeepUp" {
if (self.playerItem?.isPlaybackLikelyToKeepUp ?? false) && self.state == .buffering {
self.state = .playing
}
}
}else if (object as? UITableView == self.tableView) {
if keyPath == kOffset {
let orien = UIDevice.current.orientation
if orien == .landscapeLeft || orien == .landscapeRight {
return
}
// 当tableview滚动时处理playerView的位置
self.handleScrollOffsetWithDict(change ?? [:])
}
}
}
// KVO TableViewContentOffset
func handleScrollOffsetWithDict(_ dict: [NSKeyValueChangeKey : Any]) {
let cell = self.tableView?.cellForRow(at: indexPath)
let visableCells = self.tableView?.visibleCells
if visableCells?.contains(cell!) ?? false {
self.updatePlayerViewToCell()
}else {
self.updatePlayerViewToBottom()
}
}
// 缩小到底部,显示小视频
func updatePlayerViewToBottom() {
if (self.isBottomVideo) { return }
self.isBottomVideo = true
if (self.playDidEnd) { //如果播放完了,滑动到小屏bottom位置时,直接resetPlayer
self.repeatToPlay = false
self.playDidEnd = false
self.resetPlayer()
return
}
UIApplication.shared.keyWindow?.addSubview(self)
self.snp.makeConstraints { (make) in
make.width.equalTo(APPW * 0.5 - 20)
make.rightMargin.equalTo(10)
make.bottom.equalTo(tableView?.snp.bottom ?? self.snp.bottom).offset(-10)
make.height.equalTo(self.snp.width).multipliedBy(9.0 / 16)
}
// 不显示控制层
controlView.hideControlView()
}
// 回到cell显示
func updatePlayerViewToCell() {
if (!self.isBottomVideo) { return }
self.isBottomVideo = false
self.controlView.alpha = 1
self.setOrientationPortrait()
controlView.showControlView()
}
// 设置横屏的约束
func setOrientationLandscape() {
if (self.isCellVideo) {
tableView?.removeObserver(self, forKeyPath: kOffset)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
UIApplication.shared.keyWindow?.insertSubview(self, belowSubview: XBrightnessView.shared)
self.snp.remakeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.zero)
}
}
}
// 设置竖屏的约束
func setOrientationPortrait() {
if (self.isCellVideo) {
UIApplication.shared.setStatusBarStyle(.default, animated: true)
self.removeFromSuperview()
let cell = self.tableView?.cellForRow(at: indexPath)
let visableCells = self.tableView?.visibleCells
self.isBottomVideo = false
if !(visableCells?.contains(cell!) ?? false) {
self.updatePlayerViewToBottom()
}else {
let cellImageView = cell?.viewWithTag(self.cellImageViewTag)
self.addPlayerToCellImageView(cellImageView as! UIImageView)
}
}
}
// pragma mark 屏幕转屏相关
// 强制屏幕转屏
func interfaceOrientation(_ orientation: UIInterfaceOrientation) {
if orientation == UIInterfaceOrientation.landscapeLeft || orientation == UIInterfaceOrientation.landscapeRight {
self.setOrientationLandscape()
}else if (orientation == UIInterfaceOrientation.portrait) {
self.setOrientationPortrait()
}
// 直接调用这个方法通不过apple上架审核
// UIDevice.current.orientation = UIDeviceOrientation.landscapeRight
}
// 全屏按钮事件
@objc func fullScreenAction(_ sender: UIButton?) {
if (self.isLocked) {
self.unLockTheScreen()
return
}
if (self.isCellVideo && sender?.isSelected == true) {
self.interfaceOrientation(.portrait)
return
}
let orientation = UIDevice.current.orientation
let interfaceOrientation = UIInterfaceOrientation(rawValue: orientation.rawValue) ?? .portrait
switch (interfaceOrientation) {
case .portraitUpsideDown:
nessView.isAllowLandscape = false
self.interfaceOrientation(.portrait)
case .portrait:
nessView.isAllowLandscape = true
self.interfaceOrientation(.landscapeRight)
case .landscapeLeft:
if (self.isBottomVideo || !self.isFullScreen) {
nessView.isAllowLandscape = true
self.interfaceOrientation(.landscapeRight)
} else {
nessView.isAllowLandscape = false
self.interfaceOrientation(.portrait)
}
case .landscapeRight:
if (self.isBottomVideo || !self.isFullScreen) {
nessView.isAllowLandscape = true
self.interfaceOrientation(.landscapeRight)
} else {
nessView.isAllowLandscape = false
self.interfaceOrientation(.portrait)
}
default:
if (self.isBottomVideo || !self.isFullScreen) {
nessView.isAllowLandscape = true
self.interfaceOrientation(.landscapeRight)
} else {
nessView.isAllowLandscape = false
self.interfaceOrientation(.portrait)
}
}
}
// 屏幕方向发生变化会调用这里
@objc func onDeviceOrientationChange() {
if (self.isLocked) {
self.isFullScreen = true
return
}
let orientation = UIDevice.current.orientation
let interfaceOrientation = UIInterfaceOrientation(rawValue:orientation.rawValue) ?? .portrait
switch (interfaceOrientation) {
case .portraitUpsideDown:
self.controlView.fullScreenBtn.isSelected = true
if (self.isCellVideo) {
controlView.backBtn.setImage(XPImage.back.img, for: .normal)
}
self.isFullScreen = true
case .portrait:
self.isFullScreen = !self.isFullScreen
self.controlView.fullScreenBtn.isSelected = false
if (self.isCellVideo) {
// 改为只允许竖屏播放
nessView.isAllowLandscape = false
controlView.backBtn.setImage(XPImage.close.img, for: .normal)
// 点击播放URL时候不会调用次方法
if (!self.isFullScreen) {
// 竖屏时候table滑动到可视范围
tableView?.scrollToRow(at: indexPath, at: .middle, animated: false)
// 重新监听tableview偏移量
tableView?.addObserver(self, forKeyPath: kOffset, options: .new, context: nil)
}
// 当设备转到竖屏时候,设置为竖屏约束
self.setOrientationPortrait()
}else {
}
self.isFullScreen = false
case .landscapeLeft:
self.controlView.fullScreenBtn.isSelected = true
if (self.isCellVideo) {
controlView.backBtn.setImage(XPImage.back.img, for: .normal)
}
self.isFullScreen = true
case .landscapeRight:
self.controlView.fullScreenBtn.isSelected = true
if (self.isCellVideo) {
controlView.backBtn.setImage(XPImage.back.img, for: .normal)
}
self.isFullScreen = true
default:break
}
// 设置显示or不显示锁定屏幕方向按钮
self.controlView.lockBtn.isHidden = !self.isFullScreen
// 在cell上播放视频 && 不允许横屏(此时为竖屏状态,解决自动转屏到横屏,状态栏消失bug)
if (self.isCellVideo && !nessView.isAllowLandscape) {
controlView.backBtn.setImage(XPImage.close.img, for: .normal)
self.controlView.fullScreenBtn.isSelected = false
self.controlView.lockBtn.isHidden = true
self.isFullScreen = false
}
}
// 锁定屏幕方向按钮
@objc func lockScreenAction(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
self.isLocked = sender.isSelected
nessView.isLockScreen = sender.isSelected
}
// 解锁屏幕方向锁定
func unLockTheScreen() {
// 调用AppDelegate单例记录播放状态是否锁屏
nessView.isLockScreen = false
self.controlView.lockBtn.isSelected = false
self.isLocked = false
self.interfaceOrientation(.portrait)
}
// player添加到cellImageView上
public func addPlayerToCellImageView(_ imageView: UIImageView) {
imageView.addSubview(self)
self.snp.remakeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.zero)
}
}
// pragma mark - 缓冲较差时候
// 缓冲较差时候回调这里
func bufferingSomeSecond() {
self.state = .buffering
var isBuffering = false
if (isBuffering) { return }
isBuffering = true
self.player?.pause()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
if (self.isPauseByUser) {
isBuffering = false
return
}
self.play()
isBuffering = false
if !(self.playerItem?.isPlaybackLikelyToKeepUp ?? false) {
self.bufferingSomeSecond()
}
}
}
// 计算缓冲进度
func availableDuration() -> TimeInterval {
let loadedTimeRanges = player?.currentItem?.loadedTimeRanges
let timeRange = loadedTimeRanges?.first?.timeRangeValue
let startSeconds = CMTimeGetSeconds(timeRange!.start)
let durationSeconds = CMTimeGetSeconds(timeRange!.duration)
let result = startSeconds + durationSeconds// 计算缓冲总进度
return result
}
// 轻拍方法
@objc func tapAction(_ gesture: UITapGestureRecognizer) {
if (gesture.state == .recognized) {
if (self.isBottomVideo && !self.isFullScreen) {
self.fullScreenAction(self.controlView.fullScreenBtn)
return
}
if isMaskShowing {
self.hideControlView()
} else {
self.animateShow()
}
}
}
// 双击播放/暂停
@objc func doubleTapAction(_ gesture: UITapGestureRecognizer) {
self.animateShow()
self.startAction(self.controlView.startBtn)
}
// 播放、暂停按钮事件
@objc func startAction(_ button: UIButton?) {
button?.isSelected = !(button?.isSelected ?? false)
self.isPauseByUser = !self.isPauseByUser
if button?.isSelected ?? false {
self.play()
if (self.state == .pause) {
self.state = .playing
}
} else {
self.pause()
if (self.state == .playing) {
self.state = .pause
}
}
}
// 播放
public func play() {
self.controlView.startBtn.isSelected = true
self.isPauseByUser = false
player?.play()
}
// 暂停
public func pause() {
self.controlView.startBtn.isSelected = false
self.isPauseByUser = true
player?.pause()
}
// 返回按钮事件
@objc func backButtonAction() {
if (self.isLocked) {
self.unLockTheScreen()
return
}else {
if (!self.isFullScreen) {
if (self.isCellVideo) {
self.resetPlayer()
self.removeFromSuperview()
return
}
self.pause()
self.goBackBlock?()
}else {
self.interfaceOrientation(.portrait)
}
}
}
// 重播点击事件
@objc func repeatPlay(_ sender: UIButton) {
self.playDidEnd = false
self.repeatToPlay = false
self.isMaskShowing = false
self.animateShow()
self.controlView.resetControlView()
self.seekToTime(0)
}
@objc func downloadVideo(_ sender: UIButton) {
let urlStr = self.videoURL?.absoluteString
self.downloadBlock?(urlStr)
}
// pragma mark - NSNotification Action
// 播放完了
@objc func moviePlayDidEnd(notification: NSNotification) {
self.state = .stopped
if (self.isBottomVideo && !self.isFullScreen) {
self.repeatToPlay = false
self.playDidEnd = false
self.resetPlayer()
} else {
self.controlView.backgroundColor = UIColor(white: 0.6, alpha: 1)
self.playDidEnd = true
self.controlView.repeatBtn.isHidden = false
self.isMaskShowing = false
self.animateShow()
}
}
// 应用退到后台
@objc func appDidEnterBackground() {
self.didEnterBackground = true
player?.pause()
self.state = .pause
self.cancelAutoFadeOutControlBar()
self.controlView.startBtn.isSelected = false
}
// 应用进入前台
@objc func appDidEnterPlayGround() {
self.didEnterBackground = false
self.isMaskShowing = false
self.animateShow()
if (!self.isPauseByUser) {
self.state = .playing
self.controlView.startBtn.isSelected = true
self.isPauseByUser = false
self.play()
}
}
// pragma mark - slider事件
// slider开始滑动事件
@objc func progressSliderTouchBegan(slider: ASValueTrackingSlider) {
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
// slider滑动中事件
@objc func progressSliderValueChanged(_ slider: ASValueTrackingSlider) {
if (self.player?.currentItem?.status == .readyToPlay) {
let value = slider.value - self.sliderLastValue
if (value == 0) { return }
self.sliderLastValue = slider.value
self.pause()
let total = Float(Int32(playerItem!.duration.value) / (playerItem!.duration.timescale))
let dragedSeconds = floorf(total * slider.value)
let dragedCMTime = CMTimeMake(value: Int64(dragedSeconds), timescale: 1)
let proMin = Int(CMTimeGetSeconds(dragedCMTime)) / 60
let proSec = Int(CMTimeGetSeconds(dragedCMTime)) % 60
let durMin = Int(total) / 60//总秒
let durSec = Int(total) % 60//总分钟
let currentTime = String(format:"%02zd:%02zd", proMin, proSec)
let totalTime = String(format:"%02zd:%02zd", durMin, durSec)
if (total > 0) {
self.controlView.videoSlider.popUpView.isHidden = !self.isFullScreen
self.controlView.currentTimeLabel.text = currentTime
if (self.isFullScreen) {
self.controlView.videoSlider.popUpView.timeLabel.text = currentTime
let queue = DispatchQueue(label: "com.playerPic.queue")
queue.async {
let cgImage = try? self.imageGenerator.copyCGImage(at: dragedCMTime, actualTime: nil)
var image = XPImage.loading.img
if let cg = cgImage {
image = UIImage(cgImage: cg)
}
DispatchQueue.main.async {
self.controlView.videoSlider.setThumbImage(image, for: .normal)
}
}
} else {
self.controlView.horizontalLabel.isHidden = false
self.controlView.horizontalLabel.text = "\(currentTime) / \(totalTime)"
}
}else {
slider.value = 0
}
}else {
slider.value = 0
}
}
// slider结束滑动事件
@objc func progressSliderTouchEnded(_ slider: ASValueTrackingSlider) {
if (self.player?.currentItem?.status == .readyToPlay) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.controlView.horizontalLabel.isHidden = true
}
self.controlView.startBtn.isSelected = true
self.isPauseByUser = false
self.autoFadeOutControlBar()
let total = CGFloat(Int32(playerItem!.duration.value) / playerItem!.duration.timescale)
let dragedSeconds = floorf(Float(total) * slider.value)
self.seekToTime(Int(dragedSeconds))
}
}
// 从xx秒开始播放视频跳转
func seekToTime(_ dragedSeconds: NSInteger, completionHandler:((Bool) -> Void)? = nil) {
if (self.player?.currentItem?.status == .readyToPlay) {
// seekTime:completionHandler:不能精确定位
// 可以使用seekToTime:toleranceBefore:toleranceAfter:completionHandler:
// 转换成CMTime才能给player来控制播放进度
let dragedCMTime = CMTimeMake(value: Int64(dragedSeconds), timescale: 1)
player?.seek(to: dragedCMTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero, completionHandler: { (finished) in
// 视频跳转回调
completionHandler?(finished)
self.play()
self.seekTime = 0
if (!(self.playerItem?.isPlaybackLikelyToKeepUp ?? false) && !self.isLocalVideo) { self.state = .buffering
}
})
}
}
// pragma mark - UIPanGestureRecognizer手势方法
// pan手势事件
@objc func panDirection(_ pan: UIPanGestureRecognizer) {
let locationPoint = pan.location(in: self)
let veloctyPoint = pan.velocity(in: self)
switch (pan.state) {
case .began:
let x = abs(veloctyPoint.x)
let y = abs(veloctyPoint.y)
if (x > y) {
self.controlView.horizontalLabel.isHidden = false
self.panDirection = .horizontal
let time = self.player!.currentTime()
self.sumTime = CGFloat(time.value)/CGFloat(time.timescale)
self.pause()
} else if (x < y){
self.panDirection = .vertical
if (locationPoint.x > self.bounds.size.width / 2) {
self.isVolume = true
}else {
self.isVolume = false
}
}
case .changed:
switch (self.panDirection) {
case .horizontal:
self.controlView.horizontalLabel.isHidden = false
self.horizontalMoved(veloctyPoint.x)
case .vertical: self.verticalMoved(veloctyPoint.y)
}
case .ended:
switch (self.panDirection) {
case .horizontal:
self.play()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
self.controlView.horizontalLabel.isHidden = true
}
self.controlView.startBtn.isSelected = true
self.isPauseByUser = false
self.seekToTime(NSInteger(self.sumTime))
self.sumTime = 0
case .vertical:
self.isVolume = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.controlView.horizontalLabel.isHidden = true
}
}
default: break
}
}
// pan垂直移动的方法
func verticalMoved(_ value: CGFloat) {
if self.isVolume {
let v = volumeViewSlider?.value ?? 0
self.volumeViewSlider?.value = v - Float(value) / 10000
} else {
UIScreen.main.brightness -= value / 10000
}
}
// pan水平移动的方法
func horizontalMoved(_ value: CGFloat) {
if (value == 0) { return }
self.sumTime += value / 200
let totalTime = self.playerItem!.duration
let totalMovieDuration = CGFloat(Int32(totalTime.value)/totalTime.timescale)
if (self.sumTime > totalMovieDuration) { self.sumTime = totalMovieDuration}
if (self.sumTime < 0) { self.sumTime = 0 }
let nowTime = self.durationStringWithTime(Int(self.sumTime))
let durationTime = self.durationStringWithTime(Int(totalMovieDuration))
self.controlView.horizontalLabel.text = "\(nowTime) / \(durationTime)"
self.controlView.videoSlider.value = Float(self.sumTime/totalMovieDuration)
self.controlView.currentTimeLabel.text = nowTime
}
// 根据时长求出字符串
func durationStringWithTime(_ time: Int) -> String {
// 获取分钟
let min = String(format: "%02d",time / 60)
// 获取秒数
let sec = String(format: "%02d",time % 60)
return "\(min):\(sec)"
}
}
extension XPlayer: UIGestureRecognizerDelegate, UIAlertViewDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) {
let point = touch.location(in: self.controlView)
// (屏幕下方slider区域) || (在cell上播放视频 && 不是全屏状态) || (播放完了) =====> 不响应pan手势
if ((point.y > self.bounds.size.height-40) || (self.isCellVideo && !self.isFullScreen) || self.playDidEnd) { return false }
return true
}
// 在cell上播放视频 && 不是全屏状态 && 点在控制层上
if (self.isBottomVideo && !self.isFullScreen && touch.view == self.controlView) {
self.fullScreenAction(self.controlView.fullScreenBtn)
return false
}
if (self.isBottomVideo && !self.isFullScreen && touch.view == self.controlView.backBtn) {
// 关闭player
self.resetPlayer()
self.removeFromSuperview()
return false
}
return true
}
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex:NSInteger) {
if (alertView.tag == 1000 ) {
if (buttonIndex == 0) { self.backButtonAction()} // 点击取消,直接调用返回函数
if (buttonIndex == 1) { self.configZFPlayer()} // 点击确定,设置player相关参数
}
}
}
| mit | a81c4ad5bb36993fac4c6728b372a596 | 38.610229 | 208 | 0.602119 | 4.6054 | false | false | false | false |
lightbluefox/rcgapp | IOS App/RCGApp/RCGApp/NewsAndVacancyClass.swift | 1 | 12128 | import UIKit
class News {
var id = 0;
var title = "";
var announcement = "";
var fullText = "";
var fullTextImageURL = "";
var createdDate = "";
init (id: Int, title: String, announcement: String, fulltext: String, fullTextImageURL: String, createdDate: String) {
self.id = id;
self.title = title;
self.announcement = announcement;
self.fullText = fulltext;
self.fullTextImageURL = fullTextImageURL;
self.createdDate = createdDate;
}
}
class Vacancy: News {
//var announceImage = UIImage(named: "FullTextImage")!;
var announceImageURL = "";
var rate = "";
//TODO: Сделать пол через Enum
var gender = 2; //0 - мужчины, 1 - женщины, 2 - мужчины и женщины
var city = "";
var schedule = "";
var validTillDate = "";
init (id: Int, title: String, announcement: String, announceImageURL: String, fulltext: String, fullTextImageURL: String, createdDate: String, rate: String, gender: Int, city: String, schedule: String, validTillDate: String) {
super.init(id: id, title: title, announcement: announcement, fulltext: fulltext, fullTextImageURL: fullTextImageURL, createdDate: createdDate);
self.id = id;
self.title = title;
self.announcement = announcement;
self.announceImageURL = announceImageURL;
self.fullText = fulltext;
self.fullTextImageURL = fullTextImageURL;
self.createdDate = createdDate;
self.rate = rate;
self.gender = gender;
self.city = city;
self.schedule = schedule;
self.validTillDate = validTillDate;
}
}
class NewsAndVacanciesReceiver {
//класс-получатель новостей и вакансий
var newsStack = [News]();
var vacStack = [Vacancy]();
func getAllNews(completionHandlerNews: (success: Bool, result: String) -> Void) {
newsStack.removeAll(keepCapacity: false);
var request = HTTPTask()
request.GET("http://agency.cloudapp.net/news", parameters: nil, completionHandler: {(response: HTTPResponse) in
if let err = response.error {
dispatch_async(dispatch_get_main_queue()) {
completionHandlerNews(success: false, result: err.localizedDescription)
}
return
}
else if let data = response.responseObject as? NSData {
let requestedData = NSString(data: data, encoding: NSUTF8StringEncoding)
let requestedDataUnwrapped = requestedData!;
let jsonString = requestedDataUnwrapped;
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let jsonObject: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions(0), error: nil)
let json = JSON(jsonObject);
for var i = 0; i < json.count; i++ {
var id = json[i]["id"] != nil ? json[i]["id"].int! : 0;
var title = json[i]["title"] != nil ? json[i]["title"].string! : "";
var announcement = json[i]["shortText"] != nil ? json[i]["shortText"].string! : "";
var fulltext = json[i]["text"] != nil ? json[i]["text"].string! : "";
//
var fullTextImageURL = json[i]["picture"] != nil ? json[i]["picture"].string! : "";
//
var createdDate = json[i]["dateCreated"] != nil ? json[i]["dateCreated"].string!.formatedDate : "";
self.newsStack.append(News(id: id, title: title, announcement: announcement, fulltext: fulltext, fullTextImageURL: fullTextImageURL, createdDate: createdDate));
}
dispatch_async(dispatch_get_main_queue()) {
completionHandlerNews(success: true, result: "Новости загружены")
}
}
})
}
func getAllVacancies(completionHandlerVacancy: (success: Bool, result: String) -> Void) {
vacStack.removeAll(keepCapacity: false);
var request = HTTPTask()
request.GET("http://agency.cloudapp.net/vacancy", parameters: nil, completionHandler: {(response: HTTPResponse) in
if let err = response.error {
dispatch_async(dispatch_get_main_queue()) {
completionHandlerVacancy(success: true, result: err.localizedDescription)
}
return //also notify app of failure as needed
}
else if let data = response.responseObject as? NSData {
let requestedData = NSString(data: data, encoding: NSUTF8StringEncoding)
let requestedDataUnwrapped = requestedData!;
let jsonString = requestedDataUnwrapped;
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let jsonObject: AnyObject! = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions(0), error: nil)
let json = JSON(jsonObject);
for var i = 0; i < json.count; i++ {
//Получаем все поля, проверяем на наличие значения
var id = json[i]["id"] != nil ? json[i]["id"].int : 0;
var title = json[i]["title"] != nil ? json[i]["title"].string! : "";
var announcement = json[i]["shortText"] != nil ? json[i]["shortText"].string! : "";
var fulltext = json[i]["text"] != nil ? json[i]["text"].string! : "";
var announceImageURL = json[i]["previewPicture"] != nil ? json[i]["previewPicture"].string! : "";
var fullTextImageURL = json[i]["picture"] != nil ? json[i]["picture"].string! : "";
var gender = 0
var createdDate = json[i]["dateCreated"] != nil ? json[i]["dateCreated"].string!.formatedDate : "";
var rate = "";
var schedule = "";
var city = "";
var validTillDate = "";
var vac = json[i]["Vacancy"];
if json[i]["Vacancy"] != nil {
gender = json[i]["Vacancy"]["isMale"].int!;
rate = json[i]["Vacancy"]["money"] != nil ? json[i]["Vacancy"]["money"].string! : "";
schedule = json[i]["Vacancy"]["workTime"] != nil ? json[i]["Vacancy"]["workTime"].string! : "";
city = json[i]["Vacancy"]["city"] != nil ? json[i]["Vacancy"]["city"].string! : "";
validTillDate = json[i]["Vacancy"]["endTime"] != nil ? json[i]["Vacancy"]["endTime"].string!.formatedDate : "";
}
self.vacStack.append(Vacancy(id: id!, title: title, announcement: announcement, announceImageURL: announceImageURL, fulltext: fulltext, fullTextImageURL: fullTextImageURL, createdDate: createdDate, rate: rate, gender: gender, city: city, schedule: schedule, validTillDate: validTillDate));
}
dispatch_async(dispatch_get_main_queue()) {
completionHandlerVacancy(success: true, result: "Вакансии загружены")
}
}
})
}
// vacStack.append(Vacancy(id: 1, title: "Модель", announcement: "ВРЕМЕННАЯ РАБОТА С 23 ПО 26 АПРЕЛЯ", announceImage: UIImage(named: "FullTextImage")!, fulltext: "На железном троне сейчас бастард Ланнистеров, так же свои права на трон предъявляет младший брат Роберта - Ренли и Роб Старк. Огненным жрицам нужно будет сжигать пиявок и таким образом, при помощи огненной магии, убить всех троих.", fulltextImage: UIImage(named: "FullTextImage")!, createdDate: "15.05.2015", rate: "400р/час", gender: 0, city: "Москва", schedule: "Ежедневно с 01 до 03 часов ночи", validTillDate: "20.06.2015"));
// vacStack.append(Vacancy(id: 2, title: "Наказание узурпатора", announcement: "Ищем огненных жрецов в помощь нашему королю", announceImage: UIImage(named: "VacancyImg")!, fulltext: "На железном троне сейчас бастард Ланнистеров, так же свои права на трон предъявляет младший брат Роберта - Ренли и Роб Старк. Огненным жрицам нужно будет сжигать пиявок и таким образом, при помощи огненной магии, убить всех троих.", fulltextImage: UIImage(named: "FullTextImage")!, createdDate: "11.05.2015", rate: "5000USD", gender: 2, city: "Москва", schedule: "Ежедневно с 01 до 03 часов ночи", validTillDate: "20.08.2015"));
// vacStack.append(Vacancy(id: 3, title: "Наказание узурпатора", announcement: "Ищем огненных жрецов в помощь нашему королю", announceImage: UIImage(named: "VacancyImg")!, fulltext: "На железном троне сейчас бастард Ланнистеров, так же свои права на трон предъявляет младший брат Роберта - Ренли и Роб Старк. Огненным жрицам нужно будет сжигать пиявок и таким образом, при помощи огненной магии, убить всех троих.", fulltextImage: UIImage(named: "FullTextImage")!, createdDate: "10.05.2015", rate: "400р/час", gender: 1, city: "Москва", schedule: "Ежедневно с 01 до 03 часов ночи", validTillDate: "20.07.2015"));
// vacStack.append(Vacancy(id: 4, title: "Наказание узурпатора", announcement: "Ищем огненных жрецов в помощь нашему королю", announceImage: UIImage(named: "VacancyImg")!, fulltext: "На железном троне сейчас бастард Ланнистеров, так же свои права на трон предъявляет младший брат Роберта - Ренли и Роб Старк. Огненным жрицам нужно будет сжигать пиявок и таким образом, при помощи огненной магии, убить всех троих.", fulltextImage: UIImage(named: "FullTextImage")!, createdDate: "10.05.2015", rate: "400р/час", gender: 1, city: "Москва", schedule: "Ежедневно с 01 до 03 часов ночи", validTillDate: "20.07.2015"));
// vacStack.append(Vacancy(id: 5, title: "Наказание узурпатора", announcement: "Ищем огненных жрецов в помощь нашему королю", announceImage: UIImage(named: "VacancyImg")!, fulltext: "На железном троне сейчас бастард Ланнистеров, так же свои права на трон предъявляет младший брат Роберта - Ренли и Роб Старк. Огненным жрицам нужно будет сжигать пиявок и таким образом, при помощи огненной магии, убить всех троих.", fulltextImage: UIImage(named: "FullTextImage")!, createdDate: "10.05.2015", rate: "400р/час", gender: 2, city: "Москва", schedule: "Ежедневно с 01 до 03 часов ночи", validTillDate: "20.07.2015"));
} | gpl-2.0 | ea25196b4134a542fcd776e1efb7542b | 67.606452 | 619 | 0.609423 | 3.493101 | false | false | false | false |
iOSTestApps/HausClock | HausClock/UIColorExtension.swift | 2 | 3320 | //
// UIColorExtension.swift
// HausClock
//
// Created by Tom Brown on 7/13/14.
// Copyright (c) 2014 not. All rights reserved.
//
import UIKit
extension String {
func length() -> Int {
return countElements(self)
}
func trim() -> String {
return self.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
}
func substring(location:Int, length:Int) -> String! {
return (self as NSString).substringWithRange(NSMakeRange(location, length))
}
subscript(index: Int) -> String! {
get {
return self.substring(index, length: 1)
}
}
func location(other: String) -> Int {
return (self as NSString).rangeOfString(other).location
}
func contains(other: String) -> Bool {
return (self as NSString).containsString(other)
}
// http://stackoverflow.com/questions/6644004/how-to-check-if-nsstring-is-contains-a-numeric-value
func isNumeric() -> Bool {
return (self as NSString).rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).location == NSNotFound
}
}
// UIColor should just take have a separate init
// https://github.com/aleclarson/hex-codes-in-swift/blob/master/Hexes.swift
extension String {
public var CGColor: CGColorRef {
return self.CGColor(1)
}
public var UIColor: UIKit.UIColor {
return self.UIColor(1)
}
public func CGColor (alpha: CGFloat) -> CGColorRef {
return self.UIColor(alpha).CGColor
}
public func UIColor (alpha: CGFloat) -> UIKit.UIColor {
var hex = self
// Strip leading "#" if it exists
if hex.hasPrefix("#") {
hex = hex.substringFromIndex(hex.startIndex.successor())
}
let length = countElements(hex)
// Turn "f" into "ffffff"
if length == 1 {
hex = repeat(hex, 6)
}
// Turn "ff" into "ffffff"
else if length == 2 {
hex = repeat(hex, 3)
}
// Turn "123" into "112233"
else if length == 3 {
hex = repeat(hex[0], 2) + repeat(hex[1], 2) + repeat(hex[2], 2)
}
assert(countElements(hex) == 6, "Invalid hex value")
var r: UInt32 = 0
var g: UInt32 = 0
var b: UInt32 = 0
NSScanner(string: "0x" + hex[0...1]).scanHexInt(&r)
NSScanner(string: "0x" + hex[2...3]).scanHexInt(&g)
NSScanner(string: "0x" + hex[4...5]).scanHexInt(&b)
let red = CGFloat(Int(r)) / CGFloat(255.0)
let green = CGFloat(Int(g)) / CGFloat(255.0)
let blue = CGFloat(Int(b)) / CGFloat(255.0)
return UIKit.UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
private subscript (i: Int) -> String {
return String(Array(self)[i])
}
private subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex)))
}
}
private func repeat (string: String, count: Int) -> String {
return "".stringByPaddingToLength(countElements(string) * count, withString: string, startingAtIndex:0)
} | mit | f7464ff7ad5760a71627d42e351fb091 | 28.389381 | 135 | 0.578313 | 4.129353 | false | false | false | false |
nikitakirichek/concurrency-in-swift | PPCourseWork1/CSMatrix.swift | 1 | 1821 | //
// CSMatrix.swift
// PPCourseWork1
//
// Created by Nikita Kirichek on 5/11/17.
// Copyright © 2017 Nikita Kirichek. All rights reserved.
//
import Cocoa
class CSMatrix {
private (set) var rawValue = [[Int]]()
init(array: [[Int]]) {
rawValue = array
}
func slice(start: Int, end: Int) -> CSMatrix{
let rawMatrixPart = rawValue.map{Array($0[start...end])}
return CSMatrix(array: rawMatrixPart)
}
func replacePart(start: Int, end: Int, matrix: CSMatrix) {
for i in start..<end {
rawValue[i] = matrix.rawValue[i - start]
}
}
}
extension CSMatrix {
static func *(matrix: CSMatrix, vector: CSVector) -> CSVector {
return vector * matrix
}
static func *(vector: CSVector, matrix: CSMatrix) -> CSVector {
var result = [Int](repeating: 0, count: matrix.rawValue[0].count)
for i in 0..<matrix.rawValue[0].count {
for j in 0..<vector.rawValue.count {
result[i] += vector.rawValue[j] * matrix.rawValue[j][i]
}
}
return CSVector(array: result)
}
static func *(matrix1: CSMatrix, matrix2: CSMatrix) -> CSMatrix {
let row = [Int](repeating: 0, count: matrix2.rawValue[0].count)
var result = [[Int]](repeating: row, count: matrix2.rawValue.count)
var count = 0
for i in 0..<matrix2.rawValue[0].count {
for j in 0..<matrix2.rawValue.count {
for k in 0..<matrix2.rawValue.count {
count = count + 1
result[j][i] += matrix2.rawValue[k][i] * matrix1.rawValue[j][k]
}
}
}
print("Count \(count)")
return CSMatrix(array: result)
}
}
| mit | f6a13fd26e6766f2caf57f9ef271e4f3 | 26.164179 | 83 | 0.537912 | 3.791667 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureApp/Sources/FeatureAppUI/Onboarding/PinScreen/PinReducer.swift | 1 | 1797 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import ComposableArchitecture
import FeatureSettingsDomain
import PlatformKit
import PlatformUIKit
public enum PinCore {
public enum Action: Equatable {
/// Displays the Pin screen for authentication
case authenticate
/// Displays the Pin screen for creating a pin
case create
/// Performs a logout
case logout
/// Action that gets called with the pin is created
case pinCreated
/// Sent by the pin screen to perform wallet authentication
case handleAuthentication(_ password: String)
case none
}
public struct State: Equatable {
public var creating: Bool = false
public var authenticate: Bool = false
/// Determines if the state requires Pin
var requiresPinAuthentication: Bool {
authenticate
}
public init(
creating: Bool = false,
authenticate: Bool = false
) {
self.creating = creating
self.authenticate = authenticate
}
}
public struct Environment {
let appSettings: AppSettingsAPI
let alertPresenter: AlertViewPresenterAPI
}
}
let pinReducer = Reducer<PinCore.State, PinCore.Action, PinCore.Environment> { state, action, _ in
switch action {
case .authenticate:
state.creating = false
state.authenticate = true
return .none
case .create:
state.creating = true
state.authenticate = false
return .none
case .logout:
return .none
case .handleAuthentication(let password):
return .none
case .pinCreated:
return .none
case .none:
return .none
}
}
| lgpl-3.0 | ae82381dabac003454e770c84f9a74fc | 25.80597 | 98 | 0.625835 | 5.297935 | false | false | false | false |
huonw/swift | test/ClangImporter/objc_bridge_categories.swift | 45 | 1322 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/Inputs/custom-modules %s -verify
// REQUIRES: objc_interop
// Test the use of Objective-C categories on the value types that
// bridge to Objective-C class types.
import Foundation
import AppKit
func testStringBridge(_ str: String) {
var str2 = str.nsStringMethod()!
var int = NSString.nsStringClassMethod()
var str3 = str.nsStringProperty!
// Make sure the types worked out as expected
var str: String = str2
str2 = str
str = str3
str3 = str
var int2: Int = 0
int = int2
// Not bridged because it's in the Foundation module.
str.notBridgedMethod() // expected-error{{value of type 'String' has no member 'notBridgedMethod'}}
}
func testDictionaryBridge(_ dict: Dictionary<String, String>) {
var d2 = dict.nsDictionaryMethod() // expected-error{{value of type 'Dictionary<String, String>' has no member 'nsDictionaryMethod'}}
var int = Dictionary<String, String>.nsDictionaryClassMethod() // expected-error{{type 'Dictionary<String, String>' has no member 'nsDictionaryClassMethod'}}
var d3 = dict.nsDictionaryProperty // expected-error{{value of type 'Dictionary<String, String>' has no member 'nsDictionaryProperty'}}
}
func testStringBridge() {
var i = String.someFactoryMethod()
i = 17
_ = i
}
| apache-2.0 | 6822092da114df736ef5487d36357156 | 33.789474 | 159 | 0.726172 | 3.777143 | false | true | false | false |
vector-im/riot-ios | Riot/Modules/KeyVerification/Device/Start/DeviceVerificationStartViewModel.swift | 1 | 5062 | // File created from ScreenTemplate
// $ createScreen.sh DeviceVerification/Start DeviceVerificationStart
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
final class DeviceVerificationStartViewModel: DeviceVerificationStartViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let verificationManager: MXKeyVerificationManager
private let otherUser: MXUser
private let otherDevice: MXDeviceInfo
private var transaction: MXSASTransaction!
// MARK: Public
weak var viewDelegate: DeviceVerificationStartViewModelViewDelegate?
weak var coordinatorDelegate: DeviceVerificationStartViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, otherUser: MXUser, otherDevice: MXDeviceInfo) {
self.session = session
self.verificationManager = session.crypto.keyVerificationManager
self.otherUser = otherUser
self.otherDevice = otherDevice
}
deinit {
}
// MARK: - Public
func process(viewAction: DeviceVerificationStartViewAction) {
switch viewAction {
case .beginVerifying:
self.beginVerifying()
case .verifyUsingLegacy:
self.cancelTransaction()
self.update(viewState: .verifyUsingLegacy(self.session, self.otherDevice))
case .verifiedUsingLegacy:
self.coordinatorDelegate?.deviceVerificationStartViewModelDidUseLegacyVerification(self)
case .cancel:
self.cancelTransaction()
self.coordinatorDelegate?.deviceVerificationStartViewModelDidCancel(self)
}
}
// MARK: - Private
private func beginVerifying() {
self.update(viewState: .loading)
self.verificationManager.beginKeyVerification(withUserId: self.otherUser.userId, andDeviceId: self.otherDevice.deviceId, method: MXKeyVerificationMethodSAS, success: { [weak self] (transaction) in
guard let sself = self else {
return
}
guard let sasTransaction: MXOutgoingSASTransaction = transaction as? MXOutgoingSASTransaction else {
return
}
sself.transaction = sasTransaction
sself.update(viewState: .loaded)
sself.registerTransactionDidStateChangeNotification(transaction: sasTransaction)
}, failure: {[weak self] error in
self?.update(viewState: .error(error))
})
}
private func cancelTransaction() {
guard let transaction = self.transaction else {
return
}
transaction.cancel(with: MXTransactionCancelCode.user())
}
private func update(viewState: DeviceVerificationStartViewState) {
self.viewDelegate?.deviceVerificationStartViewModel(self, didUpdateViewState: viewState)
}
// MARK: - MXKeyVerificationTransactionDidChange
private func registerTransactionDidStateChangeNotification(transaction: MXOutgoingSASTransaction) {
NotificationCenter.default.addObserver(self, selector: #selector(transactionDidStateChange(notification:)), name: NSNotification.Name.MXKeyVerificationTransactionDidChange, object: transaction)
}
private func unregisterTransactionDidStateChangeNotification() {
NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationTransactionDidChange, object: nil)
}
@objc private func transactionDidStateChange(notification: Notification) {
guard let transaction = notification.object as? MXOutgoingSASTransaction else {
return
}
switch transaction.state {
case MXSASTransactionStateShowSAS:
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.deviceVerificationStartViewModel(self, didCompleteWithOutgoingTransaction: transaction)
case MXSASTransactionStateCancelled:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelled(reason))
case MXSASTransactionStateCancelledByMe:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelledByMe(reason))
default:
break
}
}
}
| apache-2.0 | 746f18ff1ced857b4485657554908ec8 | 35.417266 | 204 | 0.699328 | 5.791762 | false | false | false | false |
eofster/Telephone | UseCasesTestDoubles/RingtoneSpy.swift | 1 | 1130 | //
// RingtoneSpy.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UseCases
public final class RingtoneSpy {
public let interval: Double = 0
public private(set) var didCallStartPlaying = false
public private(set) var didCallStopPlaying = false
public private(set) var stopPlayingCallCount = 0
public init() {}
}
extension RingtoneSpy: Ringtone {
public func startPlaying() {
didCallStartPlaying = true
}
public func stopPlaying() {
didCallStopPlaying = true
stopPlayingCallCount += 1
}
}
| gpl-3.0 | c68b83b0634146c6317afd27c280813d | 27.2 | 72 | 0.710993 | 4.208955 | false | false | false | false |
frajaona/LiFXSwiftKit | Sources/CommandSetColor.swift | 1 | 4227 | /*
* Copyright (C) 2016 Fred Rajaona
*
* 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
final class CommandSetColor: Command {
var sequenceNumber: UInt8 = 0
var sourceNumber: UInt32 = 0
fileprivate var hue = 0
fileprivate var saturation = 0
fileprivate var brightness = 0
fileprivate var kelvin = 0
var setHue = false
var setSaturation = false
var setBrightness = false
var setKelvin = false
fileprivate var transmitProtocolHandler: TransmitProtocolHandler!
fileprivate var message: LiFXMessage!
fileprivate var completed = false
func initCommand(_ transmitProtocolHandler: TransmitProtocolHandler) {
self.transmitProtocolHandler = transmitProtocolHandler
message = LiFXMessage(messageType: LiFXMessage.MessageType.lightGet, sequenceNumber: sequenceNumber, sourceNumber: sourceNumber,targetAddress: (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)), messagePayload: nil)
}
func setHue(_ hue: Int) -> CommandSetColor {
setHue = true
self.hue = hue
return self
}
func setSaturation(_ saturation: Int) -> CommandSetColor {
setSaturation = true
self.saturation = saturation
return self
}
func setBrightness(_ brightness: Int) -> CommandSetColor {
setBrightness = true
self.brightness = brightness
return self
}
func setKelvin(_ kelvin: Int) -> CommandSetColor {
setKelvin = true
self.kelvin = kelvin
return self
}
fileprivate func getPayload() -> [UInt8] {
let data = NSMutableData()
var byte8 = 0
data.append(&byte8, length: 1)
var byte16 = hue.littleEndian
data.append(&byte16, length: 2)
byte16 = saturation.littleEndian
data.append(&byte16, length: 2)
byte16 = brightness.littleEndian
data.append(&byte16, length: 2)
byte16 = kelvin.littleEndian
data.append(&byte16, length: 2)
var byte32 = 0
data.append(&byte32, length: 4)
var payload = [UInt8](repeating: 0, count: data.length)
data.getBytes(&payload, length: data.length)
return payload
}
func getMessage() -> LiFXMessage {
return message
}
func getProtocolHandler() -> TransmitProtocolHandler {
return transmitProtocolHandler
}
func onNewMessage(_ message: LiFXMessage) {
switch message.messageType {
case LiFXMessage.MessageType.lightState:
if message.getSequenceNumber() == sequenceNumber {
let info = LiFXLightInfo(fromData: message.payload!)
if !setHue {
hue = info.hue
}
if !setSaturation {
saturation = info.saturation
}
if !setBrightness {
brightness = info.brightness
}
if !setKelvin {
kelvin = info.kelvin
}
self.message = LiFXMessage(messageType: LiFXMessage.MessageType.lightSetColor, sequenceNumber: transmitProtocolHandler.getNextTransmitSequenceNumber(), sourceNumber: sourceNumber,targetAddress: (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0)), messagePayload: getPayload())
execute()
completed = true
}
default:
break
}
}
func isComplete() -> Bool {
return completed
}
}
| apache-2.0 | e720b4b6ad85a39f6202b727f33520f5 | 31.022727 | 322 | 0.606104 | 4.701891 | false | false | false | false |
Jnosh/swift | stdlib/public/SDK/Dispatch/Time.swift | 5 | 6219 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import _SwiftDispatchOverlayShims
public struct DispatchTime : Comparable {
private static let timebaseInfo: mach_timebase_info_data_t = {
var info = mach_timebase_info_data_t(numer: 1, denom: 1)
mach_timebase_info(&info)
return info
}()
public let rawValue: dispatch_time_t
public static func now() -> DispatchTime {
let t = __dispatch_time(0, 0)
return DispatchTime(rawValue: t)
}
public static let distantFuture = DispatchTime(rawValue: ~0)
fileprivate init(rawValue: dispatch_time_t) {
self.rawValue = rawValue
}
/// Creates a `DispatchTime` relative to the system clock that
/// ticks since boot.
///
/// - Parameters:
/// - uptimeNanoseconds: The number of nanoseconds since boot, excluding
/// time the system spent asleep
/// - Returns: A new `DispatchTime`
/// - Discussion: This clock is the same as the value returned by
/// `mach_absolute_time` when converted into nanoseconds.
/// On some platforms, the nanosecond value is rounded up to a
/// multiple of the Mach timebase, using the conversion factors
/// returned by `mach_timebase_info()`. The nanosecond equivalent
/// of the rounded result can be obtained by reading the
/// `uptimeNanoseconds` property.
/// Note that `DispatchTime(uptimeNanoseconds: 0)` is
/// equivalent to `DispatchTime.now()`, that is, its value
/// represents the number of nanoseconds since boot (excluding
/// system sleep time), not zero nanoseconds since boot.
public init(uptimeNanoseconds: UInt64) {
var rawValue = uptimeNanoseconds
if (DispatchTime.timebaseInfo.numer != DispatchTime.timebaseInfo.denom) {
rawValue = (rawValue * UInt64(DispatchTime.timebaseInfo.denom)
+ UInt64(DispatchTime.timebaseInfo.numer - 1)) / UInt64(DispatchTime.timebaseInfo.numer)
}
self.rawValue = dispatch_time_t(rawValue)
}
public var uptimeNanoseconds: UInt64 {
var result = self.rawValue
if (DispatchTime.timebaseInfo.numer != DispatchTime.timebaseInfo.denom) {
result = result * UInt64(DispatchTime.timebaseInfo.numer) / UInt64(DispatchTime.timebaseInfo.denom)
}
return result
}
}
extension DispatchTime {
public static func < (a: DispatchTime, b: DispatchTime) -> Bool {
return a.rawValue < b.rawValue
}
public static func ==(a: DispatchTime, b: DispatchTime) -> Bool {
return a.rawValue == b.rawValue
}
}
public struct DispatchWallTime : Comparable {
public let rawValue: dispatch_time_t
public static func now() -> DispatchWallTime {
return DispatchWallTime(rawValue: __dispatch_walltime(nil, 0))
}
public static let distantFuture = DispatchWallTime(rawValue: ~0)
fileprivate init(rawValue: dispatch_time_t) {
self.rawValue = rawValue
}
public init(timespec: timespec) {
var t = timespec
self.rawValue = __dispatch_walltime(&t, 0)
}
}
extension DispatchWallTime {
public static func <(a: DispatchWallTime, b: DispatchWallTime) -> Bool {
let negativeOne: dispatch_time_t = ~0
if b.rawValue == negativeOne {
return a.rawValue != negativeOne
} else if a.rawValue == negativeOne {
return false
}
return -Int64(bitPattern: a.rawValue) < -Int64(bitPattern: b.rawValue)
}
public static func ==(a: DispatchWallTime, b: DispatchWallTime) -> Bool {
return a.rawValue == b.rawValue
}
}
public enum DispatchTimeInterval {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
internal var rawValue: Int64 {
switch self {
case .seconds(let s): return Int64(s) * Int64(NSEC_PER_SEC)
case .milliseconds(let ms): return Int64(ms) * Int64(NSEC_PER_MSEC)
case .microseconds(let us): return Int64(us) * Int64(NSEC_PER_USEC)
case .nanoseconds(let ns): return Int64(ns)
}
}
}
public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime {
let t = __dispatch_time(time.rawValue, interval.rawValue)
return DispatchTime(rawValue: t)
}
public func -(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime {
let t = __dispatch_time(time.rawValue, -interval.rawValue)
return DispatchTime(rawValue: t)
}
public func +(time: DispatchTime, seconds: Double) -> DispatchTime {
let interval = seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.max : Int64(interval))
return DispatchTime(rawValue: t)
}
public func -(time: DispatchTime, seconds: Double) -> DispatchTime {
let interval = -seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.min : Int64(interval))
return DispatchTime(rawValue: t)
}
public func +(time: DispatchWallTime, interval: DispatchTimeInterval) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, interval.rawValue)
return DispatchWallTime(rawValue: t)
}
public func -(time: DispatchWallTime, interval: DispatchTimeInterval) -> DispatchWallTime {
let t = __dispatch_time(time.rawValue, -interval.rawValue)
return DispatchWallTime(rawValue: t)
}
public func +(time: DispatchWallTime, seconds: Double) -> DispatchWallTime {
let interval = seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.max : Int64(interval))
return DispatchWallTime(rawValue: t)
}
public func -(time: DispatchWallTime, seconds: Double) -> DispatchWallTime {
let interval = -seconds * Double(NSEC_PER_SEC)
let t = __dispatch_time(time.rawValue,
interval.isInfinite || interval.isNaN ? Int64.min : Int64(interval))
return DispatchWallTime(rawValue: t)
}
| apache-2.0 | c56719662d0d92088cf03c4600fc2688 | 33.743017 | 102 | 0.689339 | 3.896617 | false | false | false | false |
lqwsmile/DouYuSwift | DouyuSwift/DouyuSwift/Class/Tools/Extension/UIBarbuttonItem-Extension.swift | 1 | 1196 | //
// UIBarbuttonItem-Extension.swift
// DouyuSwift
//
// Created by manito on 16/11/17.
// Copyright © 2016年 Kenway. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/*
class func createItem(normalImage:String, highlightedImage:String, size:CGSize) ->UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage.init(named: normalImage), for: UIControlState.normal)
btn.setImage(UIImage.init(named: highlightedImage), for: UIControlState.highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
convenience init(normalImage:String, highlightedImage:String = "", size:CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage.init(named: normalImage), for: UIControlState.normal)
if (highlightedImage != "") {
btn.setImage(UIImage.init(named: highlightedImage), for: UIControlState.highlighted)
}
if (size == CGSize.zero) {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView : btn)
}
}
| mit | 20074d9d4cd17f25b62ebc8eaf1d45a4 | 33.085714 | 103 | 0.642079 | 4.200704 | false | false | false | false |
thelukester92/swift-engine | swift-engine/Game/Systems/PlatformSystem.swift | 1 | 540 | //
// PlatformSystem.swift
// swift-engine
//
// Created by Luke Godfrey on 8/11/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
import LGSwiftEngine
class PlatformSystem: LGSystem
{
override func update()
{
let position = scene.entityNamed("platform")!.get(LGPosition)!
let bod = scene.entityNamed("platform")!.get(LGPhysicsBody)!
if bod.velocity.x == 0
{
bod.velocity.x = 1
}
if position.x + 32 > Double(scene.view.frame.size.width) || position.x <= 1
{
bod.velocity.x = -bod.velocity.x
}
}
}
| mit | 15a93fcc2a0308d30125e934182a4dc4 | 18.285714 | 77 | 0.655556 | 2.857143 | false | false | false | false |
paulgriffiths/macvideopoker | VideoPoker/PokerHandEvaluation.swift | 1 | 2017 | //
// PokerHandEvaluation.swift
//
// Struct to evaluate and score a poker hand.
//
// Copyright (c) 2015 Paul Griffiths.
// Distributed under the terms of the GNU General Public License. <http://www.gnu.org/licenses/>
//
func ==(first: PokerHandEvaluation, second: PokerHandEvaluation) -> Bool {
return first.score == second.score
}
func <(first: PokerHandEvaluation, second: PokerHandEvaluation) -> Bool {
return first.score < second.score
}
struct PokerHandEvaluation: Equatable, Comparable, CustomStringConvertible {
let score: PokerHandScore
let counter: CardCounter
var handType: PokerHands {
return score.handType
}
init(hand: PokerHand) {
counter = CardCounter(hand: hand)
score = PokerHandScore(counter: counter)
}
var description: String {
return handType.description
}
var topLevelRankScore: Rank {
switch handType {
case .StraightFlush, .Straight:
if let highestRank = counter.highestRankByCount(1), let lowestRank = counter.lowestRankByCount(1) {
if highestRank == .Ace && lowestRank == .Two {
return .Five
}
else {
return highestRank
}
}
case .Four:
if let highestRank = counter.highestRankByCount(4) {
return highestRank
}
case .FullHouse, .Three:
if let highestRank = counter.highestRankByCount(3) {
return highestRank
}
case .RoyalFlush, .Flush, .HighCard:
if let highestRank = counter.highestRankByCount(1) {
return highestRank
}
case .TwoPair, .Pair:
if let highestRank = counter.highestRankByCount(2) {
return highestRank
}
}
fatalError("Couldn't get top level rank score")
}
} | gpl-3.0 | 9cf24afcf6326b90f3360f86a6fc2453 | 27.828571 | 111 | 0.565692 | 4.492205 | false | false | false | false |
TheTrueTom/TransferCalculator | Transfer calculator/ParticleView.swift | 1 | 1517 | //
// ParticleView.swift
// Transfer calculator
//
// Created by Thomas Brichart on 09/01/2016.
// Copyright © 2016 Thomas Brichart. All rights reserved.
//
import Foundation
import Cocoa
class ParticleView: NSView {
var donorColor: NSColor = NSColor.blue {
didSet {
self.needsDisplay = true
}
}
var acceptorColor: NSColor = NSColor.red {
didSet {
self.needsDisplay = true
}
}
var particule: Particule? {
didSet {
self.needsDisplay = true
}
}
override func draw(_ dirtyRect: NSRect) {
// Body of the particle
NSColor.white.set()
NSBezierPath(ovalIn: self.bounds).fill()
// Outer rim of the particle
NSColor.gray.set()
NSBezierPath(ovalIn: self.bounds).stroke()
if let particule = self.particule {
for (index, molecule) in particule.moleculesList {
if index < 0 {
acceptorColor.set()
} else {
donorColor.set()
}
let x = CGFloat(molecule.x / particule.radius / 2) * self.bounds.size.width + self.bounds.size.width / 2 - 1
let y = CGFloat(molecule.y / particule.radius / 2) * self.bounds.size.height + self.bounds.size.height / 2 - 1
NSBezierPath(rect: NSRect(x: x, y: y, width: 2, height: 2)).fill()
}
}
}
}
| mit | e1fd167ceedf58ad5927fb6449a9bc3a | 26.071429 | 126 | 0.523747 | 4.13079 | false | false | false | false |
kaizeiyimi/XLYMultiCastDelegate | XLYMultiCastDelegateDemo/XLYMultiCastDelegateDemo/SwiftViewController.swift | 1 | 2296 | //
// SwiftViewController.swift
// XLMultiCastDelegate
//
// Created by kaizei on 14/9/26.
// Copyright (c) 2014年 kaizei. All rights reserved.
//
import UIKit
// we define a swift style. in swift it is actually "moduleName.ProtocolName"
//in our demo it is "XLMultiCastDelegate.SimpleSwiftProtocol"
@objc
protocol SimpleSwiftProtocol {
optional func someSwiftOptionalMethod()
func someSwiftRequiredMethod(object: AnyObject!)
}
class SwiftViewController: UIViewController, SimpleProtocol, SimpleSwiftProtocol {
//multiDelegate which uses objective-c protocol
// var multiDelegateUsingOCProtocol = XLYMultiCastDelegate(conformingProtocol: objc_getProtocol("SimpleProtocol"))
var multiDelegateUsingOCProtocol = XLYMultiCastDelegate(protocolName:"SimpleProtocol")
//multiDelegate which uses swift protocol
var multiDelegateUSingSwiftProtocol = XLYMultiCastDelegate(protocolName: "XLYMultiCastDelegateDemo.SimpleSwiftProtocol")
override func viewDidLoad() {
super.viewDidLoad()
//here we only add one delegate 'self' to the XLMultiCastDelegate
//😄you certainly can add more delegates in any queue😊
multiDelegateUsingOCProtocol.addDelegate(self, dispatchQueue: dispatch_get_main_queue())
multiDelegateUSingSwiftProtocol.addDelegate(self, dispatchQueue: dispatch_get_main_queue())
}
@IBAction func buttonClicked(button: UIButton) {
let d1 = multiDelegateUsingOCProtocol as! SimpleProtocol
d1.someOptionalMethod!()
d1.someRequiredMethod(button)
let d2 = multiDelegateUSingSwiftProtocol as! SimpleSwiftProtocol
//call of someSwiftOptionalMethod will do nothing because we have no implementation
d2.someSwiftOptionalMethod!()
d2.someSwiftRequiredMethod(button)
}
//MARK: - simple protocol
func someRequiredMethod(object: AnyObject!) -> AnyObject! {
println("swift viewController required method. \(object)")
return object
}
func someOptionalMethod() {
println("swift viewController optional method.")
}
//MARK: - simple swift protocol
func someSwiftRequiredMethod(object: AnyObject!) {
println("swift viewController required method in SimpleSwiftProtocol.")
}
}
| mit | 383d4a2f8330f59dcd58722c5f14d210 | 37.779661 | 124 | 0.734266 | 4.612903 | false | false | false | false |
ftiff/CasperSplash | SplashBuddy/Tools/Regexes.swift | 1 | 1330 | //
// Copyright © 2018 Amaris Technologies GmbH. All rights reserved.
//
import Foundation
/**
Initialize Regexes
- returns: A Dictionary of status: regex
*/
func initRegex() -> [Software.SoftwareStatus: NSRegularExpression?] {
let reOptions = NSRegularExpression.Options.anchorsMatchLines
// Installing
let reInstalling: NSRegularExpression?
do {
try reInstalling = NSRegularExpression(
pattern: "(?<=Installing )([a-zA-Z0-9._ ]*)-([a-zA-Z0-9._]*).pkg...$",
options: reOptions
)
} catch {
reInstalling = nil
}
// Failure
let reFailure: NSRegularExpression?
do {
try reFailure = NSRegularExpression(
pattern: "(?<=Installation failed. The installer reported: installer: Package name is )([a-zA-Z0-9._ ]*)-([a-zA-Z0-9._]*)$",
options: reOptions
)
} catch {
reFailure = nil
}
// Success
let reSuccess: NSRegularExpression?
do {
try reSuccess = NSRegularExpression(
pattern: "(?<=Successfully installed )([a-zA-Z0-9._ ]*)-([a-zA-Z0-9._]*).pkg",
options: reOptions
)
} catch {
reSuccess = nil
}
return [
.success: reSuccess,
.failed: reFailure,
.installing: reInstalling
]
}
| gpl-3.0 | 82e3ce5fb8c0210371659166d185ff76 | 21.913793 | 136 | 0.573363 | 4.153125 | false | false | false | false |
SwifterSwift/SwifterSwift | Sources/SwifterSwift/SwiftStdlib/SequenceExtensions.swift | 1 | 13863 | // SequenceExtensions.swift - Copyright 2022 SwifterSwift
public extension Sequence {
/// SwifterSwift: Check if all elements in collection match a condition.
///
/// [2, 2, 4].all(matching: {$0 % 2 == 0}) -> true
/// [1,2, 2, 4].all(matching: {$0 % 2 == 0}) -> false
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when all elements in the array match the specified condition.
func all(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !condition($0) }
}
/// SwifterSwift: Check if no elements in collection match a condition.
///
/// [2, 2, 4].none(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].none(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
func none(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try condition($0) }
}
/// SwifterSwift: Check if any element in collection match a condition.
///
/// [2, 2, 4].any(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].any(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
func any(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try contains { try condition($0) }
}
/// SwifterSwift: Filter elements based on a rejection condition.
///
/// [2, 2, 4, 7].reject(where: {$0 % 2 == 0}) -> [7]
///
/// - Parameter condition: to evaluate the exclusion of an element from the array.
/// - Returns: the array with rejected values filtered from it.
func reject(where condition: (Element) throws -> Bool) rethrows -> [Element] {
return try filter { return try !condition($0) }
}
/// SwifterSwift: Get element count based on condition.
///
/// [2, 2, 4, 7].count(where: {$0 % 2 == 0}) -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: number of times the condition evaluated to true.
func count(where condition: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self where try condition(element) {
count += 1
}
return count
}
/// SwifterSwift: Iterate over a collection in reverse order. (right to left)
///
/// [0, 2, 4, 7].forEachReversed({ print($0)}) -> // Order of print: 7,4,2,0
///
/// - Parameter body: a closure that takes an element of the array as a parameter.
func forEachReversed(_ body: (Element) throws -> Void) rethrows {
try reversed().forEach(body)
}
/// SwifterSwift: Calls the given closure with each element where condition is true.
///
/// [0, 2, 4, 7].forEach(where: {$0 % 2 == 0}, body: { print($0)}) -> // print: 0, 2, 4
///
/// - Parameters:
/// - condition: condition to evaluate each element against.
/// - body: a closure that takes an element of the array as a parameter.
func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows {
try lazy.filter(condition).forEach(body)
}
/// SwifterSwift: Reduces an array while returning each interim combination.
///
/// [1, 2, 3].accumulate(initial: 0, next: +) -> [1, 3, 6]
///
/// - Parameters:
/// - initial: initial value.
/// - next: closure that combines the accumulating value and next element of the array.
/// - Returns: an array of the final accumulated value and each interim combination.
func accumulate<U>(initial: U, next: (U, Element) throws -> U) rethrows -> [U] {
var runningTotal = initial
return try map { element in
runningTotal = try next(runningTotal, element)
return runningTotal
}
}
/// SwifterSwift: Filtered and map in a single operation.
///
/// [1,2,3,4,5].filtered({ $0 % 2 == 0 }, map: { $0.string }) -> ["2", "4"]
///
/// - Parameters:
/// - isIncluded: condition of inclusion to evaluate each element against.
/// - transform: transform element function to evaluate every element.
/// - Returns: Return an filtered and mapped array.
func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] {
return try lazy.filter(isIncluded).map(transform)
}
/// SwifterSwift: Get the only element based on a condition.
///
/// [].single(where: {_ in true}) -> nil
/// [4].single(where: {_ in true}) -> 4
/// [1, 4, 7].single(where: {$0 % 2 == 0}) -> 4
/// [2, 2, 4, 7].single(where: {$0 % 2 == 0}) -> nil
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: The only element in the array matching the specified condition. If there are more matching elements,
/// nil is returned. (optional)
func single(where condition: (Element) throws -> Bool) rethrows -> Element? {
var singleElement: Element?
for element in self where try condition(element) {
guard singleElement == nil else {
singleElement = nil
break
}
singleElement = element
}
return singleElement
}
/// SwifterSwift: Remove duplicate elements based on condition.
///
/// [1, 2, 1, 3, 2].withoutDuplicates { $0 } -> [1, 2, 3]
/// [(1, 4), (2, 2), (1, 3), (3, 2), (2, 1)].withoutDuplicates { $0.0 } -> [(1, 4), (2, 2), (3, 2)]
///
/// - Parameter transform: A closure that should return the value to be evaluated for repeating elements.
/// - Returns: Sequence without repeating elements
/// - Complexity: O(*n*), where *n* is the length of the sequence.
func withoutDuplicates<T: Hashable>(transform: (Element) throws -> T) rethrows -> [Element] {
var set = Set<T>()
return try filter { set.insert(try transform($0)).inserted }
}
/// SwifterSwift: Separates all items into 2 lists based on a given predicate. The first list contains all items
/// for which the specified condition evaluates to true. The second list contains those that don't.
///
/// let (even, odd) = [0, 1, 2, 3, 4, 5].divided { $0 % 2 == 0 }
/// let (minors, adults) = people.divided { $0.age < 18 }
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: A tuple of matched and non-matched items
func divided(by condition: (Element) throws -> Bool) rethrows -> (matching: [Element], nonMatching: [Element]) {
// Inspired by: http://ruby-doc.org/core-2.5.0/Enumerable.html#method-i-partition
var matching = [Element]()
var nonMatching = [Element]()
for element in self {
// swiftlint:disable:next void_function_in_ternary
try condition(element) ? matching.append(element) : nonMatching.append(element)
}
return (matching, nonMatching)
}
/// SwifterSwift: Return a sorted array based on a key path and a compare function.
///
/// - Parameter keyPath: Key path to sort by.
/// - Parameter compare: Comparation function that will determine the ordering.
/// - Returns: The sorted array.
func sorted<T>(by keyPath: KeyPath<Element, T>, with compare: (T, T) -> Bool) -> [Element] {
return sorted { compare($0[keyPath: keyPath], $1[keyPath: keyPath]) }
}
/// SwifterSwift: Return a sorted array based on a key path.
///
/// - Parameter keyPath: Key path to sort by. The key path type must be Comparable.
/// - Returns: The sorted array.
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>) -> [Element] {
return sorted { $0[keyPath: keyPath] < $1[keyPath: keyPath] }
}
/// SwifterSwift: Returns a sorted sequence based on two key paths. The second one will be used in case the values
/// of the first one match.
///
/// - Parameters:
/// - keyPath1: Key path to sort by. Must be Comparable.
/// - keyPath2: Key path to sort by in case the values of `keyPath1` match. Must be Comparable.
func sorted<T: Comparable, U: Comparable>(by keyPath1: KeyPath<Element, T>,
and keyPath2: KeyPath<Element, U>) -> [Element] {
return sorted {
if $0[keyPath: keyPath1] != $1[keyPath: keyPath1] {
return $0[keyPath: keyPath1] < $1[keyPath: keyPath1]
}
return $0[keyPath: keyPath2] < $1[keyPath: keyPath2]
}
}
/// SwifterSwift: Returns a sorted sequence based on three key paths. Whenever the values of one key path match, the
/// next one will be used.
///
/// - Parameters:
/// - keyPath1: Key path to sort by. Must be Comparable.
/// - keyPath2: Key path to sort by in case the values of `keyPath1` match. Must be Comparable.
/// - keyPath3: Key path to sort by in case the values of `keyPath1` and `keyPath2` match. Must be Comparable.
func sorted<T: Comparable, U: Comparable, V: Comparable>(by keyPath1: KeyPath<Element, T>,
and keyPath2: KeyPath<Element, U>,
and keyPath3: KeyPath<Element, V>) -> [Element] {
return sorted {
if $0[keyPath: keyPath1] != $1[keyPath: keyPath1] {
return $0[keyPath: keyPath1] < $1[keyPath: keyPath1]
}
if $0[keyPath: keyPath2] != $1[keyPath: keyPath2] {
return $0[keyPath: keyPath2] < $1[keyPath: keyPath2]
}
return $0[keyPath: keyPath3] < $1[keyPath: keyPath3]
}
}
/// SwifterSwift: Sum of a `AdditiveArithmetic` property of each `Element` in a `Sequence`.
///
/// ["James", "Wade", "Bryant"].sum(for: \.count) -> 15
///
/// - Parameter keyPath: Key path of the `AdditiveArithmetic` property.
/// - Returns: The sum of the `AdditiveArithmetic` properties at `keyPath`.
func sum<T: AdditiveArithmetic>(for keyPath: KeyPath<Element, T>) -> T {
// Inspired by: https://swiftbysundell.com/articles/reducers-in-swift/
return reduce(.zero) { $0 + $1[keyPath: keyPath] }
}
/// SwifterSwift: Returns the first element of the sequence with having property by given key path equals to given
/// `value`.
///
/// - Parameters:
/// - keyPath: The `KeyPath` of property for `Element` to compare.
/// - value: The value to compare with `Element` property.
/// - Returns: The first element of the collection that has property by given key path equals to given `value` or
/// `nil` if there is no such element.
func first<T: Equatable>(where keyPath: KeyPath<Element, T>, equals value: T) -> Element? {
return first { $0[keyPath: keyPath] == value }
}
}
public extension Sequence where Element: Equatable {
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
/// - Complexity: _O(m·n)_, where _m_ is the length of `elements` and _n_ is the length of this sequence.
func contains(_ elements: [Element]) -> Bool {
return elements.allSatisfy { contains($0) }
}
}
public extension Sequence where Element: Hashable {
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
/// - Complexity: _O(m + n)_, where _m_ is the length of `elements` and _n_ is the length of this sequence.
func contains(_ elements: [Element]) -> Bool {
let set = Set(self)
return elements.allSatisfy { set.contains($0) }
}
/// SwifterSwift: Check whether a sequence contains duplicates.
///
/// - Returns: true if the receiver contains duplicates.
func containsDuplicates() -> Bool {
var set = Set<Element>()
return contains { !set.insert($0).inserted }
}
/// SwifterSwift: Getting the duplicated elements in a sequence.
///
/// [1, 1, 2, 2, 3, 3, 3, 4, 5].duplicates().sorted() -> [1, 2, 3])
/// ["h", "e", "l", "l", "o"].duplicates().sorted() -> ["l"])
///
/// - Returns: An array of duplicated elements.
///
func duplicates() -> [Element] {
var set = Set<Element>()
var duplicates = Set<Element>()
forEach {
if !set.insert($0).inserted {
duplicates.insert($0)
}
}
return Array(duplicates)
}
}
// MARK: - Methods (AdditiveArithmetic)
public extension Sequence where Element: AdditiveArithmetic {
/// SwifterSwift: Sum of all elements in array.
///
/// [1, 2, 3, 4, 5].sum() -> 15
///
/// - Returns: sum of the array's elements.
func sum() -> Element {
return reduce(.zero, +)
}
}
| mit | 3218d5bd0fa2eab7906a15f63cca1ce6 | 43.709677 | 120 | 0.580087 | 4.015064 | false | false | false | false |
apple/swift | stdlib/public/core/Reverse.swift | 6 | 9657 | //===--- Reverse.swift - Sequence and collection reversal -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension MutableCollection where Self: BidirectionalCollection {
/// Reverses the elements of the collection in place.
///
/// The following example reverses the elements of an array of characters:
///
/// var characters: [Character] = ["C", "a", "f", "é"]
/// characters.reverse()
/// print(characters)
/// // Prints "["é", "f", "a", "C"]"
///
/// - Complexity: O(*n*), where *n* is the number of elements in the
/// collection.
@inlinable // protocol-only
public mutating func reverse() {
if isEmpty { return }
var f = startIndex
var l = index(before: endIndex)
while f < l {
swapAt(f, l)
formIndex(after: &f)
formIndex(before: &l)
}
}
}
/// A collection that presents the elements of its base collection
/// in reverse order.
///
/// - Note: This type is the result of `x.reversed()` where `x` is a
/// collection having bidirectional indices.
///
/// The `reversed()` method is always lazy when applied to a collection
/// with bidirectional indices, but does not implicitly confer
/// laziness on algorithms applied to its result. In other words, for
/// ordinary collections `c` having bidirectional indices:
///
/// * `c.reversed()` does not create new storage
/// * `c.reversed().map(f)` maps eagerly and returns a new array
/// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection`
@frozen
public struct ReversedCollection<Base: BidirectionalCollection> {
public let _base: Base
/// Creates an instance that presents the elements of `base` in
/// reverse order.
///
/// - Complexity: O(1)
@inlinable
internal init(_base: Base) {
self._base = _base
}
}
extension ReversedCollection {
// An iterator that can be much faster than the iterator of a reversed slice.
@frozen
public struct Iterator {
@usableFromInline
internal let _base: Base
@usableFromInline
internal var _position: Base.Index
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_base: Base) {
self._base = _base
self._position = _base.endIndex
}
}
}
extension ReversedCollection.Iterator: IteratorProtocol, Sequence {
public typealias Element = Base.Element
@inlinable
@inline(__always)
public mutating func next() -> Element? {
guard _fastPath(_position != _base.startIndex) else { return nil }
_base.formIndex(before: &_position)
return _base[_position]
}
}
extension ReversedCollection: Sequence {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Element = Base.Element
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base)
}
}
extension ReversedCollection {
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@frozen
public struct Index {
/// The position after this position in the underlying collection.
///
/// To find the position that corresponds with this index in the original,
/// underlying collection, use that collection's `index(before:)` method
/// with the `base` property.
///
/// The following example declares a function that returns the index of the
/// last even number in the passed array, if one is found. First, the
/// function finds the position of the last even number as a `ReversedIndex`
/// in a reversed view of the array of numbers. Next, the function calls the
/// array's `index(before:)` method to return the correct position in the
/// passed array.
///
/// func indexOfLastEven(_ numbers: [Int]) -> Int? {
/// let reversedNumbers = numbers.reversed()
/// guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 })
/// else { return nil }
///
/// return numbers.index(before: i.base)
/// }
///
/// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
/// if let lastEven = indexOfLastEven(numbers) {
/// print("Last even number: \(numbers[lastEven])")
/// }
/// // Prints "Last even number: 40"
public let base: Base.Index
/// Creates a new index into a reversed collection for the position before
/// the specified index.
///
/// When you create an index into a reversed collection using `base`, an
/// index from the underlying collection, the resulting index is the
/// position of the element *before* the element referenced by `base`. The
/// following example creates a new `ReversedIndex` from the index of the
/// `"a"` character in a string's character view.
///
/// let name = "Horatio"
/// let aIndex = name.firstIndex(of: "a")!
/// // name[aIndex] == "a"
///
/// let reversedName = name.reversed()
/// let i = ReversedCollection<String>.Index(aIndex)
/// // reversedName[i] == "r"
///
/// The element at the position created using `ReversedIndex<...>(aIndex)` is
/// `"r"`, the character before `"a"` in the `name` string.
///
/// - Parameter base: The position after the element to create an index for.
@inlinable
public init(_ base: Base.Index) {
self.base = base
}
}
}
extension ReversedCollection.Index: Comparable {
@inlinable
public static func == (
lhs: ReversedCollection<Base>.Index,
rhs: ReversedCollection<Base>.Index
) -> Bool {
// Note ReversedIndex has inverted logic compared to base Base.Index
return lhs.base == rhs.base
}
@inlinable
public static func < (
lhs: ReversedCollection<Base>.Index,
rhs: ReversedCollection<Base>.Index
) -> Bool {
// Note ReversedIndex has inverted logic compared to base Base.Index
return lhs.base > rhs.base
}
}
extension ReversedCollection.Index: Hashable where Base.Index: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(base)
}
}
extension ReversedCollection: BidirectionalCollection {
@inlinable
public var startIndex: Index {
return Index(_base.endIndex)
}
@inlinable
public var endIndex: Index {
return Index(_base.startIndex)
}
@inlinable
public func index(after i: Index) -> Index {
return Index(_base.index(before: i.base))
}
@inlinable
public func index(before i: Index) -> Index {
return Index(_base.index(after: i.base))
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return Index(_base.index(i.base, offsetBy: -n))
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base)
.map(Index.init)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _base.distance(from: end.base, to: start.base)
}
@inlinable
public subscript(position: Index) -> Element {
return _base[_base.index(before: position.base)]
}
}
extension ReversedCollection: RandomAccessCollection where Base: RandomAccessCollection { }
extension ReversedCollection {
/// Reversing a reversed collection returns the original collection.
///
/// - Complexity: O(1)
@inlinable
@available(swift, introduced: 4.2)
public __consuming func reversed() -> Base {
return _base
}
}
extension BidirectionalCollection {
/// Returns a view presenting the elements of the collection in reverse
/// order.
///
/// You can reverse a collection without allocating new space for its
/// elements by calling this `reversed()` method. A `ReversedCollection`
/// instance wraps an underlying collection and provides access to its
/// elements in reverse order. This example prints the characters of a
/// string in reverse order:
///
/// let word = "Backwards"
/// for char in word.reversed() {
/// print(char, terminator: "")
/// }
/// // Prints "sdrawkcaB"
///
/// If you need a reversed collection of the same type, you may be able to
/// use the collection's sequence-based or collection-based initializer. For
/// example, to get the reversed version of a string, reverse its
/// characters and initialize a new `String` instance from the result.
///
/// let reversedWord = String(word.reversed())
/// print(reversedWord)
/// // Prints "sdrawkcaB"
///
/// - Complexity: O(1)
@inlinable
public __consuming func reversed() -> ReversedCollection<Self> {
return ReversedCollection(_base: self)
}
}
| apache-2.0 | cacdb6bf14c160de9fc676d4462b8db3 | 31.728814 | 91 | 0.646608 | 4.253304 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/NimbleTests/Matchers/RaisesExceptionTest.swift | 47 | 9228 | import XCTest
import Nimble
class RaisesExceptionTest: XCTestCase {
var anException = NSException(name: "laugh", reason: "Lulz", userInfo: ["key": "value"])
func testPositiveMatches() {
expect { self.anException.raise() }.to(raiseException())
expect { self.anException.raise() }.to(raiseException(named: "laugh"))
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz"))
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]))
}
func testPositiveMatchesWithClosures() {
expect { self.anException.raise() }.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal("laugh"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh") { (exception: NSException) in
expect(exception.name).to(beginWith("lau"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { (exception: NSException) in
expect(exception.name).to(beginWith("lau"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { (exception: NSException) in
expect(exception.name).to(beginWith("lau"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh") { (exception: NSException) in
expect(exception.name).toNot(beginWith("as"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { (exception: NSException) in
expect(exception.name).toNot(beginWith("df"))
})
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { (exception: NSException) in
expect(exception.name).toNot(beginWith("as"))
})
}
func testNegativeMatches() {
failsWithErrorMessage("expected to raise exception with name <foo>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "foo"))
}
failsWithErrorMessage("expected to raise exception with name <laugh> with reason <bar>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "bar"))
}
failsWithErrorMessage(
"expected to raise exception with name <laugh> with reason <Lulz> with userInfo <{k = v;}>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["k": "v"]))
}
failsWithErrorMessage("expected to raise any exception, got no exception") {
expect { self.anException }.to(raiseException())
}
failsWithErrorMessage("expected to not raise any exception, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException())
}
failsWithErrorMessage("expected to raise exception with name <laugh> with reason <Lulz>, got no exception") {
expect { self.anException }.to(raiseException(named: "laugh", reason: "Lulz"))
}
failsWithErrorMessage("expected to raise exception with name <bar> with reason <Lulz>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException(named: "bar", reason: "Lulz"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException(named: "laugh"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh> with reason <Lulz>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh> with reason <Lulz> with userInfo <{key = value;}>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]))
}
}
func testNegativeMatchesDoNotCallClosureWithoutException() {
failsWithErrorMessage("expected to raise exception that satisfies block, got no exception") {
expect { self.anException }.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> that satisfies block, got no exception") {
expect { self.anException }.to(raiseException(named: "foo") { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> with reason <ha> that satisfies block, got no exception") {
expect { self.anException }.to(raiseException(named: "foo", reason: "ha") { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> with reason <Lulz> with userInfo <{}> that satisfies block, got no exception") {
expect { self.anException }.to(raiseException(named: "foo", reason: "Lulz", userInfo: [:]) { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to not raise any exception, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.toNot(raiseException())
}
}
func testNegativeMatchesWithClosure() {
failsWithErrorMessage("expected to raise exception that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.anException.raise() }.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal("foo"))
})
}
let innerFailureMessage = "expected to begin with <fo>, got <laugh>"
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "laugh") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "lol") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> with reason <Lulz> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> with reason <wrong> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "lol", reason: "wrong") { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> with reason <Lulz> with userInfo <{key = value;}> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> with reason <Lulz> with userInfo <{}> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.anException.raise() }.to(raiseException(named: "lol", reason: "Lulz", userInfo: [:]) { (exception: NSException) in
expect(exception.name).to(beginWith("fo"))
})
}
}
}
| mit | c68ef37a4bd876757a486ce92ad8751d | 59.313725 | 244 | 0.633832 | 4.330361 | false | true | false | false |
Ezimetzhan/SwiftLocation | Pod/Classes/SwiftLocation.swift | 1 | 42098 | //
// SwiftLocation.swift
// SwiftLocations
//
// Copyright (c) 2015 Daniele Margutti
// Web: http://www.danielemargutti.com
// Mail: [email protected]
// Twitter: @danielemargutti
//
// First version: July 15, 2015
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreLocation
import MapKit
/// Type of a request ID
public typealias RequestIDType = Int
//MARK: Handlers
// Location related handler
public typealias onSuccessLocate = ( (location: CLLocation?) -> Void)
public typealias onErrorLocate = ( (error: NSError?) -> Void )
// Generic timeout handler
public typealias onTimeoutReached = ( Void -> (NSTimeInterval?) )
// Region/Beacon Proximity related handlers
public typealias onRegionEvent = ( (region: AnyObject?) -> Void)
public typealias onRangingBacon = ( (regions: [AnyObject]) -> Void)
// Geocoding related handlers
public typealias onSuccessGeocoding = ( (place: CLPlacemark?) -> Void)
public typealias onErrorGeocoding = ( (error: NSError?) -> Void)
//MARK: Service Status Enum
/**
Apple location services are subject to authorization step. This enum indicate the current status of the location manager into the device. You can query it via SwiftLocation.state property.
- Available: User has already granted this app permissions to access location services, and they are enabled and ready for use by this app.
Note: this state will be returned for both the "When In Use" and "Always" permission levels.
- Undetermined: User has not yet responded to the dialog that grants this app permission to access location services.
- Denied: User has explicitly denied this app permission to access location services. (The user can enable permissions again for this app from the system Settings app.)
- Restricted: User does not have ability to enable location services (e.g. parental controls, corporate policy, etc).
- Disabled: User has turned off location services device-wide (for all apps) from the system Settings app.
*/
public enum ServiceStatus :Int {
case Available
case Undetermined
case Denied
case Restricted
case Disabled
}
//MARK: Service Type Enum
/**
For reverse geocoding service you can choose what service use to make your request.
- Apple: Apple built-in CoreLocation services
- GoogleMaps: Google Geocoding Services (https://developers.google.com/maps/documentation/geocoding/intro)
*/
public enum Service: Int, Printable {
case Apple = 0
case GoogleMaps = 1
public var description: String {
get {
switch self {
case .Apple:
return "Apple"
case .GoogleMaps:
return "Google"
default:
return "Unknown"
}
}
}
}
//MARK: Accuracy
/**
Accuracy is used to set the minimum level of precision required during location discovery
- None: Unknown level detail
- Country: Country detail. It's used only for a single shot location request and uses IP based location discovery (no auth required). Inaccurate (>5000 meters, and/or received >10 minutes ago).
- City: 5000 meters or better, and received within the last 10 minutes. Lowest accuracy.
- Neighborhood: 1000 meters or better, and received within the last 5 minutes.
- Block: 100 meters or better, and received within the last 1 minute.
- House: 15 meters or better, and received within the last 15 seconds.
- Room: 5 meters or better, and received within the last 5 seconds. Highest accuracy.
*/
public enum Accuracy:Int, Printable {
case None = 0
case Country = 1
case City = 2
case Neighborhood = 3
case Block = 4
case House = 5
case Room = 6
public var description: String {
get {
switch self {
case .None:
return "None"
case .Country:
return "Country"
case .City:
return "City"
case .Neighborhood:
return "Neighborhood"
case .Block:
return "Block"
case .House:
return "House"
case .Room:
return "Room"
default:
return "Unknown"
}
}
}
/**
This is the threshold of accuracy to validate a location
:returns: value in meters
*/
func accuracyThreshold() -> Double {
switch self {
case .None:
return Double.infinity
case .Country:
return Double.infinity
case .City:
return 5000.0
case .Neighborhood:
return 1000.0
case .Block:
return 100.0
case .House:
return 15.0
case .Room:
return 5.0
}
}
/**
Time threshold to validate the accuracy of a location
:returns: in seconds
*/
func timeThreshold() -> Double {
switch self {
case .None:
return Double.infinity
case .Country:
return Double.infinity
case .City:
return 600.0
case .Neighborhood:
return 300.0
case .Block:
return 60.0
case .House:
return 15.0
case .Room:
return 5.0
}
}
}
//MARK: ===== [PUBLIC] SwiftLocation Class =====
public class SwiftLocation: NSObject, CLLocationManagerDelegate {
//MARK: Private vars
private var manager: CLLocationManager // CoreLocationManager shared instance
private var requests: [SwiftLocationRequest]! // This is the list of running requests (does not include geocode requests)
private let blocksDispatchQueue = dispatch_queue_create("SynchronizedArrayAccess", DISPATCH_QUEUE_SERIAL) // sync operation queue for CGD
//MARK: Public vars
public static let shared = SwiftLocation()
//MARK: Simulate location and location updates
/// Set this to a valid non-nil location to receive it as current location for single location search
public var fixedLocation: CLLocation?
public var fixedLocationDictionary: [String: AnyObject]?
/// Set it to a valid existing gpx file url to receive positions during continous update
//public var fixedLocationGPX: NSURL?
/// This property report the current state of the CoreLocationManager service based on user authorization
class var state: ServiceStatus {
get {
if CLLocationManager.locationServicesEnabled() == false {
return .Disabled
} else {
switch CLLocationManager.authorizationStatus() {
case .NotDetermined:
return .Undetermined
case .Denied:
return .Denied
case .Restricted:
return .Restricted
case .AuthorizedAlways, .AuthorizedWhenInUse:
return .Available
default:
return .Undetermined
}
}
}
}
//MARK: Private Init
/**
Private init. This is called only to allocate the singleton instance
:returns: the object itself, what else?
*/
override private init() {
requests = []
manager = CLLocationManager()
super.init()
manager.delegate = self
}
//MARK: [Public] Cancel a running request
/**
Cancel a running request
:param: identifier identifier of the request
:returns: true if request is marked as cancelled, no if it was not found
*/
public func cancelRequest(identifier: Int) -> Bool {
if let request = request(identifier) as SwiftLocationRequest! {
request.markAsCancelled(nil)
}
return false
}
/**
Mark as cancelled any running request
*/
public func cancelAllRequests() {
for request in requests {
request.markAsCancelled(nil)
}
}
//MARK: [Public] Reverse Geocoding
/**
Submits a forward-geocoding request using the specified string and optional region information.
:param: service service to use
:param: address A string describing the location you want to look up. For example, you could specify the string “1 Infinite Loop, Cupertino, CA” to locate Apple headquarters.
:param: region (Optional) A geographical region to use as a hint when looking up the specified address. Region is used only when service is set to Apple
:param: onSuccess on success handler
:param: onFail on error handler
*/
public func reverseAddress(service: Service!, address: String!, region: CLRegion?, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
if service == Service.Apple {
reverseAppleAddress(address, region: region, onSuccess: onSuccess, onFail: onFail)
} else {
reverseGoogleAddress(address, onSuccess: onSuccess, onFail: onFail)
}
}
/**
This method submits the specified location data to the geocoding server asynchronously and returns.
:param: service service to use
:param: coordinates coordinates to reverse
:param: onSuccess on success handler with CLPlacemarks objects
:param: onFail on error handler with error description
*/
public func reverseCoordinates(service: Service!, coordinates: CLLocationCoordinate2D!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
if service == Service.Apple {
reverseAppleCoordinates(coordinates, onSuccess: onSuccess, onFail: onFail)
} else {
reverseGoogleCoordinates(coordinates, onSuccess: onSuccess, onFail: onFail)
}
}
//MARK: [Public] Search Location / Subscribe Location Changes
/**
Get the current location from location manager with given accuracy
:param: accuracy minimum accuracy value to accept (country accuracy uses IP based location, not the CoreLocationManager, and it does not require user authorization)
:param: timeout search timeout. When expired, method return directly onFail
:param: onSuccess handler called when location is found
:param: onFail handler called when location manager fails due to an error
:returns: return an object to manage the request itself
*/
public func currentLocation(accuracy: Accuracy, timeout: NSTimeInterval, onSuccess: onSuccessLocate, onFail: onErrorLocate) -> RequestIDType {
if let fixedLocation = fixedLocation as CLLocation! {
// If a fixed location is set we want to return it
onSuccess(location: fixedLocation)
return -1 // request cannot be aborted, of course
}
if accuracy == Accuracy.Country {
let newRequest = SwiftLocationRequest(requestType: RequestType.SingleShotIPLocation, accuracy:accuracy, timeout: timeout, success: onSuccess, fail: onFail)
locateByIP(newRequest, refresh: false, timeout: timeout, onEnd: { (place, error) -> Void in
if error != nil {
onFail(error: error)
} else {
onSuccess(location: place?.location)
}
})
addRequest(newRequest)
return newRequest.ID
} else {
let newRequest = SwiftLocationRequest(requestType: RequestType.SingleShotLocation, accuracy:accuracy, timeout: timeout, success: onSuccess, fail: onFail)
addRequest(newRequest)
return newRequest.ID
}
}
/**
This method continously report found locations with desidered or better accuracy. You need to stop it manually by calling cancel() method into the request.
:param: accuracy minimum accuracy value to accept (country accuracy is not allowed)
:param: onSuccess handler called each time a new position is found
:param: onFail handler called when location manager fail (the request itself is aborted automatically)
:returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func continuousLocation(accuracy: Accuracy, onSuccess: onSuccessLocate, onFail: onErrorLocate) -> RequestIDType {
let newRequest = SwiftLocationRequest(requestType: RequestType.ContinuousLocationUpdate, accuracy:accuracy, timeout: 0, success: onSuccess, fail: onFail)
addRequest(newRequest)
return newRequest.ID
}
/**
This method continously return only significant location changes. This capability provides tremendous power savings for apps that want to track a user’s approximate location and do not need highly accurate position information. You need to stop it manually by calling cancel() method into the request.
:param: onSuccess handler called each time a new position is found
:param: onFail handler called when location manager fail (the request itself is aborted automatically)
:returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func significantLocation(onSuccess: onSuccessLocate, onFail: onErrorLocate) -> RequestIDType {
let newRequest = SwiftLocationRequest(requestType: RequestType.ContinuousSignificantLocation, accuracy:Accuracy.None, timeout: 0, success: onSuccess, fail: onFail)
addRequest(newRequest)
return newRequest.ID
}
//MARK: [Public] Monitor Regions
/**
Start monitoring specified region by reporting when users move in/out from it. You must call this method once for each region you want to monitor. You need to stop it manually by calling cancel() method into the request.
:param: region region to monitor
:param: onEnter handler called when user move into the region
:param: onExit handler called when user move out from the region
:returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func monitorRegion(region: CLRegion!, onEnter: onRegionEvent?, onExit: onRegionEvent?) -> RequestIDType? {
let isAvailable = CLLocationManager.isMonitoringAvailableForClass(CLRegion.self) // if beacons region monitoring is not available on this device we can't satisfy the request
if isAvailable == true {
let request = SwiftLocationRequest(region: region, onEnter: onEnter, onExit: onExit)
manager.startMonitoringForRegion(region as CLRegion)
return request.ID
}
return nil
}
//MARK: [Public] Monitor Beacons Proximity
/**
Starts the delivery of notifications for beacons in the specified region.
:param: region region to monitor
:param: onRanging handler called every time one or more beacon are in range, ordered by distance (closest is the first one)
:returns: return the id of the request. Use cancelRequest() to abort it.
*/
public func monitorBeaconsInRegion(region: CLBeaconRegion!, onRanging: onRangingBacon? ) -> RequestIDType? {
let isAvailable = CLLocationManager.isRangingAvailable() // if beacons monitoring is not available on this device we can't satisfy the request
if isAvailable == true {
let request = SwiftLocationRequest(beaconRegion: region, onRanging: onRanging)
manager.startRangingBeaconsInRegion(region)
return request.ID
}
return nil
}
//MARK: [Private] Google / Reverse Geocoding
private func reverseGoogleCoordinates(coordinates: CLLocationCoordinate2D!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
var APIURLString = "http://maps.googleapis.com/maps/api/geocode/json?latlng=\(coordinates.latitude),\(coordinates.longitude)" as NSString
APIURLString = APIURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let APIURL = NSURL(string: APIURLString as String)
let APIURLRequest = NSURLRequest(URL: APIURL!)
NSURLConnection.sendAsynchronousRequest(APIURLRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
if error != nil {
onFail?(error: error)
} else {
let dataAsString: NSString? = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
let (error,noResults) = self.validateGoogleJSONResponse(jsonResult)
if noResults == true { // request is ok but not results are returned
onSuccess?(place: nil)
} else if (error != nil) { // something went wrong with request
onFail?(error: error)
} else { // we have some good results to show
let address = SwiftLocationParser()
address.parseGoogleLocationData(jsonResult)
let placemark:CLPlacemark = address.getPlacemark()
onSuccess?(place: placemark)
}
}
}
}
private func reverseGoogleAddress(address: String!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding?) {
var APIURLString = "http://maps.googleapis.com/maps/api/geocode/json?address=\(address)" as NSString
APIURLString = APIURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let APIURL = NSURL(string: APIURLString as String)
let APIURLRequest = NSURLRequest(URL: APIURL!)
NSURLConnection.sendAsynchronousRequest(APIURLRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
if error != nil {
onFail?(error: error)
} else {
let dataAsString: NSString? = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
let (error,noResults) = self.validateGoogleJSONResponse(jsonResult)
if noResults == true { // request is ok but not results are returned
onSuccess?(place: nil)
} else if (error != nil) { // something went wrong with request
onFail?(error: error)
} else { // we have some good results to show
let address = SwiftLocationParser()
address.parseGoogleLocationData(jsonResult)
let placemark:CLPlacemark = address.getPlacemark()
onSuccess?(place: placemark)
}
}
}
}
private func validateGoogleJSONResponse(jsonResult: NSDictionary!) -> (error: NSError?, noResults: Bool!) {
var status = jsonResult.valueForKey("status") as! NSString
status = status.lowercaseString
if status.isEqualToString("ok") == true { // everything is fine, the sun is shining and we have results!
return (nil,false)
} else if status.isEqualToString("zero_results") == true { // No results error
return (nil,true)
} else if status.isEqualToString("over_query_limit") == true { // Quota limit was excedeed
let message = "Query quota limit was exceeded"
return (NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : message]),false)
} else if status.isEqualToString("request_denied") == true { // Request was denied
let message = "Request denied"
return (NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : message]),false)
} else if status.isEqualToString("invalid_request") == true { // Invalid parameters
let message = "Invalid input sent"
return (NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : message]),false)
}
return (nil,false) // okay!
}
//MARK: [Private] Apple / Reverse Geocoding
private func reverseAppleCoordinates(coordinates: CLLocationCoordinate2D!, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
let geocoder = CLGeocoder()
let location = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if error != nil {
onFail?(error: error)
} else {
if let placemark = placemarks?[0] as? CLPlacemark {
var address = SwiftLocationParser()
address.parseAppleLocationData(placemark)
onSuccess?(place: address.getPlacemark())
} else {
onSuccess?(place: nil)
}
}
})
}
private func reverseAppleAddress(address: String!, region: CLRegion?, onSuccess: onSuccessGeocoding?, onFail: onErrorGeocoding? ) {
let geocoder = CLGeocoder()
if region != nil {
geocoder.geocodeAddressString(address, inRegion: region, completionHandler: { (placemarks, error) in
if error != nil {
onFail?(error: error)
} else {
if let placemark = placemarks?[0] as? CLPlacemark {
var address = SwiftLocationParser()
address.parseAppleLocationData(placemark)
onSuccess?(place: address.getPlacemark())
} else {
onSuccess?(place: nil)
}
}
})
} else {
geocoder.geocodeAddressString(address, completionHandler: { (placemarks, error) in
if error != nil {
onFail?(error: error)
} else {
if let placemark = placemarks?[0] as? CLPlacemark {
var address = SwiftLocationParser()
address.parseAppleLocationData(placemark)
onSuccess?(place: address.getPlacemark())
} else {
onSuccess?(place: nil)
}
}
})
}
}
//MARK: [Private] Helper Methods
private func locateByIP(request: SwiftLocationRequest, refresh: Bool = false, timeout: NSTimeInterval, onEnd: ( (place: CLPlacemark?, error: NSError?) -> Void)? ) {
let policy = (refresh == false ? NSURLRequestCachePolicy.ReturnCacheDataElseLoad : NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData)
let URLRequest = NSURLRequest(URL: NSURL(string: "http://ip-api.com/json")!, cachePolicy: policy, timeoutInterval: timeout)
NSURLConnection.sendAsynchronousRequest(URLRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if request.isCancelled == true {
onEnd?(place: nil, error: nil)
return
}
if let data = data as NSData? {
var jsonError: NSError?
if let resultDict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as? NSDictionary {
let address = SwiftLocationParser()
address.parseIPLocationData(resultDict)
let placemark = address.getPlacemark()
onEnd?(place: placemark, error:nil)
} else {
onEnd?(place: nil, error: jsonError)
}
} else {
onEnd?(place: nil, error: error)
}
}
}
/**
Request will be added to the pool and related services are enabled automatically
:param: request request to add
*/
private func addRequest(request: SwiftLocationRequest!) {
// Add a new request to the array. Please note: add/remove is a sync operation due to avoid problems in a multitrheading env
dispatch_sync(blocksDispatchQueue) {
self.requests.append(request)
self.updateLocationManagerStatus()
}
}
/**
Search for a request with given identifier into the pool of requests
:param: identifier identifier of the request
:returns: the request object or nil
*/
private func request(identifier: Int?) -> SwiftLocationRequest? {
if let identifier = identifier as Int! {
for cRequest in self.requests {
if cRequest.ID == identifier {
return cRequest
}
}
}
return nil
}
/**
Return the requesta associated with a given CLRegion object
:param: region region instance
:returns: request if found, nil otherwise.
*/
private func requestForRegion(region: CLRegion!) -> SwiftLocationRequest? {
for request in requests {
if request.type == RequestType.RegionMonitor && request.region == region {
return request
}
}
return nil
}
/**
This method is called to complete an existing request, send result to the appropriate handler and remove it from the pool
(the last action will not occur for subscribe continuosly location notifications, until the request is not marked as cancelled)
:param: request request to complete
:param: object optional return object
:param: error optional error to report
*/
private func completeRequest(request: SwiftLocationRequest!, object: AnyObject?, error: NSError?) {
if request.type == RequestType.RegionMonitor { // If request is a region monitor we need to explictly stop it
manager.stopMonitoringForRegion(request.region!)
} else if (request.type == RequestType.BeaconRegionProximity) { // If request is a proximity beacon monitor we need to explictly stop it
manager.stopRangingBeaconsInRegion(request.beaconReg!)
}
// Sync remove item from requests pool
dispatch_sync(blocksDispatchQueue) {
var idx = 0
for cRequest in self.requests {
if cRequest.ID == request.ID {
cRequest.stopTimeout() // stop any running timeout timer
if cRequest.type == RequestType.ContinuousSignificantLocation ||
cRequest.type == RequestType.ContinuousLocationUpdate ||
cRequest.type == RequestType.SingleShotLocation ||
cRequest.type == RequestType.SingleShotIPLocation {
// for location related event we want to report the last fetched result
if error != nil {
cRequest.onError?(error: error)
} else {
if object != nil {
cRequest.onSuccess?(location: object as! CLLocation?)
}
}
}
// If result is not continous location update notifications or, anyway, for any request marked as cancelled
// we want to remove it from the pool
if cRequest.isCancelled == true || cRequest.type != RequestType.ContinuousLocationUpdate {
self.requests.removeAtIndex(idx)
}
}
idx++
}
// Turn off any non-used hardware based upon the new list of running requests
self.updateLocationManagerStatus()
}
}
/**
This method return the highest accuracy you want to receive into the current bucket of requests
:returns: highest accuracy level you want to receive
*/
private func highestRequiredAccuracy() -> CLLocationAccuracy {
var highestAccuracy = CLLocationAccuracy(Double.infinity)
for request in requests {
let accuracyLevel = CLLocationAccuracy(request.desideredAccuracy.accuracyThreshold())
if accuracyLevel < highestAccuracy {
highestAccuracy = accuracyLevel
}
}
return highestAccuracy
}
/**
This method simply turn off/on hardware required by the list of active running requests.
The same method also ask to the user permissions to user core location.
*/
private func updateLocationManagerStatus() {
if requests.count > 0 {
let hasAlwaysKey = (NSBundle.mainBundle().objectForInfoDictionaryKey("NSLocationAlwaysUsageDescription") != nil)
let hasWhenInUseKey = (NSBundle.mainBundle().objectForInfoDictionaryKey("NSLocationWhenInUseUsageDescription") != nil)
if hasAlwaysKey == true {
manager.requestAlwaysAuthorization()
} else if hasWhenInUseKey == true {
manager.requestWhenInUseAuthorization()
} else {
// You've forgot something essential
assert(false, "To use location services in iOS 8+, your Info.plist must provide a value for either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription.")
}
}
// Location Update
if hasActiveRequests([RequestType.ContinuousLocationUpdate,RequestType.SingleShotLocation]) == true {
let requiredAccuracy = self.highestRequiredAccuracy()
if requiredAccuracy != manager.desiredAccuracy {
manager.stopUpdatingLocation()
manager.desiredAccuracy = requiredAccuracy
}
manager.startUpdatingLocation()
} else {
manager.stopUpdatingLocation()
}
// Significant Location Changes
if hasActiveRequests([RequestType.ContinuousSignificantLocation]) == true {
manager.startMonitoringSignificantLocationChanges()
} else {
manager.stopMonitoringSignificantLocationChanges()
}
// Beacon/Region monitor is turned off automatically on completeRequest()
}
/**
Return true if a request into the pool is of type described by the list of types passed
:param: list allowed types
:returns: true if at least one request with one the specified type is running
*/
private func hasActiveRequests(list: [RequestType]) -> Bool! {
for request in requests {
let idx = find(list, request.type)
if idx != nil {
return true
}
}
return false
}
/**
In case of an error we want to expire all queued notifications
:param: error error to notify
*/
private func expireAllRequests(error: NSError?) {
for request in requests {
request.markAsCancelled(error)
}
}
//MARK: [Private] Location Manager Delegate
public func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
locationsReceived(locations)
}
private func locationsReceived(locations: [AnyObject]!) {
if let location = locations.last as? CLLocation {
let acc = location.accuracyOfLocation()
for request in requests {
if request.isAcceptable(location) == true {
completeRequest(request, object: location, error: nil)
}
}
}
}
public func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
expireAllRequests(error)
}
public func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.Denied || status == CLAuthorizationStatus.Restricted {
// Clear out any pending location requests (which will execute the blocks with a status that reflects
// the unavailability of location services) since we now no longer have location services permissions
let err = NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : "Location services denied/restricted by parental control"])
expireAllRequests(err)
} else if status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.AuthorizedWhenInUse {
for request in requests {
request.startTimeout(nil)
}
updateLocationManagerStatus()
}
}
public func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
let request = requestForRegion(region)
request?.onRegionEnter?(region: region)
}
public func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
let request = requestForRegion(region)
request?.onRegionExit?(region: region)
}
public func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
for request in requests {
if request.beaconReg == region {
request.onRangingBeaconEvent?(regions: beacons)
}
}
}
}
/**
This is the request type
- SingleShotLocation: Single location request with desidered accuracy level
- SingleShotIPLocation: Single location request with IP-based location search (used automatically with accuracy set to Country)
- ContinuousLocationUpdate: Continous location update
- ContinuousSignificantLocation: Significant location update requests
- ContinuousHeadingUpdate: Continous heading update requests
- RegionMonitor: Monitor specified region
- BeaconRegionProximity: Search for beacon services nearby the device
*/
enum RequestType {
case SingleShotLocation
case SingleShotIPLocation
case ContinuousLocationUpdate
case ContinuousSignificantLocation
case ContinuousHeadingUpdate
case RegionMonitor
case BeaconRegionProximity
}
private extension CLLocation {
func accuracyOfLocation() -> Accuracy! {
let timeSinceUpdate = fabs( self.timestamp.timeIntervalSinceNow )
let horizontalAccuracy = self.horizontalAccuracy
if horizontalAccuracy <= Accuracy.Room.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.Room.timeThreshold() {
return Accuracy.Room
} else if horizontalAccuracy <= Accuracy.House.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.House.timeThreshold() {
return Accuracy.House
} else if horizontalAccuracy <= Accuracy.Block.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.Block.timeThreshold() {
return Accuracy.Block
} else if horizontalAccuracy <= Accuracy.Neighborhood.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.Neighborhood.timeThreshold() {
return Accuracy.Neighborhood
} else if horizontalAccuracy <= Accuracy.City.accuracyThreshold() &&
timeSinceUpdate <= Accuracy.City.timeThreshold() {
return Accuracy.City
} else {
return Accuracy.None
}
}
}
//MARK: ===== [PRIVATE] SwiftLocationRequest Class =====
var requestNextID: RequestIDType = 0
/// This is the class which represent a single request.
/// Usually you should not interact with it. The only action you can perform on it is to call the cancel method to abort a running request.
public class SwiftLocationRequest: NSObject {
private(set) var type: RequestType
private(set) var ID: RequestIDType
private(set) var isCancelled: Bool!
var onTimeOut: onTimeoutReached?
// location related handlers
private var onSuccess: onSuccessLocate?
private var onError: onErrorLocate?
// region/beacon related handlers
private var region: CLRegion?
private var beaconReg: CLBeaconRegion?
private var onRegionEnter: onRegionEvent?
private var onRegionExit: onRegionEvent?
private var onRangingBeaconEvent: onRangingBacon?
var desideredAccuracy: Accuracy!
private var timeoutTimer: NSTimer?
private var timeoutInterval: NSTimeInterval
private var hasTimeout: Bool!
//MARK: Init - Private Methods
private init(requestType: RequestType, accuracy: Accuracy,timeout: NSTimeInterval, success: onSuccessLocate, fail: onErrorLocate?) {
type = requestType
requestNextID++
ID = requestNextID
isCancelled = false
onSuccess = success
onError = fail
desideredAccuracy = accuracy
timeoutInterval = timeout
hasTimeout = false
super.init()
if SwiftLocation.state == ServiceStatus.Available {
self.startTimeout(nil)
}
}
private init(region: CLRegion!, onEnter: onRegionEvent?, onExit: onRegionEvent?) {
type = RequestType.RegionMonitor
requestNextID++
ID = requestNextID
isCancelled = false
onRegionEnter = onEnter
onRegionExit = onExit
desideredAccuracy = Accuracy.None
timeoutInterval = 0
hasTimeout = false
super.init()
}
private init(beaconRegion: CLBeaconRegion!, onRanging: onRangingBacon?) {
type = RequestType.BeaconRegionProximity
requestNextID++
ID = requestNextID
isCancelled = false
onRangingBeaconEvent = onRanging
desideredAccuracy = Accuracy.None
timeoutInterval = 0
hasTimeout = false
beaconReg = beaconRegion
super.init()
}
//MARK: Public Methods
/**
Cancel method abort a running request
*/
private func markAsCancelled(error: NSError?) {
isCancelled = true
stopTimeout()
SwiftLocation.shared.completeRequest(self, object: nil, error: error)
}
//MARK: Private Methods
private func isAcceptable(location: CLLocation) -> Bool! {
if isCancelled == true {
return false
}
if desideredAccuracy == Accuracy.None {
return true
}
let locAccuracy: Accuracy! = location.accuracyOfLocation()
let valid = (locAccuracy.rawValue >= desideredAccuracy.rawValue)
return valid
}
private func startTimeout(forceValue: NSTimeInterval?) {
if hasTimeout == false && timeoutInterval > 0 {
let value = (forceValue != nil ? forceValue! : timeoutInterval)
timeoutTimer = NSTimer.scheduledTimerWithTimeInterval(value, target: self, selector: "timeoutReached", userInfo: nil, repeats: false)
}
}
private func stopTimeout() {
timeoutTimer?.invalidate()
timeoutTimer = nil
}
public func timeoutReached() {
var additionalTime: NSTimeInterval? = onTimeOut?()
if additionalTime == nil {
timeoutTimer?.invalidate()
timeoutTimer = nil
hasTimeout = true
isCancelled = false
let error = NSError(domain: NSCocoaErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey : "Timeout reached"])
SwiftLocation.shared.completeRequest(self, object: nil, error: error)
} else {
hasTimeout = false
startTimeout(additionalTime!)
}
}
}
//MARK: ===== [PRIVATE] SwiftLocationParser Class =====
// Portions of this class are part of the LocationManager mady by varshylmobile (AddressParser class):
// (Made by https://github.com/varshylmobile/LocationManager)
private class SwiftLocationParser: NSObject {
private var latitude = NSString()
private var longitude = NSString()
private var streetNumber = NSString()
private var route = NSString()
private var locality = NSString()
private var subLocality = NSString()
private var formattedAddress = NSString()
private var administrativeArea = NSString()
private var administrativeAreaCode = NSString()
private var subAdministrativeArea = NSString()
private var postalCode = NSString()
private var country = NSString()
private var subThoroughfare = NSString()
private var thoroughfare = NSString()
private var ISOcountryCode = NSString()
private var state = NSString()
override init() {
super.init()
}
private func parseIPLocationData(JSON: NSDictionary) -> Bool {
let status = JSON["status"] as? String
if status != "success" {
return false
}
self.country = JSON["country"] as! NSString
self.ISOcountryCode = JSON["countryCode"] as! NSString
if let lat = JSON["lat"] as? NSNumber, lon = JSON["lon"] as? NSNumber {
self.longitude = lat.description
self.latitude = lon.description
}
self.postalCode = JSON["zip"] as! NSString
return true
}
private func parseAppleLocationData(placemark:CLPlacemark) {
var addressLines = placemark.addressDictionary["FormattedAddressLines"] as! NSArray
//self.streetNumber = placemark.subThoroughfare ? placemark.subThoroughfare : ""
self.streetNumber = placemark.thoroughfare != nil ? placemark.thoroughfare : ""
self.locality = placemark.locality != nil ? placemark.locality : ""
self.postalCode = placemark.postalCode != nil ? placemark.postalCode : ""
self.subLocality = placemark.subLocality != nil ? placemark.subLocality : ""
self.administrativeArea = placemark.administrativeArea != nil ? placemark.administrativeArea : ""
self.country = placemark.country != nil ? placemark.country : ""
self.longitude = placemark.location.coordinate.longitude.description;
self.latitude = placemark.location.coordinate.latitude.description
if addressLines.count>0 {
self.formattedAddress = addressLines.componentsJoinedByString(", ")
} else {
self.formattedAddress = ""
}
}
private func parseGoogleLocationData(resultDict:NSDictionary) {
let locationDict = (resultDict.valueForKey("results") as! NSArray).firstObject as! NSDictionary
let formattedAddrs = locationDict.objectForKey("formatted_address") as! NSString
let geometry = locationDict.objectForKey("geometry") as! NSDictionary
let location = geometry.objectForKey("location") as! NSDictionary
let lat = location.objectForKey("lat") as! Double
let lng = location.objectForKey("lng") as! Double
self.latitude = lat.description
self.longitude = lng.description
let addressComponents = locationDict.objectForKey("address_components") as! NSArray
self.subThoroughfare = component("street_number", inArray: addressComponents, ofType: "long_name")
self.thoroughfare = component("route", inArray: addressComponents, ofType: "long_name")
self.streetNumber = self.subThoroughfare
self.locality = component("locality", inArray: addressComponents, ofType: "long_name")
self.postalCode = component("postal_code", inArray: addressComponents, ofType: "long_name")
self.route = component("route", inArray: addressComponents, ofType: "long_name")
self.subLocality = component("subLocality", inArray: addressComponents, ofType: "long_name")
self.administrativeArea = component("administrative_area_level_1", inArray: addressComponents, ofType: "long_name")
self.administrativeAreaCode = component("administrative_area_level_1", inArray: addressComponents, ofType: "short_name")
self.subAdministrativeArea = component("administrative_area_level_2", inArray: addressComponents, ofType: "long_name")
self.country = component("country", inArray: addressComponents, ofType: "long_name")
self.ISOcountryCode = component("country", inArray: addressComponents, ofType: "short_name")
self.formattedAddress = formattedAddrs;
}
private func getPlacemark() -> CLPlacemark {
var addressDict = NSMutableDictionary()
var formattedAddressArray = self.formattedAddress.componentsSeparatedByString(", ") as Array
let kSubAdministrativeArea = "SubAdministrativeArea"
let kSubLocality = "SubLocality"
let kState = "State"
let kStreet = "Street"
let kThoroughfare = "Thoroughfare"
let kFormattedAddressLines = "FormattedAddressLines"
let kSubThoroughfare = "SubThoroughfare"
let kPostCodeExtension = "PostCodeExtension"
let kCity = "City"
let kZIP = "ZIP"
let kCountry = "Country"
let kCountryCode = "CountryCode"
addressDict.setObject(self.subAdministrativeArea, forKey: kSubAdministrativeArea)
addressDict.setObject(self.subLocality, forKey: kSubLocality)
addressDict.setObject(self.administrativeAreaCode, forKey: kState)
addressDict.setObject(formattedAddressArray.first as! NSString, forKey: kStreet)
addressDict.setObject(self.thoroughfare, forKey: kThoroughfare)
addressDict.setObject(formattedAddressArray, forKey: kFormattedAddressLines)
addressDict.setObject(self.subThoroughfare, forKey: kSubThoroughfare)
addressDict.setObject("", forKey: kPostCodeExtension)
addressDict.setObject(self.locality, forKey: kCity)
addressDict.setObject(self.postalCode, forKey: kZIP)
addressDict.setObject(self.country, forKey: kCountry)
addressDict.setObject(self.ISOcountryCode, forKey: kCountryCode)
var lat = self.latitude.doubleValue
var lng = self.longitude.doubleValue
var coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
var placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict as [NSObject : AnyObject])
return (placemark as CLPlacemark)
}
private func component(component:NSString,inArray:NSArray,ofType:NSString) -> NSString {
let index:NSInteger = inArray.indexOfObjectPassingTest { (obj, idx, stop) -> Bool in
var objDict:NSDictionary = obj as! NSDictionary
var types:NSArray = objDict.objectForKey("types") as! NSArray
let type = types.firstObject as! NSString
return type.isEqualToString(component as String)
}
if index == NSNotFound {
return ""
}
if index >= inArray.count {
return ""
}
var type = ((inArray.objectAtIndex(index) as! NSDictionary).valueForKey(ofType as String)!) as! NSString
if type.length > 0 {
return type
}
return ""
}
} | mit | 39218249b3a9a59c6ca1f1cc1ba7a62b | 36.119048 | 302 | 0.738264 | 4.18368 | false | false | false | false |
iCrany/iOSExample | iOSExample/Module/SQLiteExample/SQLiteExampleTableVC.swift | 1 | 2867 | //
// SQLiteExampleTableVC.swift
// iOSExample
//
// Created by iCrany on 2018/12/20.
// Copyright © 2018 iCrany. All rights reserved.
//
import Foundation
import UIKit
class SQLiteExampleTableVC: UIViewController {
struct Constant {
static let kDemo1: String = "SQLite BenchMark"
}
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: .zero, style: .plain)
tableView.tableFooterView = UIView.init()
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
fileprivate var dataSource: [String] = []
init() {
super.init(nibName: nil, bundle: nil)
self.prepareDataSource()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "SQLite Example"
self.setupUI()
}
private func setupUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { maker in
maker.edges.equalTo(self.view)
}
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self))
}
private func prepareDataSource() {
self.dataSource.append(Constant.kDemo1)
}
}
extension SQLiteExampleTableVC: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedDataSourceStr = self.dataSource[indexPath.row]
switch selectedDataSourceStr {
case Constant.kDemo1:
let vc: SQLiteBenchmarkVCViewController = SQLiteBenchmarkVCViewController()
self.navigationController?.pushViewController(vc, animated: true)
default:
break
}
}
}
extension SQLiteExampleTableVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataSourceStr: String = self.dataSource[indexPath.row]
let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self))
if let cell = tableViewCell {
cell.textLabel?.text = dataSourceStr
cell.textLabel?.textColor = UIColor.black
return cell
} else {
return UITableViewCell.init(style: .default, reuseIdentifier: "error")
}
}
}
| mit | b29b9be5deeabfb49ab5d4660f905a53 | 29.489362 | 132 | 0.647244 | 5.163964 | false | false | false | false |
filestack/filestack-ios | Sources/Filestack/Internal/Requests/FolderListRequest.swift | 1 | 4102 | //
// FolderListRequest.swift
// Filestack
//
// Created by Ruben Nine on 10/25/17.
// Copyright © 2017 Filestack. All rights reserved.
//
import FilestackSDK
import Foundation
final class FolderListRequest: CloudRequest, Cancellable {
// MARK: - Properties
let authCallbackURL: URL
let apiKey: String
let security: Security?
let pageToken: String?
let provider: CloudProvider
let path: String
private(set) var token: String?
private weak var dataTask: URLSessionDataTask?
// MARK: - Lifecyle Functions
init(authCallbackURL: URL,
apiKey: String,
security: Security? = nil,
token: String? = nil,
pageToken: String? = nil,
provider: CloudProvider,
path: String) {
self.authCallbackURL = authCallbackURL
self.apiKey = apiKey
self.security = security
self.token = token
self.pageToken = pageToken
self.provider = provider
self.path = path
}
// MARK: - Cancellable Protocol Implementation
@discardableResult func cancel() -> Bool {
guard let dataTask = dataTask else { return false }
dataTask.cancel()
return true
}
// MARK: - Internal Functions
func perform(cloudService: CloudService, completionBlock: @escaping CloudRequestCompletion) -> URLSessionDataTask {
let request = cloudService.folderListRequest(provider: provider,
path: path,
authCallbackURL: authCallbackURL,
apiKey: apiKey,
security: security,
token: token,
pageToken: pageToken)
let task = URLSession.filestackDefault.dataTask(with: request) { (data, response, error) in
// Parse JSON, or return early with error if unable to parse.
guard let data = data, let json = data.parseJSON() else {
let response = FolderListResponse(error: error)
DispatchQueue.main.async { completionBlock(nil, response) }
return
}
// Store any token we receive so we can use it next time.
self.token = json["token"] as? String
if let authURL = self.getAuthURL(from: json) {
// Auth is required — redirect to authentication URL
let response = FolderListResponse(authURL: authURL)
DispatchQueue.main.async { completionBlock(self.authCallbackURL, response) }
} else if let results = self.getResults(from: json) {
// Results received — return response with contents, and, optionally next token
let contents = results["contents"] as? [[String: Any]]
let nextToken: String? = self.token(from: results["next"] as? String)
let response = FolderListResponse(contents: contents, nextToken: nextToken, error: error)
DispatchQueue.main.async { completionBlock(nil, response) }
} else {
let response = FolderListResponse(contents: nil, nextToken: nil, error: error)
DispatchQueue.main.async { completionBlock(nil, response) }
}
}
dataTask = task
task.resume()
return task
}
private func token(from string: String?) -> String? {
guard let string = string, !string.isEmpty else { return nil }
return string
}
// MARK: - Private Functions
func getAuthURL(from json: [String: Any]) -> URL? {
guard let providerJSON = json[provider.description] as? [String: Any] else { return nil }
guard let authJSON = providerJSON["auth"] as? [String: Any] else { return nil }
guard let redirectURLString = authJSON["redirect_url"] as? String else { return nil }
return URL(string: redirectURLString)
}
}
| mit | df0e07b81b94eacb173be3917e559855 | 34.318966 | 119 | 0.57774 | 5.076828 | false | false | false | false |
AntonTheDev/XCode-DI-Templates | Source/FileTemplates-tvOS/Network Service.xctemplate/___FILEBASENAME___.swift | 2 | 3867 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
import Foundation
import Alamofire
/*
Add the following in the registerDataServices() method of the
Services class.
dataServicesContainer.register(___FILEBASENAME___.self, name: NetworkQoS.default.rawValue) { r in
let service = ___FILEBASENAME___(name: NetworkQoS.default.rawValue, qos: .default)
return service
}.inObjectScope(.container)
*/
enum NetworkQoS : String {
case background = ".background"
case utility = ".utility"
case `default` = ".default"
case userInitiated = ".userInitiated"
case userInteractive = ".userInteractive"
}
typealias ___FILEBASENAME___Response = (_ response : [String : AnyObject]?, _ error : Error?) -> ()
class ___FILEBASENAME___ {
var queue : DispatchQueue!
required init(name : String, qos: DispatchQoS, headers: HTTPHeaders = HTTPHeaders()) {
queue = DispatchQueue(label: name, qos: qos)
httpHeaders = headers
}
var httpHeaders: HTTPHeaders?
internal func performRequest(request : String,
method : Alamofire.HTTPMethod,
parameters: [String : AnyObject] = [String : AnyObject](),
completion : @escaping ___FILEBASENAME___Response) {
Alamofire.request(request,
method: method,
parameters: parameters,
headers: httpHeaders).validate().responseJSON(queue: queue) { response in
switch response.result {
case .success:
if let JSONResponse = response.result.value as? [String : AnyObject] {
completion(JSONResponse, nil)
}
case .failure(let error):
completion(nil, error)
}
}
}
func performGETRequest(request : String,
parameters: [String : AnyObject] = [String : AnyObject](),
completion : @escaping ___FILEBASENAME___Response) {
performRequest(request: request, method: .get, parameters: parameters, completion: completion)
}
func performPUTRequest(request : String,
parameters: [String : AnyObject] = [String : AnyObject](),
completion : @escaping ___FILEBASENAME___Response) {
performRequest(request: request, method: .put, parameters: parameters, completion: completion)
}
func performPOSTRequest(request : String,
parameters: [String : AnyObject] = [String : AnyObject](),
completion : @escaping ___FILEBASENAME___Response) {
performRequest(request: request, method: .post, parameters: parameters, completion: completion)
}
func performPATCHRequest(request : String,
parameters: [String : AnyObject] = [String : AnyObject](),
completion : @escaping ___FILEBASENAME___Response) {
performRequest(request: request, method: .patch, parameters: parameters, completion: completion)
}
func performDELETERequest(request : String,
parameters: [String : AnyObject] = [String : AnyObject](),
completion : @escaping ___FILEBASENAME___Response) {
performRequest(request: request, method: .delete, parameters: parameters, completion: completion)
}
}
| mit | c800f522184d799ddc0b446875c072d2 | 38.459184 | 105 | 0.534264 | 5.771642 | false | false | false | false |
JuanjoArreola/KeychainStore | Sources/KeychainStore/KeychainStore.swift | 1 | 1540 | //
// KeychainStore.swift
// KeychainStore
//
// Created by Juan Jose Arreola on 8/13/15.
// Copyright © 2015 juanjo. All rights reserved.
//
import Foundation
public final class KeychainStore<T: Codable>: AbstractKeychainStore {
private let encoder = JSONEncoder()
private let decoder = JSONDecoder()
/// Retrieves an instance from the keychain with the specified key
/// - parameter key: The key of the item to be retrieved
/// - returns: The instance from the keychain
public func instance(forKey key: String) throws -> T? {
guard let data = try data(forKey: key) else { return nil }
return try decoder.decode(T.self, from: data)
}
/// Adds an instance to the keychain with the specified key
/// - parameter instance: The object to be stored
/// - parameter key: The key of the item to be stored
/// - parameter accessibility: The accessibility type of the object
public func set(_ instance: T, forKey key: String, accessibility: KeychainAccessibility = .whenUnlocked) throws {
let data = try encoder.encode(instance)
try set(data: data, forKey: key, accessibility: accessibility)
}
/// Updates the instance associated with the specified key
/// - parameter instance: The updated object
/// - parameter key: The key of the object to be updated
public func update(_ instance: T, forKey key: String) throws {
let data = try encoder.encode(instance)
try update(data: data, forKey: key)
}
}
| mit | 2ce14e12d92cf8f140a89098857f785e | 36.536585 | 117 | 0.671865 | 4.435159 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Character/JumpClones.swift | 2 | 3426 | //
// JumpClones.swift
// Neocom
//
// Created by Artem Shimanski on 1/21/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import EVEAPI
import Alamofire
import Combine
struct JumpClones: View {
@ObservedObject private var info = Lazy<DataLoader<JumpClonesInfo, AFError>, Account>()
@Environment(\.managedObjectContext) var managedObjectContext
@EnvironmentObject private var sharedState: SharedState
private struct JumpClonesInfo {
var clones: ESI.Clones
var locations: [Int64: EVELocation]
}
private func getInfo(characterID: Int64, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> AnyPublisher<JumpClonesInfo, AFError> {
let clones = sharedState.esi.characters.characterID(Int(characterID)).clones().get(cachePolicy: cachePolicy)
.flatMap { clones in
EVELocation.locations(with: Set(clones.value.jumpClones.map{$0.locationID}), esi: self.sharedState.esi, managedObjectContext: self.managedObjectContext).setFailureType(to: AFError.self).map {
JumpClonesInfo(clones: clones.value, locations: $0)
}
}.receive(on: RunLoop.main)
return clones.eraseToAnyPublisher()
}
private func nextCloneJump(_ clones: ESI.Clones) -> some View {
let t = 3600 * 24 + (clones.lastCloneJumpDate ?? .distantPast).timeIntervalSinceNow
let subtitle = t > 0 ? Text(TimeIntervalFormatter.localizedString(from: t, precision: .minutes)) : Text("Now")
return VStack(alignment: .leading) {
Text("Clone jump availability: ") + subtitle
}
}
var body: some View {
let info = sharedState.account.map { account in
self.info.get(account, initial: DataLoader(self.getInfo(characterID: account.characterID)))
}
return Group {
if info != nil {
List {
(info?.result?.value).map { info in
Group {
Section {
self.nextCloneJump(info.clones)
}
ForEach(info.clones.jumpClones, id: \.jumpCloneID) { clone in
Section(header: info.locations[clone.locationID].map{Text($0)} ?? Text("UNKNOWN LOCATION")) {
ImplantsRows(implants: clone.implants)
}
}
}
}
}
.onRefresh(isRefreshing: Binding(info!, keyPath: \.isLoading), onRefresh: {
guard let account = self.sharedState.account, let info = info else {return}
info.update(self.getInfo(characterID: account.characterID, cachePolicy: .reloadIgnoringLocalCacheData))
})
.listStyle(GroupedListStyle())
.overlay((info?.result?.error).map{Text($0)})
}
else {
Text(RuntimeError.noAccount).padding()
}
}.navigationBarTitle(Text("Jump Clones"))
}
}
#if DEBUG
struct JumpClones_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
JumpClones()
}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| lgpl-2.1 | dd887598d37b717e2641a44da34fad53 | 37.920455 | 207 | 0.575182 | 5.044183 | false | false | false | false |
kristopherjohnson/kjchess | kjchess/bestMove.swift | 1 | 5621 | //
// bestMove.swift
// kjchess
//
// Copyright © 2017 Kristopher Johnson. All rights reserved.
//
import Foundation
/// Return the best move for the specified position.
///
/// - parameter position: The `Position` for which a move should be found.
/// - parameter searchDepth: Minimax search depth.
/// - parameter concurrentTasks: Number of asynchronous minimax tasks to run.
///
/// - returns: A `Move`, the score, and the principal variation, or `nil` if there are no legal moves.
public func bestMove(position: Position, searchDepth: Int = 1, concurrentTasks: Int = 1)
-> (Move, Double, [Move])?
{
var positionCopy = position
var moves = positionCopy.legalMoves()
moves.shuffle()
var bestMoves = [(Move, [Move])]()
var bestScore: Double
let queue = DispatchQueue(label: "bestMove")
let group = DispatchGroup()
let semaphore = DispatchSemaphore(value: concurrentTasks)
switch position.toMove {
case .white:
bestScore = -Double.infinity
for move in moves {
DispatchQueue.global().async(group: group) {
semaphore.wait()
var newPosition = position.after(move)
let (moveScore, movePV) = minimaxSearch(position: &newPosition,
depth: searchDepth - 1,
alpha: -Double.infinity,
beta: Double.infinity)
semaphore.signal()
queue.sync {
if moveScore > bestScore {
bestScore = moveScore
bestMoves = [(move, movePV.prepending(move))]
}
else if moveScore == bestScore {
bestMoves.append((move, movePV.prepending(move)))
}
}
}
}
case .black:
bestScore = Double.infinity
for move in moves {
DispatchQueue.global().async(group: group) {
semaphore.wait()
var newPosition = position.after(move)
let (moveScore, movePV) = minimaxSearch(position: &newPosition,
depth: searchDepth - 1,
alpha: -Double.infinity,
beta: Double.infinity)
semaphore.signal()
queue.sync {
if moveScore < bestScore {
bestScore = moveScore
bestMoves = [(move, movePV.prepending(move))]
}
else if moveScore == bestScore {
bestMoves.append((move, movePV.prepending(move)))
}
}
}
}
}
group.wait()
if let (move, movePV) = bestMoves.randomPick() {
return (move, bestScore, movePV)
}
else {
return nil
}
}
/// Search for best move from the specified position.
///
/// This function mutates the position while evaluating moves.
/// When it returns, the position will match its original
/// state.
private func minimaxSearch(position: inout Position, depth: Int, alpha: Double, beta: Double)
-> (Double, [Move])
{
if depth < 1 {
return (evaluate(position: position), [])
}
var moves = position.legalMoves()
moves.sort(by: capturesFirst)
var bestScore: Double
var pv: [Move] = []
var a = alpha
var b = beta
let d = depth - 1
switch position.toMove {
case .white:
bestScore = -Double.infinity
for move in moves {
let undo = position.apply(move)
let (moveScore, movePV) = minimaxSearch(position: &position,
depth: d,
alpha: a,
beta: b)
position.unapply(undo)
if moveScore > bestScore {
bestScore = moveScore
pv = movePV.prepending(move)
}
a = max(a, bestScore)
if b <= a {
break // beta cut-off
}
}
case .black:
bestScore = Double.infinity
for move in moves {
let undo = position.apply(move)
let (moveScore, movePV) = minimaxSearch(position: &position,
depth: d,
alpha: a,
beta: b)
position.unapply(undo)
if moveScore < bestScore {
bestScore = moveScore
pv = movePV.prepending(move)
}
b = min(b, bestScore)
if b <= a {
break // alpha cut-off
}
}
}
return (bestScore, pv)
}
/// Predicate used to sort Move arrays so that captures come before non-capture moves.
///
/// Such an ordering should lead to better alpha-beta pruning.
private func capturesFirst(lhs: Move, rhs: Move) -> Bool {
if lhs.isCapture {
if !rhs.isCapture {
// Captures before non-captures
return true
}
// If both captures, order by material value of the captured piece.
return lhs.capturedPiece!.materialValue > rhs.capturedPiece!.materialValue
}
else {
return false
}
}
| mit | 4fc680c456c04a1ae8b8c9e9c6e381b8 | 31.485549 | 102 | 0.490569 | 4.942832 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.