repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
roecrew/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Effects/Filters/Three Pole Low Pass Filter/AKThreePoleLowpassFilter.swift | mit | 1 | //
// AKThreePoleLowpassFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// 3-pole (18 db/oct slope) Low-Pass filter with resonance and tanh distortion.
///
/// - Parameters:
/// - input: Input node to process
/// - distortion: Distortion amount. Zero gives a clean output. Greater than zero adds tanh distortion controlled by the filter parameters, in such a way that both low cutoff and high resonance increase the distortion amount.
/// - cutoffFrequency: Filter cutoff frequency in Hertz.
/// - resonance: Resonance. Usually a value in the range 0-1. A value of 1.0 will self oscillate at the cutoff frequency. Values slightly greater than 1 are possible for more sustained oscillation and an “overdrive” effect.
///
public class AKThreePoleLowpassFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKThreePoleLowpassFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var distortionParameter: AUParameter?
private var cutoffFrequencyParameter: AUParameter?
private var resonanceParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Distortion amount. Zero gives a clean output. Greater than zero adds tanh distortion controlled by the filter parameters, in such a way that both low cutoff and high resonance increase the distortion amount.
public var distortion: Double = 0.5 {
willSet {
if distortion != newValue {
if internalAU!.isSetUp() {
distortionParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.distortion = Float(newValue)
}
}
}
}
/// Filter cutoff frequency in Hertz.
public var cutoffFrequency: Double = 1500 {
willSet {
if cutoffFrequency != newValue {
if internalAU!.isSetUp() {
cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.cutoffFrequency = Float(newValue)
}
}
}
}
/// Resonance. Usually a value in the range 0-1. A value of 1.0 will self oscillate at the cutoff frequency. Values slightly greater than 1 are possible for more sustained oscillation and an “overdrive” effect.
public var resonance: Double = 0.5 {
willSet {
if resonance != newValue {
if internalAU!.isSetUp() {
resonanceParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.resonance = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - Parameters:
/// - input: Input node to process
/// - distortion: Distortion amount. Zero gives a clean output. Greater than zero adds tanh distortion controlled by the filter parameters, in such a way that both low cutoff and high resonance increase the distortion amount.
/// - cutoffFrequency: Filter cutoff frequency in Hertz.
/// - resonance: Resonance. Usually a value in the range 0-1. A value of 1.0 will self oscillate at the cutoff frequency. Values slightly greater than 1 are possible for more sustained oscillation and an “overdrive” effect.
///
public init(
_ input: AKNode,
distortion: Double = 0.5,
cutoffFrequency: Double = 1500,
resonance: Double = 0.5) {
self.distortion = distortion
self.cutoffFrequency = cutoffFrequency
self.resonance = resonance
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = fourCC("lp18")
description.componentManufacturer = fourCC("AuKt")
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKThreePoleLowpassFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKThreePoleLowpassFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKThreePoleLowpassFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
distortionParameter = tree.valueForKey("distortion") as? AUParameter
cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter
resonanceParameter = tree.valueForKey("resonance") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.distortionParameter!.address {
self.distortion = Double(value)
} else if address == self.cutoffFrequencyParameter!.address {
self.cutoffFrequency = Double(value)
} else if address == self.resonanceParameter!.address {
self.resonance = Double(value)
}
}
}
internalAU?.distortion = Float(distortion)
internalAU?.cutoffFrequency = Float(cutoffFrequency)
internalAU?.resonance = Float(resonance)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| 23607b945c8428135faf3dfa09df4ccb | 39.317073 | 232 | 0.635965 | false | false | false | false |
AutomationStation/BouncerBuddy | refs/heads/master | BouncerBuddy(version1.1)/BouncerBuddy/ViewController.swift | apache-2.0 | 2 | //
// ViewController.swift
// BouncerBuddy
//
// Created by Sha Wu on 16/3/2.
// Copyright © 2016年 Sheryl Hong. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let background = CAGradientLayer().turquoiseColor()
background.frame = self.view.bounds
self.view.layer.insertSublayer(background, atIndex: 0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
// comment out the next lines if you want to go to homepage without sign in
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
if (isLoggedIn != 1){
self.performSegueWithIdentifier("SignInView", sender: self)
}else{
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
}
}
@IBAction func LogoutTapped(sender: AnyObject) {
let appDomain = NSBundle.mainBundle().bundleIdentifier
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)
self.performSegueWithIdentifier("SignInView", sender: self)
}
}
| cf14aa63e7b3b8a4c5406bdf77b838ad | 29.254902 | 87 | 0.656513 | false | false | false | false |
Minitour/WWDC-Collaborators | refs/heads/master | Macintosh.playground/Sources/Apps/NotePad.swift | mit | 1 | import Foundation
import UIKit
import CFNetwork
import CoreFoundation
public class NotePad: MacApp{
public var desktopIcon: UIImage?
public var identifier: String? = "notepad"
public var windowTitle: String? = "Note Pad"
public var menuActions: [MenuAction]? = []
public var currentText: [String]
lazy public var uniqueIdentifier: String = {
return UUID().uuidString
}()
public var notesCount:Int {
return currentText.count
}
public init(withIdentifier id: String = "notepad"){
identifier = id
currentText = Array(repeating: "", count: 8)
currentText[0] = "Hello world"
container = NotePadView()
container?.backgroundColor = .clear
(container as? NotePadView)?.delegate = self
(container as? NotePadView)?.dataSource = self
}
public var container: UIView?
public static func printCurrentPage(text: String){
let socket = SwiftSock(addr_: printerIP, port_: printerPort)
socket.connect()
socket.open()
socket.send(data: text)
socket.close()
}
public func reloadData(){
(container as? NotePadView)?.updateInterface()
}
public func willTerminateApplication() {
}
public func willLaunchApplication(in view: OSWindow, withApplicationWindow appWindow: OSApplicationWindow) {
}
public func didLaunchApplication(in view: OSWindow, withApplicationWindow appWindow: OSApplicationWindow) {
}
public func sizeForWindow() -> CGSize {
return CGSize(width: 200, height: 200)
}
}
extension NotePad: NotePadDelegate{
public func notePad(_ notepad: NotePadView, didChangeText text: String, atIndex index: Int) {
self.currentText[index] = text
}
public func notePad(_ notepad: NotePadView, didChangePageTo index: Int) {
}
}
extension NotePad: NotePadDataSource{
public func notePad(_ notepad: NotePadView, textForPageAtIndex index: Int) -> String? {
return currentText[index]
}
public func numberOfNotes(_ notepad: NotePadView) -> Int {
return notesCount
}
}
public protocol NotePadDelegate {
/// Delegate Function, called when user changes pages.
///
/// - Parameters:
/// - notepad: The notepad view.
/// - index: The new page which the notepad switched to.
func notePad(_ notepad: NotePadView,didChangePageTo index: Int)
/// Delegaet Function, called when user types in the notepad.
///
/// - Parameters:
/// - notepad: The notepad view.
/// - text: The new text.
/// - index: The page at which the user typed.
func notePad(_ notepad: NotePadView, didChangeText text: String, atIndex index: Int)
}
public protocol NotePadDataSource {
/// Data Source Function, used to determine the amount of pages the notepad contains.
///
/// - Parameter notepad: The notepad view.
/// - Returns: The number of pages for the notepad.
func numberOfNotes(_ notepad: NotePadView)->Int
/// Data Source Function, used to determine the text for a certain page.
///
/// - Parameters:
/// - notepad: The notepad view.
/// - index: The index for which we want to specify the text.
/// - Returns: A String that will be set on the notepad at a certain page.
func notePad(_ notepad: NotePadView,textForPageAtIndex index: Int)->String?
}
public class NotePadView: UIView{
/// The textview which displays the text.
var textView: UITextView!
/// The label which displays the current page.
var pageLabel: UILabel!
/// The delegate of the notepad.
open var delegate: NotePadDelegate?
/// The data source of the notepad.
open var dataSource: NotePadDataSource?{ didSet{updateInterface()}}
open var pageCurlAnimationDuration: TimeInterval = 0.1
/// The current page of the notepad.
private (set) open var currentPage: Int = 0
/// The aspect ratio which determines the page curl section size
let pageCurlRatio: CGFloat = 0.1
/// Computed variable to get the page count.
var pageCount: Int {
return dataSource?.numberOfNotes(self) ?? 0
}
convenience init(){
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func draw(_ rect: CGRect) {
UIColor.black.setStroke()
getLines(rect).forEach { $0.stroke()}
}
func getLines(_ rect: CGRect)->[UIBezierPath]{
var arrayOfLines = [UIBezierPath]()
let space: CGFloat = 2
let startingPoint = rect.height - 2
for i in 0...1{
let y = startingPoint - space * CGFloat(i)
let startX = rect.minX
let endX = rect.maxX
let path = UIBezierPath()
path.move(to: CGPoint(x: startX, y: y))
path.addLine(to: CGPoint(x: endX, y: y))
path.lineWidth = 1
arrayOfLines.append(path)
}
let specialPath = UIBezierPath()
let specialY: CGFloat = startingPoint - space * 2
let curlSize: CGFloat = rect.width * pageCurlRatio
specialPath.move(to: CGPoint(x: rect.maxX, y: specialY))
specialPath.addLine(to: CGPoint(x: curlSize, y: specialY))
specialPath.addLine(to: CGPoint(x: 0, y: specialY - curlSize))
specialPath.addLine(to: CGPoint(x: curlSize ,y: specialY - curlSize))
specialPath.addLine(to: CGPoint(x: curlSize, y: specialY))
specialPath.lineWidth = 1
arrayOfLines.append(specialPath)
return arrayOfLines
}
/// Primary setup function of the view.
func setup(){
layer.masksToBounds = true
textView = UITextView()
textView.font = SystemSettings.notePadFont
textView.tintColor = .black
textView.backgroundColor = .clear
textView.delegate = self
addSubview(textView)
pageLabel = UILabel()
pageLabel.font = SystemSettings.notePadFont
addSubview(pageLabel)
pageLabel.translatesAutoresizingMaskIntoConstraints = false
pageLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
textView.translatesAutoresizingMaskIntoConstraints = false
textView.topAnchor.constraint(equalTo: topAnchor).isActive = true
textView.bottomAnchor.constraint(equalTo: pageLabel.topAnchor, constant: -8).isActive = true
textView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
textView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))))
}
override public func didMoveToSuperview() {
//setup bottom anchor when view is moved to superview. This is done here because in the setup the view frame size is still 0.
pageLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -(frame.size.width * pageCurlRatio)/2).isActive = true
}
/// Handle Tap is a targer function that handles the tap gesture recognizer that is set on the view.
///
/// - Parameter sender: The Tap Gesture Recognizer
func handleTap(sender: UITapGestureRecognizer){
//declare function that checks if point is within 3 points
func isPointInTriangle(point: CGPoint,
a:CGPoint,
b:CGPoint,
c:CGPoint)->Bool{
let as_x: CGFloat = point.x - a.x
let as_y: CGFloat = point.y - a.y
let s_ab: Bool = (b.x-a.x) * as_y - (b.y-a.y) * as_x > 0
if((c.x - a.x) * as_y - (c.y - a.y) * as_x > 0) == s_ab {return false}
if((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x) > 0) != s_ab {return false}
return true
}
//touch location
let point = sender.location(in: self)
//declare the area rect of the page curl
let scaleSize = self.bounds.width * pageCurlRatio
let areaOfSelection = CGRect(x: 0,
y: self.bounds.maxY - scaleSize - 6,
width: scaleSize,
height: scaleSize)
//check if touch point is on page curl
if areaOfSelection.contains(point){
let startScale: CGAffineTransform
let endScale: CGAffineTransform
let startCenter: CGPoint
let endCenter: CGPoint
let forward: Bool
let oldIndex = currentPage
//check if touch point is in the lower triangle or the upper triangle
if isPointInTriangle(point: point,
a: CGPoint(x: areaOfSelection.minX,y:areaOfSelection.minY),
b: CGPoint(x: areaOfSelection.minX,y:areaOfSelection.maxY),
c: CGPoint(x: areaOfSelection.maxX,y:areaOfSelection.maxY)){
//go backward
goBackward()
startScale = CGAffineTransform(scaleX: 0.1, y: 0.1)
endScale = .identity
startCenter = CGPoint(x: self.bounds.maxX, y: self.bounds.minY)
endCenter = self.center
forward = false
}else{
//go forward
goForward()
startScale = CGAffineTransform(scaleX: 0.9, y: 0.9)
endScale = CGAffineTransform(scaleX: 0.1, y: 0.1)
startCenter = self.center
endCenter = CGPoint(x: self.bounds.maxX, y: self.bounds.minY)
forward = true
}
//animate page curl
let view = DummyNotePad(frame: self.frame)
view.textView.frame = textView.frame
view.pageLabel.frame = pageLabel.frame
view.textView.text = dataSource?.notePad(self, textForPageAtIndex: (forward ? oldIndex : currentPage))
view.textView.isEditable = false
view.pageLabel.text = "\((forward ? oldIndex : currentPage) + 1)"
view.backgroundColor = .white
self.addSubview(view)
view.center = startCenter
view.transform = startScale
UIView.animate(withDuration: pageCurlAnimationDuration, animations: {
view.center = endCenter
view.transform = endScale
}, completion: {(complete) in
if !forward{
self.updateInterface()
self.delegate?.notePad(self, didChangePageTo: self.currentPage)
}
view.removeFromSuperview()
})
if forward {
self.updateInterface()
self.delegate?.notePad(self, didChangePageTo: self.currentPage)
}
}
}
/// This function updates the interface, it updates the current page label and the current display text.
open func updateInterface(){
self.pageLabel.text = "\(currentPage+1)"
self.textView.text = dataSource?.notePad(self, textForPageAtIndex: currentPage) ?? ""
}
/// Function updates the current page to move forward. If the next page is "greater" than the amount of pages in the notepad then the current page will be set to 0.
func goForward(){
if currentPage + 1 > pageCount - 1{
currentPage = 0
}else{
currentPage += 1
}
}
/// Function updates the current page to move backward. If the next page is "less" than 0 (negative value), then the current page will be set to the max amount of pages.
func goBackward(){
if currentPage - 1 < 0 {
currentPage = pageCount - 1
}else{
currentPage -= 1
}
}
}
class DummyNotePad: UIView{
/// The textview which displays the text.
open var textView: UITextView!
/// The label which displays the current page.
open var pageLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
let borderLayer = CAShapeLayer()
borderLayer.frame = bounds
borderLayer.path = getShapePath(frame).cgPath
layer.mask = borderLayer
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(){
backgroundColor = .red
textView = UITextView()
textView = UITextView()
textView.font = SystemSettings.notePadFont
textView.tintColor = .black
textView.backgroundColor = .clear
addSubview(textView)
pageLabel = UILabel()
pageLabel.font = SystemSettings.notePadFont
addSubview(pageLabel)
}
override func draw(_ rect: CGRect) {
UIColor.white.setFill()
getShapePath(rect).fill()
UIColor.black.setStroke()
getLine(rect).stroke()
let space: CGFloat = 2
let startingPoint = rect.height - 2
let specialY: CGFloat = startingPoint - space * 2
let curlSize: CGFloat = rect.width * pageCurlRatio
let path = UIBezierPath()
path.move(to: CGPoint(x: 0,y:0))
path.addLine(to: CGPoint(x: 0 ,y: specialY - curlSize))
path.lineWidth = 1
path.stroke()
}
let pageCurlRatio: CGFloat = 0.3
let space: CGFloat = 2
//get the path of the shape needed
func getShapePath(_ rect: CGRect)-> UIBezierPath{
let startingPoint = rect.height - 2
let shapePath = UIBezierPath()
let specialY: CGFloat = startingPoint - space * 2
let curlSize: CGFloat = rect.width * pageCurlRatio
shapePath.move(to: CGPoint(x: rect.maxX, y: specialY))
shapePath.addLine(to: CGPoint(x: curlSize, y: specialY))
shapePath.addLine(to: CGPoint(x: 0, y: specialY - curlSize))
shapePath.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
shapePath.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
shapePath.close()
return shapePath
}
//get the lines to draw
func getLine(_ rect: CGRect)->UIBezierPath{
let startingPoint = rect.height - 2
let specialPath = UIBezierPath()
let specialY: CGFloat = startingPoint - space * 2
let curlSize: CGFloat = rect.width * pageCurlRatio
specialPath.move(to: CGPoint(x: rect.maxX, y: specialY))
specialPath.addLine(to: CGPoint(x: curlSize, y: specialY))
specialPath.addLine(to: CGPoint(x: 0, y: specialY - curlSize))
specialPath.addLine(to: CGPoint(x: curlSize ,y: specialY - curlSize))
specialPath.addLine(to: CGPoint(x: curlSize, y: specialY))
specialPath.lineWidth = 1
return specialPath
}
}
extension NotePadView: UITextViewDelegate{
public func textViewDidChange(_ textView: UITextView) {
self.delegate?.notePad(self, didChangeText: textView.text, atIndex: currentPage)
}
}
| 94069a9da8637ca2b5440c21b74250e1 | 33.939866 | 173 | 0.59383 | false | false | false | false |
AblePear/Peary | refs/heads/master | Peary/sockaddr_in6.swift | bsd-2-clause | 1 | import Foundation
import Darwin.POSIX.netinet.`in`
/* IP v6 socket address.
See [RFC 2553: Basic Socket Interface Extensions for IPv6](http://www.ietf.org/rfc/rfc2553.txt),
[RFC 2373: IP Version 6 Addressing Architecture](http://www.ietf.org/rfc/rfc2373.txt),
[RFC 5952: A Recommendation for IPv6 Address Text Representation](https://tools.ietf.org/rfc/rfc5952.txt) and
[RFC 3986: Uniform Resource Identifier (URI): Generic Syntax](https://tools.ietf.org/rfc/rfc3986.txt)
for background information.
*/
extension sockaddr_in6: SocketAddress {
public static func ==(first: sockaddr_in6, second: sockaddr_in6) -> Bool {
return first.isValid
&& second.isValid
&& first.sin6_port == second.sin6_port
&& first.sin6_addr == second.sin6_addr
}
public init(address: in6_addr, port: in_port_t) {
self.init(sin6_len: UInt8(MemoryLayout<sockaddr_in6>.size),
sin6_family: sa_family_t(AF_INET6),
sin6_port: in_port_t(port: port),
sin6_flowinfo: 0,
sin6_addr: address,
sin6_scope_id: 0)
}
public init?(_ address: String, port: in_port_t) {
guard let address = in6_addr(address) else {
return nil
}
self.init(address: address, port: port)
}
public init(_ storage: sockaddr_storage) {
precondition(sa_family_t(AF_INET6) == storage.ss_family)
var copy = storage
let (address, port) = withUnsafePointer(to: ©) {
return $0.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {
return ($0.pointee.sin6_addr, $0.pointee.port)
}
}
self.init(address: address, port: port)
}
public var description: String {
return "[\(sin6_addr)]:\(port)"
}
public var isValid: Bool {
return sin6_family == sa_family_t(AF_INET6)
&& sin6_len >= UInt8(MemoryLayout<sockaddr_in6>.size)
}
public var length: socklen_t {
return socklen_t(sin6_len)
}
public var address: in6_addr {
get {
return sin6_addr
}
set {
sin6_addr = newValue
}
}
public var port: in_port_t {
get {
return sin6_port.networkToHostByteOrder
}
set {
sin6_port = newValue.hostToNetworkByteOrder
}
}
}
| c4a46bbcaeaa8892a05dde1add57b83f | 30.512821 | 110 | 0.575264 | false | false | false | false |
borglab/SwiftFusion | refs/heads/main | Sources/SwiftFusion/Inference/BearingRangeFactor.swift | apache-2.0 | 1 | // Copyright 2020 The SwiftFusion Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import _Differentiation
import TensorFlow
import PenguinStructures
/// A `NonlinearFactor` that calculates the bearing and range error of one pose and one landmark
///
public struct BearingRangeFactor2 : LinearizableFactor2 {
public typealias Base = Pose2
public typealias Target = Vector2
public typealias Bearing = Rot2
public let edges: Variables.Indices
public let bearingMeas: Bearing
public let rangeMeas: Double
public init(_ baseId: TypedID<Base>, _ targetId: TypedID<Target>, _ bearingMeas: Bearing, _ rangeMeas: Double) {
self.edges = Tuple2(baseId, targetId)
self.bearingMeas = bearingMeas
self.rangeMeas = rangeMeas
}
public typealias Variables = Tuple2<Base, Target>
@differentiable
public func errorVector(_ base: Base, _ target: Target) -> Vector2 {
let dx = (target - base.t)
let actual_bearing = between(Rot2(c: dx.x / dx.norm, s: dx.y / dx.norm), base.rot)
let actual_range = dx.norm
let error_range = (actual_range - rangeMeas)
let error_bearing = between(actual_bearing, bearingMeas)
return Vector2(error_bearing.theta, error_range)
}
}
| 8a3056e4788adf22ddb8f980d5f9d941 | 35.458333 | 114 | 0.732 | false | false | false | false |
ivlevAstef/DITranquillity | refs/heads/master | Sources/Core/Internal/threads/Multithread.swift | mit | 1 | //
// Multithread.swift
// DITranquillity
//
// Created by Alexander Ivlev on 02.05.2018.
// Copyright © 2018 Alexander Ivlev. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
/// taken from: https://github.com/mattgallagher/CwlUtils/blob/master/Sources/CwlUtils/CwlMutex.swift?ts=3
final class PThreadMutex {
private var unsafeMutex = pthread_mutex_t()
convenience init(normal: ()) {
self.init(type: Int32(PTHREAD_MUTEX_NORMAL))
}
convenience init(recursive: ()) {
self.init(type: Int32(PTHREAD_MUTEX_RECURSIVE))
}
private init(type: Int32) {
var attr = pthread_mutexattr_t()
guard pthread_mutexattr_init(&attr) == 0 else {
preconditionFailure()
}
pthread_mutexattr_settype(&attr, type)
guard pthread_mutex_init(&unsafeMutex, &attr) == 0 else {
preconditionFailure()
}
}
deinit {
pthread_mutex_destroy(&unsafeMutex)
}
func sync<R>(execute: () -> R) -> R {
if DISetting.Defaults.multiThread {
pthread_mutex_lock(&unsafeMutex)
let result = execute()
pthread_mutex_unlock(&unsafeMutex)
return result
} else {
return execute()
}
}
}
| 85b6e47891782233326d9b6e92d9d59f | 22.943396 | 106 | 0.614657 | false | false | false | false |
dhanvi/firefox-ios | refs/heads/master | Sync/StorageClient.swift | mpl-2.0 | 1 | /* 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 Alamofire
import Shared
import Account
import XCGLogger
private let log = Logger.syncLogger
// Not an error that indicates a server problem, but merely an
// error that encloses a StorageResponse.
public class StorageResponseError<T>: MaybeErrorType {
public let response: StorageResponse<T>
public init(_ response: StorageResponse<T>) {
self.response = response
}
public var description: String {
return "Error."
}
}
public class RequestError: MaybeErrorType {
public var description: String {
return "Request error."
}
}
public class BadRequestError<T>: StorageResponseError<T> {
public let request: NSURLRequest?
public init(request: NSURLRequest?, response: StorageResponse<T>) {
self.request = request
super.init(response)
}
override public var description: String {
return "Bad request."
}
}
public class ServerError<T>: StorageResponseError<T> {
override public var description: String {
return "Server error."
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class NotFound<T>: StorageResponseError<T> {
override public var description: String {
return "Not found. (\(T.self))"
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class RecordParseError: MaybeErrorType {
public var description: String {
return "Failed to parse record."
}
}
public class MalformedMetaGlobalError: MaybeErrorType {
public var description: String {
return "Supplied meta/global for upload did not serialize to valid JSON."
}
}
/**
* Raised when the storage client is refusing to make a request due to a known
* server backoff.
* If you want to bypass this, remove the backoff from the BackoffStorage that
* the storage client is using.
*/
public class ServerInBackoffError: MaybeErrorType {
private let until: Timestamp
public var description: String {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
let s = formatter.stringFromDate(NSDate.fromTimestamp(self.until))
return "Server in backoff until \(s)."
}
public init(until: Timestamp) {
self.until = until
}
}
// Returns milliseconds. Handles decimals.
private func optionalSecondsHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
if let timestamp = decimalSecondsStringToTimestamp(val) {
return timestamp
}
}
if let seconds: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(seconds * 1000)
}
if let seconds: NSNumber = input as? NSNumber {
// Who knows.
return seconds.unsignedLongLongValue * 1000
}
return nil
}
private func optionalIntegerHeader(input: AnyObject?) -> Int64? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Int64(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.longLongValue
}
return nil
}
private func optionalUIntegerHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanUnsignedLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.unsignedLongLongValue
}
return nil
}
public enum SortOption: String {
case Newest = "newest"
case Index = "index"
}
public struct ResponseMetadata {
public let status: Int
public let alert: String?
public let nextOffset: String?
public let records: UInt64?
public let quotaRemaining: Int64?
public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request.
public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp.
public let backoffMilliseconds: UInt64?
public let retryAfterMilliseconds: UInt64?
public init(response: NSHTTPURLResponse) {
self.init(status: response.statusCode, headers: response.allHeaderFields)
}
init(status: Int, headers: [NSObject : AnyObject]) {
self.status = status
alert = headers["X-Weave-Alert"] as? String
nextOffset = headers["X-Weave-Next-Offset"] as? String
records = optionalUIntegerHeader(headers["X-Weave-Records"])
quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"])
timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"]) ?? 0
lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"])
backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"]) ??
optionalSecondsHeader(headers["X-Backoff"])
retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"])
}
}
public struct StorageResponse<T> {
public let value: T
public let metadata: ResponseMetadata
init(value: T, metadata: ResponseMetadata) {
self.value = value
self.metadata = metadata
}
init(value: T, response: NSHTTPURLResponse) {
self.value = value
self.metadata = ResponseMetadata(response: response)
}
}
public struct POSTResult {
public let modified: Timestamp
public let success: [GUID]
public let failed: [GUID: [String]]
public static func fromJSON(json: JSON) -> POSTResult? {
if json.isError {
return nil
}
if let mDecimalSeconds = json["modified"].asDouble,
let s = json["success"].asArray,
let f = json["failed"].asDictionary {
var failed = false
let asStringOrFail: JSON -> String = { $0.asString ?? { failed = true; return "" }() }
let asArrOrFail: JSON -> [String] = { $0.asArray?.map(asStringOrFail) ?? { failed = true; return [] }() }
// That's the basic structure. Now let's transform the contents.
let successGUIDs = s.map(asStringOrFail)
if failed {
return nil
}
let failedGUIDs = mapValues(f, f: asArrOrFail)
if failed {
return nil
}
let msec = Timestamp(1000 * mDecimalSeconds)
return POSTResult(modified: msec, success: successGUIDs, failed: failedGUIDs)
}
return nil
}
}
public typealias Authorizer = (NSMutableURLRequest) -> NSMutableURLRequest
public typealias ResponseHandler = (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void
// TODO: don't be so naïve. Use a combination of uptime and wall clock time.
public protocol BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp? { get set }
func clearServerBackoff()
func isInBackoff(now: Timestamp) -> Timestamp? // Returns 'until' for convenience.
}
// Don't forget to batch downloads.
public class Sync15StorageClient {
private let authorizer: Authorizer
private let serverURI: NSURL
var backoff: BackoffStorage
let workQueue: dispatch_queue_t
let resultQueue: dispatch_queue_t
public init(token: TokenServerToken, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
// This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain.
self.serverURI = NSURL(string: token.api_endpoint)!
self.authorizer = {
(r: NSMutableURLRequest) -> NSMutableURLRequest in
let helper = HawkHelper(id: token.id, key: token.key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
r.setValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization")
return r
}
}
public init(serverURI: NSURL, authorizer: Authorizer, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.serverURI = serverURI
self.authorizer = authorizer
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
}
func updateBackoffFromResponse<T>(response: StorageResponse<T>) {
// N.B., we would not have made this request if a backoff were set, so
// we can safely avoid doing the write if there's no backoff in the
// response.
// This logic will have to change if we ever invalidate that assumption.
if let ms = response.metadata.backoffMilliseconds ?? response.metadata.retryAfterMilliseconds {
log.info("Backing off for \(ms)ms.")
self.backoff.serverBackoffUntilLocalTimestamp = ms + NSDate.now()
}
}
func errorWrap<T>(deferred: Deferred<Maybe<T>>, handler: ResponseHandler) -> ResponseHandler {
return { (request, response, result) in
log.verbose("Response is \(response).")
/**
* Returns true if handled.
*/
func failFromResponse(response: NSHTTPURLResponse?) -> Bool {
guard let response = response else {
// TODO: better error.
log.error("No response")
let result = Maybe<T>(failure: RecordParseError())
deferred.fill(result)
return true
}
log.debug("Status code: \(response.statusCode).")
let storageResponse = StorageResponse(value: response, metadata: ResponseMetadata(response: response))
self.updateBackoffFromResponse(storageResponse)
if response.statusCode >= 500 {
log.debug("ServerError.")
let result = Maybe<T>(failure: ServerError(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode == 404 {
log.debug("NotFound<\(T.self)>.")
let result = Maybe<T>(failure: NotFound(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode >= 400 {
log.debug("BadRequestError.")
let result = Maybe<T>(failure: BadRequestError(request: request, response: storageResponse))
deferred.fill(result)
return true
}
return false
}
// Check for an error from the request processor.
if result.isFailure {
log.error("Response: \(response?.statusCode ?? 0). Got error \(result.error).")
// If we got one, we don't want to hit the response nil case above and
// return a RecordParseError, because a RequestError is more fitting.
if let response = response {
if failFromResponse(response) {
log.error("This was a failure response. Filled specific error type.")
return
}
}
log.error("Filling generic RequestError.")
deferred.fill(Maybe<T>(failure: RequestError()))
return
}
if failFromResponse(response) {
return
}
handler(request, response, result)
}
}
lazy private var alamofire: Alamofire.Manager = {
let ua = UserAgent.syncUserAgent
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
return Alamofire.Manager.managerWithUserAgent(ua, configuration: configuration)
}()
func requestGET(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.GET.rawValue
req.setValue("application/json", forHTTPHeaderField: "Accept")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
.validate(contentType: ["application/json"])
}
func requestDELETE(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.DELETE.rawValue
req.setValue("1", forHTTPHeaderField: "X-Confirm-Delete")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
}
func requestWrite(url: NSURL, method: String, body: String, contentType: String, ifUnmodifiedSince: Timestamp?) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = method
req.setValue(contentType, forHTTPHeaderField: "Content-Type")
let authorized: NSMutableURLRequest = self.authorizer(req)
if let ifUnmodifiedSince = ifUnmodifiedSince {
req.setValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since")
}
req.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)!
return alamofire.request(authorized)
}
func requestPUT(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.PUT.rawValue, body: body.toString(false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.POST.rawValue, body: body.toString(false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: [JSON], ifUnmodifiedSince: Timestamp?) -> Request {
let body = body.map { $0.toString(false) }.joinWithSeparator("\n")
return self.requestWrite(url, method: Method.POST.rawValue, body: body, contentType: "application/newlines", ifUnmodifiedSince: ifUnmodifiedSince)
}
/**
* Returns true and fills the provided Deferred if our state shows that we're in backoff.
* Returns false otherwise.
*/
private func checkBackoff<T>(deferred: Deferred<Maybe<T>>) -> Bool {
if let until = self.backoff.isInBackoff(NSDate.now()) {
deferred.fill(Maybe<T>(failure: ServerInBackoffError(until: until)))
return true
}
return false
}
private func doOp<T>(op: (NSURL) -> Request, path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = op(self.serverURI.URLByAppendingPathComponent(path))
let handler = self.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON {
if let v = f(json) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
req.responseParsedJSON(true, completionHandler: handler)
return deferred
}
// Sync storage responds with a plain timestamp to a PUT, not with a JSON body.
private func putResource<T>(path: String, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let url = self.serverURI.URLByAppendingPathComponent(path)
return self.putResource(url, body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: parser)
}
private func putResource<T>(URL: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = self.requestPUT(URL, body: body, ifUnmodifiedSince: ifUnmodifiedSince)
let handler = self.errorWrap(deferred) { (_, response, result) in
if let data = result.value as? String {
if let v = parser(data) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
let stringHandler = { (a: NSURLRequest?, b: NSHTTPURLResponse?, c: Result<String>) in
return handler(a, b, c.isSuccess ? Result.Success(c.value!) : Result.Failure(c.data, c.error!))
}
req.responseString(encoding: nil, completionHandler: stringHandler)
return deferred
}
private func getResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestGET, path: path, f: f)
}
private func deleteResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestDELETE, path: path, f: f)
}
func getInfoCollections() -> Deferred<Maybe<StorageResponse<InfoCollections>>> {
return getResource("info/collections", f: InfoCollections.fromJSON)
}
func getMetaGlobal() -> Deferred<Maybe<StorageResponse<GlobalEnvelope>>> {
return getResource("storage/meta/global", f: { GlobalEnvelope($0) })
}
func uploadMetaGlobal(metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
let payload = metaGlobal.toPayload()
if payload.isError {
return Deferred(value: Maybe(failure: MalformedMetaGlobalError()))
}
// TODO finish this!
let record: JSON = JSON(["payload": payload, "id": "global"])
return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
func wipeStorage() -> Deferred<Maybe<StorageResponse<JSON>>> {
// In Sync 1.5 it's preferred that we delete the root, not /storage.
return deleteResource("", f: { $0 })
}
// TODO: it would be convenient to have the storage client manage Keys,
// but of course we need to use a different set of keys to fetch crypto/keys
// itself.
func clientForCollection<T: CleartextPayloadJSON>(collection: String, encrypter: RecordEncrypter<T>) -> Sync15CollectionClient<T> {
let storage = self.serverURI.URLByAppendingPathComponent("storage", isDirectory: true)
return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, encrypter: encrypter)
}
}
/**
* We'd love to nest this in the overall storage client, but Swift
* forbids the nesting of a generic class inside another class.
*/
public class Sync15CollectionClient<T: CleartextPayloadJSON> {
private let client: Sync15StorageClient
private let encrypter: RecordEncrypter<T>
private let collectionURI: NSURL
private let collectionQueue = dispatch_queue_create("com.mozilla.sync.collectionclient", DISPATCH_QUEUE_SERIAL)
init(client: Sync15StorageClient, serverURI: NSURL, collection: String, encrypter: RecordEncrypter<T>) {
self.client = client
self.encrypter = encrypter
self.collectionURI = serverURI.URLByAppendingPathComponent(collection, isDirectory: false)
}
private func uriForRecord(guid: String) -> NSURL {
return self.collectionURI.URLByAppendingPathComponent(guid)
}
public func post(records: [Record<T>], ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<POSTResult>>> {
let deferred = Deferred<Maybe<StorageResponse<POSTResult>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
// TODO: charset
// TODO: if any of these fail, we should do _something_. Right now we just ignore them.
let json = optFilter(records.map(self.encrypter.serializer))
let req = client.requestPOST(self.collectionURI, body: json, ifUnmodifiedSince: nil)
req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON,
let result = POSTResult.fromJSON(json) {
let storageResponse = StorageResponse(value: result, response: response!)
deferred.fill(Maybe(success: storageResponse))
return
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
public func put(record: Record<T>, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
if let body = self.encrypter.serializer(record) {
log.debug("Body is \(body)")
log.debug("Original record is \(record)")
return self.client.putResource(uriForRecord(record.id), body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
return deferMaybe(RecordParseError())
}
public func get(guid: String) -> Deferred<Maybe<StorageResponse<Record<T>>>> {
let deferred = Deferred<Maybe<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
let req = client.requestGET(uriForRecord(guid))
req.responsePartialParsedJSON(queue:collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON {
let envelope = EnvelopeJSON(json)
let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
if let record = record {
let storageResponse = StorageResponse(value: record, response: response!)
deferred.fill(Maybe(success: storageResponse))
return
}
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
/**
* Unlike every other Sync client, we use the application/json format for fetching
* multiple requests. The others use application/newlines. We don't want to write
* another Serializer, and we're loading everything into memory anyway.
*/
public func getSince(since: Timestamp, sort: SortOption?=nil, limit: Int?=nil, offset: String?=nil) -> Deferred<Maybe<StorageResponse<[Record<T>]>>> {
let deferred = Deferred<Maybe<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue)
// Fills the Deferred for us.
if self.client.checkBackoff(deferred) {
return deferred
}
var params: [NSURLQueryItem] = [
NSURLQueryItem(name: "full", value: "1"),
NSURLQueryItem(name: "newer", value: millisecondsToDecimalSeconds(since)),
]
if let offset = offset {
params.append(NSURLQueryItem(name: "offset", value: offset))
}
if let limit = limit {
params.append(NSURLQueryItem(name: "limit", value: "\(limit)"))
}
if let sort = sort {
params.append(NSURLQueryItem(name: "sort", value: sort.rawValue))
}
log.debug("Issuing GET with newer = \(since).")
let req = client.requestGET(self.collectionURI.withQueryParams(params))
req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
log.debug("Response is \(response).")
guard let json: JSON = result.value as? JSON else {
log.warning("Non-JSON response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
guard let arr = json.asArray else {
log.warning("Non-array response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
func recordify(json: JSON) -> Record<T>? {
let envelope = EnvelopeJSON(json)
return Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
}
let records = optFilter(arr.map(recordify))
let response = StorageResponse(value: records, response: response!)
deferred.fill(Maybe(success: response))
})
return deferred
}
}
| e074a40d0ab27ede301b451581b177cd | 36.744928 | 180 | 0.634081 | false | false | false | false |
cardstream/iOS-SDK | refs/heads/master | MSFramework/Common/CryptoSwift/CryptoSwift-0.7.2/Tests/CryptoSwiftTests/ExtensionsTest.swift | gpl-3.0 | 2 | //
// ExtensionsTest.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 15/08/14.
// Copyright (C) 2014-2017 Krzyzanowski. All rights reserved.
//
import XCTest
import Foundation
@testable import CryptoSwift
final class ExtensionsTest: XCTestCase {
func testBytes() {
let size = MemoryLayout<UInt32>.size // 32 or 64 bit
let i: UInt32 = 1024
var bytes = i.bytes()
XCTAssertTrue(bytes.count == size, "Invalid bytes length = \(bytes.count)")
// test padding
bytes = i.bytes(totalBytes: 16)
XCTAssertTrue(bytes.count == 16, "Invalid return type \(bytes.count)")
XCTAssertTrue(bytes[14] == 4, "Invalid return type \(bytes.count)")
}
func testToUInt32Array() {
let chunk: ArraySlice<UInt8> = [1, 1, 1, 7, 2, 3, 4, 5]
let result = chunk.toUInt32Array()
XCTAssert(result.count == 2, "Invalid conversion")
XCTAssert(result[0] == 117_506_305, "Invalid conversion")
XCTAssert(result[1] == 84_148_994, "Invalid conversion")
}
func testDataInit() {
let data = Data(bytes: [0x01, 0x02, 0x03])
XCTAssert(data.count == 3, "Invalid data")
}
func testStringEncrypt() {
do {
let encryptedHex = try "my secret string".encrypt(cipher: AES(key: "secret0key000000", iv: "0123456789012345"))
XCTAssertEqual(encryptedHex, "68f7ff8bdb61f625febdfe3d791ecf624daaed2e719a6de39112de8e0cc7349b")
} catch {
XCTFail(error.localizedDescription)
}
}
func testEmptyStringEncrypt() {
do {
let cipher = try AES(key: Array("secret0key000000".utf8).md5(), iv: Array("secret0key000000".utf8).md5(), blockMode: .ECB)
let encrypted = try "".encryptToBase64(cipher: cipher)
let decrypted = try encrypted?.decryptBase64ToString(cipher: cipher)
XCTAssertEqual("", decrypted)
XCTAssertThrowsError(try "".decryptBase64(cipher: cipher))
} catch {
XCTFail(error.localizedDescription)
}
}
func testStringDecryptBase64() {
let encryptedBase64 = "aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs="
let decrypted = try! encryptedBase64.decryptBase64ToString(cipher: AES(key: "secret0key000000", iv: "0123456789012345"))
XCTAssertEqual(decrypted, "my secret string")
}
func testArrayInitHex() {
let bytes = Array<UInt8>(hex: "0xb1b1b2b2")
XCTAssertEqual(bytes, [177, 177, 178, 178])
let str = "b1b2b3b3b3b3b3b3b1b2b3b3b3b3b3b3"
let array = Array<UInt8>(hex: str)
let hex = array.toHexString()
XCTAssertEqual(str, hex)
}
}
#if !CI
extension ExtensionsTest {
func testArrayChunksPerformance() {
measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: false, for: { () -> Void in
let message = Array<UInt8>(repeating: 7, count: 1024 * 1024)
self.startMeasuring()
_ = message.chunks(size: AES.blockSize)
self.stopMeasuring()
})
}
func testArrayInitHexPerformance() {
var str = "b1b2b3b3b3b3b3b3b1b2b3b3b3b3b3b3"
for _ in 0...12 {
str += str
}
measure {
_ = Array<UInt8>(hex: str)
}
}
}
#endif
extension ExtensionsTest {
static func allTests() -> [(String, (ExtensionsTest) -> () -> Void)] {
var tests = [
("testBytes", testBytes),
("testToUInt32Array", testToUInt32Array),
("testDataInit", testDataInit),
("testStringEncrypt", testStringEncrypt),
("testStringDecryptBase64", testStringDecryptBase64),
("testEmptyStringEncrypt", testEmptyStringEncrypt),
("testArrayInitHex", testArrayInitHex),
]
#if !CI
tests += [
("testArrayChunksPerformance", testArrayChunksPerformance),
("testArrayInitHexPerformance", testArrayInitHexPerformance)
]
#endif
return tests
}
}
| f3c7a95ddfb362d3493131f66b98ca1b | 31.858268 | 134 | 0.600048 | false | true | false | false |
dtop/SwiftValidate | refs/heads/master | validate/Validators/ValidatorCharset.swift | mit | 1 | //
// ValidatorCharset.swift
// SwiftValidate
//
// Created by Danilo Topalovic on 27.12.15.
// Copyright © 2015 Danilo Topalovic. All rights reserved.
//
import Foundation
public class ValidatorCharset: BaseValidator, ValidatorProtocol {
/// allow nil values
public var allowNil: Bool = true
/// allow only ascii chars
public var allowEmpty: Bool = false
// the charset to validate against
public var charset: CharacterSet!
/// error message not alnum
public var errorMessageStringDoesNotFit: String = NSLocalizedString("The String contains illegal characters", comment: "ValidatorCharset - String not alnum")
/**
Easy init
- returns: the instance
*/
public required init( _ initializer: (ValidatorCharset) -> () = { _ in }) {
super.init()
initializer(self)
}
/**
Validates the given string against the given charset
- parameter value: the value to match
- parameter context: the context
- throws: validation errors
- returns: true if ok
*/
public override func validate<T: Any>(_ value: T?, context: [String: Any?]?) throws -> Bool {
// reset errors
self.emptyErrors()
if nil == self.charset {
throw NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "no chaset given"])
}
if self.allowNil && nil == value {
return true
}
if let strVal = value as? String {
if self.allowEmpty && strVal.isEmpty {
return true
}
if let _ = strVal.rangeOfCharacter(from: self.charset.inverted) {
return self.returnError(error: self.errorMessageStringDoesNotFit)
}
return true
}
throw NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Unable to validate chars in string incompatible value"])
}
}
| fef8e67a4807ccf739495fc0aef9f5f9 | 26.84 | 161 | 0.573755 | false | false | false | false |
brunophilipe/Noto | refs/heads/master | Noto/Views/WindowDragHandleView.swift | gpl-3.0 | 1 | //
// WindowDragHandleView.swift
// Noto
//
// Created by Bruno Philipe on 11/7/17.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
import Cocoa
// Inheriting from a concrete NSControl was the only hack I found to get mouse events that wouldn't be overriden by NSTextView.
class WindowDragHandleView: NSTextField
{
private var trackingArea: NSTrackingArea? = nil
override func viewDidMoveToWindow()
{
super.viewDidMoveToWindow()
translatesAutoresizingMaskIntoConstraints = false
isEnabled = false
isBordered = false
drawsBackground = true
alphaValue = 0.0
}
override var isOpaque: Bool
{
return false
}
override func updateTrackingAreas()
{
if let trackingArea = self.trackingArea
{
removeTrackingArea(trackingArea)
}
let trackingArea = NSTrackingArea(rect: bounds,
options: [.activeAlways, .enabledDuringMouseDrag, .mouseEnteredAndExited],
owner: self,
userInfo: nil)
addTrackingArea(trackingArea)
self.trackingArea = trackingArea
super.updateTrackingAreas()
}
override func resetCursorRects()
{
addCursorRect(bounds, cursor: .crosshair)
}
override func mouseEntered(with event: NSEvent)
{
super.mouseEntered(with: event)
if !isHidden
{
animator().alphaValue = 1.0
}
}
override func mouseExited(with event: NSEvent)
{
super.mouseExited(with: event)
if !isHidden
{
animator().alphaValue = 0.0
}
}
}
| adb3c134700f1a04f36aed50e842622c | 19.146667 | 127 | 0.680344 | false | false | false | false |
dleonard00/firebase-user-signup | refs/heads/master | Pods/Material/Sources/NavigationController.swift | mit | 1 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public class NavigationController : UINavigationController, UIGestureRecognizerDelegate {
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with an Optional nib and bundle.
- Parameter nibNameOrNil: An Optional String for the nib.
- Parameter bundle: An Optional NSBundle where the nib is located.
*/
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
An initializer that initializes the object with a rootViewController.
- Parameter rootViewController: A UIViewController for the rootViewController.
*/
public override init(rootViewController: UIViewController) {
super.init(navigationBarClass: NavigationBar.self, toolbarClass: nil)
setViewControllers([rootViewController], animated: false)
}
public override func viewDidLoad() {
super.viewDidLoad()
// This ensures the panning gesture is available when going back between views.
if let v: UIGestureRecognizer = interactivePopGestureRecognizer {
v.enabled = true
v.delegate = self
}
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let v: UIGestureRecognizer = interactivePopGestureRecognizer {
if let x: SideNavigationViewController = sideNavigationViewController {
if let p: UIPanGestureRecognizer = x.panGesture {
p.requireGestureRecognizerToFail(v)
}
}
}
}
/**
Detects the gesture recognizer being used. This is necessary when using
SideNavigationViewController. It eliminates the conflict in panning.
- Parameter gestureRecognizer: A UIGestureRecognizer to detect.
- Parameter touch: The UITouch event.
- Returns: A Boolean of whether to continue the gesture or not, true yes, false no.
*/
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
return interactivePopGestureRecognizer == gestureRecognizer && nil != navigationBar.backItem
}
/**
Delegation method that is called when a new UINavigationItem is about to be pushed.
This is used to prepare the transitions between UIViewControllers on the stack.
- Parameter navigationBar: A UINavigationBar that is used in the NavigationController.
- Parameter item: The UINavigationItem that will be pushed on the stack.
- Returns: A Boolean value that indicates whether to push the item on to the stack or not.
True is yes, false is no.
*/
public func navigationBar(navigationBar: UINavigationBar, shouldPushItem item: UINavigationItem) -> Bool {
if let v: NavigationBar = navigationBar as? NavigationBar {
item.setHidesBackButton(true, animated: false)
if var c: Array<UIControl> = item.leftControls {
c.append(v.backButton)
item.leftControls = c
} else {
item.leftControls = [v.backButton]
}
v.backButton.removeTarget(self, action: "handleBackButton", forControlEvents: .TouchUpInside)
v.backButton.addTarget(self, action: "handleBackButton", forControlEvents: .TouchUpInside)
v.layoutNavigationItem(item)
}
return true
}
public func sideNavigationStatusBarHiddenState(sideNavigationViewController: SideNavigationViewController, hidden: Bool) {
print(hidden)
}
/// Handler for the back button.
internal func handleBackButton() {
popViewControllerAnimated(true)
}
}
| c15245989a9570f9d7fa7037ea2c8599 | 40.290323 | 123 | 0.772461 | false | false | false | false |
gribozavr/swift | refs/heads/master | benchmark/Package.swift | apache-2.0 | 3 | // swift-tools-version:5.0
import PackageDescription
import Foundation
var unsupportedTests: Set<String> = []
#if !os(macOS) && !os(iOS) && !os(watchOS) && !os(tvOS)
unsupportedTests.insert("ObjectiveCNoBridgingStubs")
unsupportedTests.insert("ObjectiveCBridging")
unsupportedTests.insert("ObjectiveCBridgingStubs")
#endif
//===---
// Single Source Libraries
//
/// Return the source files in subDirectory that we will translate into
/// libraries. Each source library will be compiled as its own module.
func getSingleSourceLibraries(subDirectory: String) -> [String] {
let f = FileManager.`default`
let dirURL = URL(fileURLWithPath: subDirectory)
let fileURLs = try! f.contentsOfDirectory(at: dirURL,
includingPropertiesForKeys: nil)
return fileURLs.compactMap { (path: URL) -> String? in
let c = path.lastPathComponent.split(separator: ".")
// Too many components. Must be a gyb file.
if c.count > 2 {
return nil
}
if c[1] != "swift" {
return nil
}
let name = String(c[0])
// We do not support this test.
if unsupportedTests.contains(name) {
return nil
}
return name
}
}
var singleSourceLibraryDirs: [String] = []
singleSourceLibraryDirs.append("single-source")
var singleSourceLibraries: [String] = singleSourceLibraryDirs.flatMap {
getSingleSourceLibraries(subDirectory: $0)
}
//===---
// Multi Source Libraries
//
func getMultiSourceLibraries(subDirectory: String) -> [(String, String)] {
let f = FileManager.`default`
let dirURL = URL(string: subDirectory)!
let subDirs = try! f.contentsOfDirectory(at: dirURL, includingPropertiesForKeys: nil)
return subDirs.map { (subDirectory, $0.lastPathComponent) }
}
var multiSourceLibraryDirs: [String] = []
multiSourceLibraryDirs.append("multi-source")
var multiSourceLibraries: [(parentSubDir: String, name: String)] = multiSourceLibraryDirs.flatMap {
getMultiSourceLibraries(subDirectory: $0)
}
//===---
// Products
//
var products: [Product] = []
products.append(.library(name: "TestsUtils", type: .static, targets: ["TestsUtils"]))
products.append(.library(name: "DriverUtils", type: .static, targets: ["DriverUtils"]))
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
products.append(.library(name: "ObjectiveCTests", type: .static, targets: ["ObjectiveCTests"]))
#endif
products.append(.executable(name: "SwiftBench", targets: ["SwiftBench"]))
products += singleSourceLibraries.map { .library(name: $0, type: .static, targets: [$0]) }
products += multiSourceLibraries.map {
return .library(name: $0.name, type: .static, targets: [$0.name])
}
//===---
// Targets
//
var targets: [Target] = []
targets.append(.target(name: "TestsUtils", path: "utils", sources: ["TestsUtils.swift"]))
targets.append(.systemLibrary(name: "LibProc", path: "utils/LibProc"))
targets.append(
.target(name: "DriverUtils",
dependencies: [.target(name: "TestsUtils"), "LibProc"],
path: "utils",
sources: ["DriverUtils.swift", "ArgParse.swift"]))
var swiftBenchDeps: [Target.Dependency] = [.target(name: "TestsUtils")]
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
swiftBenchDeps.append(.target(name: "ObjectiveCTests"))
#endif
swiftBenchDeps.append(.target(name: "DriverUtils"))
swiftBenchDeps += singleSourceLibraries.map { .target(name: $0) }
swiftBenchDeps += multiSourceLibraries.map { .target(name: $0.name) }
targets.append(
.target(name: "SwiftBench",
dependencies: swiftBenchDeps,
path: "utils",
sources: ["main.swift"]))
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
targets.append(
.target(name: "ObjectiveCTests",
path: "utils/ObjectiveCTests",
publicHeadersPath: "."))
#endif
var singleSourceDeps: [Target.Dependency] = [.target(name: "TestsUtils")]
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
singleSourceDeps.append(.target(name: "ObjectiveCTests"))
#endif
targets += singleSourceLibraries.map { name in
if name == "ObjectiveCNoBridgingStubs" {
return .target(
name: name,
dependencies: singleSourceDeps,
path: "single-source",
sources: ["\(name).swift"],
swiftSettings: [.unsafeFlags(["-Xfrontend",
"-disable-swift-bridge-attr"])])
}
return .target(name: name,
dependencies: singleSourceDeps,
path: "single-source",
sources: ["\(name).swift"])
}
targets += multiSourceLibraries.map { lib in
return .target(
name: lib.name,
dependencies: [
.target(name: "TestsUtils")
],
path: lib.parentSubDir)
}
//===---
// Top Level Definition
//
let p = Package(
name: "swiftbench",
products: products,
targets: targets,
swiftLanguageVersions: [.v4]
)
| fa60c91e167301cf0ea5e24a16fa4d8b | 28.5375 | 99 | 0.677952 | false | true | false | false |
ioscreator/ioscreator | refs/heads/master | IOSAttributedStrings/IOSAttributedStrings/ViewController.swift | mit | 1 | //
// ViewController.swift
// IOSAttributedStrings
//
// Created by Arthur Knopper on 17/02/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var attributedLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// 1
let string = "Testing Attributed Strings"
let attributedString = NSMutableAttributedString(string: string)
// 2
let firstAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.blue,
.backgroundColor: UIColor.yellow,
.underlineStyle: 1]
let secondAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.red,
.backgroundColor: UIColor.blue,
.strikethroughStyle: 1]
let thirdAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.green,
.backgroundColor: UIColor.black,
.font: UIFont.systemFont(ofSize: 40)]
// 3
attributedString.addAttributes(firstAttributes, range: NSRange(location: 0, length: 8))
attributedString.addAttributes(secondAttributes, range: NSRange(location: 8, length: 11))
attributedString.addAttributes(thirdAttributes, range: NSRange(location: 19, length: 7))
// 4
attributedLabel.attributedText = attributedString
}
}
| f85d1d4751013e59bb87aac2ea00d86d | 30.595745 | 97 | 0.63367 | false | false | false | false |
SKrotkih/YTLiveStreaming | refs/heads/master | YTLiveStreaming/Credentials.swift | mit | 1 | //
// Credentials.swift
// YTLiveStreaming
//
import Foundation
final class Credentials: NSObject {
private static var _clientID: String?
private static var _APIkey: String?
private static let plistKeyClientID = "CLIENT_ID"
private static let plistKeyAPIkey = "API_KEY"
static var clientID: String {
if Credentials._clientID == nil {
Credentials._clientID = getInfo(plistKeyClientID)
}
assert(Credentials._clientID != nil, "Please put your Client ID to the Info.plist!")
return Credentials._clientID!
}
static var APIkey: String {
if Credentials._APIkey == nil {
Credentials._APIkey = getInfo(plistKeyAPIkey)
}
assert(Credentials._APIkey != nil, "Please put your APY key to the Info.plist!")
return Credentials._APIkey!
}
static private func getInfo(_ key: String) -> String? {
if let plist = getPlist("Info"), let info = plist[key] as? String, !info.isEmpty {
return info
} else if let plist = getPlist("Config"), let info = plist[key] as? String, !info.isEmpty {
return info
} else {
return nil
}
}
static private func getPlist(_ name: String) -> NSDictionary? {
var plist: NSDictionary?
if let path = Bundle.main.path(forResource: name, ofType: "plist") {
if let content = NSDictionary(contentsOfFile: path) as NSDictionary? {
plist = content
}
}
return plist
}
}
| d764e46fb06c5eb077573c6b7bacb052 | 30.653061 | 99 | 0.602837 | false | false | false | false |
mgadda/zig | refs/heads/master | Sources/MessagePackEncoder/MessagePackReferencingEncoder.swift | mit | 1 | //
// MessagePackReferencingEncoder.swift
// MessagePackEncoder
//
// Created by Matt Gadda on 9/27/17.
//
import Foundation
import MessagePack
internal class MessagePackReferencingEncoder : _MessagePackEncoder {
private enum Reference {
case array(MutableArrayReference<BoxedValue>, Int)
case dictionary(MutableDictionaryReference<BoxedValue, BoxedValue>, String)
}
let encoder: _MessagePackEncoder
private let reference: Reference
init(referencing encoder: _MessagePackEncoder, at index: Int, wrapping array: MutableArrayReference<BoxedValue>) {
self.encoder = encoder
self.reference = .array(array, index)
super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath)
codingPath.append(MessagePackKey(index: index))
}
init(referencing encoder: _MessagePackEncoder, at key: CodingKey, wrapping dictionary: MutableDictionaryReference<BoxedValue, BoxedValue>) {
self.encoder = encoder
self.reference = .dictionary(dictionary, key.stringValue)
super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath)
self.codingPath.append(key)
}
internal override var canEncodeNewValue: Bool {
return self.storage.count == self.codingPath.count - self.encoder.codingPath.count - 1
}
deinit {
let value: BoxedValue
switch self.storage.count {
case 0: value = BoxedValue.map(MutableDictionaryReference<BoxedValue, BoxedValue>())
case 1: value = self.storage.popContainer()
default: fatalError("Referencing encoder deallocated with multiple containers on stack.")
}
switch self.reference {
case .array(let arrayRef, let index):
arrayRef.insert(value, at: index)
case .dictionary(let dictRef, let key):
dictRef[BoxedValue.string(key)] = value
}
}
}
| efb883f0b2f5d5a1b1989114a10a9204 | 30.892857 | 142 | 0.741321 | false | false | false | false |
motoom/ios-apps | refs/heads/master | TeVoet3/TeVoet/WandelingController.swift | mit | 1 |
// WandelingController.swift
//
// Software by Michiel Overtoom, [email protected]
import UIKit
import MapKit
import CoreLocation
let standaardIgnoreUpdates = 3
let minimumDistance: CLLocationDistance = 10
class WandelingController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var mapView: MKMapView!
var locations = [CLLocation]()
var ignoreUpdates = standaardIgnoreUpdates // de eerste 'ignoreupdates' meldingen negeren, vanwege initiele onnauwkeurigheid
var locationsBackgroundBuffer = [CLLocation]() // for collecting locations while in background state
var prevpolyline: MKPolyline? = nil
var totaal = 0.0 // Actueel totaal aantal meters afgelegd.
var prevLocation: CLLocation? = nil // De laatst verwerkte location in 'totaal'.
override func viewDidLoad() {
super.viewDidLoad()
mapView.showsCompass = false
mapView.setUserTrackingMode(.followWithHeading, animated: false)
mapView.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
startTracking()
}
override func viewWillDisappear(_ animated: Bool) {
stopTracking()
// TODO: See if there is connectivity to retrieve location names for certain points of the route. If there is, determine the location names for some points on the route to synthesize a description (or the furthest point reached). Try this for a few seconds before giving up & saving without location names.
if locations.count >= 2 {
var footsteps = -1
if let start = locations.first?.timestamp, let end = locations.last?.timestamp {
footsteps = footstepsbetween(start, end)
}
saveWaypoints(locations, footsteps)
// saveWaypointsCSV(locations) // Used for debugging.
}
}
// Zie ook allowDeferredLocationUpdatesUntilTraveled:timeout: en deferredLocationUpdatesAvailable
func startTracking() {
locations.removeAll()
if !CLLocationManager.locationServicesEnabled() {
return
}
let apd = UIApplication.shared.delegate as! AppDelegate
if let lm = apd.lm {
lm.delegate = self
lm.activityType = .fitness
lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
lm.distanceFilter = minimumDistance // standard 10, default None, but then many locations arrive, even without moving
lm.allowsBackgroundLocationUpdates = true
ignoreUpdates = standaardIgnoreUpdates
lm.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations newLocations: [CLLocation]) {
// TODO: Dit moet beter. Bijvoorbeeld alle updates weggooien totdat ze een stabiele loopsnelheid laten zien.
// TODO: De eerste tien seconden niets opslaan, zodat de location services zich eerst kunnen stabiliseren.
if ignoreUpdates > 0 {
ignoreUpdates -= 1
return
}
// Checken of in backgroundstate. Zoja, zo snel mogelijk bufferen en verder niets doen.
if UIApplication.shared.applicationState == .background {
locationsBackgroundBuffer.append(contentsOf: newLocations)
return
}
// We're in foreground
// TODO: Query pedometer and remove any local notifications when appropriate.
// Locations that need to be processed for updating distance
var locationsToProcess = [CLLocation]()
// Are there any locations previously recorded while we were in the background? If so, we have to deal with them first.
if locationsBackgroundBuffer.count > 0 {
let filteredLocations = locationsBackgroundBuffer.filter{$0.horizontalAccuracy <= minimumDistance && $0.verticalAccuracy <= 10}
locationsBackgroundBuffer.removeAll()
locations.append(contentsOf: filteredLocations) // Record for storage
locationsToProcess.append(contentsOf: filteredLocations) // Record for distance processing
}
// Now deal with the new locations incoming to this invocation.
let filteredLocations = newLocations.filter{$0.horizontalAccuracy <= minimumDistance && $0.verticalAccuracy <= 10}
locations.append(contentsOf: filteredLocations) // For storage
locationsToProcess.append(contentsOf: filteredLocations) // For distance processing
// Update the polyline overlay.
var polylinecoords = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate})
let polyline = MKPolyline(coordinates: &polylinecoords, count: locations.count)
if let pp = prevpolyline {
mapView.remove(pp)
}
mapView.add(polyline)
prevpolyline = polyline
// Running totals like distance walked.
for location in locationsToProcess {
if prevLocation == nil {
prevLocation = location
}
else {
let delta = location.distance(from: prevLocation!)
totaal += delta
prevLocation = location
DispatchQueue.main.async {
let saf = sjiekeAfstand(self.totaal)
self.statusLabel.text = "afgelegd: \(saf)" // TODO: Om de zoveels seconden roteren: totaal afstand afgelegd, totaal aantal stappen genomen (indien pedometerdata beschikbaar), snelheid in km/hr, tijdsduur.
}
}
}
}
func stopTracking() {
if !CLLocationManager.locationServicesEnabled() {
return
}
let apd = UIApplication.shared.delegate as! AppDelegate
if let lm = apd.lm {
lm.stopUpdatingLocation()
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let route: MKPolyline = overlay as! MKPolyline
let routeRenderer = MKPolylineRenderer(polyline:route)
routeRenderer.lineWidth = 5.0
routeRenderer.strokeColor = UIColor.red
return routeRenderer
}
return MKOverlayRenderer()
}
func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) {
if mode == .none {
statusLabel.text = "kaart volgt niet"
}
else {
statusLabel.text = "kaart volgt"
}
}
@IBAction func titleButton(_ sender: UIButton) {
if mapView.userTrackingMode != .followWithHeading {
mapView.setUserTrackingMode(.followWithHeading, animated: false)
}
}
}
| 0ad685837b69a85c7e406d4db798f54c | 39.578947 | 314 | 0.644185 | false | false | false | false |
zoeyzhong520/InformationTechnology | refs/heads/master | InformationTechnology/InformationTechnology/Classes/Collection精选/View/CoolPlayCell.swift | mit | 1 | //
// CoolPlayCell.swift
// InformationTechnology
//
// Created by zzj on 16/11/13.
// Copyright © 2016年 zzj. All rights reserved.
//
import UIKit
class CoolPlayCell: UICollectionViewCell {
@IBOutlet weak var bgImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var playTimeLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
//点击事件
var jumpClosure:RecommendJumpClosure?
//显示数据
var carsInfArray:Array<CoolPlayCarsInf>? {
didSet {
showData()
}
}
//显示数据
private func showData() {
let cnt = carsInfArray?.count
if carsInfArray?.count > 0 {
for i in 0..<cnt! {
let model = carsInfArray![i]
//创建图片
if model.image_448_252 != nil {
let url = NSURL(string: model.image_448_252!)
bgImageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: model.image_448_252!), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
//添加手势
contentView.tag = 200+i
let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
contentView.addGestureRecognizer(g)
//标题
if model.title != nil {
nameLabel.text = model.title
}
//播放次数
if model.sub_title != nil {
playTimeLabel.text = model.sub_title
}
//视频时长
if model.image_b_r_title != nil {
durationLabel.text = model.image_b_r_title
}
}
}
}
//手势点击事件
func tapAction(g:UIGestureRecognizer) {
let index = (g.view?.tag)!-200
//获取点击的数据
let item = carsInfArray![index]
if jumpClosure != nil && item.skip_inf?.video_id != nil {
jumpClosure!((item.skip_inf?.video_id)!)
}
}
//创建cell的方法
class func createCellFor(collectionView:UICollectionView, atIndexPath indexPath:NSIndexPath, carsInfArray:Array<CoolPlayCarsInf>?) -> CoolPlayCell {
let cellId = "coolPlayCellId"
var cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as? CoolPlayCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CoolPlayCell", owner: nil, options: nil).last as? CoolPlayCell
}
cell?.carsInfArray = carsInfArray
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 77589731f74ffb7a35974eedf2f91c06 | 23.542373 | 173 | 0.523481 | false | false | false | false |
GuiBayma/PasswordVault | refs/heads/develop | PasswordVaultTests/Scenes/Add Group/AddGroupViewControllerTests.swift | mit | 1 | //
// AddGroupViewControllerTests.swift
// PasswordVault
//
// Created by Guilherme Bayma on 7/28/17.
// Copyright © 2017 Bayma. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import PasswordVault
class NewGroupDelegateMock: NewDataDelegate {
var group: Group?
func addNewDataAndDismiss(_ viewController: UIViewController, data: NSObject) {
if let group = data as? Group {
self.group = group
}
viewController.dismiss(animated: true) {}
}
}
class AddGroupViewControllerTests: QuickSpec {
override func spec() {
describe("AddGroupViewController tests") {
var sut: AddGroupViewController?
var newGroupDelegateMock: NewGroupDelegateMock?
beforeEach {
sut = AddGroupViewController()
newGroupDelegateMock = NewGroupDelegateMock()
sut?.delegate = newGroupDelegateMock
if let view = sut?.view as? AddGroupView {
let textField = view.labeledTextField.textField
textField.text = "New Group"
} else {
fail("view should be AddGroupView")
}
}
afterEach {
if let mock = newGroupDelegateMock {
if let group = mock.group {
if !GroupManager.sharedInstance.delete(object: group) {
fail("could not delete group")
}
}
}
}
it("should not be nil") {
expect(sut).toNot(beNil())
}
#if arch(x86_64) && _runtime(_ObjC) && !SWIFT_PACKAGE
it("should not load through storyboard") {
expect {
_ = AddGroupViewController(coder: NSCoder())
}.to(throwAssertion())
}
#endif
it("should conform to UITextFieldDelegate") {
expect(sut?.conforms(to: UITextFieldDelegate.self)).to(beTrue())
}
it("should dismiss and create new group through text field return") {
guard
let textField = (sut?.view as? AddGroupView)?.labeledTextField.textField
else {
fail("textfield should not be nil")
return
}
expect(sut?.textFieldShouldReturn(textField)).to(beTrue())
expect(newGroupDelegateMock?.group?.name) == "New Group"
}
it("should dismiss and create new group through button action") {
sut?.donePressed()
expect(newGroupDelegateMock?.group?.name) == "New Group"
}
it("should dismiss and not create new group for empty string") {
if let view = sut?.view as? AddGroupView {
let textField = view.labeledTextField.textField
textField.text = ""
expect(sut?.textFieldShouldReturn(textField)).to(beTrue())
expect(newGroupDelegateMock?.group).to(beNil())
} else {
fail("view should be AddGroupView")
}
}
}
}
}
| db6530d9b26258e9285becb8764ebb21 | 30.904762 | 92 | 0.516716 | false | false | false | false |
staticdreams/WhereAmI | refs/heads/master | Source/WhereAmI.swift | mit | 1 | // WhereAmI.swift
//
// Copyright (c) 2014 Romain Rivollier
//
// 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 CoreLocation
/**
Location authorization type
- AlwaysAuthorization: The location is updated even if the application is in background
- InUseAuthorization: The location is updated when the application is running
*/
public enum WAILocationAuthorization : Int {
case AlwaysAuthorization
case InUseAuthorization
}
/**
These profils represent different location parameters (accuracy, distance update, ...).
Look at the didSet method of the locationPrecision variable for more informations
- Default: This profil can be used for most of your usage
- Low: Low accuracy profil
- Medium: Medium accuracy profil
- High: High accuracy profil, when you need the best location
*/
public enum WAILocationProfil : Int {
case Default
case Low
case Medium
case High
}
public typealias WAIAuthorizationResult = (locationIsAuthorized : Bool) -> Void
public typealias WAILocationUpdate = (location : CLLocation) -> Void
public typealias WAIReverseGeocodedLocationResult = (placemark : CLPlacemark!) -> Void
public typealias WAILocationAuthorizationRefused = () -> Void
// MARK: - Class Implementation
public class WhereAmI : NSObject, CLLocationManagerDelegate {
// Singleton
public static let sharedInstance = WhereAmI()
public let locationManager = CLLocationManager()
/// Max location validity in seconds
public let locationValidity : NSTimeInterval = 15.0
public var horizontalAccuracy : CLLocationDistance = 500.0
public var continuousUpdate : Bool = false
public var locationAuthorization : WAILocationAuthorization = .InUseAuthorization
public var locationPrecision : WAILocationProfil {
didSet {
switch locationPrecision {
case .Low:
self.locationManager.distanceFilter = 500.0
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
self.horizontalAccuracy = 2000.0
case .Medium:
self.locationManager.distanceFilter = 100.0
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
self.horizontalAccuracy = 1000.0
case .High:
self.locationManager.distanceFilter = 10.0
self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
self.horizontalAccuracy = 200.0
case .Default:
self.locationManager.distanceFilter = 50.0
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.horizontalAccuracy = 500.0
}
}
};
var authorizationHandler : WAIAuthorizationResult?;
var locationUpdateHandler : WAILocationUpdate?;
// MARK: - Class methods
/**
Check if the location authorization has been asked
:returns: return false if the authorization has not been asked, otherwise true
*/
public class func userHasBeenPromptedForLocationUse() -> Bool {
if (CLLocationManager.authorizationStatus() == .NotDetermined) {
return false
}
return true;
}
/**
Check if the localization is authorized
:returns: false if the user's location was denied, otherwise true
*/
public class func locationIsAuthorized() -> Bool {
if (CLLocationManager.authorizationStatus() == .Denied || CLLocationManager.authorizationStatus() == .Restricted) {
return false
}
if (!CLLocationManager.locationServicesEnabled()) {
return false
}
return true
}
/**
Out of the box class method, the easiest way to obtain the user's GPS coordinate
:param: locationHandler The closure return the latest valid user's positon
:param: locationRefusedHandler When the user refuse location, this closure is called.
*/
public class func whereAmI(locationHandler : WAILocationUpdate, locationRefusedHandler : WAILocationAuthorizationRefused) {
WhereAmI.sharedInstance.whereAmI(locationHandler, locationRefusedHandler : locationRefusedHandler)
}
/**
Out of the box class method, the easiest way to obtain the user's location (street, city, etc.)
:param: geocoderHandler The closure return a placemark corresponding to the current user's location. If an error occured it return nil
:param: locationRefusedHandler When the user refuse location, this closure is called.
*/
public class func whatIsThisPlace(geocoderHandler : WAIReverseGeocodedLocationResult, locationRefusedHandler : WAILocationAuthorizationRefused) {
WhereAmI.sharedInstance.whatIsThisPlace(geocoderHandler, locationRefusedHandler : locationRefusedHandler);
}
// MARK: - Object methods
override init() {
self.locationPrecision = WAILocationProfil.Default
super.init()
self.locationManager.delegate = self
}
/**
All in one method, the easiest way to obtain the user's GPS coordinate
:param: locationHandler The closure return the latest valid user's positon
:param: locationRefusedHandler When the user refuse location, this closure is called.
*/
public func whereAmI(locationHandler : WAILocationUpdate, locationRefusedHandler : WAILocationAuthorizationRefused) {
self.askLocationAuthorization({ [unowned self] (locationIsAuthorized) -> Void in
if (locationIsAuthorized) {
self.startUpdatingLocation(locationHandler)
} else {
locationRefusedHandler()
}
});
}
/**
All in one method, the easiest way to obtain the user's location (street, city, etc.)
:param: geocoderHandler The closure return a placemark corresponding to the current user's location. If an error occured it return nil
:param: locationRefusedHandler When the user refuse location, this closure is called.
*/
public func whatIsThisPlace(geocoderHandler : WAIReverseGeocodedLocationResult, locationRefusedHandler : WAILocationAuthorizationRefused) {
self.whereAmI({ (location) -> Void in
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location, completionHandler: { (placesmark, error) -> Void in
if let anError = error {
println("Reverse geocode fail: \(anError.localizedDescription)")
return
}
if let aPlacesmark = placesmark where aPlacesmark.count > 0 {
if let placemark = aPlacesmark.first as? CLPlacemark {
geocoderHandler(placemark: placemark)
}
} else {
geocoderHandler(placemark: nil)
}
});
}, locationRefusedHandler: locationRefusedHandler)
}
/**
Start the location update. If the continuousUpdate is at true the locationHandler will be used for each postion update.
:param: locationHandler The closure returns an updated location conforms to the accuracy filters
*/
public func startUpdatingLocation(locationHandler : WAILocationUpdate?) {
self.locationUpdateHandler = locationHandler
self.locationManager.startUpdatingLocation()
}
/**
Stop the location update and release the location handler.
*/
public func stopUpdatingLocation() {
self.locationManager.stopUpdatingLocation()
self.locationUpdateHandler = nil
}
/**
Request location authorization
:param: resultHandler The closure return if the authorization is granted or not
*/
public func askLocationAuthorization(resultHandler : WAIAuthorizationResult) {
// if the authorization was already asked we return the result
if (WhereAmI.userHasBeenPromptedForLocationUse()) {
resultHandler(locationIsAuthorized: WhereAmI.locationIsAuthorized())
return
}
self.authorizationHandler = resultHandler
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) {
if (self.locationAuthorization == WAILocationAuthorization.AlwaysAuthorization) {
self.locationManager.requestAlwaysAuthorization()
} else {
self.locationManager.requestWhenInUseAuthorization()
}
} else {
//In order to prompt the authorization alert view
self.startUpdatingLocation(nil)
}
}
deinit {
//Cleaning closure
self.locationUpdateHandler = nil
self.authorizationHandler = nil
}
// MARK: - CLLocationManager Delegate
public func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == .AuthorizedAlways || status == .AuthorizedWhenInUse) {
self.authorizationHandler?(locationIsAuthorized: true);
self.authorizationHandler = nil;
}
else if (status != .NotDetermined){
self.authorizationHandler?(locationIsAuthorized: false)
self.authorizationHandler = nil
}
}
public func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let locationsArray = locations where locationsArray.count > 0 {
if let latestPosition = locationsArray.first as? CLLocation {
let locationAge = -latestPosition.timestamp.timeIntervalSinceNow
//Check if the location is valid for the accuracy profil selected
if (locationAge < self.locationValidity && CLLocationCoordinate2DIsValid(latestPosition.coordinate) && latestPosition.horizontalAccuracy < self.horizontalAccuracy) {
self.locationUpdateHandler?(location : latestPosition)
if (!self.continuousUpdate) {
self.stopUpdatingLocation()
}
}
}
}
}
}
| ae9e16c05d069579a09744770382a5fc | 38.07947 | 181 | 0.648958 | false | false | false | false |
Johennes/firefox-ios | refs/heads/master | Utils/AuthenticationKeychainInfo.swift | mpl-2.0 | 1 | /* 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 SwiftKeychainWrapper
public let KeychainKeyAuthenticationInfo = "authenticationInfo"
public let AllowedPasscodeFailedAttempts = 3
// Passcode intervals with rawValue in seconds.
public enum PasscodeInterval: Int {
case Immediately = 0
case OneMinute = 60
case FiveMinutes = 300
case TenMinutes = 600
case FifteenMinutes = 900
case OneHour = 3600
}
// MARK: - Helper methods for accessing Authentication information from the Keychain
public extension KeychainWrapper {
func authenticationInfo() -> AuthenticationKeychainInfo? {
NSKeyedUnarchiver.setClass(AuthenticationKeychainInfo.self, forClassName: "AuthenticationKeychainInfo")
return objectForKey(KeychainKeyAuthenticationInfo) as? AuthenticationKeychainInfo
}
func setAuthenticationInfo(info: AuthenticationKeychainInfo?) {
NSKeyedArchiver.setClassName("AuthenticationKeychainInfo", forClass: AuthenticationKeychainInfo.self)
if let info = info {
setObject(info, forKey: KeychainKeyAuthenticationInfo)
} else {
removeObjectForKey(KeychainKeyAuthenticationInfo)
}
}
}
public class AuthenticationKeychainInfo: NSObject, NSCoding {
private(set) public var lastPasscodeValidationInterval: NSTimeInterval?
private(set) public var passcode: String?
private(set) public var requiredPasscodeInterval: PasscodeInterval?
private(set) public var lockOutInterval: NSTimeInterval?
private(set) public var failedAttempts: Int
public var useTouchID: Bool
// Timeout period before user can retry entering passcodes
public var lockTimeInterval: NSTimeInterval = 15 * 60
public init(passcode: String) {
self.passcode = passcode
self.requiredPasscodeInterval = .Immediately
self.failedAttempts = 0
self.useTouchID = false
}
public func encodeWithCoder(aCoder: NSCoder) {
if let lastPasscodeValidationInterval = lastPasscodeValidationInterval {
let interval = NSNumber(double: lastPasscodeValidationInterval)
aCoder.encodeObject(interval, forKey: "lastPasscodeValidationInterval")
}
if let lockOutInterval = lockOutInterval where isLocked() {
let interval = NSNumber(double: lockOutInterval)
aCoder.encodeObject(interval, forKey: "lockOutInterval")
}
aCoder.encodeObject(passcode, forKey: "passcode")
aCoder.encodeObject(requiredPasscodeInterval?.rawValue, forKey: "requiredPasscodeInterval")
aCoder.encodeInteger(failedAttempts, forKey: "failedAttempts")
aCoder.encodeBool(useTouchID, forKey: "useTouchID")
}
public required init?(coder aDecoder: NSCoder) {
self.lastPasscodeValidationInterval = (aDecoder.decodeObjectForKey("lastPasscodeValidationInterval") as? NSNumber)?.doubleValue
self.lockOutInterval = (aDecoder.decodeObjectForKey("lockOutInterval") as? NSNumber)?.doubleValue
self.passcode = aDecoder.decodeObjectForKey("passcode") as? String
self.failedAttempts = aDecoder.decodeIntegerForKey("failedAttempts")
self.useTouchID = aDecoder.decodeBoolForKey("useTouchID")
if let interval = aDecoder.decodeObjectForKey("requiredPasscodeInterval") as? NSNumber {
self.requiredPasscodeInterval = PasscodeInterval(rawValue: interval.integerValue)
}
}
}
// MARK: - API
public extension AuthenticationKeychainInfo {
private func resetLockoutState() {
self.failedAttempts = 0
self.lockOutInterval = nil
}
func updatePasscode(passcode: String) {
self.passcode = passcode
self.lastPasscodeValidationInterval = nil
}
func updateRequiredPasscodeInterval(interval: PasscodeInterval) {
self.requiredPasscodeInterval = interval
self.lastPasscodeValidationInterval = nil
}
func recordValidation() {
// Save the timestamp to remember the last time we successfully
// validated and clear out the failed attempts counter.
self.lastPasscodeValidationInterval = SystemUtils.systemUptime()
resetLockoutState()
}
func lockOutUser() {
self.lockOutInterval = SystemUtils.systemUptime()
}
func recordFailedAttempt() {
if (self.failedAttempts >= AllowedPasscodeFailedAttempts) {
//This is a failed attempt after a lockout period. Reset the lockout state
//This prevents failedAttemps from being higher than 3
self.resetLockoutState()
}
self.failedAttempts += 1
}
func isLocked() -> Bool {
guard self.lockOutInterval != nil else {
return false
}
if SystemUtils.systemUptime() < self.lockOutInterval {
// Unlock and require passcode input
resetLockoutState()
return false
}
return (SystemUtils.systemUptime() - (self.lockOutInterval ?? 0)) < lockTimeInterval
}
func requiresValidation() -> Bool {
// If there isn't a passcode, don't need validation.
guard let _ = passcode else {
return false
}
// Need to make sure we've validated in the past. If not, its a definite yes.
guard let lastValidationInterval = lastPasscodeValidationInterval,
requireInterval = requiredPasscodeInterval
else {
return true
}
// We've authenticated before so lets see how long since. If the uptime is less than the last validation stamp,
// we probably restarted which means we should require validation.
return SystemUtils.systemUptime() - lastValidationInterval > Double(requireInterval.rawValue) ||
SystemUtils.systemUptime() < lastValidationInterval
}
}
| eff18b7a9a5fe941f909797769142bd4 | 38.75 | 135 | 0.696789 | false | false | false | false |
xuech/OMS-WH | refs/heads/master | OMS-WH/Classes/TakeOrder/器械信息/View/Cell/OnWayTableViewCell.swift | mit | 1 | //
// OnWayTableViewCell.swift
// OMS-WH
//
// Created by xuech on 2017/11/30.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
class OnWayTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
setUp()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUp(){
contentView.addSubview(sepelable)
contentView.addSubview(hpLB)
contentView.addSubview(lotailLB)
contentView.addSubview(countLB)
contentView.addSubview(outBoundLB)
contentView.addSubview(outBoundStatusLB)
sepelable.backgroundColor = UIColor.groupTableViewBackground
sepelable.snp.makeConstraints { (make) in
make.top.right.equalTo(self)
make.left.equalTo(8)
make.height.equalTo(1)
}
hpLB.snp.makeConstraints { (make) in
make.left.top.equalTo(8)
make.right.equalTo(-8)
make.height.equalTo(24)
}
lotailLB.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(hpLB.snp.bottom).offset(8)
make.right.equalTo(-8)
make.height.equalTo(24)
}
outBoundLB.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(lotailLB.snp.bottom).offset(8)
make.right.equalTo(-8)
make.height.equalTo(24)
}
countLB.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(outBoundLB.snp.bottom).offset(8)
make.width.equalTo(100)
make.height.equalTo(24)
}
outBoundStatusLB.textAlignment = .right
outBoundStatusLB.snp.makeConstraints { (make) in
make.right.equalTo(-8)
make.width.equalTo(180)
make.height.equalTo(24)
make.centerY.equalTo(countLB.snp.centerY)
}
}
lazy var sepelable:UILabel = self.createLB()
lazy var hpLB:UILabel = self.createLB()
lazy var lotailLB:UILabel = self.createLB()
lazy var countLB:UILabel = self.createLB()
lazy var outBoundLB:UILabel = self.createLB()
lazy var outBoundStatusLB:UILabel = self.createLB()
fileprivate func createLB() ->UILabel{
let lb = UILabel()
lb.font = UIFont.systemFont(ofSize: 13)
return lb
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| a4926f6ec4835f85e22312981f901511 | 30.326087 | 74 | 0.611728 | false | false | false | false |
benkraus/Operations | refs/heads/master | Operations/UserNotificationCapability.swift | mit | 1 | /*
The MIT License (MIT)
Original work Copyright (c) 2015 pluralsight
Modified work Copyright 2016 Ben Kraus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#if os(iOS)
import UIKit
public struct UserNotification: CapabilityType {
public static let name = "UserNotificaton"
public static func didRegisterUserSettings() {
authorizer.completeAuthorization()
}
public enum Behavior {
case Replace
case Merge
}
private let settings: UIUserNotificationSettings
private let behavior: Behavior
public init(settings: UIUserNotificationSettings, behavior: Behavior = .Merge, application: UIApplication) {
self.settings = settings
self.behavior = behavior
if authorizer._application == nil {
authorizer.application = application
}
}
public func requestStatus(completion: CapabilityStatus -> Void) {
let registered = authorizer.areSettingsRegistered(settings)
completion(registered ? .Authorized : .NotDetermined)
}
public func authorize(completion: CapabilityStatus -> Void) {
let settings: UIUserNotificationSettings
switch behavior {
case .Replace:
settings = self.settings
case .Merge:
let current = authorizer.application.currentUserNotificationSettings()
settings = current?.settingsByMerging(self.settings) ?? self.settings
}
authorizer.authorize(settings, completion: completion)
}
}
private let authorizer = UserNotificationAuthorizer()
private class UserNotificationAuthorizer {
var _application: UIApplication?
var application: UIApplication {
set {
_application = newValue
}
get {
guard let application = _application else {
fatalError("Application not yet configured. Results would be undefined.")
}
return application
}
}
var completion: (CapabilityStatus -> Void)?
var settings: UIUserNotificationSettings?
func areSettingsRegistered(settings: UIUserNotificationSettings) -> Bool {
let current = application.currentUserNotificationSettings()
return current?.contains(settings) ?? false
}
func authorize(settings: UIUserNotificationSettings, completion: CapabilityStatus -> Void) {
guard self.completion == nil else {
fatalError("Cannot request push authorization while a request is already in progress")
}
guard self.settings == nil else {
fatalError("Cannot request push authorization while a request is already in progress")
}
self.completion = completion
self.settings = settings
application.registerUserNotificationSettings(settings)
}
private func completeAuthorization() {
guard let completion = self.completion else { return }
guard let settings = self.settings else { return }
self.completion = nil
self.settings = nil
let registered = areSettingsRegistered(settings)
completion(registered ? .Authorized : .Denied)
}
}
#endif
| c654bf8b890d87715361c674c7084317 | 32.369231 | 112 | 0.670816 | false | false | false | false |
rokuz/omim | refs/heads/master | iphone/Maps/Bookmarks/Catalog/Subscription/AllPassSubscriptionViewController.swift | apache-2.0 | 1 | import UIKit
class AllPassSubscriptionViewController: BaseSubscriptionViewController {
//MARK:outlets
@IBOutlet private var backgroundImageView: ImageViewCrossDisolve!
@IBOutlet private var annualSubscriptionButton: BookmarksSubscriptionButton!
@IBOutlet private var annualDiscountLabel: BookmarksSubscriptionDiscountLabel!
@IBOutlet private var monthlySubscriptionButton: BookmarksSubscriptionButton!
@IBOutlet private var pageIndicator: PageIndicator!
@IBOutlet private var descriptionPageScrollView: UIScrollView!
//MARK: locals
private var pageWidth: CGFloat {
return self.descriptionPageScrollView.frame.width;
}
private let maxPages = 3;
private var currentPage: Int {
return Int(self.descriptionPageScrollView.contentOffset.x/self.pageWidth) + 1;
}
private var animatingTask: DispatchWorkItem?
private let animationDelay: TimeInterval = 2
private let animationDuration: TimeInterval = 0.75
private let animationBackDuration: TimeInterval = 0.3
override var subscriptionManager: ISubscriptionManager? {
get { return InAppPurchase.allPassSubscriptionManager }
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
get { return [.portrait] }
}
override var preferredStatusBarStyle: UIStatusBarStyle {
get { return .lightContent }
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.presentationController?.delegate = self;
backgroundImageView.images = [
UIImage.init(named: "AllPassSubscriptionBg1"),
UIImage.init(named: "AllPassSubscriptionBg2"),
UIImage.init(named: "AllPassSubscriptionBg3")
]
pageIndicator.pageCount = maxPages
startAnimating();
annualSubscriptionButton.config(title: L("annual_subscription_title"),
price: "...",
enabled: false)
monthlySubscriptionButton.config(title: L("montly_subscription_title"),
price: "...",
enabled: false)
annualDiscountLabel.layer.shadowRadius = 4
annualDiscountLabel.layer.shadowOffset = CGSize(width: 0, height: 2)
annualDiscountLabel.layer.shadowColor = UIColor.blackHintText().cgColor
annualDiscountLabel.layer.shadowOpacity = 0.62
annualDiscountLabel.layer.cornerRadius = 6
annualDiscountLabel.isHidden = true
self.configure(buttons: [
.year: annualSubscriptionButton,
.month: monthlySubscriptionButton],
discountLabels:[
.year: annualDiscountLabel])
Statistics.logEvent(kStatInappShow, withParameters: [kStatVendor: MWMPurchaseManager.allPassProductIds,
kStatPurchase: MWMPurchaseManager.allPassSubscriptionServerId(),
kStatProduct: BOOKMARKS_SUBSCRIPTION_YEARLY_PRODUCT_ID, //FIXME
kStatFrom: source], with: .realtime)
}
@IBAction func onAnnualButtonTap(_ sender: UIButton) {
purchase(sender: sender, period: .year)
}
@IBAction func onMonthlyButtonTap(_ sender: UIButton) {
purchase(sender: sender, period: .month)
}
}
//MARK: Animation
extension AllPassSubscriptionViewController {
private func perform(withDelay: TimeInterval, execute: DispatchWorkItem?) {
if let execute = execute {
DispatchQueue.main.asyncAfter(deadline: .now() + withDelay, execute: execute)
}
}
private func startAnimating() {
if animatingTask != nil {
animatingTask?.cancel();
}
animatingTask = DispatchWorkItem.init {[weak self, animationDelay] in
self?.scrollToWithAnimation(page: (self?.currentPage ?? 0) + 1, completion: {
self?.perform(withDelay: animationDelay, execute: self?.animatingTask)
})
}
perform(withDelay: animationDelay, execute: animatingTask)
}
private func stopAnimating() {
animatingTask?.cancel();
animatingTask = nil
view.layer.removeAllAnimations()
}
private func scrollToWithAnimation(page: Int, completion: @escaping ()->()) {
var nextPage = page
var duration = animationDuration
if nextPage < 1 || nextPage > maxPages {
nextPage = 1
duration = animationBackDuration
}
let xOffset = CGFloat(nextPage - 1) * pageWidth
UIView.animate(withDuration: duration,
delay: 0,
options: [.curveEaseInOut, .allowUserInteraction],
animations: { [weak self] in
self?.descriptionPageScrollView.contentOffset.x = xOffset
}, completion:{ complete in
completion()
})
}
}
extension AllPassSubscriptionViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageProgress = scrollView.contentOffset.x/self.pageWidth
pageIndicator.currentPage = pageProgress
backgroundImageView.currentPage = pageProgress
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopAnimating()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
startAnimating()
}
}
| 1631b41329c17f6c4d735fd70e0802c3 | 34.738562 | 121 | 0.686906 | false | false | false | false |
lieonCX/Hospital | refs/heads/master | Hospital/Hospital/ViewModel/News/ActivityIndicator.swift | mit | 1 | //
// ActivityIndicator.swift
// Hospital
//
// Created by lieon on 2017/5/9.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
private struct ActivityToken<E> : ObservableConvertibleType, Disposable {
private let _source: Observable<E>
private let _dispose: Cancelable
init(source: Observable<E>, disposeAction: @escaping () -> ()) {
_source = source
_dispose = Disposables.create(with: disposeAction)
}
func dispose() {
_dispose.dispose()
}
func asObservable() -> Observable<E> {
return _source
}
}
/**
Enables monitoring of sequence computation.
If there is at least one sequence computation in progress, `true` will be sent.
When all activities complete `false` will be sent.
*/
public class ActivityIndicator : SharedSequenceConvertibleType {
public typealias E = Bool
public typealias SharingStrategy = DriverSharingStrategy
private let _lock = NSRecursiveLock()
private let _variable = Variable(0)
private let _loading: SharedSequence<SharingStrategy, Bool>
public init() {
_loading = _variable.asDriver()
.map { $0 > 0 }
.distinctUntilChanged()
}
fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> {
return Observable.using({ () -> ActivityToken<O.E> in
self.increment()
return ActivityToken(source: source.asObservable(), disposeAction: self.decrement)
}) { t in
return t.asObservable()
}
}
private func increment() {
_lock.lock()
_variable.value = _variable.value + 1
_lock.unlock()
}
private func decrement() {
_lock.lock()
_variable.value = _variable.value - 1
_lock.unlock()
}
public func asSharedSequence() -> SharedSequence<SharingStrategy, E> {
return _loading
}
}
extension ObservableConvertibleType {
public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<E> {
return activityIndicator.trackActivityOfObservable(self)
}
}
| 20fc8bd9c17f31898e658f0366a4ec43 | 26.604938 | 110 | 0.642665 | false | false | false | false |
BananosTeam/CreativeLab | refs/heads/develop | Example/Pods/OAuthSwift/OAuthSwift/OAuthWebViewController.swift | mit | 9 | //
// OAuthWebViewController.swift
// OAuthSwift
//
// Created by Dongri Jin on 2/11/15.
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
public typealias OAuthViewController = UIViewController
#elseif os(watchOS)
import WatchKit
public typealias OAuthViewController = WKInterfaceController
#elseif os(OSX)
import AppKit
public typealias OAuthViewController = NSViewController
#endif
public class OAuthWebViewController: OAuthViewController, OAuthSwiftURLHandlerType {
public func handle(url: NSURL) {
// do UI in main thread
if NSThread.isMainThread() {
doHandle(url)
}
else {
dispatch_async(dispatch_get_main_queue()) {
self.doHandle(url)
}
}
}
#if os(watchOS)
public static var userActivityType: String = "org.github.dongri.oauthswift.connect"
#endif
public func doHandle(url: NSURL){
#if os(iOS) || os(tvOS)
if let p = self.parentViewController {
p.presentViewController(self, animated: true, completion: nil)
} else {
#if !OAUTH_APP_EXTENSIONS
UIApplication.topViewController?.presentViewController(self, animated: true, completion: nil)
#endif
}
#elseif os(watchOS)
if (url.scheme == "http" || url.scheme == "https") {
self.updateUserActivity(OAuthWebViewController.userActivityType, userInfo: nil, webpageURL: url)
}
#elseif os(OSX)
if let p = self.parentViewController { // default behaviour if this controller affected as child controller
p.presentViewControllerAsModalWindow(self)
} else if let window = self.view.window {
window.makeKeyAndOrderFront(nil)
}
// or create an NSWindow or NSWindowController (/!\ keep a strong reference on it)
#endif
}
public func dismissWebViewController() {
#if os(iOS) || os(tvOS)
self.dismissViewControllerAnimated(true, completion: nil)
#elseif os(watchOS)
self.dismissController()
#elseif os(OSX)
if self.presentingViewController != nil { // if presentViewControllerAsModalWindow
self.dismissController(nil)
if self.parentViewController != nil {
self.removeFromParentViewController()
}
}
else if let window = self.view.window {
window.performClose(nil)
}
#endif
}
} | 0587fbf67bd654c436c0e938cc74f05d | 32.575 | 119 | 0.601117 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Classes/Notifications/NoNewNotificationsCell.swift | mit | 1 | //
// NoNewNotificationsCell.swift
// Freetime
//
// Created by Ryan Nystrom on 6/30/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
final class NoNewNotificationsCell: UICollectionViewCell {
let emojiLabel = UILabel()
let messageLabel = UILabel()
let shadow = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
emojiLabel.isAccessibilityElement = false
emojiLabel.text = "🎉"
emojiLabel.textAlignment = .center
emojiLabel.backgroundColor = .clear
emojiLabel.font = .systemFont(ofSize: 60)
contentView.addSubview(emojiLabel)
emojiLabel.snp.makeConstraints { make in
make.centerX.equalTo(contentView)
make.centerY.equalTo(contentView).offset(-Styles.Sizes.tableSectionSpacing)
}
shadow.fillColor = UIColor(white: 0, alpha: 0.05).cgColor
contentView.layer.addSublayer(shadow)
messageLabel.isAccessibilityElement = false
messageLabel.text = NSLocalizedString("Inbox zero!", comment: "")
messageLabel.textAlignment = .center
messageLabel.backgroundColor = .clear
messageLabel.font = Styles.Fonts.body
messageLabel.textColor = Styles.Colors.Gray.light.color
contentView.addSubview(messageLabel)
messageLabel.snp.makeConstraints { make in
make.centerX.equalTo(emojiLabel)
make.top.equalTo(emojiLabel.snp.bottom).offset(Styles.Sizes.tableSectionSpacing)
}
resetAnimations()
// CAAnimations will be removed from layers on background. restore when foregrounding.
NotificationCenter.default
.addObserver(self,
selector: #selector(NoNewNotificationsCell.resetAnimations),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil
)
contentView.isAccessibilityElement = true
contentView.accessibilityLabel = NSLocalizedString("You have no new notifications!", comment: "Inbox Zero Accessibility Label")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutContentViewForSafeAreaInsets()
let width: CGFloat = 30
let height: CGFloat = 12
let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
shadow.path = UIBezierPath(ovalIn: rect).cgPath
let bounds = contentView.bounds
shadow.bounds = rect
shadow.position = CGPoint(
x: bounds.width/2,
y: bounds.height/2 + 15
)
}
override func prepareForReuse() {
super.prepareForReuse()
resetAnimations()
}
override func didMoveToWindow() {
super.didMoveToWindow()
resetAnimations()
}
// MARK: Public API
func configure(emoji: String, message: String) {
emojiLabel.text = emoji
messageLabel.text = message
}
// MARK: Private API
@objc private func resetAnimations() {
guard trueUnlessReduceMotionEnabled else { return }
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let duration: TimeInterval = 1
let emojiBounce = CABasicAnimation(keyPath: "transform.translation.y")
emojiBounce.toValue = -10
emojiBounce.repeatCount = .greatestFiniteMagnitude
emojiBounce.autoreverses = true
emojiBounce.duration = duration
emojiBounce.timingFunction = timingFunction
emojiLabel.layer.add(emojiBounce, forKey: "nonewnotificationscell.emoji")
let shadowScale = CABasicAnimation(keyPath: "transform.scale")
shadowScale.toValue = 0.9
shadowScale.repeatCount = .greatestFiniteMagnitude
shadowScale.autoreverses = true
shadowScale.duration = duration
shadowScale.timingFunction = timingFunction
shadow.add(shadowScale, forKey: "nonewnotificationscell.shadow")
}
}
| f3e297f5545de37519a3cb1119d02a42 | 32.04 | 135 | 0.667554 | false | false | false | false |
Alua-Kinzhebayeva/iOS-PDF-Reader | refs/heads/master | Pods/PDFReader/Sources/Classes/PDFThumbnailCollectionViewController.swift | mit | 2 | //
// PDFThumbnailCollectionViewController.swift
// PDFReader
//
// Created by Ricardo Nunez on 7/9/16.
// Copyright © 2016 AK. All rights reserved.
//
import UIKit
/// Delegate that is informed of important interaction events with the current thumbnail collection view
protocol PDFThumbnailControllerDelegate: class {
/// User has tapped on thumbnail
func didSelectIndexPath(_ indexPath: IndexPath)
}
/// Bottom collection of thumbnails that the user can interact with
internal final class PDFThumbnailCollectionViewController: UICollectionViewController {
/// Current document being displayed
var document: PDFDocument!
/// Current page index being displayed
var currentPageIndex: Int = 0 {
didSet {
guard let collectionView = collectionView else { return }
guard let pageImages = pageImages else { return }
guard pageImages.count > 0 else { return }
let curentPageIndexPath = IndexPath(row: currentPageIndex, section: 0)
if !collectionView.indexPathsForVisibleItems.contains(curentPageIndexPath) {
collectionView.scrollToItem(at: curentPageIndexPath, at: .centeredHorizontally, animated: true)
}
collectionView.reloadData()
}
}
/// Calls actions when certain cells have been interacted with
weak var delegate: PDFThumbnailControllerDelegate?
/// Small thumbnail image representations of the pdf pages
private var pageImages: [UIImage]? {
didSet {
collectionView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global(qos: .background).async {
self.document.allPageImages(callback: { (images) in
DispatchQueue.main.async {
self.pageImages = images
}
})
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pageImages?.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PDFThumbnailCell
cell.imageView?.image = pageImages?[indexPath.row]
cell.alpha = currentPageIndex == indexPath.row ? 1 : 0.2
return cell
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
return PDFThumbnailCell.cellSize
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.didSelectIndexPath(indexPath)
}
}
| 2df3d36c556ab393fb9ea62e8a6a2385 | 36.636364 | 175 | 0.678054 | false | false | false | false |
tush4r/Edbinx | refs/heads/master | EdBinx/EdBinx/ViewController.swift | mit | 1 | //
// ViewController.swift
// EdBinx
//
// Created by Tushar Sharma on 05/08/16.
// Copyright © 2016 edbinx. All rights reserved.
//
import UIKit
import XLPagerTabStrip
class ViewController: ButtonBarPagerTabStripViewController {
override func viewDidLoad() {
super.viewDidLoad()
settings.style.buttonBarItemTitleColor = .white
buttonBarView.backgroundColor = UIColor(hex: ColorCodes().barColor())
settings.style.buttonBarBackgroundColor = UIColor(hex: ColorCodes().navColor())
settings.style.buttonBarItemLeftRightMargin = 20
settings.style.buttonBarMinimumLineSpacing = 20
settings.style.buttonBarItemLeftRightMargin = 20
settings.style.buttonBarItemFont = UIFont(name: "Times New Roman", size: 17)!
buttonBarView.selectedBar.backgroundColor = UIColor(hex: ColorCodes().sliderColor())
}
override func viewControllersForPagerTabStrip(_ pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
return [ArticlesViewController(itemInfo:"ALL"), ArticlesViewController(itemInfo:"WORLD"), ArticlesViewController(itemInfo:"TECHNOLOGY"), ArticlesViewController(itemInfo: "SCIENCE")]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class NavController: UINavigationController {
}
| ecaa3322ed490d9679d37759d16e3b50 | 34.325 | 189 | 0.7339 | false | false | false | false |
auth0/Lock.iOS-OSX | refs/heads/master | LockTests/Presenters/EnterpriseActiveAuthPresenterSpec.swift | mit | 2 | // EnterprisePasswordPresenterSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.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 Quick
import Nimble
import Auth0
@testable import Lock
class EnterpriseActiveAuthPresenterSpec: QuickSpec {
override func spec() {
let authentication = Auth0.authentication(clientId: clientId, domain: domain)
var interactor: EnterpriseActiveAuthInteractor!
var presenter: EnterpriseActiveAuthPresenter!
var messagePresenter: MockMessagePresenter!
var view: EnterpriseActiveAuthView!
var options: LockOptions!
var user: User!
var connection: EnterpriseConnection!
beforeEach {
options = LockOptions()
user = User()
messagePresenter = MockMessagePresenter()
connection = EnterpriseConnection(name: "TestAD", domains: ["test.com"])
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
view = presenter.view as? EnterpriseActiveAuthView
}
describe("init") {
it("should have a presenter object") {
expect(presenter).toNot(beNil())
}
it("should set button title") {
expect(view.primaryButton?.title) == "LOG IN"
}
}
describe("user state") {
it("should return initial valid email") {
interactor.validEmail = true
interactor.email = email
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.text).to(equal(email))
}
it("should return initial username") {
interactor.validUsername = true
interactor.username = username
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.text).to(equal(username))
}
it("should expect default identifier input type to be UserName") {
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.type).toEventually(equal(InputField.InputType.username))
}
context("use email as identifier option") {
beforeEach {
options = LockOptions()
options.activeDirectoryEmailAsUsername = true
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
}
it("should expect default identifier type to be email") {
let view = (presenter.view as! EnterpriseActiveAuthView).form as! CredentialView
expect(view.identityField.type).toEventually(equal(InputField.InputType.email))
}
}
}
describe("user input") {
it("should update username if value is valid") {
let input = mockInput(.username, value: username)
view.form?.onValueChange(input)
expect(presenter.interactor.username).to(equal(username))
expect(presenter.interactor.validUsername).to(beTrue())
}
it("should hide the field error if value is valid") {
let input = mockInput(.username, value: username)
view.form?.onValueChange(input)
expect(input.valid).to(equal(true))
}
it("should show field error for empty username") {
let input = mockInput(.username, value: "")
view.form?.onValueChange(input)
expect(input.valid).to(equal(false))
}
it("should update password if value is valid") {
let input = mockInput(.password, value: password)
view.form?.onValueChange(input)
expect(presenter.interactor.password).to(equal(password))
expect(presenter.interactor.validPassword).to(beTrue())
}
it("should show field error for empty password") {
let input = mockInput(.password, value: "")
view.form?.onValueChange(input)
expect(input.valid).to(equal(false))
}
it("should not process unsupported input type") {
let input = mockInput(.oneTimePassword, value: password)
view.form?.onValueChange(input)
expect(input.valid).to(beNil())
}
context("use email as identifier option") {
beforeEach {
options = LockOptions()
options.activeDirectoryEmailAsUsername = true
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
view = presenter.view as? EnterpriseActiveAuthView
}
it("should update email if value is valid") {
let input = mockInput(.email, value: email)
view.form?.onValueChange(input)
expect(presenter.interactor.email).to(equal(email))
expect(presenter.interactor.validEmail).to(beTrue())
}
it("should hide the field error if value is valid") {
let input = mockInput(.email, value: email)
view.form?.onValueChange(input)
expect(input.valid).to(equal(true))
}
it("should show field error for invalid email") {
let input = mockInput(.email, value: "invalid")
view.form?.onValueChange(input)
expect(input.valid).to(equal(false))
}
}
}
describe("login action") {
beforeEach {
options = LockOptions()
options.activeDirectoryEmailAsUsername = true
interactor = EnterpriseActiveAuthInteractor(connection: connection, authentication: authentication, user: user, options: options, dispatcher: ObserverStore())
try! interactor.update(.username, value: username)
try! interactor.update(.password(enforcePolicy: false), value: password)
presenter = EnterpriseActiveAuthPresenter(interactor: interactor, options: options, domain: "test.com")
presenter.messagePresenter = messagePresenter
view = presenter.view as? EnterpriseActiveAuthView
}
it("should not trigger action with nil button") {
let input = mockInput(.username, value: username)
input.returnKey = .done
view.primaryButton = nil
view.form?.onReturn(input)
expect(messagePresenter.message).toEventually(beNil())
expect(messagePresenter.error).toEventually(beNil())
}
it("should trigger login on button press and fail with with CouldNotLogin") {
view.primaryButton?.onPress(view.primaryButton!)
expect(messagePresenter.error).toEventually(beError(error: CredentialAuthError.couldNotLogin))
}
it("should trigger submission of form") {
let input = mockInput(.password, value: password)
input.returnKey = .done
view.form?.onReturn(input)
expect(messagePresenter.error).toEventually(beError(error: CredentialAuthError.couldNotLogin))
}
}
}
}
extension InputField.InputType: Equatable {}
public func ==(lhs: InputField.InputType, rhs: InputField.InputType) -> Bool {
switch((lhs, rhs)) {
case (.username, .username), (.email, .email), (.oneTimePassword, .oneTimePassword), (.phone, .phone):
return true
default:
return false
}
}
| a1c32345eeb2f8185ba6839d68739915 | 41.716102 | 178 | 0.610753 | false | false | false | false |
jacobwhite/firefox-ios | refs/heads/master | XCUITests/BaseTestCase.swift | mpl-2.0 | 1 | /* 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 MappaMundi
import XCTest
class BaseTestCase: XCTestCase {
var navigator: MMNavigator<FxUserState>!
let app = XCUIApplication()
var userState: FxUserState!
// These are used during setUp(). Change them prior to setUp() for the app to launch with different args,
// or, use restart() to re-launch with custom args.
var launchArguments = [LaunchArguments.ClearProfile, LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew]
func setUpScreenGraph() {
navigator = createScreenGraph(for: self, with: app).navigator()
userState = navigator.userState
}
func setUpApp() {
app.launchArguments = [LaunchArguments.Test] + launchArguments
app.launch()
}
override func setUp() {
super.setUp()
continueAfterFailure = false
setUpApp()
setUpScreenGraph()
}
override func tearDown() {
app.terminate()
super.tearDown()
}
func restart(_ app: XCUIApplication, args: [String] = []) {
XCUIDevice.shared.press(.home)
var launchArguments = [LaunchArguments.Test]
args.forEach { arg in
launchArguments.append(arg)
}
app.launchArguments = launchArguments
app.activate()
}
//If it is a first run, first run window should be gone
func dismissFirstRunUI() {
let firstRunUI = XCUIApplication().scrollViews["IntroViewController.scrollView"]
if firstRunUI.exists {
firstRunUI.swipeLeft()
XCUIApplication().buttons["Start Browsing"].tap()
}
}
func waitforExistence(_ element: XCUIElement, file: String = #file, line: UInt = #line) {
waitFor(element, with: "exists == true", file: file, line: line)
}
func waitforNoExistence(_ element: XCUIElement, timeoutValue: TimeInterval = 5.0, file: String = #file, line: UInt = #line) {
waitFor(element, with: "exists != true", timeout: timeoutValue, file: file, line: line)
}
func waitForValueContains(_ element: XCUIElement, value: String, file: String = #file, line: UInt = #line) {
waitFor(element, with: "value CONTAINS '\(value)'", file: file, line: line)
}
private func waitFor(_ element: XCUIElement, with predicateString: String, description: String? = nil, timeout: TimeInterval = 5.0, file: String, line: UInt) {
let predicate = NSPredicate(format: predicateString)
let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
let result = XCTWaiter().wait(for: [expectation], timeout: timeout)
if result != .completed {
let message = description ?? "Expect predicate \(predicateString) for \(element.description)"
self.recordFailure(withDescription: message, inFile: file, atLine: Int(line), expected: false)
}
}
func loadWebPage(_ url: String, waitForLoadToFinish: Bool = true, file: String = #file, line: UInt = #line) {
let app = XCUIApplication()
UIPasteboard.general.string = url
app.textFields["url"].press(forDuration: 2.0)
app.tables["Context Menu"].cells["menu-PasteAndGo"].firstMatch.tap()
if waitForLoadToFinish {
let finishLoadingTimeout: TimeInterval = 30
let progressIndicator = app.progressIndicators.element(boundBy: 0)
waitFor(progressIndicator,
with: "exists != true",
description: "Problem loading \(url)",
timeout: finishLoadingTimeout,
file: file, line: line)
}
}
func iPad() -> Bool {
if UIDevice.current.userInterfaceIdiom == .pad {
return true
}
return false
}
func waitUntilPageLoad() {
let app = XCUIApplication()
let progressIndicator = app.progressIndicators.element(boundBy: 0)
waitforNoExistence(progressIndicator, timeoutValue: 20.0)
}
}
extension BaseTestCase {
func tabTrayButton(forApp app: XCUIApplication) -> XCUIElement {
return app.buttons["TopTabsViewController.tabsButton"].exists ? app.buttons["TopTabsViewController.tabsButton"] : app.buttons["TabToolbar.tabsButton"]
}
}
extension XCUIElement {
func tap(force: Bool) {
// There appears to be a bug with tapping elements sometimes, despite them being on-screen and tappable, due to hittable being false.
// See: http://stackoverflow.com/a/33534187/1248491
if isHittable {
tap()
} else if force {
coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()
}
}
}
| 98119fff1f6ab4ef3d799aff3cfbcdbd | 36.361538 | 163 | 0.64196 | false | true | false | false |
huonw/swift | refs/heads/master | stdlib/public/core/Reverse.swift | apache-2.0 | 1 | //===--- 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 // FIXME(sil-serialize-all)
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`
@_fixed_layout
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.
@_fixed_layout
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 func makeIterator() -> Iterator {
return Iterator(_base: _base)
}
}
extension ReversedCollection {
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
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 = ReversedIndex<String>(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 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 func reversed() -> ReversedCollection<Self> {
return ReversedCollection(_base: self)
}
}
extension LazyCollectionProtocol
where
Self: BidirectionalCollection,
Elements: BidirectionalCollection {
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@inlinable
public func reversed() -> LazyCollection<ReversedCollection<Elements>> {
return ReversedCollection(_base: elements).lazy
}
}
// @available(*, deprecated, renamed: "ReversedCollection")
public typealias ReversedRandomAccessCollection<T: RandomAccessCollection> = ReversedCollection<T>
// @available(*, deprecated, renamed: "ReversedCollection.Index")
public typealias ReversedIndex<T: BidirectionalCollection> = ReversedCollection<T>
| 505ae2365cf65a8b2fcb690d29e3d87f | 31.707937 | 98 | 0.654178 | false | false | false | false |
Limon-O-O/Lady | refs/heads/master | Lady/HighPassFilter.swift | mit | 1 | //
// HighPassFilter.swift
// Example
//
// Created by Limon on 8/3/16.
// Copyright © 2016 Lady. All rights reserved.
//
import CoreImage
class HighPassFilter {
var inputImage: CIImage?
/// A number value that controls the radius (in pixel) of the filter. The default value of this parameter is 1.0.
var inputRadius: Float = 1.0
private static let kernel: CIColorKernel = {
let shaderPath = Bundle(for: HighPassFilter.self).path(forResource: "\(HighPassFilter.self)", ofType: "cikernel")
guard let path = shaderPath, let kernelString = try? String(contentsOfFile: path, encoding: String.Encoding.utf8), let kernel = CIColorKernel(source: kernelString) else {
fatalError("Unable to build HighPassFilter Kernel")
}
return kernel
}()
var outputImage: CIImage? {
guard let unwrappedInputImage = inputImage, let blurFilter = blurFilter else { return nil }
blurFilter.setValue(unwrappedInputImage.clampedToExtent(), forKey: kCIInputImageKey)
blurFilter.setValue(inputRadius, forKey: kCIInputRadiusKey)
guard let outputImage = blurFilter.outputImage else { return nil }
return HighPassFilter.kernel.apply(extent: unwrappedInputImage.extent, arguments: [unwrappedInputImage, outputImage])
}
private lazy var blurFilter: CIFilter? = {
let filter = CIFilter(name: "CIGaussianBlur")
return filter
}()
func setDefaults() {
inputImage = nil
inputRadius = 1.0
}
}
| 91fd77fe0444bd380f8e0540ea8acd32 | 28.461538 | 178 | 0.682115 | false | false | false | false |
exchangegroup/Dodo | refs/heads/master | Dodo/Dodo.swift | mit | 2 | import UIKit
/**
Main class that coordinates the process of showing and hiding of the message bar.
Instance of this class is created automatically in the `dodo` property of any UIView instance.
It is not expected to be instantiated manually anywhere except unit tests.
For example:
let view = UIView()
view.dodo.info("Horses are blue?")
*/
final class Dodo: DodoInterface, DodoButtonViewDelegate {
private weak var superview: UIView!
private var hideTimer: MoaTimer?
// Gesture handler that hides the bar when it is tapped
var onTap: OnTap?
/**
Specify optional anchor for positioning the bar view.
This can be an anchor from the safe area.
*/
var topAnchor: NSLayoutYAxisAnchor?
/**
Specify optional anchor for positioning the bar view.
This can be an anchor from the safe area.
*/
var bottomAnchor: NSLayoutYAxisAnchor?
/// Specify optional layout guide for positioning the bar view. Deprecated, use bottomAnchor instead.
@available(*, deprecated, message: "use topAnchor instead")
var topLayoutGuide: UILayoutSupport? {
set { self.topAnchor = newValue?.bottomAnchor }
get { return nil }
}
/// Specify optional layout guide for positioning the bar view. Deprecated, use bottomAnchor instead.
@available(*, deprecated, message: "use bottomAnchor instead")
var bottomLayoutGuide: UILayoutSupport? {
set { self.bottomAnchor = newValue?.topAnchor }
get { return nil }
}
/// Defines styles for the bar.
var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style)
/// Creates an instance of Dodo class
init(superview: UIView) {
self.superview = superview
DodoKeyboardListener.startListening()
}
/// Changes the style preset for the bar widget.
var preset: DodoPresets = DodoPresets.defaultPreset {
didSet {
if preset != oldValue {
style.parent = preset.style
}
}
}
/**
Shows the message bar with *.success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
func success(_ message: String) {
preset = .success
show(message)
}
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
func info(_ message: String) {
preset = .info
show(message)
}
/**
Shows the message bar with *.warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
func warning(_ message: String) {
preset = .warning
show(message)
}
/**
Shows the message bar with *.warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
func error(_ message: String) {
preset = .error
show(message)
}
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
func show(_ message: String) {
removeExistingBars()
setupHideTimer()
let bar = DodoToolbar(witStyle: style)
setupHideOnTap(bar)
bar.anchor = style.bar.locationTop ? topAnchor: bottomAnchor
bar.buttonViewDelegate = self
bar.show(inSuperview: superview, withMessage: message)
}
/// Hide the message bar if it's currently shown.
func hide() {
hideTimer?.cancel()
toolbar?.hide({})
}
func listenForKeyboard() {
}
private var toolbar: DodoToolbar? {
get {
return superview.subviews.filter { $0 is DodoToolbar }.map { $0 as! DodoToolbar }.first
}
}
private func removeExistingBars() {
for view in superview.subviews {
if let existingToolbar = view as? DodoToolbar {
existingToolbar.removeFromSuperview()
}
}
}
// MARK: - Hiding after delay
private func setupHideTimer() {
hideTimer?.cancel()
if style.bar.hideAfterDelaySeconds > 0 {
hideTimer = MoaTimer.runAfter(style.bar.hideAfterDelaySeconds) { [weak self] timer in
DispatchQueue.main.async {
self?.hide()
}
}
}
}
// MARK: - Reacting to tap
private func setupHideOnTap(_ toolbar: UIView) {
onTap = OnTap(view: toolbar, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTapTheBar()
}
}
/// The bar has been tapped
private func didTapTheBar() {
style.bar.onTap?()
if style.bar.hideOnTap {
hide()
}
}
// MARK: - DodoButtonViewDelegate
func buttonDelegateDidTap(_ buttonStyle: DodoButtonStyle) {
if buttonStyle.hideOnTap {
hide()
}
}
}
| 9983e88991e458a832020efbc9f20a8d | 23.712121 | 162 | 0.662784 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | refs/heads/master | v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/ListExamples/Controller/ListExamplesViewController.swift | mit | 1 | //
// ViewController.swift
// SciChartShowcaseDemo
//
// Created by Mykola Hrybeniuk on 2/22/17.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import UIKit
struct ListExamplesSeguesId {
static let medical = "MedicalExampleSegueId"
static let audio = "AudioExampleSegueId"
static let trader = "TraderExampleSegueId"
static let dashboard = "DashboardExampleSegueId"
static let sales = "SalesDashboardExampleSegueId"
}
class ListExamplesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var examplesTableView: UITableView!
let dataSource = [ExampleItem("Heartbeat ECG", "This is a brand new way of presenting some medical data.", "MedicalExample", ListExamplesSeguesId.medical),
ExampleItem("Audio Analyzer", "And this is a brand new way of presenting audio data.", "AudioAnalyzerExample", ListExamplesSeguesId.audio),
ExampleItem("Trader", "Another cool example, which shows how amazing we are when you need to display trading data.", "", ListExamplesSeguesId.trader),
ExampleItem("Dashboard", "", "", ListExamplesSeguesId.dashboard),
ExampleItem("Sales Dashboard", "", "", ListExamplesSeguesId.sales)]
override func viewDidLoad() {
super.viewDidLoad()
examplesTableView.delegate = self
examplesTableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isHidden = true
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
return
}
performSegue(withIdentifier: dataSource[indexPath.row - 1].segueId, sender: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count + 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
return self.examplesTableView.dequeueReusableCell(withIdentifier: "exampleTableViewHeader")! as UITableViewCell
}
else{
let cell: ExampleTableViewCell = Bundle.main.loadNibNamed("ExampleTableViewCell", owner: self, options: nil)![0] as! ExampleTableViewCell
cell.updateContent(exampleDetails: dataSource[indexPath.row-1])
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 70
}
return 160
}
}
| 5be3caf61d629e4d1271f425ba6259ac | 37.824324 | 172 | 0.673164 | false | false | false | false |
hachinobu/CleanQiitaClient | refs/heads/master | PresentationLayer/Routing/Item/ItemRouting.swift | mit | 1 | //
// ItemRouting.swift
// CleanQiitaClient
//
// Created by Takahiro Nishinobu on 2016/09/25.
// Copyright © 2016年 hachinobu. All rights reserved.
//
import Foundation
public protocol ItemRouting: Routing {
func segueItemList(userId: String)
}
//public class ItemRoutingImpl: ItemRouting {
//
// weak public var viewController: UIViewController? {
// didSet {
// viewController?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
// }
// }
//
// public func segueItemList(userId: String) {
//
// let repository = UserItemListRepositoryImpl.shared
// let useCase = UserItemListUseCaseImpl(repository: repository, userId: userId)
// let presenter = UserItemListPresenterImpl(useCase: useCase)
//
// let navigationController = UIStoryboard(name: "ItemListScreen", bundle: Bundle(for: ItemListViewController.self)).instantiateInitialViewController() as! UINavigationController
// let vc = navigationController.topViewController as! ItemListViewController
//
// let routing = UserItemListRoutingImpl()
// routing.viewController = vc
// vc.injection(presenter: presenter, routing: routing)
//
// viewController?.navigationController?.pushViewController(vc, animated: true)
//
// }
//
//}
//
//
//public class UserItemRoutingImpl: ItemRoutingImpl {
//
// override public func segueItemList(userId: String) {
// let _ = viewController?.navigationController?.popViewController(animated: true)
// }
//
//}
| 82506e1a15ac8f959edea4c676ecaf34 | 32.326531 | 185 | 0.670545 | false | false | false | false |
leo150/Pelican | refs/heads/develop | Sources/Pelican/API/Types/Markup/Inline.swift | mit | 1 | //
// Inline.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
import Vapor
import FluentProvider
/**
Represents a series of inline buttons that will be displayed underneath the message when included with it.
Each inline button can do one of the following:
_ _ _ _ _
**Callback Data**
This sends a small String back to the bot as a `CallbackQuery`, which is automatically filtered
back to the session and to a `callbackState` if one exists.
Alternatively if the keyboard the button belongs to is part of a `Prompt`, it will automatically
be received by it in the respective ChatSession, and the prompt will respond based on how you have set
it up.
**URL**
The button when pressed will re-direct users to a webpage.
**Inine Query Switch**
This can only be used when the bot supports Inline Queries. This prompts the user to select one of their chats
to open it, and when open the client will insert the bot‘s username and a specified query in the input field.
**Inline Query Current Chat**
This can only be used when the bot supports Inline Queries. Pressing the button will insert the bot‘s username
and an optional specific inline query in the current chat's input field.
*/
final public class MarkupInline: Model, MarkupType, Equatable {
public var storage = Storage()
public var keyboard: [[MarkupInlineKey]] = []
//public var keyboard: [MarkupInlineRow] = []
// Blank!
public init() {
return
}
/**
Creates an Inline Keyboard using a series of specified `MarkupInlineKey` types, where all buttons will
be arranged on a single row.
- parameter buttonsIn: The buttons to be included in the keyboard.
*/
public init(withButtons buttonsIn: MarkupInlineKey...) {
var array: [MarkupInlineKey] = []
for button in buttonsIn {
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of specified button label and URL string pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/url String tuples that will define each key on the keyboard.
*/
public init(withURL sequence: (url: String, text: String)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
let button = MarkupInlineKey(fromURL: tuple.url, text: tuple.text)
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of specified button label and callback String pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/callback String tuples that will define each key on the keyboard.
*/
public init?(withCallback sequence: (query: String, text: String?)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
// Try to process them, but propogate the error if it fails.
guard let button = MarkupInlineKey(fromCallbackData: tuple.query, text: tuple.text) else {
return nil
}
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using sets of arrays containing label and callback tuples, where each tuple array
is a single row.
- parameter array: A an array of label/callback String tuple arrays that will define each row on the keyboard.
*/
public init?(withCallback array: [[(query: String, text: String)]]) {
for row in array {
var array: [MarkupInlineKey] = []
for tuple in row {
// Try to process them, but propogate the error if it fails.
guard let button = MarkupInlineKey(fromCallbackData: tuple.query, text: tuple.text) else {
return nil
}
array.append(button)
}
keyboard.append(array)
}
}
/**
Creates an Inline Keyboard using a series of specified button label and "Inline Query Current Chat" String pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/"Inline Query Current Chat" String tuples that will define each key on the keyboard.
*/
public init(withInlineQueryCurrent sequence: (query: String, text: String)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
let button = MarkupInlineKey(fromInlineQueryCurrent: tuple.query, text: tuple.text)
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of specified button label and "Inline Query New Chat" String pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/"Inline Query New Chat" String tuples that will define each key on the keyboard.
*/
public init(withInlineQueryNewChat sequence: (query: String, text: String)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
let button = MarkupInlineKey(fromInlineQueryNewChat: tuple.query, text: tuple.text)
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of labels. The initializer will then generate an associated ID value for each
label and assign it to the button as Callback data, starting with "1" and incrementing upwards.
All buttons wil be arranged on a single row.
- parameter labels: A sequence of String labels that will define each key on the keyboard.
*/
public init?(withGenCallback sequence: String...) {
var array: [MarkupInlineKey] = []
var id = 1
for label in sequence {
guard let button = MarkupInlineKey(fromCallbackData: String(id), text: label) else {
return nil
}
array.append(button)
id += 1
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a set of nested String Arrays, where the array structure defines the specific arrangement
of the keyboard.
The initializer will generate an associated ID value for eachlabel and assign it to the button as Callback data, starting
with "1" and incrementing upwards.
- parameter rows: A nested set of String Arrays, where each String array will form a single row on the inline keyboard.
*/
public init?(withGenCallback rows: [[String]]) {
var id = 1
for row in rows {
var array: [MarkupInlineKey] = []
for label in row {
guard let button = MarkupInlineKey(fromCallbackData: String(id), text: label) else {
return nil
}
array.append(button)
id += 1
}
keyboard.append(array)
}
}
/**
Adds an extra row to the keyboard using the sequence of buttons provided.
*/
public func addRow(sequence: MarkupInlineKey...) {
var array: [MarkupInlineKey] = []
for button in sequence {
array.append(button)
}
keyboard.append(array)
}
/**
Adds extra rows to the keyboard based on the array of buttons you provide.
*/
public func addRow(array: [MarkupInlineKey]...) {
for item in array {
keyboard.append(item)
}
}
/**
Returns all available callback data from any button held inside this markup
*/
public func getCallbackData() -> [String]? {
var data: [String] = []
for row in keyboard {
for key in row {
if key.type == .callbackData {
data.append(key.data)
}
}
}
return data
}
/**
Returns all labels associated with the inline keyboard.
*/
public func getLabels() -> [String] {
var labels: [String] = []
for row in keyboard {
for key in row {
labels.append(key.text)
}
}
return labels
}
/**
Returns the label thats associated with the provided data, if it exists.
*/
public func getLabel(withData data: String) -> String? {
for row in keyboard {
for key in row {
if key.data == data { return key.text }
}
}
return nil
}
/**
Returns the key thats associated with the provided data, if it exists.
*/
public func getKey(withData data: String) -> MarkupInlineKey? {
for row in keyboard {
for key in row {
if key.data == data { return key }
}
}
return nil
}
/**
Replaces a key with another provided one, by trying to match the given data with a key
*/
public func replaceKey(usingType type: InlineKeyType, data: String, newKey: MarkupInlineKey) -> Bool {
for (rowIndex, row) in keyboard.enumerated() {
var newRow = row
var replaced = false
// Iterate through each key in each row for a match
for (i, key) in newRow.enumerated() {
if replaced == true { continue }
if key.type == type {
if key.data == data {
newRow.remove(at: i)
newRow.insert(newKey, at: i)
replaced = true
}
}
}
// If we made a match, switch out the rows and exit
if replaced == true {
keyboard.remove(at: rowIndex)
keyboard.insert(newRow, at: rowIndex)
return true
}
}
return false
}
/**
Replaces a key with another provided one, by trying to match the keys it has with one that's provided.
*/
public func replaceKey(oldKey: MarkupInlineKey, newKey: MarkupInlineKey) -> Bool {
for (rowIndex, row) in keyboard.enumerated() {
var newRow = row
var replaced = false
// Iterate through each key in each row for a match
for (i, key) in newRow.enumerated() {
if replaced == true { continue }
if key == oldKey {
newRow.remove(at: i)
newRow.insert(newKey, at: i)
replaced = true
}
}
// If we made a match, switch out the rows and exit
if replaced == true {
keyboard.remove(at: rowIndex)
keyboard.insert(newRow, at: rowIndex)
return true
}
}
return false
}
/**
Tries to find and delete a key, based on a match with one provided.
*/
public func deleteKey(key: MarkupInlineKey) -> Bool {
for (rowIndex, row) in keyboard.enumerated() {
var newRow = row
var removed = false
// Iterate through each key in each row for a match
for (i, newKey) in newRow.enumerated() {
if removed == true { continue }
if key == newKey {
newRow.remove(at: i)
removed = true
}
}
// If we made a match, switch out the rows and exit
if removed == true {
keyboard.remove(at: rowIndex)
keyboard.insert(newRow, at: rowIndex)
return true
}
}
return false
}
static public func ==(lhs: MarkupInline, rhs: MarkupInline) -> Bool {
if lhs.keyboard.count != rhs.keyboard.count { return false }
for (i, lhsRow) in lhs.keyboard.enumerated() {
let rhsRow = rhs.keyboard[i]
if lhsRow.count != rhsRow.count { return false }
for (iKey, lhsKey) in lhsRow.enumerated() {
let rhsKey = rhsRow[iKey]
if lhsKey != rhsKey { return false }
}
}
return true
}
public required init(row: Row) throws {
keyboard = try row.get("inline_keyboard")
}
public func makeRow() throws -> Row {
var row = Row()
try row.set("inline_keyboard", keyboard)
return row
}
}
| 2d513b319f9c6b2f8509b87ef1865841 | 24.783654 | 137 | 0.67975 | false | false | false | false |
artursDerkintis/Starfly | refs/heads/master | Starfly/SFConstants.swift | mit | 1 | //
// Constants.swift
// Starfly
//
// Created by Arturs Derkintis on 9/13/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import UIKit
struct Images {
static let back = "back"
static let forward = "forward"
static let reload = "reload"
static let stop = "stopLoading"
static let home = "home"
static let bookmark = "bookmark"
static let bookmarkFill = "bookmarkFilled"
static let menu = "logo"
static let addTab = "addTab"
static let closeTab = "closeTab"
static let edit = "edit"
static let image = "image"
}
// MARK: Button Actions
struct SFActions{
static let goBack = "goBack"
static let goForward = "goForward"
static let reload = "reload"
static let stop = "stop"
static let goHome = "goHome"
static let share = "share"
static let menu = "menu"
}
enum SFTags : Int{
case goBack = 0
case goForward = 1
case reload = 2
case stop = 3
case home = 4
case share = 5
case menu = 6
}
func getAction(tag : SFTags) -> String{
switch tag{
case .goBack:
return SFActions.goBack
case .goForward:
return SFActions.goForward
case .home:
return SFActions.goHome
case .reload:
return SFActions.reload
case .stop:
return SFActions.stop
case .share:
return SFActions.share
case .menu:
return SFActions.menu
}
}
func backgroundImages() -> [String]{
var array = [String]()
for i in 1...20{
array.append("abs" + String(i))
}
return array
}
func backgroundImagesThumbnails() -> [String]{
var array = [String]()
for image in backgroundImages(){
array.append(image + "_small")
}
return array
}
typealias SFTabWeb = SFWebController -> Void
typealias SFContains = Bool -> Void
typealias SFNewContentLoaded = Bool -> Void
enum SFClockFace : Int {
case analog = 1//Default
case digital = 2
case battery = 3
}
struct SFColors {
static let lightBlue = UIColor(rgba: "#03A9F4")
static let darkBlue = UIColor(rgba: "#2196F3")
static let orange = UIColor(rgba: "#FF6D00")
static let red = UIColor(rgba: "#FF1744")
static let green = UIColor(rgba: "#4CAF50")
static let lime = UIColor(rgba: "#CDDC39")
static let indigo = UIColor(rgba: "#3F51B5")
static let pink = UIColor(rgba: "#E91E63")
static let cyan = UIColor(rgba: "#00BCD4")
static let teal = UIColor(rgba: "#009688")
static let grey = UIColor(rgba: "#607D8B")
static let dark = UIColor(rgba: "#212121")
static let yellow = UIColor(rgba: "#CFA601")
static let allColors =
[SFColors.cyan,
SFColors.dark,
SFColors.darkBlue,
SFColors.green,
SFColors.grey,
SFColors.indigo,
SFColors.lightBlue,
SFColors.lime,
SFColors.orange,
SFColors.pink,
SFColors.red,
SFColors.teal,
SFColors.yellow]
}
enum SFWebState{
case web
case home
}
| afa983cdaac562f4499cd182d06aa3f8 | 23.808 | 54 | 0.601741 | false | false | false | false |
gpancio/iOS-Prototypes | refs/heads/master | GPUIKit/GPUIKit/Classes/CheckboxLabelView.swift | mit | 1 | //
// CheckboxLabelView.swift
// GPUIKit
//
// Created by Graham Pancio on 2016-04-27.
// Copyright © 2016 Graham Pancio. All rights reserved.
//
import UIKit
@IBDesignable
public class CheckboxLabelView: UIView {
@IBOutlet public weak var checkbox: CheckBox!
@IBOutlet weak var titleLabel: UILabel!
@IBInspectable
public var title: String? {
didSet {
titleLabel?.text = title
}
}
@IBInspectable
public var checked: Bool = false {
didSet {
checkbox?.isChecked = checked
}
}
@IBInspectable
public var checkboxTag: Int = -1 {
didSet {
checkbox?.tag = checkboxTag
}
}
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
view = loadViewFromNib()
view.frame = bounds
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "CheckboxLabelView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
| 9e510ec07ed1cc0db34e45f89bba29c8 | 20.587302 | 77 | 0.570588 | false | false | false | false |
cache0928/CCWeibo | refs/heads/master | CCWeibo/CCWeibo/Classes/NewPost/EmoticonsKB/EmoticonModel/EmoticonAttachment.swift | mit | 1 | //
// EmoticonAttachment.swift
// CCWeibo
//
// Created by 徐才超 on 16/2/24.
// Copyright © 2016年 徐才超. All rights reserved.
//
import UIKit
class EmoticonAttachment: NSTextAttachment {
var chs: String?
class func createEmoticonAttachmentString(emoticon: EmoticonInfo, size: CGFloat) -> NSAttributedString? {
// 图片附件
if let image = "\(emoticon.id!)/\(emoticon.png!)".sinaEmoticon() {
let attachment = EmoticonAttachment()
attachment.chs = emoticon.chs
attachment.image = image
attachment.bounds = CGRect(x: 0, y: -3, width: 18, height: 18)
// 创建图文属性文本
let imageText = NSAttributedString(attachment: attachment)
return imageText
}
return nil
}
}
| 2770834d76285fb33146f403ad00ae5a | 27.777778 | 109 | 0.615187 | false | false | false | false |
carabina/Carlos | refs/heads/master | Tests/SwitchCacheTests.swift | mit | 2 | import Foundation
import Quick
import Nimble
import Carlos
let switchClosure: (String) -> CacheLevelSwitchResult = { str in
if count(str) > 5 {
return .CacheA
} else {
return .CacheB
}
}
private struct SwitchCacheSharedExamplesContext {
static let CacheA = "cacheA"
static let CacheB = "cacheB"
static let CacheToTest = "sutCache"
}
class SwitchCacheSharedExamplesConfiguration: QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("should correctly get") { (sharedExampleContext: SharedExampleContext) in
var cacheA: CacheLevelFake<String, Int>!
var cacheB: CacheLevelFake<String, Int>!
var finalCache: BasicCache<String, Int>!
beforeEach {
cacheA = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheA] as? CacheLevelFake<String, Int>
cacheB = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheB] as? CacheLevelFake<String, Int>
finalCache = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int>
}
context("when calling get") {
var fakeRequest: CacheRequest<Int>!
var result: CacheRequest<Int>!
var successValue: Int?
var errorValue: NSError?
beforeEach {
fakeRequest = CacheRequest<Int>()
cacheA.cacheRequestToReturn = fakeRequest
cacheB.cacheRequestToReturn = fakeRequest
successValue = nil
errorValue = nil
}
context("when the switch closure returns cacheA") {
let key = "quite long key"
beforeEach {
result = finalCache.get(key)
.onSuccess { value in
successValue = value
}
.onFailure { error in
errorValue = error
}
}
it("should not dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledGet).to(equal(0))
}
it("should dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledGet).to(equal(1))
}
it("should pass the right key") {
expect(cacheA.didGetKey).to(equal(key))
}
context("when the request succeeds") {
let value = 2010
beforeEach {
fakeRequest.succeed(value)
}
it("should call the original success closure") {
expect(successValue).to(equal(value))
}
it("should not call the original failure closure") {
expect(errorValue).to(beNil())
}
}
context("when the request fails") {
let errorCode = 101
beforeEach {
fakeRequest.fail(NSError(domain: "", code: errorCode, userInfo: nil))
}
it("should call the original failure closure") {
expect(errorValue?.code).to(equal(errorCode))
}
it("should not call the original success closure") {
expect(successValue).to(beNil())
}
}
}
context("when the switch closure returns cacheB") {
let key = "short"
beforeEach {
result = finalCache.get(key)
.onSuccess { value in
successValue = value
}
.onFailure { error in
errorValue = error
}
}
it("should not dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledGet).to(equal(0))
}
it("should dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledGet).to(equal(1))
}
it("should pass the right key") {
expect(cacheB.didGetKey).to(equal(key))
}
context("when the request succeeds") {
let value = 2010
beforeEach {
fakeRequest.succeed(value)
}
it("should call the original success closure") {
expect(successValue).to(equal(value))
}
it("should not call the original failure closure") {
expect(errorValue).to(beNil())
}
}
context("when the request fails") {
let errorCode = 101
beforeEach {
fakeRequest.fail(NSError(domain: "", code: errorCode, userInfo: nil))
}
it("should call the original failure closure") {
expect(errorValue?.code).to(equal(errorCode))
}
it("should not call the original success closure") {
expect(successValue).to(beNil())
}
}
}
}
}
sharedExamples("a switched cache with 2 fetch closures") { (sharedExampleContext: SharedExampleContext) in
var cacheA: CacheLevelFake<String, Int>!
var cacheB: CacheLevelFake<String, Int>!
var finalCache: BasicCache<String, Int>!
beforeEach {
cacheA = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheA] as? CacheLevelFake<String, Int>
cacheB = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheB] as? CacheLevelFake<String, Int>
finalCache = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int>
}
itBehavesLike("should correctly get") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
}
sharedExamples("a switched cache with 2 cache levels") { (sharedExampleContext: SharedExampleContext) in
var cacheA: CacheLevelFake<String, Int>!
var cacheB: CacheLevelFake<String, Int>!
var finalCache: BasicCache<String, Int>!
beforeEach {
cacheA = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheA] as? CacheLevelFake<String, Int>
cacheB = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheB] as? CacheLevelFake<String, Int>
finalCache = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int>
}
itBehavesLike("should correctly get") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
context("when calling set") {
let value = 30
context("when the switch closure returns cacheA") {
let key = "quite long key"
beforeEach {
finalCache.set(value, forKey: key)
}
it("should not dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledSet).to(equal(0))
}
it("should dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledSet).to(equal(1))
}
it("should pass the right key") {
expect(cacheA.didSetKey).to(equal(key))
}
it("should pass the right value") {
expect(cacheA.didSetValue).to(equal(value))
}
}
context("when the switch closure returns cacheB") {
let key = "short"
beforeEach {
finalCache.set(value, forKey: key)
}
it("should not dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledSet).to(equal(0))
}
it("should dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledSet).to(equal(1))
}
it("should pass the right key") {
expect(cacheB.didSetKey).to(equal(key))
}
it("should pass the right value") {
expect(cacheB.didSetValue).to(equal(value))
}
}
}
context("when calling clear") {
beforeEach {
finalCache.clear()
}
it("should dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledClear).to(equal(1))
}
it("should dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledClear).to(equal(1))
}
}
context("when calling onMemoryWarning") {
beforeEach {
finalCache.onMemoryWarning()
}
it("should dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledOnMemoryWarning).to(equal(1))
}
it("should dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledOnMemoryWarning).to(equal(1))
}
}
}
sharedExamples("a switched cache with a cache level and a fetch closure") { (sharedExampleContext: SharedExampleContext) in
var cacheA: CacheLevelFake<String, Int>!
var cacheB: CacheLevelFake<String, Int>!
var finalCache: BasicCache<String, Int>!
beforeEach {
cacheA = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheA] as? CacheLevelFake<String, Int>
cacheB = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheB] as? CacheLevelFake<String, Int>
finalCache = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int>
}
itBehavesLike("should correctly get") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
context("when calling set") {
let value = 30
context("when the switch closure returns cacheA") {
let key = "quite long key"
beforeEach {
finalCache.set(value, forKey: key)
}
it("should not dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledSet).to(equal(0))
}
it("should dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledSet).to(equal(1))
}
it("should pass the right key") {
expect(cacheA.didSetKey).to(equal(key))
}
it("should pass the right value") {
expect(cacheA.didSetValue).to(equal(value))
}
}
context("when the switch closure returns cacheB") {
let key = "short"
beforeEach {
finalCache.set(value, forKey: key)
}
it("should not dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledSet).to(equal(0))
}
it("should not dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledSet).to(equal(0))
}
}
}
context("when calling clear") {
beforeEach {
finalCache.clear()
}
it("should dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledClear).to(equal(1))
}
it("should not dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledClear).to(equal(0))
}
}
context("when calling onMemoryWarning") {
beforeEach {
finalCache.onMemoryWarning()
}
it("should dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledOnMemoryWarning).to(equal(1))
}
it("should not dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledOnMemoryWarning).to(equal(0))
}
}
}
sharedExamples("a switched cache with a fetch closure and a cache level") { (sharedExampleContext: SharedExampleContext) in
var cacheA: CacheLevelFake<String, Int>!
var cacheB: CacheLevelFake<String, Int>!
var finalCache: BasicCache<String, Int>!
beforeEach {
cacheA = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheA] as? CacheLevelFake<String, Int>
cacheB = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheB] as? CacheLevelFake<String, Int>
finalCache = sharedExampleContext()[SwitchCacheSharedExamplesContext.CacheToTest] as? BasicCache<String, Int>
}
itBehavesLike("should correctly get") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
context("when calling set") {
let value = 30
context("when the switch closure returns cacheA") {
let key = "quite long key"
beforeEach {
finalCache.set(value, forKey: key)
}
it("should not dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledSet).to(equal(0))
}
it("should not dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledSet).to(equal(0))
}
}
context("when the switch closure returns cacheB") {
let key = "short"
beforeEach {
finalCache.set(value, forKey: key)
}
it("should not dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledSet).to(equal(0))
}
it("should dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledSet).to(equal(1))
}
it("should pass the right key") {
expect(cacheB.didSetKey).to(equal(key))
}
it("should pass the right value") {
expect(cacheB.didSetValue).to(equal(value))
}
}
}
context("when calling clear") {
beforeEach {
finalCache.clear()
}
it("should not dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledClear).to(equal(0))
}
it("should dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledClear).to(equal(1))
}
}
context("when calling onMemoryWarning") {
beforeEach {
finalCache.onMemoryWarning()
}
it("should not dispatch the call to the first cache") {
expect(cacheA.numberOfTimesCalledOnMemoryWarning).to(equal(0))
}
it("should dispatch the call to the second cache") {
expect(cacheB.numberOfTimesCalledOnMemoryWarning).to(equal(1))
}
}
}
}
}
class SwitchCacheTests: QuickSpec {
override func spec() {
var cacheA: CacheLevelFake<String, Int>!
var cacheB: CacheLevelFake<String, Int>!
var finalCache: BasicCache<String, Int>!
describe("Switching two cache levels") {
beforeEach {
cacheA = CacheLevelFake<String, Int>()
cacheB = CacheLevelFake<String, Int>()
finalCache = switchLevels(cacheA, cacheB, switchClosure)
}
itBehavesLike("a switched cache with 2 cache levels") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
}
describe("Switching two fetch closures") {
beforeEach {
cacheA = CacheLevelFake<String, Int>()
cacheB = CacheLevelFake<String, Int>()
finalCache = switchLevels(cacheA.get, cacheB.get, switchClosure)
}
itBehavesLike("a switched cache with 2 fetch closures") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
}
describe("Switching a cache level and a fetch closure") {
beforeEach {
cacheA = CacheLevelFake<String, Int>()
cacheB = CacheLevelFake<String, Int>()
finalCache = switchLevels(cacheA, cacheB.get, switchClosure)
}
itBehavesLike("a switched cache with a cache level and a fetch closure") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
}
describe("Switching a fetch closure and a cache level") {
beforeEach {
cacheA = CacheLevelFake<String, Int>()
cacheB = CacheLevelFake<String, Int>()
finalCache = switchLevels(cacheA.get, cacheB, switchClosure)
}
itBehavesLike("a switched cache with a fetch closure and a cache level") {
[
SwitchCacheSharedExamplesContext.CacheA: cacheA,
SwitchCacheSharedExamplesContext.CacheB: cacheB,
SwitchCacheSharedExamplesContext.CacheToTest: finalCache
]
}
}
}
} | 47ac214f06db62c2b0b62670c16b8e62 | 32.116236 | 127 | 0.574103 | false | false | false | false |
apple/swift-argument-parser | refs/heads/main | Tests/ArgumentParserPackageManagerTests/PackageManager/Describe.swift | apache-2.0 | 1 | //===----------------------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift Argument Parser open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
import ArgumentParser
extension Package {
/// Describe the current package
struct Describe: ParsableCommand {
@OptionGroup()
var options: Options
@Option(help: "Output format")
var type: OutputType
enum OutputType: String, ExpressibleByArgument, Decodable {
case json
case text
}
}
}
| 898634bad6f8c66acc1c7a71b5fcd1db | 26.928571 | 80 | 0.561381 | false | false | false | false |
svachmic/ios-url-remote | refs/heads/master | URLRemote/Classes/Controllers/CategoryEditTableViewController.swift | apache-2.0 | 1 | //
// EditTableViewController.swift
// URLRemote
//
// Created by Michal Švácha on 17/01/17.
// Copyright © 2017 Svacha, Michal. All rights reserved.
//
import UIKit
import Bond
import Material
///
class CategoryEditTableViewController: UITableViewController, PersistenceStackController, Dismissable {
var stack: PersistenceStack! {
didSet {
viewModel = CategoryEditViewModel(dataSource: stack.dataSource!)
}
}
var viewModel: CategoryEditViewModel!
override func viewDidLoad() {
super.viewDidLoad()
self.setupBar()
self.setupTableView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - View setup
///
func setupBar() {
setupDismissButton(with: .close)
let editButton = IconButton(image: Icon.cm.edit, tintColor: .white)
editButton.pulseColor = .white
editButton.reactive.tap.bind(to: self) { me, _ in
me.displayCategoryNameChange()
}.dispose(in: reactive.bag)
let deleteButton = IconButton(image: UIImage(named: "delete"), tintColor: .white)
deleteButton.pulseColor = .white
deleteButton.reactive.tap.bind(to: self) { me, _ in
me.presentCategoryRemovalDialog()
}.dispose(in: reactive.bag)
self.toolbarController?.toolbar.rightViews = [editButton, deleteButton]
self.toolbarController?.toolbar.titleLabel.textColor = .white
viewModel.categoryName
.bind(to: toolbarController!.toolbar.reactive.title)
.dispose(in: reactive.bag)
}
///
func setupTableView() {
viewModel.entries.bind(to: tableView) { [unowned self] conts, indexPath, tableView in
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.TableViewCell.entryEdit) as! EntryEditTableViewCell
cell.bag.dispose()
let entry = conts[indexPath.row]
cell.nameLabel.text = entry.name
cell.showsReorderControl = true
cell.editButton.reactive.tap.bind(to: self) { me, _ in
let filteredEntries = me.viewModel.entries.array.filter { $0 == entry }
if let filteredEntry = filteredEntries[safe: 0] {
me.displayEntrySetup(entry: filteredEntry)
}
}.dispose(in: cell.reactive.bag)
return cell
}.dispose(in: reactive.bag)
tableView.reactive.dataSource.forwardTo = self
tableView.tableFooterView = UIView(frame: .zero)
tableView.separatorInset = UIEdgeInsets.zero
tableView.backgroundColor = UIColor(named: .gray)
tableView.setEditing(true, animated: false)
}
///
func displayEntrySetup(entry: Entry) {
let entryController = self.storyboard?.instantiateViewController(withIdentifier: Constants.StoryboardID.entrySetup) as! EntrySetupViewController
entryController.stack = self.stack
entryController.viewModel.setup(with: entry)
self.presentEmbedded(viewController: entryController, barTintColor: UIColor(named: .green))
}
// MARK: - Category renaming
///
func displayCategoryNameChange() {
let categoryDialog = AlertDialogBuilder
.dialog(title: "CHANGE_CATEGORY_NAME", text: "CHANGE_CATEGORY_NAME_DESC")
.cancelAction()
let okAction = UIAlertAction(
title: NSLocalizedString("OK", comment: ""),
style: .default,
handler: { [unowned self] _ in
if let textFields = categoryDialog.textFields, let textField = textFields[safe: 0], let text = textField.text, text != "" {
self.viewModel.renameCategory(name: text)
}
})
categoryDialog.addAction(okAction)
categoryDialog.addTextField { [unowned self] textField in
textField.placeholder = NSLocalizedString("CHANGE_CATEGORY_NAME_PLACEHOLDER", comment: "")
textField.text = self.viewModel.categoryName.value
textField.reactive
.isEmpty
.bind(to: okAction.reactive.enabled)
.dispose(in: categoryDialog.bag)
}
self.present(categoryDialog, animated: true, completion: nil)
}
// MARK: - Category removal
///
func presentCategoryRemovalDialog() {
let categoryDialog = AlertDialogBuilder
.dialog(title: "DELETE_CATEGORY", text: "DELETE_CATEGORY_DESC")
.cancelAction()
.destructiveAction(title: "DELETE", handler: { [unowned self] _ in
self.viewModel.removeCategory()
self.parent?.dismiss(animated: true, completion: nil)
})
self.present(categoryDialog, animated: true, completion: nil)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
viewModel.removeItem(index: indexPath.row)
}
}
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
viewModel.moveItem(from: fromIndexPath.row, to: to.row)
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
}
| e3792adf94366c77bd97d4f00073308d | 35.14557 | 152 | 0.622658 | false | false | false | false |
mspvirajpatel/SwiftyBase | refs/heads/master | SwiftyBase/Classes/View/BaseView.swift | mit | 1 | //
// BaseView.swift
// Pods
//
// Created by MacMini-2 on 30/08/17.
//
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
public typealias ControlTouchUpInsideEvent = (_ sender: AnyObject?, _ object: AnyObject?) -> ()
public typealias TableCellSelectEvent = (_ sender: AnyObject?, _ object: AnyObject?) -> ()
public typealias ScrollViewDidScrollEvent = (_ scrollView: UIScrollView?, _ object: AnyObject?) -> ()
public typealias TaskFinishedEvent = (_ successFlag: Bool?, _ object: AnyObject?) -> ()
public typealias SwitchStateChangedEvent = (_ sender: AnyObject?, _ state: Bool?) -> ()
@IBDesignable
open class BaseView: UIView {
// MARK: - Attributes -
/// Its object of BaseLayout Class for Mack the Constraint
open var baseLayout: AppBaseLayout!
/// Its for Set the Footer of TableView
open var tableFooterView: UIView!
/// Its for set the Backgroudimage in whole application
var backgroundImageView: BaseImageView!
/// Its for show the Error on View
var errorMessageLabel: UILabel!
/// Its for Show the Activity Indiacter at Footer of view
open var footerIndicatorView: UIActivityIndicatorView!
/// Its for Trackt current request is running in view or not
open var isLoadedRequest: Bool = false
var layoutSubViewEvent: TaskFinishedEvent!
/// Its for maintaint the multipule API Call queue.
open var operationQueue: OperationQueue!
/// Its for TableView Footer Height
open var tableFooterHeight: CGFloat = 0.0
// MARK: - Lifecycle -
/// Its will set corder radius of Whole Application View's
@IBInspectable open var cornerRadius: CGFloat = 0.0 {
didSet {
self.updateProperties()
}
}
/// The shadow color of the `ShadowView`, inspectable in Interface Builder
@IBInspectable open var shadowColor: UIColor = AppColor.shadow.value {
didSet {
self.updateProperties()
}
}
/// The shadow offset of the `ShadowView`, inspectable in Interface Builder
@IBInspectable open var shadowOffset: CGSize = CGSize(width: 0.0, height: 2) {
didSet {
self.updateProperties()
}
}
/// The shadow radius of the `ShadowView`, inspectable in Interface Builder
@IBInspectable open var shadowRadius: CGFloat = 4.0 {
didSet {
self.updateProperties()
}
}
/// The shadow opacity of the `ShadowView`, inspectable in Interface Builder
@IBInspectable open var shadowOpacity: Float = 0.5 {
didSet {
self.updateProperties()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func layoutSubviews() {
super.layoutSubviews()
self.updateShadowPath()
}
/**
Its will free the memory of basebutton's current hold object's. Mack every object nill her which is declare in class as Swift not automattically release the object.
*/
deinit {
print("BaseView Deinit Called")
self.releaseObject()
}
/**
Its will free the memory of basebutton's current hold object's. Mack every object nill her which is declare in class as Swift not automattically release the object. This method is need to over ride in every chiled view for memory managment.
*/
open func releaseObject() {
NotificationCenter.default.removeObserver(self)
if baseLayout != nil {
baseLayout.releaseObject()
baseLayout.metrics = nil
baseLayout.viewDictionary = nil
baseLayout = nil
}
if backgroundImageView != nil && backgroundImageView.superview != nil {
backgroundImageView.removeFromSuperview()
backgroundImageView = nil
}
else {
backgroundImageView = nil
}
if errorMessageLabel != nil && errorMessageLabel.superview != nil {
errorMessageLabel.removeFromSuperview()
errorMessageLabel = nil
}
else {
errorMessageLabel = nil
}
if tableFooterView != nil && tableFooterView.superview != nil {
tableFooterView.removeFromSuperview()
tableFooterView = nil
}
else {
tableFooterView = nil
}
if footerIndicatorView != nil && footerIndicatorView.superview != nil {
footerIndicatorView.removeFromSuperview()
footerIndicatorView = nil
} else {
footerIndicatorView = nil
}
if(operationQueue != nil) {
operationQueue.cancelAllOperations()
}
operationQueue = nil
}
// MARK: - Layout -
/// This method is used for the Load the Control when initialized.
open func loadViewControls() {
operationQueue = OperationQueue()
self.translatesAutoresizingMaskIntoConstraints = false
self.isExclusiveTouch = true
self.isMultipleTouchEnabled = true
self.layer.masksToBounds = false
self.updateProperties()
self.updateShadowPath()
}
fileprivate func updateProperties() {
self.layer.cornerRadius = self.cornerRadius
self.layer.shadowColor = self.shadowColor.cgColor
self.layer.shadowOffset = self.shadowOffset
self.layer.shadowRadius = self.shadowRadius
self.layer.shadowOpacity = self.shadowOpacity
}
/**
Updates the bezier path of the shadow to be the same as the layer's bounds, taking the layer's corner radius into account.
*/
fileprivate func updateShadowPath() {
self.layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).cgPath
}
/// This method is used called after View iniit, For set the Layout constraint of subView's
open func setViewlayout() {
if(baseLayout == nil) {
baseLayout = AppBaseLayout()
baseLayout.releaseObject()
}
}
/// This method is used to check internet is on or not.
/// It will Show the Footerview at bottom of View with indiacateView
open func loadTableFooterView() {
let screenSize: CGSize = UIScreen.main.bounds.size
footerIndicatorView = UIActivityIndicatorView(style: .white)
tableFooterHeight = footerIndicatorView.frame.size.height + 20.0
tableFooterView = UIView()
tableFooterView.backgroundColor = UIColor.clear
tableFooterView.frame = CGRect(x: 0.0, y: 0.0, width: screenSize.width, height: tableFooterHeight)
let tableHeaderSize: CGSize = tableFooterView.frame.size
footerIndicatorView.center = CGPoint(x: tableHeaderSize.width / 2.0, y: tableHeaderSize.height / 2.0)
footerIndicatorView.startAnimating()
footerIndicatorView.hidesWhenStopped = true
tableFooterView.addSubview(footerIndicatorView)
}
// MARK: - Public Interface -
/**
This is will check the TextControl is first in its SuperView
*/
open class func isFirstTextControlInSuperview(_ superview: UIView, textControl: UIView) -> Bool {
var isFirstTextControl: Bool = true
var textControlIndex: Int = -1
var viewControlIndex: Int = -1
if((superview.subviews.contains(textControl))) {
textControlIndex = superview.subviews.firstIndex(of: textControl)!
}
for view in (superview.subviews) {
if(view.isTextControl() && textControl != view) {
viewControlIndex = superview.subviews.firstIndex(of: view)!
if(viewControlIndex < textControlIndex) {
isFirstTextControl = false
break
}
}
}
return isFirstTextControl
}
/**
This is will check the TextControl is last in its SuperView
*/
open class func isLastTextControlInSuperview(_ superview: UIView, textControl: UIView) -> Bool {
var isLastTextControl: Bool = true
var textControlIndex: Int = -1
var viewControlIndex: Int = -1
if((superview.subviews.contains(textControl))) {
textControlIndex = superview.subviews.firstIndex(of: textControl)!
}
for view in (superview.subviews) {
if(view.isTextControl() && textControl != view) {
viewControlIndex = superview.subviews.firstIndex(of: view)!
if(viewControlIndex > textControlIndex) {
isLastTextControl = false
break
}
}
}
return isLastTextControl
}
/// This method is initialize the Background ImageView in Whole Application
func displayBackgroundImageView(_ image: UIImage?) {
if(backgroundImageView == nil) {
backgroundImageView = BaseImageView(frame: CGRect.zero)
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
backgroundImageView.contentMode = .scaleToFill
self.addSubview(backgroundImageView)
if(baseLayout == nil) {
baseLayout = AppBaseLayout()
}
baseLayout.expandView(backgroundImageView, insideView: self)
baseLayout = nil
}
if(image != nil) {
backgroundImageView.image = image
}
}
/**
This will Display Error message Label on View.
- parameter errorMessage : if Message Passed Blank than errorLabel Will Hide else if message not blank than error label will show.
*/
public func displayErrorMessageLabel(_ errorMessage: String?) {
AppUtility.executeTaskInMainQueueWithCompletion { [weak self] in
if self == nil {
return
}
if(self!.errorMessageLabel != nil) {
self!.errorMessageLabel.isHidden = true
self!.errorMessageLabel.text = ""
if(self!.errorMessageLabel.tag == -1) {
self!.sendSubviewToBack(self!.errorMessageLabel)
}
if(errorMessage != nil) {
if(self!.errorMessageLabel.tag == -1) {
self!.bringSubviewToFront(self!.errorMessageLabel)
}
self!.errorMessageLabel.isHidden = false
self!.errorMessageLabel.text = errorMessage
}
self!.errorMessageLabel.layoutSubviews()
}
else {
self!.errorMessageLabel = UILabel(frame: (self?.bounds)!)
self!.errorMessageLabel.font = Font(.installed(.AppleMedium), size: SystemConstants.IS_IPAD ? .standard(.h3) : .standard(.h4)).instance
self!.errorMessageLabel.numberOfLines = 0
self!.errorMessageLabel.preferredMaxLayoutWidth = 200
self!.errorMessageLabel.textAlignment = .center
self!.errorMessageLabel.backgroundColor = UIColor.clear
self!.errorMessageLabel.textColor = AppColor.labelErrorText.withAlpha(1.0)
self!.errorMessageLabel.tag = -1
self!.addSubview(self!.errorMessageLabel)
self!.displayErrorMessageLabel(errorMessage)
}
}
}
// MARK: - User Interaction -
// MARK: - Internal Helpers -
open func handleNetworkCheck(isAvailable: Bool, viewController from: UIView, showLoaddingView: Bool) {
AppUtility.executeTaskInMainQueueWithCompletion { [weak self] in
if self == nil {
return
}
if isAvailable == true {
if showLoaddingView == true
{
self?.makeToastActivity()
// BaseProgressHUD.shared.showInView(view: from)
}
}
else {
self?.isLoadedRequest = false
}
}
}
// MARK: - Server Request -
open func loadOperationServerRequest() {
if(!isLoadedRequest)
{
AppUtility.executeTaskInMainQueueWithCompletion { [weak self] in
if self == nil {
return
}
}
}
}
open func beginServerRequest() {
isLoadedRequest = true
}
}
extension UIView {
open func isShowEmptyView(_ isShow: Bool, message: String)
{
if isShow
{
//first remove old
for view in self.subviews {
if view.tag == 99 {
view.removeFromSuperview()
break
}
}
//init
let emptyStateView: BaseEmptyState = BaseEmptyState()
//customize
emptyStateView.message = message
emptyStateView.tag = 99
emptyStateView.buttonHidden = true
//add subview
self.addSubview(emptyStateView)
//add autolayout
emptyStateView.translatesAutoresizingMaskIntoConstraints = false
emptyStateView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
emptyStateView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
emptyStateView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true
emptyStateView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.55).isActive = true
self.layoutIfNeeded()
}
else {
for view in self.subviews {
if view.tag == 99 {
view.removeFromSuperview()
break
}
}
}
}
}
| bde99dd9cacf35eb09208c113eed8e60 | 29.182213 | 245 | 0.604715 | false | false | false | false |
schurik/ABCircularTimer | refs/heads/master | ABCircularTimer/ABCircularTimer.swift | mit | 1 | //
// ABProgressTimer.swift
// ABProgressTimerDemo
//
// Created by Alexander Buss on 08.02.15.
// Copyright (c) 2015 Alexander Buss. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = advance(rgba.startIndex, 1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
if countElements(hex) == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if countElements(hex) == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("invalid rgb string, length should be 7 or 9")
}
} else {
println("scan hex error")
}
} else {
print("invalid rgb string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
typealias ABProgressBlock = () -> (CGFloat)
@objc protocol ABCircularTimerDelegate: NSObjectProtocol {
optional func willUpdate(circularTimer: ABCircularTimer, percentage: CGFloat)
optional func didUpdate(circularTimer: ABCircularTimer, percentage: CGFloat)
optional func didFinish(circularTimer: ABCircularTimer, percentage: CGFloat)
}
@IBDesignable
class ABCircularTimer: UIView {
private var progress: CGFloat!
private var timer: NSTimer!
private var block: ABProgressBlock!
var delegate: ABCircularTimerDelegate?
var frameWidth: CGFloat!
var progressColor: UIColor!
var progressBackgroundColor: UIColor!
var circleBackgroundColor: UIColor!
override init(frame: CGRect) {
super.init(frame: frame)
setupDefault()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupDefault()
}
override func setValue(value: AnyObject?, forKey key: String) {
if key == "progressBackgroundColor" {
progressBackgroundColor = value as? UIColor
} else if key == "frameWidth" {
frameWidth = value as? CGFloat
} else if key == "progressColor" {
progressColor = value as? UIColor
} else if key == "circleBackgroundColor" {
circleBackgroundColor = value as? UIColor
} else {
super.setValue(value, forKey: key)
}
}
private func setupDefault() {
frameWidth = 5
progress = 0.3
backgroundColor = UIColor.clearColor()
progressColor = UIColor(rgba: "#00688b")
progressBackgroundColor = UIColor(rgba: "#87ceff")
circleBackgroundColor = UIColor.whiteColor()
}
private func makeIncrementer(seconds:Int) -> () -> CGFloat {
var i:CGFloat = 0
let sec = seconds*100
func incrementor() -> CGFloat {
return i++ / CGFloat(sec)
}
return incrementor
}
func startTimer(seconds: Int) {
progress = 0
block = makeIncrementer(seconds)
if timer == nil || !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1.0/100), target: self, selector: Selector("updateProgress"), userInfo: nil, repeats: true)
timer.fire()
}
}
func startWithProgressBlock(progressBlock:ABProgressBlock) {
block = progressBlock
if timer == nil || !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1.0/10), target: self, selector: Selector("updateProgress"), userInfo: nil, repeats: true)
timer.fire()
}
}
func updateProgress() {
delegate?.willUpdate?(self, percentage: progress)
progress = block()
setNeedsDisplay()
delegate?.didUpdate?(self, percentage: progress)
if progress >= 1.0 {
stopTimer()
}
}
func stopTimer() {
timer.invalidate()
delegate?.didFinish?(self, percentage: progress)
//progress = 0
//setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
drawFillPie(rect, margin: 0, color: circleBackgroundColor, percentage: 1)
drawFramePie(rect)
drawFillPie(rect, margin: frameWidth, color: progressBackgroundColor, percentage: 1)
drawFillPie(rect, margin: frameWidth, color: progressColor, percentage: progress)
}
func drawFramePie(frame: CGRect) {
let radius = min(CGRectGetHeight(frame), CGRectGetWidth(frame)) * 0.5;
let centerX = CGRectGetWidth(frame) * 0.5;
let centerY = CGRectGetHeight(frame) * 0.5;
UIColor.grayColor().set()
let fw = self.frameWidth + 2;
let frameRect = CGRectMake(
centerX - radius + fw,
centerY - radius + fw,
(radius - fw) * 2,
(radius - fw) * 2);
let insideFrame = UIBezierPath(ovalInRect: frameRect)
insideFrame.lineWidth = 5;
insideFrame.stroke();
}
func drawFillPie(frame: CGRect, margin: CGFloat, color: UIColor, percentage: CGFloat) {
let radius: CGFloat = min(CGRectGetHeight(frame), CGRectGetWidth(frame)) * 0.5 - margin;
let centerX: CGFloat = CGRectGetWidth(frame) * 0.5;
let centerY: CGFloat = CGRectGetHeight(frame) * 0.5;
let cgContext = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(cgContext, color.CGColor);
CGContextMoveToPoint(cgContext, centerX, centerY);
let end = CGFloat(-M_PI_2) + CGFloat(M_PI * 2) * CGFloat(percentage)
CGContextAddArc(cgContext, centerX, centerY, radius, CGFloat(-M_PI_2), end, 0);
CGContextClosePath(cgContext);
CGContextFillPath(cgContext);
}
} | d419208db97fa0614e1a3f8560d32e05 | 27.84375 | 156 | 0.696587 | false | false | false | false |
exchangegroup/MprHttp | refs/heads/master | MprHttpTests/TegHttpTextLoggerTests.swift | mit | 2 | import XCTest
import MprHttp
class TegHttpTextLoggerTests: XCTestCase {
var obj: TegHttpText!
override func setUp() {
obj = TegHttpText()
}
func testHttpTextLogger_success() {
StubHttp.withText("Hello", forUrlPart: "server.com")
var identity = TegHttpRequestIdentity(url: "http://server.com/")
var httpLogMessages = [String]()
var logTypes = [TegHttpLogTypes]()
var statusCodes = [Int?]()
identity.logger = { message, logType, statusCode in
httpLogMessages.append(message)
logTypes.append(logType)
statusCodes.append(statusCode)
}
let expectation = expectationWithDescription("HTTP response received")
obj.load(identity,
onSuccess: { text in },
onError: { error, reponse, body in },
onAlways: {
expectation.fulfill()
}
)
waitForExpectationsWithTimeout(1) { error in }
XCTAssertEqual(2, httpLogMessages.count)
XCTAssertEqual("GET http://server.com/", httpLogMessages[0])
XCTAssertEqual(TegHttpLogTypes.RequestMethodAndUrl, logTypes[0])
XCTAssert(statusCodes[0] == nil)
XCTAssertEqual("Hello", httpLogMessages[1])
XCTAssertEqual(TegHttpLogTypes.ResponseSuccessBody, logTypes[1])
XCTAssertEqual(200, statusCodes[1]!)
}
func testHttpTextLogger_error() {
StubHttp.withText("Test error", forUrlPart: "server.com", statusCode: 422)
var identity = TegHttpRequestIdentity(url: "http://server.com/")
var httpLogMessages = [String]()
var logTypes = [TegHttpLogTypes]()
var statusCodes = [Int?]()
identity.logger = { message, logType, statusCode in
httpLogMessages.append(message)
logTypes.append(logType)
statusCodes.append(statusCode)
}
let expectation = expectationWithDescription("HTTP response received")
obj.load(identity,
onSuccess: { text in },
onError: { error, reponse, body in },
onAlways: {
expectation.fulfill()
}
)
waitForExpectationsWithTimeout(1) { error in }
XCTAssertEqual(2, httpLogMessages.count)
XCTAssertEqual("GET http://server.com/", httpLogMessages[0])
XCTAssertEqual(TegHttpLogTypes.RequestMethodAndUrl, logTypes[0])
XCTAssert(statusCodes[0] == nil)
XCTAssertEqual("Test error", httpLogMessages[1])
XCTAssertEqual(TegHttpLogTypes.ResponseErrorBody, logTypes[1])
XCTAssertEqual(422, statusCodes[1]!)
}
func testHttpTextLogger_httpError() {
// Code: -1009
let notConnectedErrorCode = Int(CFNetworkErrors.CFURLErrorNotConnectedToInternet.rawValue)
let notConnectedError = NSError(domain: NSURLErrorDomain,
code: notConnectedErrorCode, userInfo: nil)
StubHttp.withError(notConnectedError, forUrlPart: "server.com")
var identity = TegHttpRequestIdentity(url: "http://server.com/")
var httpLogMessages = [String]()
var logTypes = [TegHttpLogTypes]()
var statusCodes = [Int?]()
identity.logger = { message, logType, statusCode in
httpLogMessages.append(message)
logTypes.append(logType)
statusCodes.append(statusCode)
}
let expectation = expectationWithDescription("HTTP response received")
obj.load(identity,
onSuccess: { text in },
onError: { error, reponse, body in },
onAlways: {
expectation.fulfill()
}
)
waitForExpectationsWithTimeout(1) { error in }
XCTAssertEqual(2, httpLogMessages.count)
XCTAssertEqual("GET http://server.com/", httpLogMessages[0])
XCTAssertEqual(TegHttpLogTypes.RequestMethodAndUrl, logTypes[0])
XCTAssert(statusCodes[0] == nil)
XCTAssertEqual("Error Domain=NSURLErrorDomain Code=-1009 \"(null)\"", httpLogMessages[1])
XCTAssertEqual(TegHttpLogTypes.ResponseHttpError, logTypes[1])
XCTAssert(statusCodes[1] == nil)
}
}
| b677c0451c6a8decdf9059b5e4786007 | 29.046154 | 94 | 0.674091 | false | true | false | false |
Moya/Moya | refs/heads/master | Tests/MoyaTests/Single+MoyaSpec.swift | mit | 1 | import Quick
import Moya
import RxSwift
import Nimble
import Foundation
final class SingleMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes closed range upperbound") {
let data = Data()
let single = Response(statusCode: 10, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0...9).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes closed range lowerbound") {
let data = Data()
let single = Response(statusCode: -1, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0...9).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes with range upperbound") {
let data = Data()
let single = Response(statusCode: 10, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0..<10).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes with range lowerbound") {
let data = Data()
let single = Response(statusCode: -1, data: data).asSingle()
var errored = false
_ = single.filter(statusCodes: 0..<10).subscribe { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = Data()
let single = Response(statusCode: 404, data: data).asSingle()
var errored = false
_ = single.filterSuccessfulStatusCodes().subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = Data()
let single = Response(statusCode: 404, data: data).asSingle()
var errored = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = Data()
let single = Response(statusCode: 304, data: data).asSingle()
var called = false
_ = single.filterSuccessfulStatusAndRedirectCodes().subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("knows how to filter individual status code") {
let data = Data()
let single = Response(statusCode: 42, data: data).asSingle()
var called = false
_ = single.filter(statusCode: 42).subscribe(onSuccess: { _ in
called = true
})
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = Data()
let single = Response(statusCode: 43, data: data).asSingle()
var errored = false
_ = single.filter(statusCode: 42).subscribe { event in
switch event {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testImage
guard let data = image.asJPEGRepresentation(0.75) else {
fatalError("Failed creating Data from Image")
}
let single = Response(statusCode: 200, data: data).asSingle()
var size: CGSize?
_ = single.mapImage().subscribe(onSuccess: { image in
size = image.size
})
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = Data()
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapImage().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
fatalError("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedJSON: [String: String]?
_ = single.mapJSON().subscribe(onSuccess: { json in
if let json = json as? [String: String] {
receivedJSON = json
}
})
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
guard let data = json.data(using: .utf8) else {
fatalError("Failed creating Data from JSON String")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapJSON().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
switch receivedError {
case .some(.jsonMapping):
break
default:
fail("expected NSError with \(NSCocoaErrorDomain) domain")
}
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
guard let data = string.data(using: .utf8) else {
fatalError("Failed creating Data from String")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedString: String?
_ = single.mapString().subscribe(onSuccess: { string in
receivedString = string
})
expect(receivedString).to(equal(string))
}
it("maps data representing a string at a key path to a string") {
let string = "You have the rights to the remains of a silent attorney."
let json = ["words_to_live_by": string]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
fatalError("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedString: String?
_ = single.mapString(atKeyPath: "words_to_live_by").subscribe(onSuccess: { string in
receivedString = string
})
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: MoyaError?
_ = single.mapString().subscribe { event in
switch event {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error as? MoyaError
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("object mapping") {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let json: [String: Any] = [
"title": "Hello, Moya!",
"createdAt": "1995-01-14T12:34:56"
]
it("maps data representing a json to a decodable object") {
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObject: Issue?
_ = single.map(Issue.self, using: decoder).subscribe(onSuccess: { object in
receivedObject = object
})
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to an array of decodable objects") {
let jsonArray = [json, json, json]
guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObjects: [Issue]?
_ = single.map([Issue].self, using: decoder).subscribe(onSuccess: { objects in
receivedObjects = objects
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 3
expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"]
}
it("maps empty data to a decodable object with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: OptionalIssue?
_ = single.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: [OptionalIssue]?
_ = single.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
context("when using key path mapping") {
it("maps data representing a json to a decodable object") {
let json: [String: Any] = ["issue": json] // nested json
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObject: Issue?
_ = single.map(Issue.self, atKeyPath: "issue", using: decoder).subscribe(onSuccess: { object in
receivedObject = object
})
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to a decodable object (#1311)") {
let json: [String: Any] = ["issues": [json]] // nested json array
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedObjects: [Issue]?
_ = single.map([Issue].self, atKeyPath: "issues", using: decoder).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title) == "Hello, Moya!"
expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps empty data to a decodable object with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: OptionalIssue?
_ = single.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let single = Response(statusCode: 200, data: Data()).asSingle()
var receivedObjects: [OptionalIssue]?
_ = single.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).subscribe(onSuccess: { object in
receivedObjects = object
})
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
it("map Int data to an Int value") {
let json: [String: Any] = ["count": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var count: Int?
_ = observable.map(Int.self, atKeyPath: "count", using: decoder).subscribe(onSuccess: { value in
count = value
})
expect(count).notTo(beNil())
expect(count) == 1
}
it("map Bool data to a Bool value") {
let json: [String: Any] = ["isNew": true]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var isNew: Bool?
_ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in
isNew = value
})
expect(isNew).notTo(beNil())
expect(isNew) == true
}
it("map String data to a String value") {
let json: [String: Any] = ["description": "Something interesting"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var description: String?
_ = observable.map(String.self, atKeyPath: "description", using: decoder).subscribe(onSuccess: { value in
description = value
})
expect(description).notTo(beNil())
expect(description) == "Something interesting"
}
it("map String data to a URL value") {
let json: [String: Any] = ["url": "http://www.example.com/test"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var url: URL?
_ = observable.map(URL.self, atKeyPath: "url", using: decoder).subscribe(onSuccess: { value in
url = value
})
expect(url).notTo(beNil())
expect(url) == URL(string: "http://www.example.com/test")
}
it("shouldn't map Int data to a Bool value") {
let json: [String: Any] = ["isNew": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var isNew: Bool?
_ = observable.map(Bool.self, atKeyPath: "isNew", using: decoder).subscribe(onSuccess: { value in
isNew = value
})
expect(isNew).to(beNil())
}
it("shouldn't map String data to an Int value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: Int?
_ = observable.map(Int.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
it("shouldn't map Array<String> data to an String value") {
let json: [String: Any] = ["test": ["123", "456"]]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: String?
_ = observable.map(String.self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
it("shouldn't map String data to an Array<String> value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let observable = Response(statusCode: 200, data: data).asSingle()
var test: [String]?
_ = observable.map([String].self, atKeyPath: "test", using: decoder).subscribe(onSuccess: { value in
test = value
})
expect(test).to(beNil())
}
}
it("ignores invalid data") {
var json = json
json["createdAt"] = "Hahaha" // invalid date string
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let single = Response(statusCode: 200, data: data).asSingle()
var receivedError: Error?
_ = single.map(Issue.self, using: decoder).subscribe { event in
switch event {
case .success:
fail("success called for invalid data")
case .failure(let error):
receivedError = error
}
}
if case let MoyaError.objectMapping(nestedError, _)? = receivedError {
expect(nestedError).to(beAKindOf(DecodingError.self))
} else {
fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>")
}
}
}
}
}
| 0892e3c1d26778d5a3af81ea2cd2c479 | 43.385666 | 150 | 0.495771 | false | false | false | false |
hazzargm/CSSE-290-iOSDev | refs/heads/master | GasStats/GasStats/CarFuelLogViewController.swift | mit | 1 | //
// CarFuelLogViewController.swift
// GasStats
//
// Created by CSSE Department on 1/30/15.
// Copyright (c) 2015 Gordon Hazzard & Grant Smith. All rights reserved.
//
import UIKit
class CarFuelLogViewController: SuperViewController, UITableViewDataSource, UITableViewDelegate {
let headingCellId = "HeadingCell"
let logCellId = "LogCell"
let loadingLogsCellId = "LoadingLogsCell"
@IBOutlet weak var carNameLabel: UILabel!
@IBOutlet weak var logTable: UITableView!
var carId: NSNumber?
var carName: String?
var logs = [GTLGasstatsGasStat]()
var logStrings = [String]()
var queryComplete = false
override func viewWillAppear(animated: Bool) {
self.carNameLabel.text = carName
self.logs = [GTLGasstatsGasStat]()
self.logStrings = [String]()
self.queryComplete = false
_queryForLogs()
}
override func viewDidLoad() {
super.viewDidLoad()
self.logTable.delegate = self
self.logTable.dataSource = self
}
// MARK: - Table View Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return max(1, self.logs.count)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
if(self.logs.count == 0){
if(!self.queryComplete){
cell = logTable.dequeueReusableCellWithIdentifier(loadingLogsCellId, forIndexPath: indexPath) as UITableViewCell
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
cell.accessoryView = spinner
spinner.startAnimating()
}
}else{
let log = logs[indexPath.row]
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
let date = dateFormatter.dateFromString(log.createDateTime)
dateFormatter.dateFormat = "EE, MMM dd, yyyy 'at' H:mm a"
let dateString = dateFormatter.stringFromDate(date!)
cell = logTable.dequeueReusableCellWithIdentifier(logCellId, forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = String(format: "%.2f MPG", log.mpg.doubleValue)
cell.detailTextLabel?.text = dateString
}
return cell
}
// MARK: - Private Helper Methods
func _queryForLogs(){
let query = GTLQueryGasstats.queryForGasstatListByCarUser() as GTLQueryGasstats
query.userId = self.user_id.longLongValue
query.carId = self.carId!.longLongValue
query.order = "create_date_time"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
service.executeQuery(query, completionHandler: { (ticket, response, e) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if e != nil {
self._showErrorDialog(e!)
} else {
let logCollection = response as GTLGasstatsGasStatCollection
if logCollection.items() != nil{
self.logs = logCollection.items() as [GTLGasstatsGasStat]
// self._generateCellStrings()
}
self.queryComplete = true
self.logTable.reloadData()
}
})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
(segue.destinationViewController as GasStatsTabBarViewController).selectedIndex = 1
}
// func _generateCellStrings(){
//
// }
}
| 4e7e474295b5547e049e0805de73cbcf | 29.561905 | 116 | 0.733873 | false | false | false | false |
ProfileCreator/ProfileCreator | refs/heads/master | ProfileCreator/ProfileCreator/Profile Settings/ProfileSettingsPayloadKeysEnabled.swift | mit | 1 | //
// ProfileSettingsPayloadKeysEnabled.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Foundation
import ProfilePayloads
extension ProfileSettings {
// MARK: -
// MARK: Check Any Subkey
// if ANY payload has this subkey enabled
func isEnabled(_ subkey: PayloadSubkey, onlyByUser: Bool, ignoreConditionals: Bool) -> Bool {
let domainSettings = self.viewSettings(forDomainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType) ?? [[String: Any]]()
if domainSettings.isEmpty {
return self.isEnabled(subkey, onlyByUser: onlyByUser, ignoreConditionals: ignoreConditionals, payloadIndex: 0)
} else {
for payloadIndex in domainSettings.indices {
if self.isEnabled(subkey, onlyByUser: onlyByUser, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex) { return true }
}
}
return false
}
// MARK: -
// MARK: Is Enabled: Subkey
// MARK: -
// MARK: Is Enabled: By…
func isEnabledByRequired(_ subkey: PayloadSubkey, parentIsEnabled: Bool, onlyByUser: Bool, isRequired: Bool, payloadIndex: Int) -> Bool {
if !onlyByUser, parentIsEnabled, isRequired {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Required", category: String(describing: self))
#endif
self.setCacheIsEnabled(true, forSubkey: subkey, payloadIndex: payloadIndex)
return true
}
return false
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByUser(_ subkey: PayloadSubkey, payloadIndex: Int) -> Bool? {
guard let isEnabled = self.viewValueEnabled(forSubkey: subkey, payloadIndex: payloadIndex) else { return nil }
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(isEnabled) - User", category: String(describing: self))
#endif
return isEnabled
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByDefault(_ subkey: PayloadSubkey, parentIsEnabled: Bool, onlyByUser: Bool) -> Bool? {
guard !onlyByUser, parentIsEnabled, subkey.enabledDefault else { return nil }
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Default", category: String(describing: self))
#endif
return true
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByDynamicDictionary(_ subkey: PayloadSubkey, parentIsEnabled: Bool, onlyByUser: Bool, payloadIndex: Int) -> Bool? {
guard !onlyByUser, parentIsEnabled, subkey.parentSubkey?.type == .dictionary, (subkey.key == ManifestKeyPlaceholder.key || subkey.key == ManifestKeyPlaceholder.value) else { return nil }
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Dynamic Dictionary", category: String(describing: self))
#endif
self.setCacheIsEnabled(true, forSubkey: subkey, payloadIndex: payloadIndex)
return true
}
// swiftlint:disable:next discouraged_optional_boolean
func isEnabledByArrayOfDictionaries(_ subkey: PayloadSubkey, parentIsEnabled: Bool, payloadIndex: Int, arrayIndex: Int) -> Bool? {
guard parentIsEnabled, subkey.isParentArrayOfDictionaries else { return nil }
let isEnabled: Bool
if arrayIndex == -1 || (arrayIndex != -1 && self.value(forSubkey: subkey, payloadIndex: payloadIndex) != nil) {
isEnabled = true
} else {
isEnabled = false
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(isEnabled) - Child in Array of Dictionaries", category: String(describing: self))
#endif
return isEnabled
}
func isEnabled(_ subkey: PayloadSubkey, onlyByUser: Bool, ignoreConditionals: Bool, payloadIndex: Int, arrayIndex: Int = -1) -> Bool {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking - onlyByUser: \(onlyByUser), ignoreConditionals: \(ignoreConditionals), payloadIndex: \(payloadIndex), arrayIndex: \(arrayIndex)", category: String(describing: self))
#endif
// ---------------------------------------------------------------------
// Check if the subkey has a cached isEnabled-value, if so return that
// ---------------------------------------------------------------------
if let isEnabledCache = self.cacheIsEnabled(subkey, payloadIndex: payloadIndex) { return isEnabledCache }
// ---------------------------------------------------------------------
// Check if all parent subkeys are enabled
// ---------------------------------------------------------------------
let isEnabledParent = self.isEnabledParent(subkey, onlyByUser: onlyByUser, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex, arrayIndex: arrayIndex)
// ---------------------------------------------------------------------
// Check if the parent subkey is an array and enabled, then this subkey is automatically enabled
// ---------------------------------------------------------------------
guard !self.isEnabledParentAnArray(isEnabledParent, subkey: subkey, onlyByUser: onlyByUser, payloadIndex: payloadIndex) else { return true }
// ---------------------------------------------------------------------
// Set the default isEnabled state
// ---------------------------------------------------------------------
var isEnabled = !self.disableOptionalKeys
// ---------------------------------------------------------------------
// Check if the subkey is required
// ---------------------------------------------------------------------
let isRequired = self.isRequired(subkey: subkey, ignoreConditionals: ignoreConditionals, isEnabledOnlyByUser: onlyByUser, payloadIndex: payloadIndex)
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isRequired: \(isRequired)", category: String(describing: self))
#endif
// ---------------------------------------------------------------------
// Check if the subkey is required, it's parent is enabled and not only keys manually enabled by the user should be returned.
// ---------------------------------------------------------------------
guard !isEnabledByRequired(subkey, parentIsEnabled: isEnabledParent, onlyByUser: onlyByUser, isRequired: isRequired, payloadIndex: payloadIndex) else { return true }
// ---------------------------------------------------------------------
// Check if the subkey is manually enabled/disabled by the user
// ---------------------------------------------------------------------
if let isEnabledByUser = self.isEnabledByUser(subkey, payloadIndex: payloadIndex) {
isEnabled = isEnabledByUser
// ---------------------------------------------------------------------
// Check if the subkey is enabled by default in the manifest, it's parent is enabled and not only keys manually enabled by the user should be returned.
// ---------------------------------------------------------------------
} else if let isEnabledByDefault = self.isEnabledByDefault(subkey, parentIsEnabled: isEnabledParent, onlyByUser: onlyByUser) {
isEnabled = isEnabledByDefault
// ---------------------------------------------------------------------
// Check if the subkey is a dynamic dictionary, it's parent is enabled and not only keys manually enabled by the user should be returned.
// ---------------------------------------------------------------------
} else if let isEnabledByDynamicDictionary = self.isEnabledByDynamicDictionary(subkey, parentIsEnabled: isEnabledParent, onlyByUser: onlyByUser, payloadIndex: payloadIndex) {
return isEnabledByDynamicDictionary
// ---------------------------------------------------------------------
// Check if the subkey is a child in an array of dictionaries, and if it's parent is enabled.
// ---------------------------------------------------------------------
} else if let isEnabledByArrayOfDictionaries = self.isEnabledByArrayOfDictionaries(subkey, parentIsEnabled: isEnabledParent, payloadIndex: payloadIndex, arrayIndex: arrayIndex) {
return isEnabledByArrayOfDictionaries
}
// ---------------------------------------------------------------------
// Check if key was not enabled, and if key is an array, then loop through each child subkeys and if any child is enabled this key should also be enabled
// ---------------------------------------------------------------------
// FIXME: Should this be typeInput aswell?
if !isEnabled, (subkey.type != .array || subkey.rangeMax as? Int == 1) {
isEnabled = self.isEnabled(childSubkeys: subkey.subkeys, forSubkey: subkey, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex)
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(isEnabled)", category: String(describing: self))
#endif
// ---------------------------------------------------------------------
// Check if enabled state should be cached
// ---------------------------------------------------------------------
if !ignoreConditionals && ( !onlyByUser || onlyByUser && !isRequired ) {
self.setCacheIsEnabled(isEnabled, forSubkey: subkey, payloadIndex: payloadIndex)
}
// ---------------------------------------------------------------------
// Return if key is enabled
// ---------------------------------------------------------------------
return isEnabled
}
// MARK: -
// MARK: Is Enabled: Parent
func isEnabledParent(_ subkey: PayloadSubkey, onlyByUser: Bool, ignoreConditionals: Bool, payloadIndex: Int, arrayIndex: Int) -> Bool {
guard !onlyByUser, let parentSubkeys = subkey.parentSubkeys else {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabledParent: \(true)", category: String(describing: self))
#endif
return true
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking - Parents", category: String(describing: self))
#endif
// Loop through all parents
for parentSubkey in parentSubkeys {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking - Parent: \(parentSubkey.keyPath)", category: String(describing: self))
#endif
// Ignore Dictionaries in Single Dictionary Arrays
if parentSubkey.type == .dictionary, (parentSubkey.parentSubkey?.type == .array && parentSubkey.parentSubkey?.rangeMax as? Int == 1) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - IGNORING parent: \(parentSubkey.keyPath) - Dictionary in single dictionary array", category: String(describing: self))
#endif
continue
} else {
if !self.isEnabled(parentSubkey, onlyByUser: false, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex, arrayIndex: arrayIndex) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabledParent: \(false)", category: String(describing: self))
#endif
return false
}
}
}
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabledParent: \(true)", category: String(describing: self))
#endif
return true
}
// Check if parent is an array, except if the array key has rangeMax set to 1
func isEnabledParentAnArray(_ isEnabledParent: Bool, subkey: PayloadSubkey, onlyByUser: Bool, payloadIndex: Int) -> Bool {
if !onlyByUser, isEnabledParent, subkey.parentSubkey?.typeInput == .array, !(subkey.parentSubkey?.rangeMax as? Int == 1) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - ParentArray", category: String(describing: self))
#endif
self.setCacheIsEnabled(true, forSubkey: subkey, payloadIndex: payloadIndex)
return true
}
return false
}
// MARK: -
// MARK: Check Child Subkeys
func isEnabled(childSubkeys: [PayloadSubkey], forSubkey subkey: PayloadSubkey, ignoreConditionals: Bool, payloadIndex: Int) -> Bool {
for childSubkey in childSubkeys {
if childSubkey.type == .dictionary, subkey.rangeMax as? Int == 1 {
for dictSubkey in subkey.subkeys {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking Child Dictionary Subkey: \(dictSubkey.keyPath)", category: String(describing: self))
#endif
if self.isEnabled(dictSubkey, onlyByUser: true, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Child: \(childSubkey.keyPath)", category: String(describing: self))
#endif
return true
}
}
} else {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled - Checking Child Subkey: \(childSubkey.keyPath)", category: String(describing: self))
#endif
if self.isEnabled(childSubkey, onlyByUser: true, ignoreConditionals: ignoreConditionals, payloadIndex: payloadIndex) {
#if DEBUGISENABLED
Log.shared.debug(message: "Subkey: \(subkey.keyPath) isEnabled: \(true) - Child: \(childSubkey.keyPath)", category: String(describing: self))
#endif
return true
}
}
}
return false
}
}
| 18802865fa9059ac57dda1d31e593a10 | 49.694158 | 248 | 0.564195 | false | false | false | false |
xcodeswift/xcproj | refs/heads/master | Sources/XcodeProj/Objects/BuildPhase/PBXBuildRule.swift | mit | 1 | import Foundation
/// A PBXBuildRule is used to specify a method for transforming an input file in to an output file(s).
public final class PBXBuildRule: PBXObject {
// MARK: - Attributes
/// Element compiler spec.
public var compilerSpec: String
/// Element file patterns.
public var filePatterns: String?
/// Element file type.
public var fileType: String
/// Element is editable.
public var isEditable: Bool
/// Element name.
public var name: String?
/// Element output files.
public var outputFiles: [String]
/// Element input files.
public var inputFiles: [String]?
/// Element output files compiler flags.
public var outputFilesCompilerFlags: [String]?
/// Element script.
public var script: String?
/// Element run once per architecture.
public var runOncePerArchitecture: Bool?
// MARK: - Init
public init(compilerSpec: String,
fileType: String,
isEditable: Bool = true,
filePatterns: String? = nil,
name: String? = nil,
outputFiles: [String] = [],
inputFiles: [String]? = nil,
outputFilesCompilerFlags: [String]? = nil,
script: String? = nil,
runOncePerArchitecture: Bool? = nil) {
self.compilerSpec = compilerSpec
self.filePatterns = filePatterns
self.fileType = fileType
self.isEditable = isEditable
self.name = name
self.outputFiles = outputFiles
self.inputFiles = inputFiles
self.outputFilesCompilerFlags = outputFilesCompilerFlags
self.script = script
self.runOncePerArchitecture = runOncePerArchitecture
super.init()
}
// MARK: - Decodable
enum CodingKeys: String, CodingKey {
case compilerSpec
case filePatterns
case fileType
case isEditable
case name
case outputFiles
case inputFiles
case outputFilesCompilerFlags
case script
case runOncePerArchitecture
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
compilerSpec = try container.decodeIfPresent(.compilerSpec) ?? ""
filePatterns = try container.decodeIfPresent(.filePatterns)
fileType = try container.decodeIfPresent(.fileType) ?? ""
isEditable = try container.decodeIntBool(.isEditable)
name = try container.decodeIfPresent(.name)
outputFiles = try container.decodeIfPresent(.outputFiles) ?? []
inputFiles = try container.decodeIfPresent(.inputFiles)
outputFilesCompilerFlags = try container.decodeIfPresent(.outputFilesCompilerFlags)
script = try container.decodeIfPresent(.script)
runOncePerArchitecture = try container.decodeIntBoolIfPresent(.runOncePerArchitecture)
try super.init(from: decoder)
}
}
// MARK: - PBXBuildRule Extension (PlistSerializable)
extension PBXBuildRule: PlistSerializable {
var multiline: Bool { true }
func plistKeyAndValue(proj _: PBXProj, reference: String) -> (key: CommentedString, value: PlistValue) {
var dictionary: [CommentedString: PlistValue] = [:]
dictionary["isa"] = .string(CommentedString(PBXBuildRule.isa))
dictionary["compilerSpec"] = .string(CommentedString(compilerSpec))
if let filePatterns = filePatterns {
dictionary["filePatterns"] = .string(CommentedString(filePatterns))
}
dictionary["fileType"] = .string(CommentedString(fileType))
dictionary["isEditable"] = .string(CommentedString("\(isEditable.int)"))
if let name = name {
dictionary["name"] = .string(CommentedString(name))
}
dictionary["outputFiles"] = .array(outputFiles.map { .string(CommentedString($0)) })
if let inputFiles = inputFiles {
dictionary["inputFiles"] = .array(inputFiles.map { .string(CommentedString($0)) })
}
if let outputFilesCompilerFlags = outputFilesCompilerFlags {
dictionary["outputFilesCompilerFlags"] = .array(outputFilesCompilerFlags.map { PlistValue.string(CommentedString($0)) })
}
if let script = script {
dictionary["script"] = .string(CommentedString(script))
}
if let runOncePerArchitecture = runOncePerArchitecture {
dictionary["runOncePerArchitecture"] = .string(CommentedString("\(runOncePerArchitecture.int)"))
}
return (key: CommentedString(reference, comment: PBXBuildRule.isa),
value: .dictionary(dictionary))
}
}
| ae1bc80cc333c84fe04b47f5e8af9261 | 36.301587 | 132 | 0.65 | false | false | false | false |
pawel-sp/AppFlowController | refs/heads/master | AppFlowControllerTests/MockNavigationController.swift | mit | 1 | //
// MockNavigationController.swift
// AppFlowController
//
// Created by Paweł Sporysz on 20.06.2017.
// Copyright © 2017 Paweł Sporysz. All rights reserved.
//
import UIKit
class MockNavigationController: UINavigationController {
var pushViewControllerParams: (UIViewController, Bool)?
var popViewControllerParams: (Bool)?
var setViewControllersParams: ([UIViewController], Bool)?
var presentViewControllerParams: (UIViewController, Bool)?
var visibleViewControllerResult: UIViewController?
var didDismissAllPresentedViewControllers: Bool?
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
pushViewControllerParams = (viewController, animated)
}
override func popViewController(animated: Bool) -> UIViewController? {
popViewControllerParams = (animated)
return nil
}
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
presentViewControllerParams = (viewControllerToPresent, flag)
completion?()
}
override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) {
setViewControllersParams = (viewControllers, animated)
}
override var visibleViewController: UIViewController? {
return visibleViewControllerResult ?? super.visibleViewController
}
override func dismissAllPresentedViewControllers(completion: (() -> ())?) {
didDismissAllPresentedViewControllers = true
completion?()
}
}
class MockPopNavigationController: UINavigationController {
var popViewControllerParams: (Bool)?
override func popViewController(animated: Bool) -> UIViewController? {
popViewControllerParams = (animated)
return nil
}
}
| a8c85b2ea2eda3f9ea6e9450c4d2d9d8 | 32.763636 | 126 | 0.716209 | false | false | false | false |
djfitz/SFFontFeatures | refs/heads/master | SFFontFeaturesDemo/SFFontFeaturesDemo/SFFontFeaturesTableViewController.swift | mit | 1 | //
// SFFontFeaturesTableViewController.swift
// SFFontFeaturesDemo
//
// Created by Doug Hill on 12/8/16.
// Copyright © 2016 doughill. All rights reserved.
//
import UIKit
class SFFontFeaturesTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 50
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 11
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: FeatureTableViewCell.cellID, for: indexPath) as! FeatureTableViewCell
// Reset any previous default traits from the reused cell.
// Contextual alternatives encapsulate a number of font features, often dependent on the character string, so turn this feature
// off so it doesn't affect the results in the table.
cell.regularLabel.font = UIFont.systemFont(ofSize: cell.regularLabel.font.pointSize, weight: .regular).withTraits( SFFontFeatureTraits.withContextualAlternativeDisabled() )
cell.featuredLabel.font = UIFont.systemFont(ofSize: cell.featuredLabel.font.pointSize, weight: .regular).withTraits( SFFontFeatureTraits.withContextualAlternativeDisabled() )
// Show one font feature for each row
switch indexPath.row {
case 0:
cell.descLabel.text = "Straight-sided six and nine"
cell.regularLabel.text = "6 9"
cell.featuredLabel.text = "6 9"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withStraightSidedSixAndNineEnabled())
case 1:
cell.descLabel.text = "Open 4"
cell.regularLabel.text = "1234"
cell.featuredLabel.text = "1234"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withOpenFourEnabled())
case 2:
cell.descLabel.text = "High Legibility"
cell.regularLabel.text = "labcd0123456789 11:15"
cell.featuredLabel.text = "labcd0123456789 11:15"
let traits = SFFontFeatureTraits()
traits.highLegibility = TriState.on
cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withHighLegibilityEnabled())
case 3:
cell.descLabel.text = "Vertically Centered Colon"
cell.regularLabel.text = ":21"
let regTraits = SFFontFeatureTraits()
regTraits.contextualAlternatives = TriState.off
cell.regularLabel.font = cell.featuredLabel.font.withTraits(regTraits)
cell.featuredLabel.text = ":21"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withVerticallyCenteredColonEnabled())
case 4:
cell.descLabel.text = "One Story A"
cell.regularLabel.text = "a"
cell.featuredLabel.text = "a"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits(SFFontFeatureTraits.withOneStoryAEnabled())
case 5:
cell.descLabel.text = "Upper Case Small Capitals"
cell.regularLabel.text = "abcdefghABCDEFGH"
cell.featuredLabel.text = "abcdefghABCDEFGH"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withUpperCaseSmallCapitalsEnabled() )
case 6:
cell.descLabel.text = "Lower Case Small Capitals"
cell.regularLabel.text = "abcdefghABCDEFGH"
cell.featuredLabel.text = "abcdefghABCDEFGH"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withLowerCaseSmallCapitalsEnabled() )
case 7:
cell.descLabel.text = "Contextual Fractional Form"
cell.regularLabel.text = "99/100"
cell.featuredLabel.text = "99/100"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withContextualFractionalFormsEnabled() )
case 8:
cell.descLabel.text = "Monospaced vs. Proportional Numbers"
cell.regularHeaderLabel.text = " Proportional Numbers"
cell.regularLabel.text = "0123456789"
cell.regularLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withProportionallySpacedNumbersEnabled() )
cell.featuredHeaderLabel.text = "Monospaced Numbers"
cell.featuredLabel.text = "0123456789"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withMonospacedNumbersEnabled() )
case 9:
cell.descLabel.text = "Superior Positions (Superscript)"
cell.regularLabel.text = "See alsoibid"
let pref = NSMutableAttributedString(string: "See also")
pref.append(
NSMutableAttributedString(
string: "ibid",
attributes:
[
.font :
cell.regularLabel.font?.withTraits(
SFFontFeatureTraits.withSuperiorPositionsEnabled()) as Any
] ))
cell.featuredLabel.attributedText = pref
case 10:
cell.descLabel.text = "Inferior Positions (Subscript)"
cell.regularLabel.text = "C1H2O3S"
cell.featuredLabel.text = "C1H2O3S"
cell.featuredLabel.font = cell.featuredLabel.font.withTraits( SFFontFeatureTraits.withInferiorPositionsEnabled() )
default:
cell.descLabel.text = "Dunno about this one"
cell.regularLabel.text = "1 maybe 2"
cell.featuredLabel.text = "1 or 2"
}
return cell
}
}
| d0518f5332243c591921b9c7c0c6b0a2 | 44.291667 | 182 | 0.622815 | false | false | false | false |
kumabook/FeedlyKit | refs/heads/master | Spec/FeedsAPISpec.swift | mit | 1 | //
// FeedsAPISpec.swift
// FeedlyKit
//
// Created by Hiroki Kumamoto on 3/10/16.
// Copyright © 2016 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import FeedlyKit
import Quick
import Nimble
class FeedsAPISpec: QuickSpec {
let feedId = "feed/http://kumabook.github.io/feed.xml"
let feedId2 = "feed/https://news.ycombinator.com/rss"
let client: CloudAPIClient = CloudAPIClient(target: SpecHelper.target)
override func spec() {
beforeEach {
sleep(1)
}
describe("fetchFeed") {
var statusCode = 0
var feed: Feed?
beforeEach {
let _ = self.client.fetchFeed(self.feedId) {
guard let code = $0.response?.statusCode,
let _feed = $0.result.value else { return }
statusCode = code
feed = _feed
}
}
it ("fetches a specified feed") {
expect(statusCode).toFinally(equal(200))
expect(feed).toFinallyNot(beNil())
}
}
describe("fetchFeeds") {
var statusCode = 0
var feeds: [Feed]?
beforeEach {
feeds = []
let _ = self.client.fetchFeeds([self.feedId, self.feedId2]) {
guard let code = $0.response?.statusCode,
let _feeds = $0.result.value else { return }
statusCode = code
feeds = _feeds
}
}
it ("fetches specified feeds") {
expect(statusCode).toFinally(equal(200))
expect(feeds).toFinallyNot(beNil())
expect(feeds!.count).toFinally(equal(2))
}
}
}
}
| 9afbbf4daff281095c41e55c5223d5e0 | 30.568966 | 77 | 0.493173 | false | false | false | false |
zalando/ModularDemo | refs/heads/master | IPLookupUI/IPLookupUI/IPLookupViewController.swift | bsd-2-clause | 1 | //
// IPLookupViewController.swift
// IPLookupUI
//
// Created by Oliver Eikemeier on 26.09.15.
// Copyright © 2015 Zalando SE. All rights reserved.
//
import UIKit
import ZContainer
class IPLookupViewController: UIViewController {
// MARK: Dependencies
private let lookupService: IPLookupUIService
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
let container = ZContainer.defaultContainer()
lookupService = container.resolve()
super.init(coder: aDecoder)
}
// MARK: Outlets
@IBOutlet weak var myIPLabel: UILabel!
@IBOutlet weak var myIPButton: UIButton!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
// MARK: Actions
@IBAction func lookupIP(sender: AnyObject) {
guard !activityIndicatorView.isAnimating() else {
return
}
myIPLabel.text = labelTextForWaiting()
myIPLabel.textColor = UIColor.blackColor()
startLookup()
lookupService.lookupIP { [weak self] (IP, error) in
guard let this = self else {
return
}
dispatch_async(dispatch_get_main_queue()) {
this.lookupHandler(IP, error: error)
}
}
}
// MARK: Internal methods
// Handle IP lookup result
private func lookupHandler(IP: String?, error: ErrorType?) {
endLookup()
switch (IP, error) {
case (let IP?, nil):
lookupSuccess(IP)
case (nil, let error?):
lookupFailure(error)
default:
assertionFailure("Expecting result or error")
}
}
// IP Lookup successful, set Label
private func lookupSuccess(textIP: String) {
myIPLabel.text = labelTextForTextIP(textIP)
storyboard
}
// IP Lookup failed, set Label
private func lookupFailure(error: ErrorType) {
myIPLabel.text = labelTextForError(error)
myIPLabel.textColor = UIColor.redColor()
}
// Visually indicate activity
private func startLookup() {
myIPButton.enabled = false
activityIndicatorView.startAnimating()
}
// Visually end activity
private func endLookup() {
activityIndicatorView.stopAnimating()
myIPButton.enabled = true
}
// MARK: - Localization
private lazy var localizationBundle: NSBundle = {
let cls = IPLookupViewController.self
return NSBundle(forClass: cls)
}()
private var localizationTable: String {
return "IPLookup"
}
}
extension IPLookupViewController {
private func localizedString(string: String) -> String {
return localizationBundle.localizedStringForKey(string, value: string, table: localizationTable)
}
private func labelTextForWaiting() -> String {
return localizedString("Please wait")
}
private func labelTextForTextIP(textIP: String) -> String {
let formatString = localizedString("Your IP is: %1$@")
return String(format: formatString, textIP)
}
private func labelTextForError(error: ErrorType) -> String {
switch error {
case NSURLError.TimedOut:
return localizedString("Timeout")
default:
let formatString = localizedString("An error occured: %1$@")
let localizedDescription = (error as NSError).localizedDescription
return String(format: formatString, localizedDescription)
}
}
}
| 45c51c021e92235118282076ecd4088f | 26.757576 | 104 | 0.607533 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Client/Cliqz/Frontend/Browser/WebView/WebViewBackForward.swift | mpl-2.0 | 2 | /* 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
class LegacyBackForwardListItem {
var url: URL {
didSet {
checkForLocalWebserver()
}
}
var initialURL: URL
var title:String = "" {
didSet {
checkForLocalWebserver()
}
}
private func checkForLocalWebserver() {
if AboutUtils.isAboutURL(url) && !title.isEmpty {
title = ""
}
}
init(url: URL) {
self.url = url
// In order to mimic the built-in API somewhat, the initial url is stripped of mobile site
// parts of the host (mobile.nytimes.com -> initial url is nytimes.com). The initial url
// is the pre-page-forwarding url
let normal = url.scheme ?? "http" + "://" + (url.normalizedHostAndPath() ?? url.absoluteString)
initialURL = URL(string: normal) ?? url
}
}
extension LegacyBackForwardListItem: Equatable {}
func == (lhs: LegacyBackForwardListItem, rhs: LegacyBackForwardListItem) -> Bool {
return lhs.url.absoluteString == rhs.url.absoluteString;
}
class WebViewBackForwardList {
var currentIndex: Int = 0
var backForwardList: [LegacyBackForwardListItem] = []
weak var webView: CliqzWebView?
var cachedHistoryStringLength = 0
var cachedHistoryStringPositionOfCurrentMarker = -1
init(webView: CliqzWebView) {
self.webView = webView
}
private func isSpecial(_url: URL?) -> Bool {
guard let url = _url else { return false }
#if !TEST
return url.absoluteString.range(of: WebServer.sharedInstance.base) != nil
#else
return false
#endif
}
func update() {
let currIndicator = ">>> "
guard let obj = webView?.value(forKeyPath: "documentView.webView.backForwardList") else { return }
let history = (obj as AnyObject).description
// let nsHistory = history as NSString
guard let nsHistory = history as? NSString, !(cachedHistoryStringLength > 0 && cachedHistoryStringLength == nsHistory.length &&
cachedHistoryStringPositionOfCurrentMarker > -1 &&
nsHistory.substring(with: NSMakeRange(cachedHistoryStringPositionOfCurrentMarker, currIndicator.characters.count)) == currIndicator) else {
// the history is unchanged (based on this guesstimate)
return
}
cachedHistoryStringLength = nsHistory.length
backForwardList = []
let regex = try! NSRegularExpression(pattern:"\\d+\\) +<WebHistoryItem.+> (http.+) ", options: [])
let result = regex.matches(in: nsHistory as String, options: [], range: NSMakeRange(0, nsHistory.length))
var i = 0
var foundCurrent = false
for match in result {
var extractedUrl = nsHistory.substring(with: match.rangeAt(1))
let parts = extractedUrl.components(separatedBy: " ")
if parts.count > 1 {
extractedUrl = parts[0]
}
guard let url = NSURL(string: extractedUrl) else { continue }
let item = LegacyBackForwardListItem(url: url as URL)
backForwardList.append(item)
let rangeStart = match.range.location - currIndicator.characters.count
if rangeStart > -1 && nsHistory.substring(with: NSMakeRange(rangeStart, currIndicator.characters.count)) == currIndicator {
currentIndex = i
foundCurrent = true
cachedHistoryStringPositionOfCurrentMarker = rangeStart
}
i += 1
}
if !foundCurrent {
currentIndex = 0
}
}
var currentItem: LegacyBackForwardListItem? {
get {
guard let item = itemAtIndex(index: currentIndex) else {
if let url = webView?.url {
let item = LegacyBackForwardListItem(url: url)
return item
} else {
return nil
}
}
return item
}}
var backItem: LegacyBackForwardListItem? {
get {
return itemAtIndex(index: currentIndex - 1)
}}
var forwardItem: LegacyBackForwardListItem? {
get {
return itemAtIndex(index: currentIndex + 1)
}}
func itemAtIndex(index: Int) -> LegacyBackForwardListItem? {
if (backForwardList.count == 0 ||
index > backForwardList.count - 1 ||
index < 0) {
return nil
}
return backForwardList[index]
}
var backList: [LegacyBackForwardListItem] {
get {
return (currentIndex > 0 && backForwardList.count > 0) ? Array(backForwardList[0..<currentIndex]) : []
}}
var forwardList: [LegacyBackForwardListItem] {
get {
return (currentIndex + 1 < backForwardList.count && backForwardList.count > 0) ?
Array(backForwardList[(currentIndex + 1)..<backForwardList.count]) : []
}}
}
| 422455f081bc81da25201e96e4d4aacb | 34.1 | 198 | 0.590883 | false | false | false | false |
Chaosspeeder/YourGoals | refs/heads/master | YourGoals/UI/Views/CalendarBarView/CalendarBarCell.swift | lgpl-3.0 | 1 | //
// CalendarBarCell.swift
// YourGoals
//
// Created by André Claaßen on 26.07.19.
// Copyright © 2019 André Claaßen. All rights reserved.
//
import UIKit
import Foundation
struct CalendarBarCellValue {
let date:Date
let progress:CGFloat
init(date: Date, progress: Double) {
self.date = date
assert(progress >= 0.0 && progress <= 1.0)
self.progress = CGFloat(progress)
}
}
/// a cell representing a day in week for a date
class CalendarBarCell: UICollectionViewCell {
let dayNumberLabel = UILabel()
let dayNameLabel = UILabel()
let dayProgressRing = CircleProgressView(frame: CGRect.zero)
let dayNumberLabelColor = UIColor.lightGray
var dayNumberLabelSelectedColor = UIColor.blue
override init(frame: CGRect) {
super.init(frame: frame)
setupControls()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupControls()
}
fileprivate func createControls() {
self.addSubview(dayProgressRing)
self.dayProgressRing.addSubview(dayNumberLabel)
self.addSubview(dayNameLabel)
}
fileprivate func formatLabel(label: UILabel, textAlignment: NSTextAlignment, fontSize: CGFloat, color: UIColor? = nil) {
label.textAlignment = textAlignment
label.font = label.font.withSize(fontSize)
label.textColor = color
}
fileprivate func createConstraints() {
let views: [String: Any] = [
"dayNumberLabel": dayNumberLabel,
"dayProgressRing": dayProgressRing,
"dayNameLabel": dayNameLabel
]
// disable autoresizing in all views
views.values.forEach { ($0 as! UIView).translatesAutoresizingMaskIntoConstraints = false }
var constraints = [NSLayoutConstraint]()
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-2-[dayProgressRing]-2-[dayNameLabel(10)]-2-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-2-[dayProgressRing]-2-|", options: [ .alignAllCenterX ], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[dayNumberLabel]-0-|", options: [ .alignAllCenterY ], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[dayNumberLabel]-0-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-2-[dayNameLabel]-2-|", options: [.alignAllCenterX], metrics: nil, views: views)
NSLayoutConstraint.activate(constraints)
}
fileprivate func setupControls() {
createControls()
formatLabel(label: dayNameLabel, textAlignment: .center, fontSize: 12.0)
formatLabel(label: dayNumberLabel, textAlignment: .center, fontSize: 14.0, color: dayNumberLabelColor)
createConstraints()
}
/// configure the view with a date
///
/// - Parameter date: the date
func configure(value: CalendarBarCellValue) {
dayNumberLabel.text = String(value.date.dayNumberOfMonth)
dayNameLabel.text = value.date.weekdayChar
dayProgressRing.progress = value.progress
}
// MARK: - Factory Method
/// get a resuable cell from the collection view.
///
/// - Preconditions
/// You must register the cell first
///
/// - Parameters:
/// - collectionView: a ui collecition view
/// - indexPath: the index path
/// - Returns: a calendar bar cell
internal static func dequeue(fromCollectionView collectionView: UICollectionView, atIndexPath indexPath: IndexPath) -> CalendarBarCell {
guard let cell: CalendarBarCell = collectionView.dequeueReusableCell(indexPath: indexPath) else {
fatalError("*** Failed to dequeue CalendarBarCell ***")
}
return cell
}
/// color the cell, so that it is visible, that it is selected
override var isSelected: Bool {
didSet {
self.dayNumberLabel.textColor = self.isSelected ? self.dayNumberLabelSelectedColor : self.dayNumberLabelColor
}
}
}
| 9d193ca5cdfbd6336f66befc98560281 | 35.896552 | 164 | 0.658879 | false | false | false | false |
JetBrains/kotlin-native | refs/heads/archive | performance/KotlinVsSwift/ring/src/ClassBaselineBenchmark.swift | apache-2.0 | 4 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import Foundation
class ClassBaselineBenchmark {
func consume() {
for item in 1...Constants.BENCHMARK_SIZE {
Blackhole.consume(Value(item))
}
}
func consumeField() {
let value = Value(0)
for item in 1...Constants.BENCHMARK_SIZE {
value.value = item
Blackhole.consume(value)
}
}
func allocateList() -> [Value] {
let list = [Value](repeating: Value(0), count: Constants.BENCHMARK_SIZE)
return list
}
func allocateArray() -> [Value?] {
let list = [Value?](repeating: nil, count: Constants.BENCHMARK_SIZE)
return list
}
func allocateListAndFill() -> [Value] {
var list: [Value] = []
for item in 1...Constants.BENCHMARK_SIZE {
list.append(Value(item))
}
return list
}
func allocateListAndWrite() -> [Value] {
let value = Value(0)
var list: [Value] = []
for _ in 1...Constants.BENCHMARK_SIZE {
list.append(value)
}
return list
}
func allocateArrayAndFill() -> [Value?] {
var list = [Value?](repeating: nil, count: Constants.BENCHMARK_SIZE)
var index = 0
for item in 1...Constants.BENCHMARK_SIZE {
list[index] = Value(item)
index += 1
}
return list
}
}
| 24ef9fcb06b161d32b06c60d15e16dd6 | 24.9 | 101 | 0.545689 | false | false | false | false |
AndrewBennet/readinglist | refs/heads/master | ReadingList/ViewControllers/Settings/SafariView/SafariViewPresenter.swift | gpl-3.0 | 1 | import SwiftUI
import SafariServices
struct SafariViewPresenter<Item: Identifiable>: UIViewControllerRepresentable {
// MARK: Representation
@Binding var item: Item?
var onDismiss: (() -> Void)?
var representationBuilder: (Item) -> SafariView
// MARK: UIViewControllerRepresentable
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
func makeUIViewController(context: Context) -> UIViewController {
return context.coordinator.uiViewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
// Keep the coordinator updated with a new presenter struct.
context.coordinator.parent = self
context.coordinator.item = item
}
}
extension SafariViewPresenter {
class Coordinator: NSObject, SFSafariViewControllerDelegate {
// MARK: Parent Copying
var parent: SafariViewPresenter
init(parent: SafariViewPresenter) {
self.parent = parent
}
// MARK: View Controller Holding
let uiViewController = UIViewController()
// MARK: Item Handling
var item: Item? {
didSet(oldItem) {
handleItemChange(from: oldItem, to: item)
}
}
// Ensure the proper presentation handler is executed only once
// during a one SwiftUI view update life cycle.
private func handleItemChange(from oldItem: Item?, to newItem: Item?) {
switch (oldItem, newItem) {
case (.none, .none):
()
case let (.none, .some(newItem)):
presentSafariViewController(with: newItem)
case let (.some(oldItem), .some(newItem)) where oldItem.id != newItem.id:
dismissSafariViewController {
self.presentSafariViewController(with: newItem)
}
case let (.some, .some(newItem)):
updateSafariViewController(with: newItem)
case (.some, .none):
dismissSafariViewController()
}
}
// MARK: Presentation Handlers
private func presentSafariViewController(with item: Item) {
let representation = parent.representationBuilder(item)
let safariViewController = SFSafariViewController(url: representation.url, configuration: representation.configuration)
safariViewController.delegate = self
representation.applyModification(to: safariViewController)
// There is a problem that page loading and parallel push animation are not working when a modifier is attached to the view in a `List`.
// As a workaround, use a `rootViewController` of the `window` for presenting.
// (Unlike the other view controllers, a view controller hosted by a cell doesn't have a parent, but has the same window.)
let presentingViewController = uiViewController.view.window?.rootViewController ?? uiViewController
presentingViewController.present(safariViewController, animated: true)
}
private func updateSafariViewController(with item: Item) {
guard let safariViewController = uiViewController.presentedViewController as? SFSafariViewController else {
return
}
let representation = parent.representationBuilder(item)
representation.applyModification(to: safariViewController)
}
private func dismissSafariViewController(completion: (() -> Void)? = nil) {
// Check if the `uiViewController` is a instance of the `SFSafariViewController`
// to prevent other controllers presented by the container view from being dismissed unintentionally.
guard uiViewController.presentedViewController is SFSafariViewController else {
return
}
uiViewController.dismiss(animated: true) {
self.handleDismissalWithoutResettingItemBinding()
completion?()
}
}
// MARK: Dismissal Handlers
// Used when the Safari view controller is finished by an item change during view update.
private func handleDismissalWithoutResettingItemBinding() {
parent.onDismiss?()
}
// Used when the Safari view controller is finished by a user interaction.
private func resetItemBindingAndHandleDismissal() {
parent.item = nil
parent.onDismiss?()
}
// MARK: SFSafariViewControllerDelegate
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
resetItemBindingAndHandleDismissal()
}
}
}
| 56ebee494b1fe69f65d3ff74b2813239 | 36.328125 | 148 | 0.644412 | false | false | false | false |
VArbiter/Rainville_iOS-Swift | refs/heads/master | Rainville-Swift/Rainville-Swift/Classes/Category/CCLabelExtension.swift | gpl-3.0 | 1 | //
// CCLabelExtension.swift
// Rainville-Swift
//
// Created by 冯明庆 on 01/06/2017.
// Copyright © 2017 冯明庆. All rights reserved.
//
import Foundation
import UIKit
let _CC_SYSTEM_FONT_SIZE_ : CGFloat = 17.0 ;
extension UILabel {
func ccMusketWithString(_ string : String) -> UILabel {
return self.ccMusket(_CC_SYSTEM_FONT_SIZE_, string);
}
func ccMusket(_ float : CGFloat ,_ string : String) -> UILabel {
self.font = UIFont.ccMusketFontWithSize(float);
self.text = string;
return self;
}
func ccWeatherIconsWithString(_ string : String) -> UILabel {
return self.ccWeatherIcons(_CC_SYSTEM_FONT_SIZE_, string);
}
func ccWeatherIcons(_ float : CGFloat ,_ string : String) -> UILabel {
self.font = UIFont.ccWeatherIconsWithSize(float);
self.text = string;
return self;
}
func ccElegantIconsWithString(_ string : String) -> UILabel {
return self.ccElegantIcons(_CC_SYSTEM_FONT_SIZE_, string);
}
func ccElegantIcons(_ float : CGFloat ,_ string : String) -> UILabel {
self.font = UIFont.ccElegantIconsWithSize(float);
self.text = string;
return self;
}
}
| 2827e5f7e8dad91506a8c713409172a5 | 25.826087 | 74 | 0.618314 | false | false | false | false |
phimage/CryptoPrephirences | refs/heads/master | Sources/Plist+Cipher.swift | mit | 1 | //
// DictionaryPreferences+Cipher.swift
// CryptoPrephirences
/*
The MIT License (MIT)
Copyright (c) 2015-2016 Eric Marchand (phimage)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
import Prephirences
import CryptoSwift
public enum CryptoPrephirencesError: Error {
case failedToDeserializePropertyList
}
public extension Plist {
public static func readFrom(_ filePath: String, withCipher cipher: CryptoSwift.Cipher, options opt: PropertyListSerialization.ReadOptions = .mutableContainersAndLeaves, format: UnsafeMutablePointer<PropertyListSerialization.PropertyListFormat>? = nil, readOptionsMask: NSData.ReadingOptions = []) throws -> Dictionary<String,Any> {
let encrypted = try Data(contentsOf: URL(fileURLWithPath: filePath), options: readOptionsMask)
let decrypted = try encrypted.decrypt(cipher: cipher)
guard let dictionary = try PropertyListSerialization.propertyList(from: decrypted,
options: opt, format: format) as? Dictionary<String,AnyObject> else {
throw CryptoPrephirencesError.failedToDeserializePropertyList
}
return dictionary
}
public static func writeTo(_ filePath: String, withCipher cipher: CryptoSwift.Cipher, dictionary: Dictionary<String,Any>, format: PropertyListSerialization.PropertyListFormat = PropertyListSerialization.PropertyListFormat.xml, options opt: PropertyListSerialization.WriteOptions = 0, writeOptionMask: NSData.WritingOptions = .atomicWrite) throws {
let decrypted = try PropertyListSerialization.data(fromPropertyList: dictionary, format: format, options: opt)
let encrypted = try decrypted.encrypt(cipher: cipher)
try encrypted.write(to: URL(fileURLWithPath: filePath), options: writeOptionMask)
}
}
public extension DictionaryPreferences {
public convenience init(filePath: String, withCipher cipher: CryptoSwift.Cipher) throws {
let dictionary = try Plist.readFrom(filePath, withCipher: cipher)
self.init(dictionary: dictionary)
}
}
extension PreferencesType {
public func saveTo(filePath: String, withCipher cipher: CryptoSwift.Cipher) throws {
try Plist.writeTo(filePath, withCipher: cipher, dictionary: self.dictionary())
}
}
extension MutablePreferencesType {
public func loadFrom(filePath: String, withCipher cipher: CryptoSwift.Cipher) throws {
let dictionary = try Plist.readFrom(filePath, withCipher: cipher)
self.set(dictionary: dictionary)
}
}
| 96aa2375e1d729aab92e031ef7b2f94d | 42.036585 | 351 | 0.762822 | false | false | false | false |
ostatnicky/kancional-ios | refs/heads/master | Cancional/Utilities/UIViewControllerExtension.swift | mit | 1 | //
// UIViewControllerExtension.swift
// Cancional
//
// Created by Jiri Ostatnicky on 09/09/2017.
// Copyright © 2017 Jiri Ostatnicky. All rights reserved.
//
import UIKit
extension UIViewController {
public typealias UIAlertControllerButtonHandler = ((UIAlertAction) -> Void)
public func alert(_ message: String,
title: String? = nil,
cancelTitle: String = "OK",
cancelHandler: UIAlertControllerButtonHandler? = nil)
{
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
| da43f805c909bad0d86997528f9a682b | 31.037037 | 103 | 0.648555 | false | false | false | false |
ciscospark/spark-ios-sdk-example | refs/heads/master | KitchenSink/SparkLoginViewController.swift | mit | 1 | // Copyright 2016-2017 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SparkSDK
import Toast_Swift
class SparkLoginViewController: BaseViewController {
// MARK: - UI outlets variables
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet var labelFontScaleCollection: [UILabel]!
@IBOutlet var heightScaleCollection: [NSLayoutConstraint]!
@IBOutlet var widthScaleCollection: [NSLayoutConstraint]!
@IBOutlet var buttonFontScaleCollection: [UIButton]!
@IBOutlet weak var loginButtonHeight: NSLayoutConstraint!
/// saparkSDK reperesent for the SparkSDK API instance
var sparkSDK: Spark?
// MARK: - Life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
statusLabel.text = "Powered by SparkSDK v" + Spark.version
}
override func viewDidAppear(_ animated: Bool) {
/*
An [OAuth](https://oauth.net/2/) based authentication strategy
is to be used to authenticate a user on Cisco Spark.
*/
let authenticator = OAuthAuthenticator(clientId: SparkEnvirmonment.ClientId, clientSecret: SparkEnvirmonment.ClientSecret, scope: SparkEnvirmonment.Scope, redirectUri: SparkEnvirmonment.RedirectUri)
self.sparkSDK = Spark(authenticator: authenticator)
self.sparkSDK?.logger = KSLogger() //Register a console logger into SDK
/*
Check wether sparkSDK is already authorized, sparkSDk saves authorization info in device key-chain
-note: if user didn't logged out or didn't deauthorize, "self.sparkSDK.authenticator" function will return true
-note: if sparkSDK is authorized, directly jump to login success process
*/
if (self.sparkSDK?.authenticator as! OAuthAuthenticator).authorized{
self.sparkSDK?.authenticator.accessToken{ res in
print("\(res ?? "")")
}
self.loginSuccessProcess()
return
}
}
// MARK: - SparkSDK: sparkID Login
@IBAction func sparkLoginBtnClicked(_ sender: AnyObject) {
/*
An [OAuth](https://oauth.net/2/) based authentication strategy
is to be used to authenticate a user on Cisco Spark.
*/
let authenticator = OAuthAuthenticator(clientId: SparkEnvirmonment.ClientId, clientSecret: SparkEnvirmonment.ClientSecret, scope: SparkEnvirmonment.Scope, redirectUri: SparkEnvirmonment.RedirectUri)
self.sparkSDK = Spark(authenticator: authenticator)
self.sparkSDK?.logger = KSLogger() //Register a console logger into SDK
/*
Brings up a web-based authorization view controller and directs the user through the OAuth process.
-note: parentViewController must contain a navigation Controller,so that the OAuth view controller can push on it.
*/
(self.sparkSDK?.authenticator as! OAuthAuthenticator).authorize(parentViewController: self) { [weak self] success in
if success {
/* Spark Login Success codes here... */
if let strongSelf = self {
strongSelf.loginSuccessProcess()
}
}
else {
/* Spark Login Fail codes here... */
if let strongSelf = self {
strongSelf.loginFailureProcess()
}
}
}
}
private func loginSuccessProcess() {
let homeViewController = storyboard?.instantiateViewController(withIdentifier: "HomeTableViewController") as! HomeTableViewController
homeViewController.sparkSDK = self.sparkSDK
navigationController?.pushViewController(homeViewController, animated: true)
}
fileprivate func loginFailureProcess() {
let alert = UIAlertController(title: "Alert", message: "Spark login failed", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
// MARK: - UI Implementation
override func initView() {
for label in labelFontScaleCollection {
label.font = UIFont.labelLightFont(ofSize: label.font.pointSize * Utils.HEIGHT_SCALE)
}
for button in buttonFontScaleCollection {
button.titleLabel?.font = UIFont.buttonLightFont(ofSize: (button.titleLabel?.font.pointSize)! * Utils.HEIGHT_SCALE)
}
for heightConstraint in heightScaleCollection {
heightConstraint.constant *= Utils.HEIGHT_SCALE
}
for widthConstraint in widthScaleCollection {
widthConstraint.constant *= Utils.WIDTH_SCALE
}
loginButton.setBackgroundImage(UIImage.imageWithColor(UIColor.buttonBlueNormal(), background: nil), for: .normal)
loginButton.setBackgroundImage(UIImage.imageWithColor(UIColor.buttonBlueHightlight(), background: nil), for: .highlighted)
loginButton.layer.cornerRadius = loginButtonHeight.constant/2
}
}
| 51d7e4e6cf51c21102c0dd1e3648851b | 45.977273 | 206 | 0.681019 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/SwipeCellKit/Example/MailExample/MailTableViewController.swift | apache-2.0 | 4 | //
// MailTableViewController.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
import SwipeCellKit
class MailTableViewController: UITableViewController {
var emails: [Email] = []
var defaultOptions = SwipeOptions()
var isSwipeRightEnabled = true
var buttonDisplayMode: ButtonDisplayMode = .titleAndImage
var buttonStyle: ButtonStyle = .backgroundColor
var usesTallCells = false
// MARK: - Lifecycle
override func viewDidLoad() {
tableView.allowsSelection = true
tableView.allowsMultipleSelectionDuringEditing = true
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
navigationItem.rightBarButtonItem = editButtonItem
view.layoutMargins.left = 32
resetData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emails.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MailCell") as! MailCell
cell.delegate = self
cell.selectedBackgroundView = createSelectedBackgroundView()
let email = emails[indexPath.row]
cell.fromLabel.text = email.from
cell.dateLabel.text = email.relativeDateString
cell.subjectLabel.text = email.subject
cell.bodyLabel.text = email.body
cell.bodyLabel.numberOfLines = usesTallCells ? 0 : 2
cell.unread = email.unread
return cell
}
func visibleRect(for tableView: UITableView) -> CGRect? {
if usesTallCells == false { return nil }
if #available(iOS 11.0, *) {
return tableView.safeAreaLayoutGuide.layoutFrame
} else {
let topInset = navigationController?.navigationBar.frame.height ?? 0
let bottomInset = navigationController?.toolbar?.frame.height ?? 0
let bounds = tableView.bounds
return CGRect(x: bounds.origin.x, y: bounds.origin.y + topInset, width: bounds.width, height: bounds.height - bottomInset)
}
}
// MARK: - Actions
@IBAction func moreTapped(_ sender: Any) {
let controller = UIAlertController(title: "Swipe Transition Style", message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Border", style: .default, handler: { _ in self.defaultOptions.transitionStyle = .border }))
controller.addAction(UIAlertAction(title: "Drag", style: .default, handler: { _ in self.defaultOptions.transitionStyle = .drag }))
controller.addAction(UIAlertAction(title: "Reveal", style: .default, handler: { _ in self.defaultOptions.transitionStyle = .reveal }))
controller.addAction(UIAlertAction(title: "\(isSwipeRightEnabled ? "Disable" : "Enable") Swipe Right", style: .default, handler: { _ in self.isSwipeRightEnabled = !self.isSwipeRightEnabled }))
controller.addAction(UIAlertAction(title: "Button Display Mode", style: .default, handler: { _ in self.buttonDisplayModeTapped() }))
controller.addAction(UIAlertAction(title: "Button Style", style: .default, handler: { _ in self.buttonStyleTapped() }))
controller.addAction(UIAlertAction(title: "Cell Height", style: .default, handler: { _ in self.cellHeightTapped() }))
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
controller.addAction(UIAlertAction(title: "Reset", style: .destructive, handler: { _ in self.resetData() }))
present(controller, animated: true, completion: nil)
}
func buttonDisplayModeTapped() {
let controller = UIAlertController(title: "Button Display Mode", message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Image + Title", style: .default, handler: { _ in self.buttonDisplayMode = .titleAndImage }))
controller.addAction(UIAlertAction(title: "Image Only", style: .default, handler: { _ in self.buttonDisplayMode = .imageOnly }))
controller.addAction(UIAlertAction(title: "Title Only", style: .default, handler: { _ in self.buttonDisplayMode = .titleOnly }))
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(controller, animated: true, completion: nil)
}
func buttonStyleTapped() {
let controller = UIAlertController(title: "Button Style", message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Background Color", style: .default, handler: { _ in
self.buttonStyle = .backgroundColor
self.defaultOptions.transitionStyle = .border
}))
controller.addAction(UIAlertAction(title: "Circular", style: .default, handler: { _ in
self.buttonStyle = .circular
self.defaultOptions.transitionStyle = .reveal
}))
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(controller, animated: true, completion: nil)
}
func cellHeightTapped() {
let controller = UIAlertController(title: "Cell Height", message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Normal", style: .default, handler: { _ in
self.usesTallCells = false
self.tableView.reloadData()
}))
controller.addAction(UIAlertAction(title: "Tall", style: .default, handler: { _ in
self.usesTallCells = true
self.tableView.reloadData()
}))
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(controller, animated: true, completion: nil)
}
// MARK: - Helpers
func createSelectedBackgroundView() -> UIView {
let view = UIView()
view.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
return view
}
func resetData() {
emails = mockEmails
emails.forEach { $0.unread = false }
usesTallCells = false
tableView.reloadData()
}
}
extension MailTableViewController: SwipeTableViewCellDelegate {
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
let email = emails[indexPath.row]
if orientation == .left {
guard isSwipeRightEnabled else { return nil }
let read = SwipeAction(style: .default, title: nil) { action, indexPath in
let updatedStatus = !email.unread
email.unread = updatedStatus
let cell = tableView.cellForRow(at: indexPath) as! MailCell
cell.setUnread(updatedStatus, animated: true)
}
read.hidesWhenSelected = true
read.accessibilityLabel = email.unread ? "Mark as Read" : "Mark as Unread"
let descriptor: ActionDescriptor = email.unread ? .read : .unread
configure(action: read, with: descriptor)
return [read]
} else {
let flag = SwipeAction(style: .default, title: nil, handler: nil)
flag.hidesWhenSelected = true
configure(action: flag, with: .flag)
let delete = SwipeAction(style: .destructive, title: nil) { action, indexPath in
self.emails.remove(at: indexPath.row)
}
configure(action: delete, with: .trash)
let cell = tableView.cellForRow(at: indexPath) as! MailCell
let closure: (UIAlertAction) -> Void = { _ in cell.hideSwipe(animated: true) }
let more = SwipeAction(style: .default, title: nil) { action, indexPath in
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Reply", style: .default, handler: closure))
controller.addAction(UIAlertAction(title: "Forward", style: .default, handler: closure))
controller.addAction(UIAlertAction(title: "Mark...", style: .default, handler: closure))
controller.addAction(UIAlertAction(title: "Notify Me...", style: .default, handler: closure))
controller.addAction(UIAlertAction(title: "Move Message...", style: .default, handler: closure))
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: closure))
self.present(controller, animated: true, completion: nil)
}
configure(action: more, with: .more)
return [delete, flag, more]
}
}
func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
var options = SwipeOptions()
options.expansionStyle = orientation == .left ? .selection : .destructive
options.transitionStyle = defaultOptions.transitionStyle
switch buttonStyle {
case .backgroundColor:
options.buttonSpacing = 4
case .circular:
options.buttonSpacing = 4
#if canImport(Combine)
if #available(iOS 13.0, *) {
options.backgroundColor = UIColor.systemGray6
} else {
options.backgroundColor = #colorLiteral(red: 0.9467939734, green: 0.9468161464, blue: 0.9468042254, alpha: 1)
}
#else
options.backgroundColor = #colorLiteral(red: 0.9467939734, green: 0.9468161464, blue: 0.9468042254, alpha: 1)
#endif
}
return options
}
func configure(action: SwipeAction, with descriptor: ActionDescriptor) {
action.title = descriptor.title(forDisplayMode: buttonDisplayMode)
action.image = descriptor.image(forStyle: buttonStyle, displayMode: buttonDisplayMode)
switch buttonStyle {
case .backgroundColor:
action.backgroundColor = descriptor.color(forStyle: buttonStyle)
case .circular:
action.backgroundColor = .clear
action.textColor = descriptor.color(forStyle: buttonStyle)
action.font = .systemFont(ofSize: 13)
action.transitionDelegate = ScaleTransition.default
}
}
}
class MailCell: SwipeTableViewCell {
@IBOutlet var fromLabel: UILabel!
@IBOutlet var dateLabel: UILabel!
@IBOutlet var subjectLabel: UILabel!
@IBOutlet var bodyLabel: UILabel!
var animator: Any?
var indicatorView = IndicatorView(frame: .zero)
var unread = false {
didSet {
indicatorView.transform = unread ? CGAffineTransform.identity : CGAffineTransform.init(scaleX: 0.001, y: 0.001)
}
}
override func awakeFromNib() {
setupIndicatorView()
}
func setupIndicatorView() {
indicatorView.translatesAutoresizingMaskIntoConstraints = false
indicatorView.color = tintColor
indicatorView.backgroundColor = .clear
contentView.addSubview(indicatorView)
let size: CGFloat = 12
indicatorView.widthAnchor.constraint(equalToConstant: size).isActive = true
indicatorView.heightAnchor.constraint(equalTo: indicatorView.widthAnchor).isActive = true
indicatorView.centerXAnchor.constraint(equalTo: fromLabel.leftAnchor, constant: -16).isActive = true
indicatorView.centerYAnchor.constraint(equalTo: fromLabel.centerYAnchor).isActive = true
}
func setUnread(_ unread: Bool, animated: Bool) {
let closure = {
self.unread = unread
}
if #available(iOS 10, *), animated {
var localAnimator = self.animator as? UIViewPropertyAnimator
localAnimator?.stopAnimation(true)
localAnimator = unread ? UIViewPropertyAnimator(duration: 1.0, dampingRatio: 0.4) : UIViewPropertyAnimator(duration: 0.3, dampingRatio: 1.0)
localAnimator?.addAnimations(closure)
localAnimator?.startAnimation()
self.animator = localAnimator
} else {
closure()
}
}
}
| f997763d46001cb54ea4a1f03c345f45 | 43.698582 | 200 | 0.640777 | false | false | false | false |
vanhuyz/learn_swift | refs/heads/master | Core Data Demo/Core Data Demo/ViewController.swift | mit | 1 | //
// ViewController.swift
// Core Data Demo
//
// Created by Van Huy on 12/3/15.
// Copyright (c) 2015 Example. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
// var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as! NSManagedObject
//
// newUser.setValue("Jon", forKey: "username")
// newUser.setValue("pass", forKey: "password")
//
// context.save(nil)
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
if results?.count > 0 {
for result: AnyObject in results! {
println(result)
println(result.valueForKey("username"))
}
} else {
println("No results")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| bd88942b4a377a35c364d41e396d7d62 | 27.134615 | 137 | 0.613807 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformKit/Coincore/Address/PlainCryptoReceiveAddressFactory.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import MoneyKit
/// A `CryptoReceiveAddressFactory` that doesn't know how to validate the asset/address and assumes it is correct.
public final class PlainCryptoReceiveAddressFactory: ExternalAssetAddressFactory {
private static let knownSchemes: [String] = [
"bitcoin:", "bitcoincash:", "ethereum:"
]
private let asset: CryptoCurrency
public init(asset: CryptoCurrency) {
self.asset = asset
}
public func makeExternalAssetAddress(
address: String,
label: String,
onTxCompleted: @escaping TxCompleted
) -> Result<CryptoReceiveAddress, CryptoReceiveAddressFactoryError> {
guard !Self.knownSchemes.contains(where: { address.hasPrefix($0) }) else {
return .failure(.invalidAddress)
}
guard let regex = try? NSRegularExpression(pattern: "[a-zA-Z0-9]{15,}") else {
return .failure(.invalidAddress)
}
let range = NSRange(location: 0, length: address.utf16.count)
let firstMatch = regex.firstMatch(in: address, options: [], range: range)
guard firstMatch != nil else {
return .failure(.invalidAddress)
}
return .success(PlainCryptoReceiveAddress(address: address, asset: asset, label: label))
}
}
| a87545c322725c2254800975ae240648 | 35.675676 | 114 | 0.66986 | false | false | false | false |
kmikiy/SpotMenu | refs/heads/master | SpotMenu/AppDelegate/EventMonitor.swift | mit | 1 | import Cocoa
open class EventMonitor {
fileprivate var monitor: AnyObject?
fileprivate let mask: NSEvent.EventTypeMask
fileprivate let handler: (NSEvent?) -> Void
public init(mask: NSEvent.EventTypeMask, handler: @escaping (NSEvent?) -> Void) {
self.mask = mask
self.handler = handler
}
deinit {
stop()
}
open func start() {
monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler) as AnyObject?
}
open func stop() {
if monitor != nil {
NSEvent.removeMonitor(monitor!)
monitor = nil
}
}
}
| f7860992a533483169deea5ff8385669 | 20.133333 | 99 | 0.602524 | false | false | false | false |
sjtu-meow/iOS | refs/heads/master | Meow/UserProfileViewController.swift | apache-2.0 | 1 | //
// UserProfileViewController.swift
// Meow
//
// Created by 林武威 on 2017/7/19.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import UIKit
import RxSwift
import SwiftyJSON
class UserProfileViewController: UITableViewController {
class func show(_ profile: Profile, from viewController: UIViewController) {
let vc = R.storyboard.main.userProfileViewController()!
vc.profile = profile
vc.userId = profile.userId
viewController.navigationController?.pushViewController(vc, animated: true)
}
enum ContentType: Int {
case article = 1, moment = 0, questionAnswer = 2
}
let disposeBag = DisposeBag()
var userId: Int!
var contentType = ContentType.moment
// var answers = [AnswerSummary]()
// var questions = [QuestionSummary]()
var isFollowing = false
var questionAnswers = [ItemProtocol]()
var articles = [ArticleSummary]()
var moments = [Moment]()
var profile: Profile?
override func viewDidLoad() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
tableView.register(R.nib.articleUserPageTableViewCell)
// tableView.register(R.nib.momentHomePageTableViewCell)
tableView.register(R.nib.questionRecordTableViewCell)
tableView.register(R.nib.answerRecordTableViewCell)
loadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section <= 1 {
return profile != nil ? 1: 0
}
switch contentType {
case .article:
return articles.count
case .moment:
return moments.count
case .questionAnswer:
return questionAnswers.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.userProfileWithButtonsTableViewCell)!
view.configure(model: profile!)
view.delegate = self
view.updateFollowingButton(isFollowing: isFollowing)
return view
} else if indexPath.section == 1 {
let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.userProfileContentSwitcherCell)!
initContentSwitcher(switcher: view)
return view
}
switch contentType {
case .moment:
let item = moments[indexPath.row]
//let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.momentHomePageTableViewCell)!
let view = R.nib.momentHomePageTableViewCell.firstView(owner: nil)!
view.configure(model: item)
return view
case .article:
let item = articles[indexPath.row]
let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.articleUserPageTableViewCell)!
view.configure(model: item)
return view
case .questionAnswer:
let item = questionAnswers[indexPath.row]
if item is QuestionSummary {
let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.questionRecordTableViewCell)!
view.configure(model: item as! QuestionSummary)
return view
} else {
let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.answerRecordTableViewCell)!
view.configure(model: item as! AnswerSummary)
return view
}
}
}
func initContentSwitcher(switcher: UserProfileContentSwitcher) {
switcher.momentButton.tag = 0
switcher.articleButton.tag = 1
switcher.answerButton.tag = 2
for button in [switcher.momentButton, switcher.articleButton, switcher.answerButton] {
button!.addTarget(self, action: #selector(self.switchContent(_:)), for: .touchUpInside)
}
}
func switchContent(_ sender: UIButton) {
let raw = sender.tag
contentType = ContentType(rawValue: raw)!
tableView.reloadData()
}
func configure(userId: Int) {
self.userId = userId
}
func loadData() {
MeowAPIProvider.shared
.request(.herMoments(id: self.userId))
.mapTo(arrayOf: Moment.self)
.subscribe(onNext: {
[weak self]
items in
self?.moments.append(contentsOf: items)
self?.tableView.reloadData()
})
.addDisposableTo(disposeBag)
MeowAPIProvider.shared.request(.herArticles(id: self.userId))
.mapTo(arrayOf: ArticleSummary.self)
.subscribe(onNext: {
[weak self]
items in
self?.articles.append(contentsOf: items)
self?.tableView.reloadData()
})
.addDisposableTo(disposeBag)
let observableQuestions = MeowAPIProvider.shared.request(.herQuestions(id: userId)).mapTo(arrayOf: QuestionSummary.self)
MeowAPIProvider.shared
.request(.herAnswers(id: userId))
.mapTo(arrayOf: AnswerSummary.self)
.flatMap{[weak self] items -> Observable<[QuestionSummary]> in
for item in items {
self?.questionAnswers.append(item)
}
return observableQuestions
} .subscribe(onNext: {
[weak self]
items in
for item in items {
self?.questionAnswers.append(item)
}
self?.tableView.reloadData()
})
.addDisposableTo(disposeBag)
MeowAPIProvider.shared.request(.herProfile(id: userId)).mapTo(type: Profile.self).subscribe(onNext: {
[weak self] profile in self?.profile = profile
self?.tableView.reloadData()
}).addDisposableTo(disposeBag)
MeowAPIProvider.shared.request(.isFollowingUser(id: userId))
.subscribe(onNext: {
[weak self] json in
self?.isFollowing = (json as! JSON)["following"].bool!
self?.tableView.reloadData()
}).addDisposableTo(disposeBag)
}
func isCurrentContentType(_ type: ContentType) -> Bool {
return type == self.contentType
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section == 2 else { return }
switch contentType {
case .article :
let article = articles[indexPath.row]
let vc = R.storyboard.articlePage.articleDetailViewController()!
vc.configure(id: article.id, type: .article)
navigationController?.pushViewController(vc, animated: true)
case .questionAnswer:
let item = questionAnswers[indexPath.row]
if item.type == .question {
let vc = R.storyboard.questionAnswerPage.questionDetailViewController()!
vc.configure(questionId: item.id)
navigationController?.pushViewController(vc, animated: true)
} else {
ArticleDetailViewController.show(item, from: self)
}
default:
break
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0 {
return nil
}
return indexPath
}
}
extension UserProfileViewController: UserProfileCellDelegate {
func didTapFollowButton(_ sender: UIButton) {
if isFollowing {
MeowAPIProvider.shared
.request(.unfollowUser(id: userId))
.subscribe(onNext: {
[weak self] _ in
self?.isFollowing = false
self?.tableView.reloadData()
}).addDisposableTo(disposeBag)
} else {
MeowAPIProvider.shared
.request(.followUser(id: userId))
.subscribe(onNext: {
[weak self]
_ in self?.isFollowing = true
self?.tableView.reloadData()
})
.addDisposableTo(disposeBag)
}
}
func didTapSendMessageButton(_ sender: UIButton) {
guard let profile = profile else { return }
let clientId = "\(profile.userId!)"
ChatManager.openConversationViewController(withPeerId: clientId, from: self.navigationController!)
}
}
| aa6ecd81ebfec0c290508b0e15308a32 | 34.580392 | 128 | 0.587678 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01745-swift-typebase-getcanonicaltype.swift | apache-2.0 | 1 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func g<B == { c<b(t: d {
return self.a(#object1, d>([T : [c> {
func f: C {
}
enum A {
}
}
}
print(a<S : NSObject {
i<T> T: P> (")!)
struct A {
func c(t.Iterator.Iterator.a<h: ExtensibleCollectionType>) -> {
var b = B(#object1, g == Swift.B
}
override func g.E == a)
}
class b: AnyObject) {
}
[1])?) -> (
| 7f6074bdaf6f95c88076797cbb644414 | 25 | 79 | 0.665242 | false | false | false | false |
emersonbroga/TakePhoto | refs/heads/master | TakePhoto/ViewController.swift | mit | 1 | //
// ViewController.swift
// TakePhoto
//
// Created by Emerson Carvalho on 11/21/15.
// Copyright © 2015 Emerson Carvalho. All rights reserved.
//
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var TakePhotoButton = UIButton()
var UploadFromPhotos = UIButton()
var ImageView = ImageDisplayView()
var PickerController = UIImagePickerController()
var CameraController = UIImagePickerController()
var SmileButton = UIButton()
var CancelButton = UIButton()
var isTakePhotoEnabled = false
var isUploadPhotoEnabled = false
let kTakePhotoButtonTag = 1
let kUploadFromPhotosTag = 2
let kSmileButtonTag = 3
let kCancelButtonTag = 4
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
TakePhotoButton.frame = CGRectMake(50, 50, 200, 30)
TakePhotoButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
TakePhotoButton.setTitle("Take Photo", forState: UIControlState.Normal)
TakePhotoButton.tag = kTakePhotoButtonTag
TakePhotoButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
UploadFromPhotos.frame = CGRectMake(50, 100, 200, 30)
UploadFromPhotos.setTitle("Upload Photo", forState: UIControlState.Normal)
UploadFromPhotos.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
UploadFromPhotos.tag = kUploadFromPhotosTag
UploadFromPhotos.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
ImageView.view.frame = CGRectMake(0, 150, self.view.frame.size.width, 200)
SmileButton.frame = CGRectMake(100, self.view.frame.size.height - 50, self.view.frame.size.width - 100, 50)
SmileButton.setTitle("Smile =)", forState: UIControlState.Normal)
SmileButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
SmileButton.tag = kSmileButtonTag
SmileButton.alpha = 0.8
SmileButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
SmileButton.hidden = true
CancelButton.frame = CGRectMake(0, self.view.frame.size.height - 50, 100, 50)
CancelButton.setTitle("=( Cancel", forState: UIControlState.Normal)
CancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
CancelButton.tag = kCancelButtonTag
CancelButton.alpha = 0.8
CancelButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
CancelButton.hidden = true
PickerController.delegate = self
PickerController.sourceType = UIImagePickerControllerSourceType.Camera
PickerController.mediaTypes = [kUTTypeImage as String]
PickerController.allowsEditing = false
PickerController.showsCameraControls = false
CameraController.delegate = self
CameraController.sourceType = UIImagePickerControllerSourceType.Camera
CameraController.mediaTypes = [kUTTypeImage as String]
CameraController.allowsEditing = false
CameraController.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
CameraController.showsCameraControls = false
CameraController.view.frame = CGRectMake(0, self.view.frame.size.height - 300, self.view.frame.size.width, 250)
CameraController.view.hidden = true
self.view.addSubview(TakePhotoButton)
self.view.addSubview(UploadFromPhotos)
self.view.addSubview(ImageView.view)
self.view.addSubview(CameraController.view)
self.view.addSubview(SmileButton)
self.view.addSubview(CancelButton)
}
func buttonClicked(sender: UIButton!) {
switch sender.tag {
case kTakePhotoButtonTag:
print("Take Photos clicked")
if isTakePhotoEnabled == false {
CameraController.view.hidden = false
SmileButton.hidden = false
CancelButton.hidden = false
isTakePhotoEnabled = true
}
if isUploadPhotoEnabled == true {
self.dismissViewControllerAnimated(true, completion: nil)
isUploadPhotoEnabled = false
}
break
case kUploadFromPhotosTag:
print("Upload Photos clicked")
if isUploadPhotoEnabled == false {
PickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(PickerController, animated: true, completion: nil)
isUploadPhotoEnabled = true
}
if isTakePhotoEnabled == true {
CameraController.view.hidden = true
SmileButton.hidden = true
CancelButton.hidden = true
isTakePhotoEnabled = false
}
break
case kSmileButtonTag:
print("Upload Photos clicked")
if isTakePhotoEnabled == true {
CameraController.takePicture()
SmileButton.setTitle("Loading...", forState: UIControlState.Normal)
}
break
case kCancelButtonTag:
print("Cancel Button clicked")
if isTakePhotoEnabled == true {
CameraController.view.hidden = true
SmileButton.hidden = true
CancelButton.hidden = true
isTakePhotoEnabled = false
}
break
default:
print("Which button is this?")
break
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("didFinishPickingMediaWithInfo", picker.sourceType)
let _image = (info[UIImagePickerControllerOriginalImage] as! UIImage)
if picker.sourceType == UIImagePickerControllerSourceType.Camera {
let image = imageByCroppingImage(_image, _size: CGSize(width: 600,height: 800))
ImageView.addImage(image)
SmileButton.setTitle("Smile =)", forState: UIControlState.Normal)
}else if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary {
self.dismissViewControllerAnimated(true, completion: nil)
isUploadPhotoEnabled = false
ImageView.addImage(_image)
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
print("CANCEL \(picker.sourceType.rawValue)")
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func imageByCroppingImage(image : UIImage, _size : CGSize) -> UIImage {
//@ref: http://stackoverflow.com/questions/158914/cropping-an-uiimage
// step 1: Scale from the original size to a smaller size.
let newHeight = CGFloat(800.0)
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("WIDTH: \(image.size.width) HEIGHT: \(image.size.width) NEWWIDTH: \(newWidth) NEWHEIGHT: \(newHeight)")
// step 3: crop obttom
return croppIngimage(scaledImage, toRect: CGRectMake(0, 0, newWidth, newHeight / 2 ))
}
func croppIngimage(imageToCrop:UIImage, toRect rect:CGRect) -> UIImage{
let imageRef:CGImageRef = CGImageCreateWithImageInRect(imageToCrop.CGImage, rect)!
let cropped:UIImage = UIImage(CGImage:imageRef)
return cropped
}
}
| e9dacb13f5ed14f0a25772c676381086 | 38.23348 | 123 | 0.621716 | false | false | false | false |
SSU-CS-Department/ssumobile-ios | refs/heads/master | SSUMobile/Modules/Core/Moonlight/Builder/SSUJSONEntityBuilder.swift | apache-2.0 | 1 | //
// SSUJSONEntityBuilder.swift
// SSUMobile
//
// Created by Eric Amorde on 7/8/18.
// Copyright © 2018 Sonoma State University Department of Computer Science. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
/**
A specialized builder that knows how to build entities which conform to `SSUJSONInitializable`
Subclasses should override `build(json:)` to perform their custom build logic
*/
class SSUJSONEntityBuilder<Entity: SSUJSONInitializable & SSUCoreDataEntity & NSManagedObject>: SSUMoonlightBuilder {
/**
The primary key of `Entity`
Default: `Entity.primaryKey`
*/
@objc
var idKey: String {
return Entity.identifierKey
}
/**
If `true`, data will be parsed as a single instance instead of an array of instances
*/
@objc
var shouldBuildSingleObject: Bool = false
/**
If `true`, entries that have a deletion date associated with them will trigger a deletion in the database
Default: `true`
*/
@objc
var autoDetectDeletion: Bool = true
/**
The most recent created, modified, or deleted date received in the JSON.
*/
var mostRecentModification: Date?
func id(fromJSON json: JSON) -> Entity.IdentifierType? {
return json[idKey].rawValue as? Entity.IdentifierType
}
func build(json: JSON, completion: (([Entity]) -> Void)? = nil) {
context.perform {
let results = self.build(json: json)
completion?(results)
}
}
override func buildJSON(_ json: JSON) {
self.build(json: json)
}
@discardableResult
func build(json: JSON) -> [Entity] {
SSULogging.logDebug("Building \(Entity.self)")
let startDate = Date()
var results = [Entity]()
let objectsToBuild: [JSON] = shouldBuildSingleObject ? [json] : json.arrayValue
// TODO: add error handling / logging for a non-array response
for entryData in objectsToBuild {
let id = self.id(fromJSON: entryData)
let instance: Entity = type(of: self).object(id: id, context: context)
let dates = self.dateInfo(from: entryData.dictionaryValue)
let mode = self.mode(from: dates)
mostRecentModification = maxValue(mostRecentModification, dates?.mostRecent)
if autoDetectDeletion {
if mode == .deleted {
context.delete(instance)
continue
}
}
do {
try instance.initializeWith(json: entryData)
results.append(instance)
} catch {
SSULogging.logError("Received an error while attempting to initialize \(instance) with data \(entryData): \(error)")
}
}
willFinishBuilding(objects: results)
saveContext()
didFinishBuilding(objects: results)
let buildTime = Date().timeIntervalSince(startDate)
let buildSeconds = String.init(format: "%.2f", buildTime)
SSULogging.logDebug("Finished building \(results.count) \(Entity.self) (\(buildSeconds)s)")
return results
}
/**
Called when `build(json:)` finishes, but before the context has been saved.
Override to perform any operations before saving the context
*/
func willFinishBuilding(objects: [Entity]) {
}
/**
Called when `build(json:)` finishes, after the context has been saved. Override to perform operations on the created/updated objects
*/
func didFinishBuilding(objects: [Entity]) {
}
// MARK: Static helpers
@objc
class var entityName: String {
return "\(Entity.self)"
}
class func idPredicate(_ id: Entity.IdentifierType?, key: String = Entity.identifierKey) -> NSPredicate? {
guard let id = id else { return nil }
return NSPredicate(format: "%K == %@", argumentArray: [key, id])
}
class func object(id: Entity.IdentifierType?, context: NSManagedObjectContext) -> Entity {
let predicate = idPredicate(id, key: Entity.identifierKey)
let result: Entity = object(matchingPredicate: predicate, context: context)
result.setValue(id, forKey: Entity.identifierKey)
return result
}
class func object(matchingPredicate predicate: NSPredicate?, context: NSManagedObjectContext) -> Entity {
guard let result = object(withEntityName: entityName, predicate: predicate, context: context) as? Entity else {
fatalError("Name of entity `\(Entity.self)` does not match any entites in provided context")
}
return result
}
class func allObjects(context: NSManagedObjectContext) -> [Entity] {
return allObjects(context: context, matching: nil)
}
class func allObjects(context: NSManagedObjectContext, matching predicate: NSPredicate?) -> [Entity] {
return allObjects(withEntityName: entityName, matchingPredicate: predicate, context: context).compactMap { $0 as? Entity }
}
/**
Load objects matching the provided predicate (or all, if predicate is nil) in to memory
*/
class func prefetch(context: NSManagedObjectContext, matching predicate: NSPredicate?) {
_ = allObjects(context: context, matching: predicate)
}
class func deleteObjects(matchingPredicate predicate: NSPredicate?, context: NSManagedObjectContext) {
deleteObjects(withEntityName: entityName, matchingPredicate: predicate, context: context)
}
}
| b4e1ac6b47393a144708afc2b5b41691 | 34.018519 | 137 | 0.634585 | false | false | false | false |
CallMeDaKing/DouYuAPP | refs/heads/master | DouYuProject/DouYuProject/Classes/Main/View/CollectionViewBaseCell.swift | mit | 1 | //
// CollectionViewBaseCell.swift
// DouYuProject
//
// Created by li king on 2017/11/22.
// Copyright © 2017年 li king. All rights reserved.
//
import UIKit
class CollectionViewBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nickname: UILabel!
//MARK -- 定义房间模型属性
var anchor : AnchorModel?{
didSet{
//0校验是否优质
guard let anchor = anchor else{return}
//1取出在线人数显示的文字
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))在线"
}else{
onlineStr = "\(anchor.online)在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
//2 .显示昵称
nickname.text = anchor.nickname
//3.显示封面图片 (oc 经常是使用 sd_webimage) 在swift中我们使用喵神的 Kingfisher 和sd 的使用方式基本一样的
guard let iconUrl = URL(string: anchor.vertical_src) else {return}
// sourceImage.kf.setImage(with: iconUrl as? Resource)
iconImageView.kf.setImage(with: iconUrl)
}
}
}
| 08fb135c446e224f29d071c7a5abc3cd | 25.375 | 78 | 0.659716 | false | false | false | false |
artsy/eigen | refs/heads/main | ios/Artsy/View_Controllers/Live_Auctions/Views/LiveAuctionLotCollectionViewDataSource.swift | mit | 1 | import UIKit
class LiveAuctionLotCollectionViewDataSource: NSObject {
static let RestingIndex = 1
static let CellIdentifier = "Cell"
static let CellClass = LiveAuctionLotImageCollectionViewCell.self
let salesPerson: LiveAuctionsSalesPersonType
let imagePrefetcher = SDWebImagePrefetcher.shared
init(salesPerson: LiveAuctionsSalesPersonType) {
self.salesPerson = salesPerson
super.init()
ar_dispatch_after(2) { [weak self] in
self?.beginThumbnailPrecache()
}
}
func beginThumbnailPrecache() {
let thumbnailURLs = (1..<salesPerson.lotCount).compactMap { return salesPerson.lotViewModelForIndex($0).urlForThumbnail }
imagePrefetcher.prefetchURLs(thumbnailURLs)
}
fileprivate func offsetForIndex(_ index: Int) -> Int {
return index - 1
}
}
private typealias CollectionViewDataSource = LiveAuctionLotCollectionViewDataSource
extension CollectionViewDataSource: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// We always have three, for: previous, current, and next. We rely on the UIPageViewControllerDelegate callbacks
// in the SalesPerson to update our collection view's content offset and the corresponding currentFocusedLotIndex.
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let _cell = collectionView.dequeueReusableCell(withReuseIdentifier: LiveAuctionLotCollectionViewDataSource.CellIdentifier, for: indexPath)
guard let cell = _cell as? LiveAuctionLotImageCollectionViewCell else { return _cell }
let lot = salesPerson.lotViewModelRelativeToShowingIndex(offsetForIndex(indexPath.item))
cell.configureForLot(lot, atIndex: indexPath.item)
return cell
}
}
private typealias FancyLayoutDelegate = LiveAuctionLotCollectionViewDataSource
extension FancyLayoutDelegate: LiveAuctionLotCollectionViewDelegateLayout {
func aspectRatioForIndex(_ index: RelativeIndex) -> CGFloat {
let lot = salesPerson.lotViewModelRelativeToShowingIndex(offsetForIndex(index))
return lot.imageAspectRatio
}
func thumbnailURLForIndex(_ index: RelativeIndex) -> URL? {
let lot = salesPerson.lotViewModelRelativeToShowingIndex(offsetForIndex(index))
return lot.urlForThumbnail
}
}
| 226ebb656f1f8d3ba533eeecb3c65118 | 37.169231 | 146 | 0.749698 | false | false | false | false |
ForrestAlfred/firefox-ios | refs/heads/master | Utils/Extensions/StringExtensions.swift | mpl-2.0 | 8 | /* 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
public extension String {
public func contains(other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
return self.rangeOfString(other) != nil
}
public func startsWith(other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
if let range = self.rangeOfString(other,
options: NSStringCompareOptions.AnchoredSearch) {
return range.startIndex == self.startIndex
}
return false
}
public func endsWith(other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
if let range = self.rangeOfString(other,
options: NSStringCompareOptions.AnchoredSearch | NSStringCompareOptions.BackwardsSearch) {
return range.endIndex == self.endIndex
}
return false
}
func escape() -> String {
var raw: NSString = self
var str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
raw,
"[].",":/?&=;+!@#$()',*",
CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
return str as! String
}
func unescape() -> String {
var raw: NSString = self
var str = CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, raw, "[].")
return str as! String
}
/**
Ellipsizes a String only if it's longer than `maxLength`
"ABCDEF".ellipsize(4)
// "AB…EF"
:param: maxLength The maximum length of the String.
:returns: A String with `maxLength` characters or less
*/
func ellipsize(var #maxLength: Int) -> String {
if (maxLength >= 2) && (count(self) > maxLength) {
let index1 = advance(self.startIndex, (maxLength + 1) / 2) // `+ 1` has the same effect as an int ceil
let index2 = advance(self.endIndex, maxLength / -2)
return self.substringToIndex(index1) + "…\u{2060}" + self.substringFromIndex(index2)
}
return self
}
public var asURL: NSURL? {
return NSURL(string: self)
}
}
| 2e4d893b09a9b8d07e57ab21cb3892d1 | 32.833333 | 114 | 0.611595 | false | false | false | false |
jeffellin/VideoPlayer | refs/heads/master | VideoPlayer/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// VideoPlayer
//
// Created by Jeffrey Ellin on 11/2/15.
// Copyright © 2015 Jeffrey Ellin. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doSomething() {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(paths)!
print (paths)
var file:String = ""
while let element = enumerator.nextObject() as? String {
file = element
}
let url = NSURL.fileURLWithPath("\(paths)/\(file)")
let player = AVPlayer(URL: url.absoluteURL)
print(url.absoluteURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.addChildViewController(playerViewController)
self.view.addSubview(playerViewController.view)
playerViewController.view.frame = self.view.frame
player.play()
}
}
| 89aa45398efeec1023d1f159c5e66dab | 23.688525 | 111 | 0.644754 | false | false | false | false |
BeanstalkData/beanstalk-ios-sdk | refs/heads/master | Carthage/Checkouts/ObjectMapper/ObjectMapper/Core/ToJSON.swift | mit | 3 | //
// ToJSON.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-13.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// 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 class Foundation.NSNumber
private func setValue(value: AnyObject, map: Map) {
setValue(value, key: map.currentKey!, checkForNestedKeys: map.keyIsNested, dictionary: &map.JSONDictionary)
}
private func setValue(value: AnyObject, key: String, checkForNestedKeys: Bool, inout dictionary: [String : AnyObject]) {
if checkForNestedKeys {
let keyComponents = ArraySlice(key.characters.split { $0 == "." })
setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary)
} else {
dictionary[key] = value
}
}
private func setValue(value: AnyObject, forKeyPathComponents components: ArraySlice<String.CharacterView.SubSequence>, inout dictionary: [String : AnyObject]) {
if components.isEmpty {
return
}
let head = components.first!
if components.count == 1 {
dictionary[String(head)] = value
} else {
var child = dictionary[String(head)] as? [String : AnyObject]
if child == nil {
child = [:]
}
let tail = components.dropFirst()
setValue(value, forKeyPathComponents: tail, dictionary: &child!)
dictionary[String(head)] = child
}
}
internal final class ToJSON {
class func basicType<N>(field: N, map: Map) {
if let x = field as? AnyObject where false
|| x is NSNumber // Basic types
|| x is Bool
|| x is Int
|| x is Double
|| x is Float
|| x is String
|| x is Array<NSNumber> // Arrays
|| x is Array<Bool>
|| x is Array<Int>
|| x is Array<Double>
|| x is Array<Float>
|| x is Array<String>
|| x is Array<AnyObject>
|| x is Array<Dictionary<String, AnyObject>>
|| x is Dictionary<String, NSNumber> // Dictionaries
|| x is Dictionary<String, Bool>
|| x is Dictionary<String, Int>
|| x is Dictionary<String, Double>
|| x is Dictionary<String, Float>
|| x is Dictionary<String, String>
|| x is Dictionary<String, AnyObject>
{
setValue(x, map: map)
}
}
class func optionalBasicType<N>(field: N?, map: Map) {
if let field = field {
basicType(field, map: map)
}
}
class func object<N: BaseMappable>(field: N, map: Map) {
setValue(Mapper(context: map.context).toJSON(field), map: map)
}
class func optionalObject<N: BaseMappable>(field: N?, map: Map) {
if let field = field {
object(field, map: map)
}
}
class func objectArray<N: BaseMappable>(field: Array<N>, map: Map) {
let JSONObjects = Mapper(context: map.context).toJSONArray(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectArray<N: BaseMappable>(field: Array<N>?, map: Map) {
if let field = field {
objectArray(field, map: map)
}
}
class func twoDimensionalObjectArray<N: BaseMappable>(field: Array<Array<N>>, map: Map) {
var array = [[[String : AnyObject]]]()
for innerArray in field {
let JSONObjects = Mapper(context: map.context).toJSONArray(innerArray)
array.append(JSONObjects)
}
setValue(array, map: map)
}
class func optionalTwoDimensionalObjectArray<N: BaseMappable>(field: Array<Array<N>>?, map: Map) {
if let field = field {
twoDimensionalObjectArray(field, map: map)
}
}
class func objectSet<N: BaseMappable where N: Hashable>(field: Set<N>, map: Map) {
let JSONObjects = Mapper(context: map.context).toJSONSet(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectSet<N: BaseMappable where N: Hashable>(field: Set<N>?, map: Map) {
if let field = field {
objectSet(field, map: map)
}
}
class func objectDictionary<N: BaseMappable>(field: Dictionary<String, N>, map: Map) {
let JSONObjects = Mapper(context: map.context).toJSONDictionary(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectDictionary<N: BaseMappable>(field: Dictionary<String, N>?, map: Map) {
if let field = field {
objectDictionary(field, map: map)
}
}
class func objectDictionaryOfArrays<N: BaseMappable>(field: Dictionary<String, [N]>, map: Map) {
let JSONObjects = Mapper(context: map.context).toJSONDictionaryOfArrays(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectDictionaryOfArrays<N: BaseMappable>(field: Dictionary<String, [N]>?, map: Map) {
if let field = field {
objectDictionaryOfArrays(field, map: map)
}
}
}
| 1ff39a2db381d3599dda5b832575f025 | 30.293103 | 160 | 0.69899 | false | false | false | false |
onmyway133/Github.swift | refs/heads/master | Sources/Classes/Notification/Notification.swift | mit | 1 | //
// Notification.swift
// GithubSwift
//
// Created by Khoa Pham on 02/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import Tailor
import Sugar
// A notification of some type of activity.
public class Notification: Object {
// The type of the notification.
//
// OCTNotificationTypeUnknown - An unknown type of notification.
// OCTNotificationTypeIssue - A new issue, or a new comment on one.
// OCTNotificationTypePullRequest - A new pull request, or a new comment on one.
// OCTNotificationTypeCommit - A new comment on a commit.
public enum Kind: String {
case Unknown = ""
case Issue = "Issue"
case PullRequest = "PullRequest"
case Commit = "Commit"
}
// The title of the notification.
public private(set) var title: String = ""
// The API URL to the notification's thread.
public private(set) var threadURL: NSURL?
// The API URL to the subject that the notification was generated for (e.g., the
// issue or pull request).
public private(set) var subjectURL: NSURL?
// The API URL to the latest comment in the thread.
//
// If the notification does not represent a comment, this will be the same as
// the subjectURL.
public private(set) var latestCommentURL: NSURL?
// The notification type.
public private(set) var kind: Kind = .Unknown
// The repository to which the notification belongs.
public private(set) var repository: Repository?
// The date on which the notification was last updated.
public private(set) var lastUpdatedDate: NSDate?
// Whether this notification has yet to be read.
public private(set) var isUnread: Bool = false
public required init(_ map: JSONDictionary) {
super.init(map)
let subject = map.dictionary("subject")
self.title <- subject?.property("title")
self.threadURL <- map.transform("url", transformer: NSURL.init(string: ))
self.subjectURL <- subject?.transform("url", transformer: NSURL.init(string: ))
self.latestCommentURL <- subject?.transform("latest_comment_url", transformer: NSURL.init(string: ))
self.kind = subject?.`enum`("type") ?? .Unknown
self.repository = map.relation("repository")
self.lastUpdatedDate = map.transform("updated_at", transformer: Transformer.stringToDate)
}
}
| 796979a4ae4719e18b93252d197c286d | 32.4 | 104 | 0.695466 | false | true | false | false |
ZhaoBingDong/EasySwifty | refs/heads/master | EasySwifty/Classes/Easy+UIImage.swift | apache-2.0 | 1 | //
// Easy+UIImage.swift
// EaseSwifty
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIImage
extension UIImage {
/// 调整图片的方向
func normalizedImage() -> UIImage {
if self.imageOrientation == UIImage.Orientation.up {
return self
}
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
self.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img!
}
// func cirleImage() -> UIImage {
//
// // NO代表透明
// UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
// // 获得上下文
// let ctx = UIGraphicsGetCurrentContext()
//
// // 添加一个圆
// let rect = CGRect(x: 0, y : 0, width : self.size.width, height: self.size.height);
// ctx!.addEllipse(in: rect);
//
// // 裁剪
// ctx?.clip();
//
// // 将图片画上去
// self.draw(in: rect)
//
// let cirleImage = UIGraphicsGetImageFromCurrentImageContext();
//
// UIGraphicsEndImageContext();
//
// return cirleImage!
//
//
// }
/// 通过一个 UIColor 生成一个 UIImage
@discardableResult
class func imageWithColor(_ color: UIColor) -> UIImage {
let rect:CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext()
return image
}
}
| 4a9114224264e2e7107be9c7cfc588f1 | 23.876712 | 95 | 0.594714 | false | false | false | false |
PaulWoodIII/tipski | refs/heads/master | TipskyiOS/Tipski/Appearance.swift | mit | 1 | //
// Appearance.swift
// Tipski
//
// Created by Paul Wood on 10/14/16.
// Copyright © 2016 Paul Wood. All rights reserved.
//
import UIKit
class Appearance {
private struct Cache {
static let Label30Font = UIFont(name: "OpenSans", size:30)
}
class func setAppearance () {
UIView.appearance().tintColor = TipskiIcons.orangeHighlight
UINavigationBar.appearance().barStyle = .black
UINavigationBar.appearance().barTintColor = TipskiIcons.orangeHighlight
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
UISlider.appearance().minimumTrackTintColor = TipskiIcons.orange
UISlider.appearance().maximumTrackTintColor = TipskiIcons.foreground3
UIButton.appearance(whenContainedInInstancesOf: [UINavigationBar.self])
.tintColor = UIColor.white
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self])
.tintColor = UIColor.white
}
class func reloadViewsFrom(windows : [UIWindow]){
for window in windows {
for view in window.subviews {
view.removeFromSuperview()
window.addSubview(view)
}
}
}
class func createWellFromView(view : UIView){
view.backgroundColor = TipskiIcons.foreground4
view.layer.cornerRadius = 10.0
view.layer.masksToBounds = true
view.layer.borderWidth = 1
view.layer.borderColor = TipskiIcons.foreground2.cgColor
}
class func createInput(textField : UITextField){
textField.backgroundColor = TipskiIcons.foreground3
textField.layer.cornerRadius = 3.0
textField.layer.masksToBounds = true
textField.layer.borderWidth = 1
textField.layer.borderColor = TipskiIcons.foreground1.cgColor
}
class func createSubmitButton(button : UIButton){
button.backgroundColor = TipskiIcons.greenHighlight
button.layer.cornerRadius = 22.0
button.layer.masksToBounds = true
button.layer.borderWidth = 1
button.layer.borderColor = TipskiIcons.green.cgColor
}
}
| 204be4ffa79e930d27cc4f2c61837c83 | 32.536232 | 107 | 0.659032 | false | false | false | false |
ThumbWorks/i-meditated | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Reduce.swift | mit | 6 | //
// Reduce.swift
// Rx
//
// Created by Krunoslav Zaher on 4/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ReduceSink<SourceType, AccumulateType, O: ObserverType> : Sink<O>, ObserverType {
typealias ResultType = O.E
typealias Parent = Reduce<SourceType, AccumulateType, ResultType>
private let _parent: Parent
private var _accumulation: AccumulateType
init(parent: Parent, observer: O) {
_parent = parent
_accumulation = parent._seed
super.init(observer: observer)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let value):
do {
_accumulation = try _parent._accumulator(_accumulation, value)
}
catch let e {
forwardOn(.error(e))
dispose()
}
case .error(let e):
forwardOn(.error(e))
dispose()
case .completed:
do {
let result = try _parent._mapResult(_accumulation)
forwardOn(.next(result))
forwardOn(.completed)
dispose()
}
catch let e {
forwardOn(.error(e))
dispose()
}
}
}
}
class Reduce<SourceType, AccumulateType, ResultType> : Producer<ResultType> {
typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType
typealias ResultSelectorType = (AccumulateType) throws -> ResultType
fileprivate let _source: Observable<SourceType>
fileprivate let _seed: AccumulateType
fileprivate let _accumulator: AccumulatorType
fileprivate let _mapResult: ResultSelectorType
init(source: Observable<SourceType>, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) {
_source = source
_seed = seed
_accumulator = accumulator
_mapResult = mapResult
}
override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == ResultType {
let sink = ReduceSink(parent: self, observer: observer)
sink.disposable = _source.subscribe(sink)
return sink
}
}
| 175acca853d46ce342eaca48eae6e810 | 29.824324 | 145 | 0.594476 | false | false | false | false |
JohnBehnke/RPI_Tours_iOS | refs/heads/master | RPI Tours/RPI Tours/InfoViewController.swift | mit | 2 | //
// InfoViewController.swift
// RPI Tours
//
// Created by Jacob Speicher on 8/1/16.
// Copyright © 2016 RPI Web Tech. All rights reserved.
//
import UIKit
import ReachabilitySwift
import CoreLocation
import ImageSlideshow
import AlamofireImage
class InfoViewController: UITableViewController {
// MARK: IBOutlets
@IBOutlet var landmarkDescriptionLabel: UILabel!
@IBOutlet var descriptionCell: UITableViewCell!
// MARK: Global Variables
var landmarkName: String = ""
var landmarkDesc: String = ""
var landmarkInformation: [Landmark] = []
@IBOutlet weak var slideShow: ImageSlideshow!
var cameFromMap: Bool = false
// MARK: Segues
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// if segue.identifier == "imageSlider" {
// }
// }
// MARK: System Functions
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = self.landmarkName
let chosenLandmark = searchForLandmark()
self.landmarkDescriptionLabel.text = chosenLandmark.desc
var images: [InputSource] = []
for imageURL in chosenLandmark.urls {
images.append(AlamofireSource(urlString: imageURL)!)
}
slideShow.setImageInputs(images)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Helper Functions
func searchForLandmark() -> Landmark {
for landmark in self.landmarkInformation {
if landmark.name == self.landmarkName && !landmark.desc.isEmpty {
return landmark
}
}
let blankLandmark = Landmark(name: "Unknown Landmark",
desc: "I'm sorry, there is no information yet for this landmark.",
lat: 0.0,
long: 0.0, urls:[])
return blankLandmark
}
// MARK: TableView Functions
override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return CGFloat(Constants.CellHeights.InfoHeights.tall)
}
return CGFloat(Constants.CellHeights.InfoHeights.short)
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return CGFloat(Constants.CellHeights.InfoHeights.tall)
}
return CGFloat(Constants.CellHeights.InfoHeights.short)
}
}
| d489a37cba0b5e815547553c13de6931 | 26.393617 | 112 | 0.632621 | false | false | false | false |
rudedogg/TiledSpriteKit | refs/heads/master | Sources/SKTilemapCamera.swift | mit | 1 | /*
SKTilemap
SKTilemapCamera.swift
Created by Thomas Linthwaite on 07/04/2016.
GitHub: https://github.com/TomLinthwaite/SKTilemap
Website (Guide): http://tomlinthwaite.com/
Wiki: https://github.com/TomLinthwaite/SKTilemap/wiki
YouTube: https://www.youtube.com/channel/UCAlJgYx9-Ub_dKD48wz6vMw
Twitter: https://twitter.com/Mr_Tomoso
-----------------------------------------------------------------------------------------------------------------------
MIT License
Copyright (c) 2016 Tom Linthwaite
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 SpriteKit
#if os(iOS)
import UIKit
#endif
protocol SKTilemapCameraDelegate : class {
func didUpdatePosition(position: CGPoint, scale: CGFloat, bounds: CGRect)
func didUpdateZoomScale(position: CGPoint, scale: CGFloat, bounds: CGRect)
func didUpdateBounds(position: CGPoint, scale: CGFloat, bounds: CGRect)
}
// MARK: Camera
public class SKTilemapCamera : SKCameraNode {
// MARK: Properties
/** The node the camera intereacts with. Anything you want to be effected by the camera should be a child of this node. */
let worldNode: SKNode
/** Bounds the camera constrains the worldNode to. Default value is the size of the view but this can be changed. */
fileprivate var bounds: CGRect
/** The current zoom scale of the camera. */
fileprivate var zoomScale: CGFloat
/** Min/Max scale the camera can zoom in/out. */
var zoomRange: (min: CGFloat, max: CGFloat)
/** Enable/Disable the ability to zoom the camera. */
var allowZoom: Bool
fileprivate var isEnabled: Bool
/** Enable/Disable the camera. */
var enabled: Bool {
get { return isEnabled }
set {
isEnabled = newValue
#if os(iOS)
longPressGestureRecognizer.isEnabled = newValue
pinchGestureRecognizer.isEnabled = newValue
#endif
}
}
/** Enable/Disable clamping of the worldNode */
var enableClamping: Bool
/** Delegates are informed when the camera repositions or performs some other action. */
fileprivate var delegates: [SKTilemapCameraDelegate] = []
/** Previous touch/mouse location the last time the position was updated. */
fileprivate var previousLocation: CGPoint!
// MARK: Initialization
/** Initialize a basic camera. */
init(scene: SKScene, view: SKView, worldNode: SKNode) {
self.worldNode = worldNode
bounds = view.bounds
zoomScale = 1.0
zoomRange = (0.05, 4.0)
allowZoom = true
isEnabled = true
enableClamping = true
super.init()
#if os(iOS)
pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.updateScale(_:)))
view.addGestureRecognizer(pinchGestureRecognizer)
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.updatePosition(_:)))
longPressGestureRecognizer.numberOfTouchesRequired = 1
longPressGestureRecognizer.numberOfTapsRequired = 0
longPressGestureRecognizer.allowableMovement = 0
longPressGestureRecognizer.minimumPressDuration = 0
view.addGestureRecognizer(longPressGestureRecognizer)
#endif
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/** Adds a delegate to camera. Will not allow duplicate delegates to be added. */
func addDelegate(_ delegate: SKTilemapCameraDelegate) {
if let _ = delegates.index(where: { $0 === delegate }) { return }
delegates.append(delegate)
}
/** Removes a delegate from the camera. */
func removeDelegate(_ delegate: SKTilemapCameraDelegate) {
if let index = delegates.index( where: { $0 === delegate } ) {
delegates.remove(at: index)
}
}
// MARK: Input - iOS
#if os(iOS)
/** Used for zooming/scaling the camera. */
var pinchGestureRecognizer: UIPinchGestureRecognizer!
var longPressGestureRecognizer: UILongPressGestureRecognizer!
/** Used to determine the intial touch location when the user performs a pinch gesture. */
fileprivate var initialTouchLocation = CGPoint.zero
/** Will move the camera based on the direction of a touch from the longPressGestureRecognizer.
Any delegates of the camera will be informed that the camera moved. */
func updatePosition(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .began {
previousLocation = recognizer.location(in: recognizer.view)
}
if recognizer.state == .changed {
if previousLocation == nil { return }
let location = recognizer.location(in: recognizer.view)
let difference = CGPoint(x: location.x - previousLocation.x, y: location.y - previousLocation.y)
centerOnPosition(CGPoint(x: Int(position.x - difference.x), y: Int(position.y - -difference.y)))
previousLocation = location
}
}
/** Scales the worldNode using input from a pinch gesture recogniser.
Any delegates of the camera will be informed that the camera changed scale. */
func updateScale(_ recognizer: UIPinchGestureRecognizer) {
guard let scene = self.scene else { return }
if recognizer.state == .began {
initialTouchLocation = scene.convertPoint(fromView: recognizer.location(in: recognizer.view))
}
if recognizer.state == .changed && enabled && allowZoom {
zoomScale *= recognizer.scale
applyZoomScale(zoomScale)
recognizer.scale = 1
centerOnPosition(CGPoint(x: initialTouchLocation.x * zoomScale, y: initialTouchLocation.y * zoomScale))
}
if recognizer.state == .ended { }
}
#endif
// MARK: Input - OSX
#if os(OSX)
/** Updates the camera position based on mouse movement.
Any delegates of the camera will be informed that the camera moved. */
func updatePosition(event: NSEvent) {
if scene == nil || !enabled { return }
if previousLocation == nil { previousLocation = event.location(in: self) }
let location = event.location(in: self)
let difference = CGPoint(x: location.x - previousLocation.x, y: location.y - previousLocation.y)
centerOnPosition(CGPoint(x: Int(position.x - difference.x), y: Int(position.y - difference.y)))
previousLocation = location
}
/** Call this on mouseUp so the camera can reset the previous position. Without this the update position function
will assume the mouse was in the last place as before an cause undesired "jump" effect. */
func finishedInput() {
previousLocation = nil
}
#endif
// MARK: Positioning
/** Moves the camera so it centers on a certain position within the scene. Easing can be applied by setting a timing
interval. Otherwise the position is changed instantly. */
func centerOnPosition(_ scenePosition: CGPoint, easingDuration: TimeInterval = 0) {
if easingDuration == 0 {
position = scenePosition
clampWorldNode()
for delegate in delegates { delegate.didUpdatePosition(position: position, scale: zoomScale, bounds: self.bounds) }
} else {
let moveAction = SKAction.move(to: scenePosition, duration: easingDuration)
moveAction.timingMode = .easeOut
let blockAction = SKAction.run({
self.clampWorldNode()
for delegate in self.delegates { delegate.didUpdatePosition(position: self.position, scale: self.zoomScale, bounds: self.bounds) }
})
run(SKAction.group([moveAction, blockAction]))
}
}
func centerOnNode(node: SKNode?, easingDuration: TimeInterval = 0) {
guard let theNode = node , theNode.parent != nil else { return }
let position = scene!.convert(theNode.position, from: theNode.parent!)
centerOnPosition(position, easingDuration: easingDuration)
}
// MARK: Scaling and Zoom
/** Applies a scale to the worldNode. Ensures that the scale stays within its range and that the worldNode is
clamped within its bounds. */
func applyZoomScale(_ scale: CGFloat) {
var zoomScale = scale
if zoomScale < zoomRange.min {
zoomScale = zoomRange.min
} else if zoomScale > zoomRange.max {
zoomScale = zoomRange.max
}
self.zoomScale = zoomScale
worldNode.setScale(zoomScale)
for delegate in delegates { delegate.didUpdateZoomScale(position: position, scale: zoomScale, bounds: self.bounds) }
}
/** Returns the minimum zoom scale possible for the size of the worldNode. Useful when you don't want the worldNode
to be displayed smaller than the current bounds. */
func minimumZoomScale() -> CGFloat {
let frame = worldNode.calculateAccumulatedFrame()
if bounds == CGRect.zero || frame == CGRect.zero { return 0 }
let xScale = (bounds.width * zoomScale) / frame.width
let yScale = (bounds.height * zoomScale) / frame.height
return min(xScale, yScale)
}
// MARK: Bounds
/** Keeps the worldNode clamped between a specific bounds. If the worldNode is smaller than these bounds it will
stop it from moving outside of those bounds. */
fileprivate func clampWorldNode() {
if !enableClamping { return }
let frame = worldNode.calculateAccumulatedFrame()
var minX = frame.minX + (bounds.size.width / 2)
var maxX = frame.maxX - (bounds.size.width / 2)
var minY = frame.minY + (bounds.size.height / 2)
var maxY = frame.maxY - (bounds.size.height / 2)
if frame.width < bounds.width {
swap(&minX, &maxX)
}
if frame.height < bounds.height {
swap(&minY, &maxY)
}
if position.x < minX {
position.x = CGFloat(Int(minX))
} else if position.x > maxX {
position.x = CGFloat(Int(maxX))
}
if position.y < minY {
position.y = CGFloat(Int(minY))
} else if position.y > maxY {
position.y = CGFloat(Int(maxY))
}
}
/** Returns the current bounds the camera is using. */
func getBounds() -> CGRect {
return bounds
}
/** Updates the bounds for the worldNode to be constrained to. Will inform all delegates this change occured. */
func updateBounds(_ bounds: CGRect) {
self.bounds = bounds
for delegate in delegates { delegate.didUpdateBounds(position: position, scale: zoomScale, bounds: self.bounds) }
}
}
| 2e1829a8648e302f445dfa6d02036311 | 36.609756 | 146 | 0.630512 | false | false | false | false |
Frainbow/ShaRead.frb-swift | refs/heads/master | ShaRead/ShaRead/ShaStore.swift | mit | 1 | //
// ShaStore.swift
// ShaRead
//
// Created by martin on 2016/5/14.
// Copyright © 2016年 Frainbow. All rights reserved.
//
import Foundation
import SwiftyJSON
enum ShaAdminStoreItem: Int {
case ShaAdminStoreName = 0
case ShaAdminStoreDescription
case ShaAdminStorePosition
}
class ShaStorePosition {
var address: String = ""
var longitude: Float = 0
var latitude: Float = 0
}
class ShaStore {
var id: Int = 0
var name: String = ""
var image: NSURL?
var description: String = ""
var avatar: NSURL?
var owner: ShaUser?
var position = ShaStorePosition()
var books: [ShaBook] = []
init() {
}
init (data: JSON) {
self.id = data["store_id"].intValue
self.name = data["store_name"].stringValue
self.description = data["description"].stringValue
self.position.address = data["position"]["address"].stringValue
if data["store_image"].error == nil {
self.image = NSURL(string: data["store_image"].stringValue)
}
if data["owner"].error == nil {
self.owner = ShaUser(jsonData: data["owner"])
}
if data["avatar"].error == nil {
self.avatar = NSURL(string: data["avatar"].stringValue)
}
for book in data["books"].arrayValue {
self.books.append(ShaBook(data: book))
}
}
}
extension ShaManager {
func newAdminStore(store: ShaStore, success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodPost,
path: "/stores?auth_token=\(authToken)",
param: [ "store_name": store.name ],
success: { code, data in
store.id = data["store_id"].intValue
self.adminStores.append(store)
success()
},
failure: { code, data in
failure()
}
)
}
func getAdminStore(success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores",
param: ["auth_token": self.authToken],
success: { code, data in
let storeList = data["data"].arrayValue
self.adminStores.removeAll()
for store in storeList {
let adminStore = ShaStore(data: store)
self.adminStores.append(adminStore)
}
success()
},
failure: { code, data in
failure()
}
)
}
func updateAdminStore(store: ShaStore, column: [ShaAdminStoreItem],
success: () -> Void, failure: () -> Void) {
var param = [String: AnyObject]()
for item in column {
switch item {
case .ShaAdminStoreName:
param["store_name"] = store.name
case .ShaAdminStoreDescription:
param["description"] = store.description
case .ShaAdminStorePosition:
param["address"] = store.position.address
param["longitude"] = store.position.longitude
param["latitude"] = store.position.latitude
}
}
HttpManager.sharedInstance.request(
.HttpMethodPut,
path: "/stores/\(store.id)?auth_token=\(authToken)",
param: param,
success: { code, data in
success()
},
failure: { code, data in
failure()
}
)
}
func uploadAdminStoreImage(store: ShaStore, image: UIImage, success: (url: NSURL) -> Void, failure: () -> Void) {
let resizedImage = resizeImage(image, newWidth: 200)
if let data = UIImageJPEGRepresentation(resizedImage, 0.1) {
HttpManager.sharedInstance.uploadData(
"/stores/\(store.id)/images?auth_token=\(authToken)",
name: "store_image",
data: data,
success: { (code, data) in
if let url = NSURL(string: data["image_path"].stringValue) {
success(url: url)
} else {
failure()
}
},
failure: { (code, data) in
failure()
}
)
} else {
failure()
}
}
}
extension ShaManager {
func getPopularStore(complete: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores",
param: ["order": "popular"],
success: { code, data in
self.popularStores.removeAll()
for store in data["data"].arrayValue {
self.popularStores.append(ShaStore(data: store))
}
},
complete: {
complete()
}
)
}
func getLatestStore(complete: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores",
param: ["order": "latest"],
success: { code, data in
self.latestStores.removeAll()
for store in data["data"].arrayValue {
self.latestStores.append(ShaStore(data: store))
}
},
complete: {
complete()
}
)
}
func getStoreByID(id: Int, success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores/\(id)",
param: [:],
success: { code, data in
self.stores[id] = ShaStore(data: data["data"])
success()
},
failure: { code, data in
failure()
}
)
}
func getStoreBooks(store: ShaStore, success: () -> Void, failure: () -> Void) {
HttpManager.sharedInstance.request(
.HttpMethodGet,
path: "/stores/\(store.id)/books",
param: [:],
success: { code, data in
store.books.removeAll()
for book in data["data"].arrayValue {
store.books.append(ShaBook(data: book))
}
success()
},
failure: { code, data in
failure()
}
)
}
}
| 24393c0b13b762d447953600283e582d | 27.608333 | 117 | 0.464171 | false | false | false | false |
xibe/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Reader/ReaderStreamViewController.swift | gpl-2.0 | 1 | import Foundation
@objc public class ReaderStreamViewController : UIViewController, UIActionSheetDelegate,
WPContentSyncHelperDelegate,
WPTableViewHandlerDelegate,
ReaderPostCellDelegate,
ReaderStreamHeaderDelegate
{
// MARK: - Properties
private var tableView: UITableView!
private var refreshControl: UIRefreshControl!
private var tableViewHandler: WPTableViewHandler!
private var syncHelper: WPContentSyncHelper!
private var tableViewController: UITableViewController!
private var cellForLayout: ReaderPostCardCell!
private var resultsStatusView: WPNoResultsView!
private var footerView: PostListFooterView!
private var objectIDOfPostForMenu: NSManagedObjectID?
private var anchorViewForMenu: UIView?
private let footerViewNibName = "PostListFooterView"
private let readerCardCellNibName = "ReaderPostCardCell"
private let readerCardCellReuseIdentifier = "ReaderCardCellReuseIdentifier"
private let readerBlockedCellNibName = "ReaderBlockedSiteCell"
private let readerBlockedCellReuseIdentifier = "ReaderBlockedCellReuseIdentifier"
private let estimatedRowHeight = CGFloat(100.0)
private let blockedRowHeight = CGFloat(66.0)
private let loadMoreThreashold = 4
private let refreshInterval = 300
private var displayContext: NSManagedObjectContext?
private var cleanupAndRefreshAfterScrolling = false
private let recentlyBlockedSitePostObjectIDs = NSMutableArray()
private var showShareActivityAfterActionSheetIsDismissed = false
private let frameForEmptyHeaderView = CGRect(x: 0.0, y: 0.0, width: 320.0, height: 30.0)
private let heightForFooterView = CGFloat(34.0)
private var siteID:NSNumber? {
didSet {
if siteID != nil {
fetchSiteTopic()
}
}
}
public var readerTopic: ReaderAbstractTopic? {
didSet {
if readerTopic != nil {
if isViewLoaded() {
configureControllerForTopic()
}
// Discard the siteID (if there was one) now that we have a good topic
siteID = nil
}
}
}
/**
Convenience method for instantiating an instance of ReaderListViewController
for a particular topic.
@param topic The reader topic for the list.
@return A ReaderListViewController instance.
*/
public class func controllerWithTopic(topic:ReaderAbstractTopic) -> ReaderStreamViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: NSBundle.mainBundle())
let controller = storyboard.instantiateViewControllerWithIdentifier("ReaderStreamViewController") as! ReaderStreamViewController
controller.readerTopic = topic
return controller
}
public class func controllerWithSiteID(siteID:NSNumber) -> ReaderStreamViewController {
let storyboard = UIStoryboard(name: "Reader", bundle: NSBundle.mainBundle())
let controller = storyboard.instantiateViewControllerWithIdentifier("ReaderStreamViewController") as! ReaderStreamViewController
controller.siteID = siteID
return controller
}
// MARK: - LifeCycle Methods
public override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
tableViewController = segue.destinationViewController as? UITableViewController
}
public override func viewDidLoad() {
super.viewDidLoad()
setupCellForLayout()
setupTableView()
setupFooterView()
setupTableViewHandler()
setupSyncHelper()
setupResultsStatusView()
WPStyleGuide.configureColorsForView(view, andTableView: tableView)
if readerTopic != nil {
configureControllerForTopic()
} else if siteID != nil {
displayLoadingStream()
}
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
refreshTableViewHeaderLayout()
}
// MARK: -
public override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
private func fetchSiteTopic() {
if isViewLoaded() {
displayLoadingStream()
}
assert(siteID != nil, "A siteID is required before fetching a site topic")
var service = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext)
service.siteTopicForSiteWithID(siteID!,
success: { [weak self] (objectID:NSManagedObjectID!, isFollowing:Bool) -> Void in
var error:NSError?
var topic = self?.managedObjectContext().existingObjectWithID(objectID, error: &error) as? ReaderSiteTopic
if let anError = error {
DDLogSwift.logError(anError.localizedDescription)
}
self?.readerTopic = topic
},
failure: {[weak self] (error:NSError!) -> Void in
self?.displayLoadingStreamFailed()
})
}
// MARK: - Setup
private func setupTableView() {
assert(tableViewController != nil, "The tableViewController must be assigned before configuring the tableView")
tableView = tableViewController.tableView
tableView.separatorStyle = .None
refreshControl = tableViewController.refreshControl!
refreshControl.addTarget(self, action: Selector("handleRefresh:"), forControlEvents: .ValueChanged)
var nib = UINib(nibName: readerCardCellNibName, bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: readerCardCellReuseIdentifier)
nib = UINib(nibName: readerBlockedCellNibName, bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: readerBlockedCellReuseIdentifier)
}
private func setupTableViewHandler() {
assert(tableView != nil, "A tableView must be assigned before configuring a handler")
tableViewHandler = WPTableViewHandler(tableView: tableView)
tableViewHandler.cacheRowHeights = true
tableViewHandler.updateRowAnimation = .None
tableViewHandler.delegate = self
}
private func setupSyncHelper() {
syncHelper = WPContentSyncHelper()
syncHelper.delegate = self
}
private func setupCellForLayout() {
cellForLayout = NSBundle.mainBundle().loadNibNamed(readerCardCellNibName, owner: nil, options: nil).first as! ReaderPostCardCell
// Add layout cell to superview (briefly) so constraint constants reflect the correct size class.
view.addSubview(cellForLayout)
cellForLayout.removeFromSuperview()
}
private func setupResultsStatusView() {
resultsStatusView = WPNoResultsView()
}
private func setupFooterView() {
footerView = NSBundle.mainBundle().loadNibNamed(footerViewNibName, owner: nil, options: nil).first as! PostListFooterView
footerView.showSpinner(false)
var frame = footerView.frame
frame.size.height = heightForFooterView
footerView.frame = frame
tableView.tableFooterView = footerView
}
// MARK: - Handling Loading and No Results
func displayLoadingStream() {
resultsStatusView.titleText = NSLocalizedString("Loading stream...", comment:"A short message to inform the user the requested stream is being loaded.")
resultsStatusView.messageText = ""
displayResultsStatus()
}
func displayLoadingStreamFailed() {
resultsStatusView.titleText = NSLocalizedString("Problem loading stream", comment:"Error message title informing the user that a stream could not be loaded.");
resultsStatusView.messageText = NSLocalizedString("Sorry. The stream could not be loaded.", comment:"A short error message leting the user know the requested stream could not be loaded.");
displayResultsStatus()
}
func displayLoadingViewIfNeeded() {
var count = tableViewHandler.resultsController.fetchedObjects?.count ?? 0
if count > 0 {
return
}
resultsStatusView.titleText = NSLocalizedString("Fetching posts...", comment:"A brief prompt shown when the reader is empty, letting the user know the app is currently fetching new posts.")
resultsStatusView.messageText = ""
var boxView = WPAnimatedBox.new()
resultsStatusView.accessoryView = boxView
displayResultsStatus()
boxView.prepareAndAnimateAfterDelay(0.3)
}
func displayNoResultsView() {
// Its possible the topic was deleted before a sync could be completed,
// so make certain its not nil.
if readerTopic == nil {
return
}
let response:NoResultsResponse = ReaderStreamViewController.responseForNoResults(readerTopic!)
resultsStatusView.titleText = response.title
resultsStatusView.messageText = response.message
resultsStatusView.accessoryView = nil
displayResultsStatus()
}
func displayResultsStatus() {
if resultsStatusView.isDescendantOfView(tableView) {
resultsStatusView.centerInSuperview()
} else {
tableView.addSubviewWithFadeAnimation(resultsStatusView)
}
footerView.hidden = true
}
func hideResultsStatus() {
resultsStatusView.removeFromSuperview()
footerView.hidden = false
}
// MARK: - Topic Presentation
func configureStreamHeader() {
assert(readerTopic != nil, "A reader topic is required")
var header:ReaderStreamHeader? = ReaderStreamViewController.headerForStream(readerTopic!)
if header == nil {
if UIDevice.isPad() {
var headerView = UIView(frame: frameForEmptyHeaderView)
headerView.backgroundColor = UIColor.clearColor()
tableView.tableHeaderView = headerView
} else {
tableView.tableHeaderView = nil
}
return
}
header!.configureHeader(readerTopic!)
header!.delegate = self
tableView.tableHeaderView = header as? UIView
refreshTableViewHeaderLayout()
}
func configureControllerForTopic() {
assert(readerTopic != nil, "A reader topic is required")
assert(isViewLoaded(), "The controller's view must be loaded before displaying the topic")
hideResultsStatus()
recentlyBlockedSitePostObjectIDs.removeAllObjects()
updateAndPerformFetchRequest()
configureStreamHeader()
tableView.setContentOffset(CGPointZero, animated: false)
tableViewHandler.refreshTableView()
syncIfAppropriate()
var count = tableViewHandler.resultsController.fetchedObjects?.count ?? 0
// Make sure we're showing the no results view if appropriate
if !syncHelper.isSyncing && count == 0 {
displayNoResultsView()
}
WPAnalytics.track(.ReaderLoadedTag, withProperties: propertyForStats())
if ReaderHelpers.topicIsFreshlyPressed(readerTopic!) {
WPAnalytics.track(.ReaderLoadedFreshlyPressed)
}
}
// MARK: - Instance Methods
func refreshTableViewHeaderLayout() {
if tableView.tableHeaderView == nil {
return
}
let headerView = tableView.tableHeaderView!
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
var height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
tableView.tableHeaderView = headerView
}
public func scrollViewToTop() {
tableView.setContentOffset(CGPoint.zeroPoint, animated: true)
}
private func propertyForStats() -> [NSObject: AnyObject] {
assert(readerTopic != nil, "A reader topic is required")
var title = readerTopic!.title ?? ""
var key: String = "list"
if ReaderHelpers.isTopicTag(readerTopic!) {
key = "tag"
} else if ReaderHelpers.isTopicSite(readerTopic!) {
key = "site"
}
return [key : title]
}
private func shouldShowBlockSiteMenuItem() -> Bool {
return ReaderHelpers.isTopicTag(readerTopic!) || ReaderHelpers.topicIsFreshlyPressed(readerTopic!)
}
private func showMenuForPost(post:ReaderPost, fromView anchorView:UIView) {
objectIDOfPostForMenu = post.objectID
anchorViewForMenu = anchorView
let cancel = NSLocalizedString("Cancel", comment:"The title of a cancel button.")
let blockSite = NSLocalizedString("Block This Site", comment:"The title of a button that triggers blocking a site from the user's reader.")
let share = NSLocalizedString("Share", comment:"Verb. Title of a button. Pressing the lets the user share a post to others.")
var actionSheet = UIActionSheet(title: nil,
delegate: self,
cancelButtonTitle: cancel,
destructiveButtonTitle: shouldShowBlockSiteMenuItem() ? blockSite : nil
)
actionSheet.addButtonWithTitle(share)
if UIDevice.isPad() {
actionSheet.showFromRect(anchorViewForMenu!.bounds, inView:anchorViewForMenu, animated:true)
} else {
actionSheet.showFromTabBar(tabBarController?.tabBar)
}
}
private func sharePost(post: ReaderPost) {
var controller = ReaderHelpers.shareController(
post.titleForDisplay(),
summary: post.contentPreviewForDisplay(),
tags: post.tags,
link: post.permaLink
)
if !UIDevice.isPad() {
presentViewController(controller, animated: true, completion: nil)
return
}
// Gah! Stupid iPad and UIPopovoers!!!!
var popover = UIPopoverController(contentViewController: controller)
popover.presentPopoverFromRect(anchorViewForMenu!.bounds,
inView: anchorViewForMenu!,
permittedArrowDirections: UIPopoverArrowDirection.Unknown,
animated: false)
}
private func showAttributionForPost(post: ReaderPost) {
// Fail safe. If there is no attribution exit.
if post.sourceAttribution == nil {
return
}
// If there is a blogID preview the site
if post.sourceAttribution!.blogID != nil {
let controller = ReaderStreamViewController.controllerWithSiteID(post.sourceAttribution!.blogID)
navigationController?.pushViewController(controller, animated: true)
return
}
if post.sourceAttribution!.attributionType != SourcePostAttributionTypeSite {
return
}
let linkURL = NSURL(string: post.sourceAttribution.blogURL)
let controller = WPWebViewController(URL: linkURL)
let navController = UINavigationController(rootViewController: controller)
presentViewController(navController, animated: true, completion: nil)
}
private func toggleLikeForPost(post: ReaderPost) {
let service = ReaderPostService(managedObjectContext: managedObjectContext())
service.toggleLikedForPost(post, success: nil, failure: { (error:NSError?) in
if let anError = error {
DDLogSwift.logError("Error (un)liking post: \(anError.localizedDescription)")
}
})
}
private func updateAndPerformFetchRequest() {
assert(NSThread.isMainThread(), "ReaderStreamViewController Error: updating fetch request on a background thread.")
var error:NSError?
tableViewHandler.resultsController.fetchRequest.predicate = predicateForFetchRequest()
tableViewHandler.resultsController.performFetch(&error)
if let anError = error {
DDLogSwift.logError("Error fetching posts after updating the fetch reqeust predicate: \(anError.localizedDescription)")
}
}
// MARK: - Blocking
private func blockSiteForPost(post: ReaderPost) {
let objectID = post.objectID
recentlyBlockedSitePostObjectIDs.addObject(objectID)
updateAndPerformFetchRequest()
let indexPath = tableViewHandler.resultsController.indexPathForObject(post)!
tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let service = ReaderSiteService(managedObjectContext: managedObjectContext())
service.flagSiteWithID(post.siteID,
asBlocked: true,
success: nil,
failure: { [weak self] (error:NSError!) in
self?.recentlyBlockedSitePostObjectIDs.removeObject(objectID)
self?.tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
self?.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let alertView = UIAlertView(
title: NSLocalizedString("Error Blocking Site", comment:"Title of a prompt letting the user know there was an error trying to block a site from appearing in the reader."),
message: error.localizedDescription,
delegate: nil,
cancelButtonTitle: NSLocalizedString("OK", comment:"Text for an alert's dismissal button.")
)
alertView.show()
})
}
private func unblockSiteForPost(post: ReaderPost) {
let objectID = post.objectID
recentlyBlockedSitePostObjectIDs.removeObject(objectID)
let indexPath = tableViewHandler.resultsController.indexPathForObject(post)!
tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let service = ReaderSiteService(managedObjectContext: managedObjectContext())
service.flagSiteWithID(post.siteID,
asBlocked: false,
success: nil,
failure: { [weak self] (error:NSError!) in
self?.recentlyBlockedSitePostObjectIDs.addObject(objectID)
self?.tableViewHandler.invalidateCachedRowHeightAtIndexPath(indexPath)
self?.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
let alertView = UIAlertView(
title: NSLocalizedString("Error Unblocking Site", comment:"Title of a prompt letting the user know there was an error trying to unblock a site from appearing in the reader."),
message: error.localizedDescription,
delegate: nil,
cancelButtonTitle: NSLocalizedString("OK", comment:"Text for an alert's dismissal button.")
)
alertView.show()
})
}
// MARK: - Actions
/**
Handles the user initiated pull to refresh action.
*/
func handleRefresh(sender:UIRefreshControl) {
if !canSync() {
cleanupAfterSync()
return
}
syncHelper.syncContentWithUserInteraction(true)
}
// MARK: - Sync Methods
func canSync() -> Bool {
let appDelegate = WordPressAppDelegate.sharedInstance()
return (readerTopic != nil) && appDelegate.connectionAvailable
}
func canLoadMore() -> Bool {
var fetchedObjects = tableViewHandler.resultsController.fetchedObjects ?? []
if fetchedObjects.count == 0 {
return false
}
return canSync()
}
/**
Kicks off a "background" sync without updating the UI if certain conditions
are met.
- The app must have a internet connection.
- The current time must be greater than the last sync interval.
*/
func syncIfAppropriate() {
let lastSynced = readerTopic?.lastSynced == nil ? NSDate(timeIntervalSince1970: 0) : readerTopic!.lastSynced
if canSync() && Int(lastSynced.timeIntervalSinceNow) < refreshInterval {
syncHelper.syncContentWithUserInteraction(false)
}
}
func syncItems(success:((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
let syncContext = ContextManager.sharedInstance().newDerivedContext()
let service = ReaderPostService(managedObjectContext: syncContext)
syncContext.performBlock {[weak self] () -> Void in
var error: NSError?
let topic = syncContext.existingObjectWithID(self!.readerTopic!.objectID, error: &error) as! ReaderAbstractTopic
service.fetchPostsForTopic(topic,
earlierThan: NSDate(),
success: {[weak self] (count:Int, hasMore:Bool) in
dispatch_async(dispatch_get_main_queue(), {
if let strongSelf = self {
if strongSelf.recentlyBlockedSitePostObjectIDs.count > 0 {
strongSelf.recentlyBlockedSitePostObjectIDs.removeAllObjects()
strongSelf.updateAndPerformFetchRequest()
}
}
success?(hasMore: hasMore)
})
}, failure: { (error:NSError!) in
dispatch_async(dispatch_get_main_queue(), {
failure?(error: error)
})
})
}
}
func backfillItems(success:((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
let syncContext = ContextManager.sharedInstance().newDerivedContext()
let service = ReaderPostService(managedObjectContext: syncContext)
syncContext.performBlock {[weak self] () -> Void in
var error: NSError?
let topic = syncContext.existingObjectWithID(self!.readerTopic!.objectID, error: &error) as! ReaderAbstractTopic
service.backfillPostsForTopic(topic,
success: { (count:Int, hasMore:Bool) -> Void in
dispatch_async(dispatch_get_main_queue(), {
success?(hasMore: hasMore)
})
}, failure: { (error:NSError!) -> Void in
dispatch_async(dispatch_get_main_queue(), {
failure?(error: error)
})
})
}
}
func loadMoreItems(success:((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
let post = tableViewHandler.resultsController.fetchedObjects?.last as? ReaderPost
if post == nil {
// failsafe
return
}
footerView.showSpinner(true)
let earlierThan = post!.sortDate
let syncContext = ContextManager.sharedInstance().newDerivedContext()
let service = ReaderPostService(managedObjectContext: syncContext)
syncContext.performBlock { [weak self] () -> Void in
var error: NSError?
let topic = syncContext.existingObjectWithID(self!.readerTopic!.objectID, error: &error) as! ReaderAbstractTopic
service.fetchPostsForTopic(topic,
earlierThan: earlierThan,
success: { (count:Int, hasMore:Bool) -> Void in
dispatch_async(dispatch_get_main_queue(), {
success?(hasMore: hasMore)
})
},
failure: { (error:NSError!) -> Void in
dispatch_async(dispatch_get_main_queue(), {
failure?(error: error)
})
})
}
WPAnalytics.track(.ReaderInfiniteScroll, withProperties: propertyForStats())
}
func syncHelper(syncHelper: WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
displayLoadingViewIfNeeded()
if userInteraction {
syncItems(success, failure: failure)
} else {
backfillItems(success, failure: failure)
}
}
func syncHelper(syncHelper: WPContentSyncHelper, syncMoreWithSuccess success: ((hasMore: Bool) -> Void)?, failure: ((error: NSError) -> Void)?) {
loadMoreItems(success, failure: failure)
}
public func syncContentEnded() {
if tableViewHandler.isScrolling {
cleanupAndRefreshAfterScrolling = true
return
}
cleanupAfterSync()
}
public func cleanupAfterSync() {
cleanupAndRefreshAfterScrolling = false
tableViewHandler.refreshTableViewPreservingOffset()
refreshControl.endRefreshing()
footerView.showSpinner(false)
}
public func tableViewHandlerWillRefreshTableViewPreservingOffset(tableViewHandler: WPTableViewHandler!) {
// Reload the table view to reflect new content.
managedObjectContext().reset()
updateAndPerformFetchRequest()
}
public func tableViewHandlerDidRefreshTableViewPreservingOffset(tableViewHandler: WPTableViewHandler!) {
if self.tableViewHandler.resultsController.fetchedObjects?.count == 0 {
displayNoResultsView()
} else {
hideResultsStatus()
}
}
// MARK: - Helpers for TableViewHandler
func predicateForFetchRequest() -> NSPredicate {
if readerTopic == nil {
return NSPredicate(format: "topic = NULL")
}
var error:NSError?
var topic = managedObjectContext().existingObjectWithID(readerTopic!.objectID, error:&error) as! ReaderAbstractTopic
if let anError = error {
DDLogSwift.logError(anError.description)
}
if recentlyBlockedSitePostObjectIDs.count > 0 {
return NSPredicate(format: "topic = %@ AND (isSiteBlocked = NO OR SELF in %@)", topic, recentlyBlockedSitePostObjectIDs)
}
return NSPredicate(format: "topic = %@ AND isSiteBlocked = NO", topic)
}
func sortDescriptorsForFetchRequest() -> [NSSortDescriptor] {
let sortDescriptor = NSSortDescriptor(key: "sortDate", ascending: false)
return [sortDescriptor]
}
// MARK: - TableViewHandler Delegate Methods
public func scrollViewWillBeginDragging(scrollView: UIScrollView!) {
if refreshControl.refreshing {
refreshControl.endRefreshing()
}
}
public func scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool) {
if decelerate {
return
}
if cleanupAndRefreshAfterScrolling {
cleanupAfterSync()
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView!) {
if cleanupAndRefreshAfterScrolling {
cleanupAfterSync()
}
}
public func managedObjectContext() -> NSManagedObjectContext {
if let context = displayContext {
return context
}
displayContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
displayContext!.parentContext = ContextManager.sharedInstance().mainContext
return displayContext!
}
public func fetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: ReaderPost.classNameWithoutNamespaces())
fetchRequest.predicate = predicateForFetchRequest()
fetchRequest.sortDescriptors = sortDescriptorsForFetchRequest()
return fetchRequest
}
public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return estimatedRowHeight
}
public func tableView(aTableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let width = aTableView.bounds.width
return tableView(aTableView, heightForRowAtIndexPath: indexPath, forWidth: width)
}
public func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!, forWidth width: CGFloat) -> CGFloat {
if tableViewHandler.resultsController.fetchedObjects == nil {
return 0.0
}
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
if recentlyBlockedSitePostObjectIDs.containsObject(post.objectID) {
return blockedRowHeight
}
configureCell(cellForLayout, atIndexPath: indexPath)
let size = cellForLayout.sizeThatFits(CGSize(width:width, height:CGFloat.max))
return size.height
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell? {
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
if recentlyBlockedSitePostObjectIDs.containsObject(post.objectID) {
var cell = tableView.dequeueReusableCellWithIdentifier(readerBlockedCellReuseIdentifier) as! ReaderBlockedSiteCell
configureBlockedCell(cell, atIndexPath: indexPath)
return cell
}
var cell = tableView.dequeueReusableCellWithIdentifier(readerCardCellReuseIdentifier) as! ReaderPostCardCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
public func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
// Check to see if we need to load more.
let criticalRow = tableView.numberOfRowsInSection(indexPath.section) - loadMoreThreashold
if (indexPath.section == tableView.numberOfSections() - 1) && (indexPath.row >= criticalRow) {
if syncHelper.hasMoreContent {
syncHelper.syncMoreContent()
}
}
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
if recentlyBlockedSitePostObjectIDs.containsObject(post.objectID) {
unblockSiteForPost(post)
return
}
var controller: ReaderPostDetailViewController?
if post.sourceAttributionStyle() == .Post &&
post.sourceAttribution.postID != nil &&
post.sourceAttribution.blogID != nil {
controller = ReaderPostDetailViewController.detailControllerWithPostID(post.sourceAttribution.postID!, siteID: post.sourceAttribution.blogID!)
} else {
controller = ReaderPostDetailViewController.detailControllerWithPost(post)
}
navigationController?.pushViewController(controller!, animated: true)
}
public func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
if tableViewHandler.resultsController.fetchedObjects == nil {
return
}
cell.accessoryType = .None
cell.selectionStyle = .None
let postCell = cell as! ReaderPostCardCell
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
let shouldLoadMedia = postCell != cellForLayout
postCell.blogNameButtonIsEnabled = !ReaderHelpers.isTopicSite(readerTopic!)
postCell.configureCell(post, loadingMedia: shouldLoadMedia)
postCell.delegate = self
}
public func configureBlockedCell(cell: ReaderBlockedSiteCell, atIndexPath indexPath: NSIndexPath) {
if tableViewHandler.resultsController.fetchedObjects == nil {
return
}
cell.accessoryType = .None
cell.selectionStyle = .None
let posts = tableViewHandler.resultsController.fetchedObjects as! [ReaderPost]
let post = posts[indexPath.row]
cell.setSiteName(post.blogName)
}
// MARK: - ReaderStreamHeader Delegate Methods
public func handleFollowActionForHeader(header:ReaderStreamHeader) {
// TODO: Pending data model improvements
}
// MARK: - ReaderCard Delegate Methods
public func readerCell(cell: ReaderPostCardCell, headerActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
let controller = ReaderStreamViewController.controllerWithSiteID(post.siteID)
navigationController?.pushViewController(controller, animated: true)
WPAnalytics.track(.ReaderPreviewedSite)
}
public func readerCell(cell: ReaderPostCardCell, commentActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
let controller = ReaderCommentsViewController(post: post)
navigationController?.pushViewController(controller, animated: true)
}
public func readerCell(cell: ReaderPostCardCell, likeActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
toggleLikeForPost(post)
}
public func readerCell(cell: ReaderPostCardCell, visitActionForProvider provider: ReaderPostContentProvider) {
// TODO: No longer needed. Remove when cards are updated
}
public func readerCell(cell: ReaderPostCardCell, tagActionForProvider provider: ReaderPostContentProvider) {
// TODO: Waiting on Core Data support
}
public func readerCell(cell: ReaderPostCardCell, menuActionForProvider provider: ReaderPostContentProvider, fromView sender: UIView) {
let post = provider as! ReaderPost
showMenuForPost(post, fromView:sender)
}
public func readerCell(cell: ReaderPostCardCell, attributionActionForProvider provider: ReaderPostContentProvider) {
let post = provider as! ReaderPost
showAttributionForPost(post)
}
// MARK: - UIActionSheet Delegate Methods
public func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == actionSheet.cancelButtonIndex {
return
}
if objectIDOfPostForMenu == nil {
return
}
var error: NSError?
var post = managedObjectContext().existingObjectWithID(objectIDOfPostForMenu!, error: &error) as? ReaderPost
if post == nil {
return
}
if buttonIndex == actionSheet.destructiveButtonIndex {
blockSiteForPost(post!)
return
}
showShareActivityAfterActionSheetIsDismissed = true
}
public func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
if showShareActivityAfterActionSheetIsDismissed {
var error: NSError?
var post = managedObjectContext().existingObjectWithID(objectIDOfPostForMenu!, error: &error) as? ReaderPost
if let readerPost = post {
sharePost(readerPost)
}
}
showShareActivityAfterActionSheetIsDismissed = false
objectIDOfPostForMenu = nil
anchorViewForMenu = nil
}
}
| 019c2ea07bb2f99ef646b671cc835eb6 | 38.069536 | 197 | 0.664039 | false | false | false | false |
mssun/pass-ios | refs/heads/master | passKit/Crypto/ObjectivePGPInterface.swift | mit | 2 | //
// ObjectivePGPInterface.swift
// passKit
//
// Created by Danny Moesch on 08.09.19.
// Copyright © 2019 Bob Sun. All rights reserved.
//
import ObjectivePGP
struct ObjectivePGPInterface: PGPInterface {
private let keyring = ObjectivePGP.defaultKeyring
init(publicArmoredKey: String, privateArmoredKey: String) throws {
guard let publicKeyData = publicArmoredKey.data(using: .ascii), let privateKeyData = privateArmoredKey.data(using: .ascii) else {
throw AppError.keyImport
}
let publicKeys = try ObjectivePGP.readKeys(from: publicKeyData)
let privateKeys = try ObjectivePGP.readKeys(from: privateKeyData)
keyring.import(keys: publicKeys)
keyring.import(keys: privateKeys)
guard publicKeys.first != nil, privateKeys.first != nil else {
throw AppError.keyImport
}
}
func decrypt(encryptedData: Data, keyID _: String?, passphrase: String) throws -> Data? {
try ObjectivePGP.decrypt(encryptedData, andVerifySignature: false, using: keyring.keys) { _ in passphrase }
}
func encrypt(plainData: Data, keyID _: String?) throws -> Data {
let encryptedData = try ObjectivePGP.encrypt(plainData, addSignature: false, using: keyring.keys, passphraseForKey: nil)
if Defaults.encryptInArmored {
return Armor.armored(encryptedData, as: .message).data(using: .ascii)!
}
return encryptedData
}
func containsPublicKey(with keyID: String) -> Bool {
keyring.findKey(keyID)?.isPublic ?? false
}
func containsPrivateKey(with keyID: String) -> Bool {
keyring.findKey(keyID)?.isSecret ?? false
}
var keyID: [String] {
keyring.keys.map(\.keyID.longIdentifier)
}
var shortKeyID: [String] {
keyring.keys.map(\.keyID.shortIdentifier)
}
}
| 5b1d8b2c697d92eadd9c38b8313bf76e | 33.444444 | 137 | 0.67043 | false | false | false | false |
ICTFractal/IF_FirebaseFollowHelperKit | refs/heads/master | IF_FirebaseFollowHelperKit/IF_FirebaseFollowHelper.swift | mit | 1 | //
// IF_FirebaseFollowHelper.swift
// IF_FirebaseFollowHelper
//
// Created by 久保島 祐磨 on 2016/04/21.
// Copyright © 2016年 ICT Fractal Inc. All rights reserved.
//
import UIKit
import Firebase
/*
Firebaseデータ構造
root
+IFFollowHelper
+Follow (フォロー情報ノード)
+autoID
-uid (ログインユーザのuid)
-followID (フォロー対象ユーザのuid)
-notifiedUser (ログインユーザに通知したか)
-notifiedFollower (フォロー対象ユーザに通知したか)
-timestamp (レコードを作成したサーバー日時)
+autoID
...
+Block (ブロック情報ノード)
+autoID
-uid (ログインユーザのuid)
-blockID (ブロック対象ユーザのuid)
-notifiedUser (ログインユーザに通知したか)
-notifiedBlockUser (ブロック対象ユーザに通知したか)
-timestamp (レコードを作成したサーバー日時)
+autoID
...
*/
/// IF_FirebaseFollowHelper間でやり取りされるユーザ情報Tupleの別名定義
public typealias IF_FirebaseFollowHelperBasicUserInfo = (uid: String, timestamp: NSDate)
/**
IF_FirebaseFollowHelperからNSNotificationCenterへ発行されるメッセージ
notification.userInfoから詳細な情報を得る事ができます。
*/
public struct IF_FirebaseFollowHelperMessage {
/**
ログインユーザが他ユーザをフォローした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(server)
*/
public static let AddedFollow = "IF_FirebaseFollowHelperMessage_AddedFollow"
/**
フォロー追加処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedFollow = "IF_FirebaseFollowHelperMessage_FailedFollow"
/**
フォロー追加処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidAddFollowProc = "IF_FirebaseFollowHelperMessage_DidAddFollowProc"
/**
ログインユーザが他ユーザのフォローを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: フォロー日時
*/
public static let RemovedFollow = "IF_FirebaseFollowHelperMessage_RemovedFollow"
/**
フォロー解除処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedRemoveFollow = "IF_FirebaseFollowHelperMessage_FailedRemoveFollow"
/**
フォロー解除処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidRemoveFollowProc = "IF_FirebaseFollowHelperMessage_DidRemoveFollowProc"
/**
他ユーザがログインユーザをフォローした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: フォロー日時
*/
public static let AddedFollower = "IF_FirebaseFollowHelperMessage_AddedFollower"
/**
他ユーザがログインユーザのフォローを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: フォロー日時
*/
public static let RemovedFollower = "IF_FirebaseFollowHelperMessage_RemovedFollower"
/**
ログインユーザが他ユーザをブロックした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(server)
*/
public static let AddedBlock = "IF_FirebaseFollowHelperMessage_AddedBlock"
/**
ブロック追加処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedBlock = "IF_FirebaseFollowHelperMessage_FailedBlock"
/**
ブロック追加処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidAddBlockProc = "IF_FirebaseFollowHelperMessage_DidAddBlockProc"
/**
ログインユーザが他ユーザのブロックを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: ブロック日時
*/
public static let RemovedBlock = "IF_FirebaseFollowHelperMessage_RemovedBlock"
/**
ブロック解除処理に失敗した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: 処理日時(local)
- parameter error: エラー情報
*/
public static let FailedRemoveBlock = "IF_FirebaseFollowHelperMessage_FailedRemoveBlock"
/**
ブロック解除処理完了時に通知されます
- attention : ローカルの処理完了通知であり、サーバからの応答タイミングは保証しません。
*/
public static let DidRemoveBlockProc = "IF_FirebaseFollowHelperMessage_DidRemoveBlockProc"
/**
他ユーザがログインユーザをブロックした際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: ブロック日時
*/
public static let BlockedFromSomeone = "IF_FirebaseFollowHelperMessage_BlockedFromSomeone"
/**
他ユーザがログインユーザのブロックを解除した際に通知されます
notification.userInfoから詳細な情報を得る事ができます。
- parameter uid: 対象のuid
- parameter timestamp: ブロック日時
*/
public static let RemoveBlockFromSomeone = "IF_FirebaseFollowHelperMessage_RemoveBlockFromSomeone"
}
/**
Firebaseにフォロー/フォロワー管理機能を追加すヘルパークラス
主な特徴は次の通りです。
1. Firebaseのデータ構造を意識せずに、フォロー関連の機能を利用できます
2. 他ユーザがログインユーザに関わる操作を行った場合、リアルタイムに通知を受け取る事ができます
- important: イベントはリアルタイムにNSNotificationCenterから通知されます。
通知は1つのイベントにつき1回のみです。
すべての通知を受け取りたい場合は初回インスタンス生成以降、常にいずれかのインスタンスにオブザーバを設定してください。
*/
public class IF_FirebaseFollowHelper {
/**
共有インスタンス
こちらからIF_FirebaseFollowHelperの各機能をコールしてください。
*/
public static let sharedHelper = IF_FirebaseFollowHelper()
private var firebaseRef: FIRDatabaseReference!
private var followRef: FIRDatabaseReference!
private var blockRef: FIRDatabaseReference!
private let followHelperPath = "IFFollowHelper"
private let followPath = "Follow"
private let blockPath = "Block"
// firebase項目
private let item_uid = "uid"
private let item_followID = "followID"
private let item_notifiedUser = "notifiedUser"
private let item_notifiedFollower = "notifiedFollower"
private let item_timestamp = "timestamp"
private let item_blockID = "blockID"
private let item_notifiedBlockUser = "notifiedBlockUser"
// オブザーバ登録
private var observeUID: String? = nil
private var observeHandles = [(FIRDatabaseQuery, UInt)]()
// NSNotification.userInfo項目
private let notifyInfo_uid = "uid"
private let notifyInfo_timestamp = "timestamp"
private let notifyInfo_error = "error"
/// error domain
public static let errorDomain = "IF_FirebaseFollowHelper"
/// error code
public enum errorCode: Int {
/// 不明
case Unknown = 0
/// ブロック由来の処理失敗
case FailureByBlock
/// サインインしていない事による処理失敗
case NotSignedIn
}
/// デバッグ情報出力設定
public static var outputDebug = true
private init() {
self.firebaseRef = FIRDatabase.database().reference()
self.followRef = self.firebaseRef.child(self.followHelperPath).child(self.followPath)
self.blockRef = self.firebaseRef.child(self.followHelperPath).child(self.blockPath)
self.observeUID = FIRAuth.auth()?.currentUser?.uid
if self.observeUID != nil {
self.observe()
}
// ユーザ切り替えに対応
FIRAuth.auth()!.addAuthStateDidChangeListener() { auth, user in
if let user = user {
self.debugLog("User is signed in with [\(user.uid)]")
if self.observeUID != user.uid {
self.observeUID = user.uid
self.observe()
}
} else {
self.debugLog("No user is signed in. remove all observer.")
self.observeUID = nil
self.observeHandles.forEach() {
$0.removeObserverWithHandle($1)
}
self.observeHandles.removeAll()
}
}
}
/**
オブザーバ登録
*/
private func observe() {
if self.observeUID == nil {
return
}
self.debugLog("add observe [\(self.observeUID!)]")
self.observeHandles.forEach() {
$0.removeObserverWithHandle($1)
}
self.observeHandles.removeAll()
// Followノードの監視対象
let targetFollowRef = self.followRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!)
let targetFollowerRef = self.followRef.queryOrderedByChild(item_followID).queryEqualToValue(self.observeUID!)
// フォロー追加の監視
self.observeHandles.append((targetFollowRef,
targetFollowRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedUser] as? Bool {
if isNotified == false {
let updateRef = self.followRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedUser: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_followID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.AddedFollow, object: self, userInfo: userInfo)
}
}
}
}
})))
// フォロー削除の監視
self.observeHandles.append((targetFollowRef,
targetFollowRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_followID] as? String,
let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemovedFollow, object: self, userInfo: userInfo)
}
}
})))
// フォロワー追加の監視
self.observeHandles.append((targetFollowerRef,
targetFollowerRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedFollower] as? Bool {
if isNotified == false {
let updateRef = self.followRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedFollower: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.AddedFollower, object: self, userInfo: userInfo)
}
}
}
}
})))
// フォロワー削除の監視
self.observeHandles.append((targetFollowerRef,
targetFollowerRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_uid] as? String,
let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemovedFollower, object: self, userInfo: userInfo)
}
}
})))
// Blockノードの監視対象
let targetBlockRef = self.blockRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!)
let targetBlockerRef = self.blockRef.queryOrderedByChild(item_blockID).queryEqualToValue(self.observeUID!)
// ブロック追加の監視
self.observeHandles.append((targetBlockRef,
targetBlockRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedUser] as? Bool {
if isNotified == false {
let updateRef = self.blockRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedUser: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_blockID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.AddedBlock, object: self, userInfo: userInfo)
}
}
}
}
})))
// ブロック削除の監視
self.observeHandles.append((targetBlockRef,
targetBlockRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_blockID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemovedBlock, object: self, userInfo: userInfo)
}
}
})))
// 被ブロック追加の監視
self.observeHandles.append((targetBlockerRef,
targetBlockerRef.observeEventType(.ChildAdded, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let isNotified = value[self.item_notifiedBlockUser] as? Bool {
if isNotified == false {
let updateRef = self.blockRef.child(data.key)
let dic: [String: AnyObject] = [self.item_notifiedBlockUser: true]
updateRef.updateChildValues(dic)
if let uid = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.BlockedFromSomeone, object: self, userInfo: userInfo)
}
}
}
}
})))
// 被ブロック削除の監視
self.observeHandles.append((targetBlockerRef,
targetBlockerRef.observeEventType(.ChildRemoved, withBlock: { data in
if let value = data.value as? [String: AnyObject] {
if let uid = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: uid, self.notifyInfo_timestamp: self.convertToNSDate(timestamp)]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.RemoveBlockFromSomeone, object: self, userInfo: userInfo)
}
}
})))
}
/**
Firebase.TimeStampをNSDateに変換する
- parameter timestamp: タイムスタンプ
- returns: NSDateインスタンス
*/
private func convertToNSDate(timestamp: NSTimeInterval) -> NSDate {
return NSDate(timeIntervalSince1970: timestamp / 1000)
}
/**
NSErrorインスタンスを得る
- parameter code: エラーコード
- parameter message: エラーメッセージ
- returns: NSErrorインスタンス
*/
private func error(code: errorCode, message: String) -> NSError {
let userInfo: [String: AnyObject] = [NSLocalizedDescriptionKey: message]
return NSError(domain: IF_FirebaseFollowHelper.errorDomain, code: code.rawValue, userInfo: userInfo)
}
/**
デバッグログの出力
- parameter message: メッセージ
*/
private func debugLog(message: String) {
if IF_FirebaseFollowHelper.outputDebug == true {
print("IF_FirebaseFollowHelper debug: \(message)")
}
}
/**
ログインユーザがフォローしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getFollowList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.followRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var followList = [IF_FirebaseFollowHelperBasicUserInfo]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let followID = value[self.item_followID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
followList.append((followID, self.convertToNSDate(timestamp)))
}
}
}
// 最新順に並び替える
followList = followList.sort() { $0.1.timeIntervalSince1970 > $1.1.timeIntervalSince1970 }
completion?(followList)
})
}
/**
ログインユーザをフォローしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getFollowerList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.followRef.queryOrderedByChild(item_followID).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var followerList = [IF_FirebaseFollowHelperBasicUserInfo]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let followerID = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
followerList.append((followerID, self.convertToNSDate(timestamp)))
}
}
}
completion?(followerList)
})
}
/**
ログインユーザがブロックしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getBlockList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.blockRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var blockList = [(uid: String, timestamp: NSDate)]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let blockID = value[self.item_blockID] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
blockList.append((blockID, self.convertToNSDate(timestamp)))
}
}
}
// 最新順に並び替える
blockList = blockList.sort() { $0.1.timeIntervalSince1970 > $1.1.timeIntervalSince1970 }
completion?(blockList)
})
}
/**
ログインユーザをブロックしているユーザ一覧を取得します
- parameter completion: 取得完了時に実行するClosure
Closureでは取得したユーザのuidと登録日時の一覧を使用できます。
*/
public func getBlockerList(completion: (([IF_FirebaseFollowHelperBasicUserInfo]) -> Void)?) {
if self.observeUID == nil {
self.debugLog("Not signed in user.")
completion?([IF_FirebaseFollowHelperBasicUserInfo]())
return
}
self.blockRef.queryOrderedByChild(item_blockID).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var blockerList = [(uid: String, timestamp: NSDate)]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let blockerID = value[self.item_uid] as? String, let timestamp = value[self.item_timestamp] as? NSTimeInterval {
blockerList.append((blockerID, self.convertToNSDate(timestamp)))
}
}
}
completion?(blockerList)
})
}
/**
対象ユーザをフォローします
- parameter userID: 対象ユーザのuid
フォローに成功した場合、*IF_FirebaseFollowHelperMessage.AddedFollow*が通知されます。
フォローに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedFollow*が通知されます。
すでにフォロー済みかフォローに失敗した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidAddFollowProc*が通知されます。
*/
public func follow(userID: String) {
self.follow([userID])
}
/**
対象ユーザ(複数)をフォローします
- parameter userIDs: 対象ユーザのuid一覧
フォローに成功した場合、*IF_FirebaseFollowHelperMessage.AddedFollow*が通知されます。
フォローに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedFollow*が通知されます。
すでにフォロー済みかフォローに失敗した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidAddFollowProc*が通知されます。
*/
public func follow(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedFollow, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddFollowProc, object: self, userInfo: nil)
return
}
self.getFollowList() { followList in
let addList = userIDs.filter() { !followList.map() { $0.0 }.contains($0) }
var procCount = 0
addList.forEach() {
let userRef = self.followRef.childByAutoId()
let followID = $0
let dic: [String: AnyObject] = [self.item_uid: self.observeUID!, self.item_followID: followID, self.item_notifiedUser: false, self.item_notifiedFollower: false, self.item_timestamp: FIRServerValue.timestamp()]
userRef.updateChildValues(dic, withCompletionBlock: { error, firebaseRef in
if let error = error {
self.debugLog("follow failed [\(followID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: followID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedFollow, object: self, userInfo: userInfo)
}
else {
self.debugLog("following [\(followID)]")
}
procCount += 1
if procCount >= addList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddFollowProc, object: self, userInfo: nil)
}
})
}
if addList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddFollowProc, object: self, userInfo: nil)
}
}
}
/**
対象ユーザのフォローを解除します
- parameter userID: 対象ユーザのuid
フォロー解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedFollow*が通知されます。
フォロー解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveFollow*が通知されます。
フォローしていないユーザをフォロー解除した場合かフォロー解除に失敗した場合、何も通知されません。
処理完了時に*IF_FirebaseFollowHelperMessage.DidRemoveFollowProc*が通知されます。
*/
public func unFollow(userID: String) {
self.unFollow([userID])
}
/**
対象ユーザ(複数)のフォローを解除します
- parameter userIDs: 対象ユーザのuid一覧
フォロー解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedFollow*が通知されます。
フォロー解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveFollow*が通知されます。
フォローしていないユーザをフォロー解除した場合かフォロー解除に失敗した場合、何も通知されません。
処理完了時に*IF_FirebaseFollowHelperMessage.DidRemoveFollowProc*が通知されます。
*/
public func unFollow(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveFollow, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveFollowProc, object: self, userInfo: nil)
return
}
self.followRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var removeList = [FIRDataSnapshot]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let followID = value[self.item_followID] as? String {
if userIDs.contains(followID) {
removeList.append(user)
}
}
}
}
var procCount = 0
removeList.forEach() {
if let value = $0.value as? [String: AnyObject] {
if let followID = value[self.item_followID] as? String {
let removeRef = self.followRef.child($0.key)
removeRef.removeValueWithCompletionBlock({ error, firebaseRef in
if let error = error {
self.debugLog("remove follow failed [\(followID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: followID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveFollow, object: self, userInfo: userInfo)
}
else {
self.debugLog("remove follow [\(followID)]")
}
procCount += 1
if procCount >= removeList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveFollowProc, object: self, userInfo: nil)
}
})
}
}
}
if removeList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveFollowProc, object: self, userInfo: nil)
}
})
}
/**
対象ユーザをブロックします
- parameter userID: 対象ユーザのuid
ブロックに成功した場合、*IF_FirebaseFollowHelperMessage.AddedBlock*が通知されます。
ブロックに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedBlock*が通知されます。
すでにブロック済みのuidを指定した場合、何も通知されません。
処理完了時に、*DIF_FirebaseFollowHelperMessage.idAddBlockProc*が通知されます。
*/
public func block(userID: String) {
self.block([userID])
}
/**
対象ユーザ(複数)をブロックします
- parameter userIDs: 対象ユーザのuid一覧
ブロックに成功した場合、*IF_FirebaseFollowHelperMessage.AddedBlock*が通知されます。
ブロックに失敗した場合、*IF_FirebaseFollowHelperMessage.FailedBlock*が通知されます。
すでにブロック済みのuidを指定した場合、何も通知されません。
処理完了時に、*DIF_FirebaseFollowHelperMessage.DidAddBlockProc*が通知されます。
*/
public func block(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedBlock, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddBlockProc, object: self, userInfo: nil)
return
}
self.getBlockList() { blockList in
let addList = userIDs.filter() { !blockList.map() { $0.0 }.contains($0) }
var procCount = 0
addList.forEach() {
let userRef = self.blockRef.childByAutoId()
let blockID = $0
let dic: [String: AnyObject] = [self.item_uid: self.observeUID!, self.item_blockID: blockID, self.item_notifiedUser: false, self.item_notifiedBlockUser:false, self.item_timestamp: FIRServerValue.timestamp()]
userRef.updateChildValues(dic, withCompletionBlock: { error, firebaseRef in
if let error = error {
self.debugLog("blocking failed [\(blockID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: blockID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedBlock, object: self, userInfo: userInfo)
}
else {
self.debugLog("blocking [\(blockID)]")
}
procCount += 1
if procCount >= addList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddBlockProc, object: self, userInfo: nil)
}
})
}
if addList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidAddBlockProc, object: self, userInfo: nil)
}
}
}
/**
対象ユーザのブロックを解除します
- parameter userID: 対象ユーザのuid一覧
ブロックの解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedBlock*が通知されます。
ブロックの解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveBlock*が通知されます。
ブロックしていないユーザをブロック解除した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidRemoveBlockProc*が通知されます。
*/
public func unBlock(userID: String) {
self.unBlock([userID])
}
/**
対象ユーザ(複数)のブロックを解除します
- parameter userIDs: 対象ユーザのuid一覧
ブロックの解除に成功した場合、*IF_FirebaseFollowHelperMessage.RemovedBlock*が通知されます。
ブロックの解除に失敗した場合、*IF_FirebaseFollowHelperMessage.FailedRemoveBlock*が通知されます。
ブロックしていないユーザをブロック解除した場合、何も通知されません。
処理完了時に、*IF_FirebaseFollowHelperMessage.DidRemoveBlockProc*が通知されます。
*/
public func unBlock(userIDs: [String]) {
let timestamp = NSDate() // 処理失敗時にメッセージに載せる
if self.observeUID == nil {
self.debugLog("Not signed in user.")
let error = self.error(.NotSignedIn, message: "Not signed in user.")
userIDs.forEach() {
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: $0, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveBlock, object: self, userInfo: userInfo)
}
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveBlockProc, object: self, userInfo: nil)
return
}
self.blockRef.queryOrderedByChild(item_uid).queryEqualToValue(self.observeUID!).observeSingleEventOfType(.Value, withBlock: { data in
var removeList = [FIRDataSnapshot]()
data.children.forEach() {
let user = $0 as! FIRDataSnapshot
if let value = user.value as? [String: AnyObject] {
if let blockID = value[self.item_blockID] as? String {
if userIDs.contains(blockID) {
removeList.append(user)
}
}
}
}
var procCount = 0
removeList.forEach() {
if let value = $0.value as? [String: AnyObject] {
if let blockID = value[self.item_blockID] as? String {
let removeRef = self.blockRef.child($0.key)
removeRef.removeValueWithCompletionBlock() { error, firebaseRef in
if let error = error {
self.debugLog("remove block failed [\(blockID)]")
let userInfo: [String: AnyObject] = [self.notifyInfo_uid: blockID, self.notifyInfo_error: error, self.notifyInfo_timestamp: timestamp]
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.FailedRemoveBlock, object: self, userInfo: userInfo)
}
else {
self.debugLog("remove block [\(blockID)]")
}
procCount += 1
if procCount >= removeList.count {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveBlockProc, object: self, userInfo: nil)
}
}
}
}
}
if removeList.count == 0 {
NSNotificationCenter.defaultCenter().postNotificationName(IF_FirebaseFollowHelperMessage.DidRemoveBlockProc, object: self, userInfo: nil)
}
})
}
}
| d7fb41654b767b923c07fecfb783d24c | 32.837626 | 213 | 0.729325 | false | false | false | false |
deyton/swift | refs/heads/master | stdlib/public/core/StringIndexConversions.swift | apache-2.0 | 5 | //===----------------------------------------------------------------------===//
//
// 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 String.Index {
/// Creates an index in the given string that corresponds exactly to the
/// specified position.
///
/// If the index passed as `sourcePosition` represents the start of an
/// extended grapheme cluster---the element type of a string---then the
/// initializer succeeds.
///
/// The following example converts the position of the Unicode scalar `"e"`
/// into its corresponding position in the string. The character at that
/// position is the composed `"é"` character.
///
/// let cafe = "Cafe\u{0301}"
/// print(cafe)
/// // Prints "Café"
///
/// let scalarsIndex = cafe.unicodeScalars.index(of: "e")!
/// let stringIndex = String.Index(scalarsIndex, within: cafe)!
///
/// print(cafe[...stringIndex])
/// // Prints "Café"
///
/// If the index passed as `sourcePosition` doesn't have an exact
/// corresponding position in `target`, the result of the initializer is
/// `nil`. For example, an attempt to convert the position of the combining
/// acute accent (`"\u{0301}"`) fails. Combining Unicode scalars do not have
/// their own position in a string.
///
/// let nextScalarsIndex = cafe.unicodeScalars.index(after: scalarsIndex)
/// let nextStringIndex = String.Index(nextScalarsIndex, within: cafe)
///
/// print(nextStringIndex)
/// // Prints "nil"
///
/// - Parameters:
/// - sourcePosition: A position in a view of the `target` parameter.
/// `sourcePosition` must be a valid index of at least one of the views
/// of `target`.
/// - target: The string referenced by the resulting index.
public init?(
_ sourcePosition: String.Index,
within target: String
) {
guard target.unicodeScalars._isOnGraphemeClusterBoundary(sourcePosition)
else { return nil }
self = target.characters._index(
atEncodedOffset: sourcePosition.encodedOffset)
}
/// Returns the position in the given UTF-8 view that corresponds exactly to
/// this index.
///
/// This example first finds the position of the character `"é"`, and then
/// uses this method find the same position in the string's `utf8` view.
///
/// let cafe = "Café"
/// if let i = cafe.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf8)!
/// print(Array(cafe.utf8[j...]))
/// }
/// // Prints "[195, 169]"
///
/// - Parameter utf8: The view to use for the index conversion. This index
/// must be a valid index of at least one view of the string shared by
/// `utf8`.
/// - Returns: The position in `utf8` that corresponds exactly to this index.
/// If this index does not have an exact corresponding position in `utf8`,
/// this method returns `nil`. For example, an attempt to convert the
/// position of a UTF-16 trailing surrogate returns `nil`.
public func samePosition(
in utf8: String.UTF8View
) -> String.UTF8View.Index? {
return String.UTF8View.Index(self, within: utf8)
}
/// Returns the position in the given UTF-16 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf16)`.
///
/// This example first finds the position of the character `"é"` and then
/// uses this method find the same position in the string's `utf16` view.
///
/// let cafe = "Café"
/// if let i = cafe.index(of: "é") {
/// let j = i.samePosition(in: cafe.utf16)!
/// print(cafe.utf16[j])
/// }
/// // Prints "233"
///
/// - Parameter utf16: The view to use for the index conversion. This index
/// must be a valid index of at least one view of the string shared by
/// `utf16`.
/// - Returns: The position in `utf16` that corresponds exactly to this
/// index. If this index does not have an exact corresponding position in
/// `utf16`, this method returns `nil`. For example, an attempt to convert
/// the position of a UTF-8 continuation byte returns `nil`.
public func samePosition(
in utf16: String.UTF16View
) -> String.UTF16View.Index? {
return String.UTF16View.Index(self, within: utf16)
}
}
| 43c450db8983b6ff249694e551493d91 | 39.136752 | 80 | 0.624574 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Client/Frontend/Theme/LightTheme.swift | mpl-2.0 | 1 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
struct LightTheme: Theme {
var type: ThemeType = .light
var colors: ThemeColourPalette = LightColourPalette()
}
private struct LightColourPalette: ThemeColourPalette {
// MARK: - Layers
var layer1: UIColor = FXColors.LightGrey10
var layer2: UIColor = FXColors.White
var layer3: UIColor = FXColors.LightGrey20
var layer4: UIColor = FXColors.LightGrey30.withAlphaComponent(0.6)
var layer5: UIColor = FXColors.White
var layer6: UIColor = FXColors.White
var layer5Hover: UIColor = FXColors.LightGrey20
var layerScrim: UIColor = FXColors.DarkGrey30.withAlphaComponent(0.95)
var layerGradient: Gradient = Gradient(start: FXColors.Violet70, end: FXColors.Violet40)
var layerAccentNonOpaque: UIColor = FXColors.Blue50.withAlphaComponent(0.1)
var layerAccentPrivate: UIColor = FXColors.Purple60
var layerAccentPrivateNonOpaque: UIColor = FXColors.Purple60.withAlphaComponent(0.1)
var layerLightGrey30: UIColor = FXColors.LightGrey30
// MARK: - Actions
var actionPrimary: UIColor = FXColors.Blue50
var actionPrimaryHover: UIColor = FXColors.Blue60
var actionSecondary: UIColor = FXColors.LightGrey30
var actionSecondaryHover: UIColor = FXColors.LightGrey40
var formSurfaceOff: UIColor = FXColors.LightGrey30
var formKnob: UIColor = FXColors.White
var indicatorActive: UIColor = FXColors.LightGrey50
var indicatorInactive: UIColor = FXColors.LightGrey30
// MARK: - Text
var textPrimary: UIColor = FXColors.DarkGrey90
var textSecondary: UIColor = FXColors.DarkGrey05
var textDisabled: UIColor = FXColors.DarkGrey90.withAlphaComponent(0.4)
var textWarning: UIColor = FXColors.Red70
var textAccent: UIColor = FXColors.Blue50
var textOnColor: UIColor = FXColors.LightGrey05
var textInverted: UIColor = FXColors.LightGrey05
// MARK: - Icons
var iconPrimary: UIColor = FXColors.DarkGrey90
var iconSecondary: UIColor = FXColors.DarkGrey05
var iconDisabled: UIColor = FXColors.DarkGrey90.withAlphaComponent(0.4)
var iconAction: UIColor = FXColors.Blue50
var iconOnColor: UIColor = FXColors.LightGrey05
var iconWarning: UIColor = FXColors.Red70
var iconSpinner: UIColor = FXColors.LightGrey80
var iconAccentViolet: UIColor = FXColors.Violet60
var iconAccentBlue: UIColor = FXColors.Blue60
var iconAccentPink: UIColor = FXColors.Pink60
var iconAccentGreen: UIColor = FXColors.Green60
var iconAccentYellow: UIColor = FXColors.Yellow60
// MARK: - Border
var borderPrimary: UIColor = FXColors.LightGrey30
var borderAccent: UIColor = FXColors.Blue50
var borderAccentNonOpaque: UIColor = FXColors.Blue50.withAlphaComponent(0.1)
var borderAccentPrivate: UIColor = FXColors.Purple60
// MARK: - Shadow
var shadowDefault: UIColor = FXColors.DarkGrey40.withAlphaComponent(0.16)
}
| 255ecbf9bf82284ef509ebb2ded158fb | 43.666667 | 92 | 0.753407 | false | false | false | false |
Eric217/-OnSale | refs/heads/master | 打折啦/打折啦/UploadController.swift | apache-2.0 | 1 | //
// UploadView.swift
// 打折啦
//
// Created by Eric on 7/26/17.
// Copyright © 2017 INGStudio. All rights reserved.
//
import Foundation
import Alamofire
//upload 时候,picRatio是 长:宽的值1|2,都是 float
//这个扩展包括 texfield, texview, scrollview
extension UpLoadViewController: UITextFieldDelegate, UITextViewDelegate {
//MARK: - @objc functions
@objc func fabu() {
let bigImgArr: [UIImage]
let smaImgArr: [UIImage]
if txf.text!.len() <= 1 {
hud.showError(withStatus: "标题过短"); return
}
if location.textLabel?.text == chooseLoca {
hud.showError(withStatus: "请选择地点"); return
}
if type == -1 {
hud.showError(withStatus: "请选择种类"); return
}else if business.status {
type += 100
}
if l3 == "" {
hud.showError(withStatus: "")
}
bigImgArr = getBigImageArray() as! [UIImage]
smaImgArr = getSmallImageArray() as! [UIImage]
let dict = ["type": type, "title": (txf.text)!, "description": (txv.text)!,
"l1": l1, "l2": l2, "l3": l3, "location": locaStr, "longitude": lon,
"latitude": lat, "deadline": deadLine] as [String : Any]
let data1 = Data()
let imageData1 = Data()
let imageSmallData1 = Data()
Alamofire.upload(multipartFormData: { multi in
/*
//这几个是那几个string或int,double的属性的数据的拼接,name一会写接口里的,
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
multi.append(data1, withName: "name")
//下面是 大图数据.其中第三个参数是 扩展名,是个可选参数,
multi.append(imageData1, withName: "pic1")
multi.append(imageData1, withName: "pic2", mimeType: "jpg")
multi.append(imageData1, withName: "pic3")
//下面是 小图数据
multi.append(imageSmallData1, withName: "picSmall1", mimeType: "jpg")
multi.append(imageSmallData1, withName: "picSmall")
multi.append(imageSmallData1, withName: "picSmall")
multi.append(<#T##data: Data##Data#>, withName: <#T##String#>, fileName: <#T##String#>, mimeType: <#T##String#>)
*/
}, with: Router.upGood, encodingCompletion: { encodeResult in
switch encodeResult {
case .success(let upload, _, _): upload
.uploadProgress { progress in
print(progress.fractionCompleted)
}
.responseJSON { response in
}
case .failure(let error):
print(dk+"\(error)")
}
})
}
@objc func didClick(_ sender: RoundButton) {
let ta = sender.tag
if ta != 201 {
if ta == 202 || ta == 203 {
sender.changeStatus(true)
}else {
sender.changeStatus()
}
}else{
print("😄弹出视图")
}
}
@objc func cancel(){
print(hh+"是否保存草稿 ")
dismiss(animated: true, completion: nil)
}
@objc func showtip() {
print("😄弹出视图")
}
@objc func didTap(_ sender: UITapGestureRecognizer) {
let temp = sender.view
if temp == location {
let controller = LocationChooser()
controller.delegate = self
navigationController?.pushViewController(controller, animated: true)
}else if temp == kind {
let controller = TypeChooser()
controller.delegate = self
navigationController?.pushViewController(controller, animated: true)
}else if temp == time {
BRStringPickerView.showStringPicker(withTitle: "", dataSource: timeArr, defaultSelValue: time.rightLabel.text!, isAutoSelect: false, tintColor: Config.themeColor, resultBlock: { result in
self.time.setRightText(result as! String)
for i in 0..<self.timeArr.count {
if self.timeArr[i] == (result as! String) {
self.deadLine = self.dateArr[i]
break
}
}
})
}
}
//MARK: - 回调与重要的几个方法
///value: y值。x值是屏幕宽度.dir默认0,如果不是0,就是变化量
func updateContentSize(value: CGFloat = 0, dir: CGFloat = 0) {
if dir == 0 {
scrollView.contentSize = CGSize(width: ScreenWidth, height: value)
}else {
let h = scrollView.contentSize.height
scrollView.contentSize = CGSize(width: ScreenWidth, height: h + dir)
}
}
override func pickerViewFrameChanged() {
let pickH = pickerCollectionView.frame.height
if pickH != currPickerHeight {
updateContentSize(dir: pickH - currPickerHeight)
currPickerHeight = pickH
}
}
func textViewDidBeginEditing(_ textView: UITextView) {
updateScrollFrameY(true)
}
func textViewDidEndEditing(_ textView: UITextView) {
updateScrollFrameY()
}
///默认值为false 原位置
func updateScrollFrameY(_ drag: Bool = false) {
UIView.animate(withDuration: 0.2, animations: {
if drag {
self.scrollView.contentOffset = CGPoint(x: 0, y: self.scrollView.contentSize.height - self.scrollView.frame.height)
}
}) { finished in
if finished && drag {
self.txv.becomeFirstResponder()
}
}
}
//MARK: - some methods not that important
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.endEditing(true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
scrollView.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard textField.text!.len() < 25 else {
return false
}
return true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
///如果不设置这个,在推出地址选择器再回来时,出发didBeginEditing的动画,类似QQ。
scrollView.endEditing(true)
}
}
//MARK: - 实现了回调传值
extension UpLoadViewController : ValueRecaller {
func transferLocation(_ value: [Any]) {
}
func transferType(_ value: String, position: Int) {
kind.setRightText(value)
type = position
}
}
/*
class UpLoadView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
//alpha = 0.5
// let view2 = UIScrollView(frame: CGRect(x: 0, y: 30, width: view.bounds.width, height: view.bounds.height))
// view2.backgroundColor = UIColor.white
// let maskPath = UIBezierPath(roundedRect: view2.bounds, byRoundingCorners:
// [UIRectCorner.topRight, UIRectCorner.topLeft], cornerRadii: CGSize(width: 8, height: 8))
// let maskLayer = CAShapeLayer()
// maskLayer.frame = view2.bounds
// maskLayer.path = maskPath.cgPath
//
// view2.layer.mask = maskLayer
//
// view.addSubview(view2)
//
// view2.isUserInteractionEnabled = true
// let gesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
// view2.addGestureRecognizer(gesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
*/
| aa5221bd9c0dd527bc76c56fa98bd71b | 27.964158 | 199 | 0.548199 | false | false | false | false |
Alienson/Bc | refs/heads/master | source-code/Cell-old.swift | apache-2.0 | 1 | //
// Cell-old.swift
// Parketovanie
//
// Created by Adam Turna on 12.1.2016.
// Copyright © 2016 Adam Turna. All rights reserved.
//
import Foundation
import SpriteKit
class Cell-old: SKSpriteNode {
var row: Int = Int()
var collumn: Int = Int()
var reserved: Bool = Bool()
init(row: Int, collumn: Int, isEmpty: Bool = true) {
if isEmpty {
super.init(texture: nil, color: UIColor.whiteColor(), size: CGSize(width: 50, height: 50))
reserved = true
}
else {
let imageNamed = "stvorec-50x50"
let cellTexture = SKTexture(imageNamed: imageNamed)
super.init(texture: cellTexture, color: UIColor.whiteColor(), size: cellTexture.size())
reserved = false
}
self.name = "cell"
self.row = row
self.collumn = collumn
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.zPosition = CGFloat(2.0)
}
func reserve(reserved: Bool) {
self.reserved = reserved
}
func isReserved() -> Bool {
return reserved
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
}
| 046f4808170c9fce43a99afaf0c47aff | 25.688889 | 102 | 0.577852 | false | false | false | false |
ThumbWorks/i-meditated | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Take.swift | mit | 6 | //
// Take.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// count version
class TakeCountSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType {
typealias Parent = TakeCount<ElementType>
typealias E = ElementType
private let _parent: Parent
private var _remaining: Int
init(parent: Parent, observer: O) {
_parent = parent
_remaining = parent._count
super.init(observer: observer)
}
func on(_ event: Event<E>) {
switch event {
case .next(let value):
if _remaining > 0 {
_remaining -= 1
forwardOn(.next(value))
if _remaining == 0 {
forwardOn(.completed)
dispose()
}
}
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
}
class TakeCount<Element>: Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _count: Int
init(source: Observable<Element>, count: Int) {
if count < 0 {
rxFatalError("count can't be negative")
}
_source = source
_count = count
}
override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
let sink = TakeCountSink(parent: self, observer: observer)
sink.disposable = _source.subscribe(sink)
return sink
}
}
// time version
class TakeTimeSink<ElementType, O: ObserverType>
: Sink<O>
, LockOwnerType
, ObserverType
, SynchronizedOnType where O.E == ElementType {
typealias Parent = TakeTime<ElementType>
typealias E = ElementType
fileprivate let _parent: Parent
let _lock = NSRecursiveLock()
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next(let value):
forwardOn(.next(value))
case .error:
forwardOn(event)
dispose()
case .completed:
forwardOn(event)
dispose()
}
}
func tick() {
_lock.lock(); defer { _lock.unlock() }
forwardOn(.completed)
dispose()
}
func run() -> Disposable {
let disposeTimer = _parent._scheduler.scheduleRelative((), dueTime: _parent._duration) {
self.tick()
return Disposables.create()
}
let disposeSubscription = _parent._source.subscribe(self)
return Disposables.create(disposeTimer, disposeSubscription)
}
}
class TakeTime<Element> : Producer<Element> {
typealias TimeInterval = RxTimeInterval
fileprivate let _source: Observable<Element>
fileprivate let _duration: TimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, duration: TimeInterval, scheduler: SchedulerType) {
_source = source
_scheduler = scheduler
_duration = duration
}
override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
let sink = TakeTimeSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
}
| 561c7ea0189c1f9e8edf7f2b53ea2a3e | 24.347222 | 100 | 0.564658 | false | false | false | false |
rastogigaurav/mTV | refs/heads/master | mTV/mTV/Views/MovieDetailsViewController.swift | mit | 1 | //
// MovieDetailsViewController.swift
// mTV
//
// Created by Gaurav Rastogi on 6/25/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import UIKit
import SDWebImage
class MovieDetailsViewController: UIViewController,UITableViewDataSource {
let repository:MovieDetailsRepository = MovieDetailsRepository()
var displayMovieDetails:DisplayMovieDetails?
var viewModel:MovieDetailsViewModel?
@IBOutlet weak var movieDetailsTableView:UITableView!
var movieId:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
movieDetailsTableView.rowHeight = UITableViewAutomaticDimension
movieDetailsTableView.estimatedRowHeight = 140
self.setupViewModel()
self.viewModel?.fetchDetailAndPopulate(forMovieWith: self.movieId, reload:{[unowned self] _ in
self.movieDetailsTableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: IBActions
@IBAction func onTapping(back sender: UIBarButtonItem) {
self.navigationController?.popViewController(animated: true)
}
//Private Methods
func setupViewModel(){
self.displayMovieDetails = DisplayMovieDetails(with: self.repository)
self.viewModel = MovieDetailsViewModel(with: self.displayMovieDetails!)
}
//TableView Datasource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.viewModel?.numberOfRowsInSection(section: section))!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MovieDetailCustomCell = tableView.dequeueReusableCell(withIdentifier: MovieDetailCustomCell.reuseIdentifier) as! MovieDetailCustomCell
self.configure(cell:cell, forRowAt:indexPath)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func configure(cell:MovieDetailCustomCell, forRowAt indexPath:IndexPath){
if let posterImage = self.viewModel?.movie?.posterPathURL(){
cell.posterImageView.sd_setImage(with: URL(string: posterImage), placeholderImage: UIImage(named: "movie-poster-default"))
}
else{
cell.posterImageView.image = nil
}
if let movieTitle = self.viewModel?.movie?.title{
cell.movieTitleLabel.text = movieTitle
}
if let tagline = self.viewModel?.movie?.tagline{
cell.taglineLabel.text = tagline
}
if let releaseYear = self.viewModel?.movie?.releaseYear{
cell.releaseYearLabel.text = String(releaseYear)
}
if let language = self.viewModel?.spokenLanguagesString(){
cell.languageLabel.text = language
}
if let companiesNames = self.viewModel?.namesOfProductionCompanies(){
cell.productionCompanyLabel.text = companiesNames
}
if let movieOverview = self.viewModel?.movie?.overview{
cell.movieOverviewLabel.text = movieOverview
}
}
}
| 829b54134c226ae3a63f56e1290e7960 | 34.552083 | 151 | 0.674187 | false | false | false | false |
dmrschmidt/DSWaveformImage | refs/heads/main | Sources/DSWaveformImage/WaveformImageDrawer+iOS.swift | mit | 1 | #if os(iOS)
import Foundation
import AVFoundation
import UIKit
import CoreGraphics
public extension WaveformImageDrawer {
/// Renders a DSImage of the provided waveform samples.
///
/// Samples need to be normalized within interval `(0...1)`.
func waveformImage(from samples: [Float], with configuration: Waveform.Configuration, renderer: WaveformRenderer) -> DSImage? {
guard samples.count > 0, samples.count == Int(configuration.size.width * configuration.scale) else {
print("ERROR: samples: \(samples.count) != \(configuration.size.width) * \(configuration.scale)")
return nil
}
let format = UIGraphicsImageRendererFormat()
format.scale = configuration.scale
let imageRenderer = UIGraphicsImageRenderer(size: configuration.size, format: format)
let dampenedSamples = configuration.shouldDampen ? dampen(samples, with: configuration) : samples
return imageRenderer.image { renderContext in
draw(on: renderContext.cgContext, from: dampenedSamples, with: configuration, renderer: renderer)
}
}
}
#endif
| fe9199b6ea5c1d0858c418006e11e712 | 40.740741 | 131 | 0.699201 | false | true | false | false |
Igor-Palaguta/YoutubeEngine | refs/heads/master | Tests/YoutubeEngineTests/DateComponents+EasyConstruction.swift | mit | 1 | import Foundation
extension DateComponents {
static func makeComponents(year: Int? = nil,
month: Int? = nil,
weekOfYear: Int? = nil,
day: Int? = nil,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil) -> DateComponents {
var components = DateComponents()
_ = year.map { components.year = $0 }
_ = month.map { components.month = $0 }
_ = day.map { components.day = $0 }
_ = weekOfYear.map { components.weekOfYear = $0 }
_ = hour.map { components.hour = $0 }
_ = minute.map { components.minute = $0 }
_ = second.map { components.second = $0 }
return components
}
}
| ef59ef800b4689308e1dda23b3e14554 | 38.857143 | 70 | 0.446834 | false | false | false | false |
hashemp206/WorldClock | refs/heads/master | Pods/Agent/Agent/Agent.swift | mit | 1 | //
// Agent.swift
// Agent
//
// Created by Christoffer Hallas on 6/2/14.
// Copyright (c) 2014 Christoffer Hallas. All rights reserved.
//
import Foundation
public class Agent {
public typealias Headers = Dictionary<String, String>
public typealias Response = (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void
public typealias RawResponse = (NSHTTPURLResponse?, NSData?, NSError?) -> Void
/**
* Members
*/
var base: NSURL?
var headers: Dictionary<String, String>?
var request: NSMutableURLRequest?
let queue = NSOperationQueue()
/**
* Initialize
*/
init(url: String, headers: Dictionary<String, String>?) {
self.base = NSURL(string: url)
self.headers = headers
}
convenience init(url: String) {
self.init(url: url, headers: nil)
}
init(method: String, url: String, headers: Dictionary<String, String>?) {
self.headers = headers
self.request(method, path: url)
}
convenience init(method: String, url: String) {
self.init(method: method, url: url, headers: nil)
}
/**
* Request
*/
func request(method: String, path: String) -> Agent {
var u: NSURL
if self.base != nil {
u = self.base!.URLByAppendingPathComponent(path)
} else {
u = NSURL(string: path)!
}
self.request = NSMutableURLRequest(URL: u)
self.request!.HTTPMethod = method
if self.headers != nil {
self.request!.allHTTPHeaderFields = self.headers
}
return self
}
/**
* GET
*/
public class func get(url: String) -> Agent {
return Agent(method: "GET", url: url, headers: nil)
}
public class func get(url: String, headers: Headers) -> Agent {
return Agent(method: "GET", url: url, headers: headers)
}
public class func get(url: String, done: Response) -> Agent {
return Agent.get(url).end(done)
}
public class func get(url: String, headers: Headers, done: Response) -> Agent {
return Agent.get(url, headers: headers).end(done)
}
public func get(url: String, done: Response) -> Agent {
return self.request("GET", path: url).end(done)
}
/**
* POST
*/
public class func post(url: String) -> Agent {
return Agent(method: "POST", url: url, headers: nil)
}
public class func post(url: String, headers: Headers) -> Agent {
return Agent(method: "POST", url: url, headers: headers)
}
public class func post(url: String, done: Response) -> Agent {
return Agent.post(url).end(done)
}
public class func post(url: String, headers: Headers, data: AnyObject) -> Agent {
return Agent.post(url, headers: headers).send(data)
}
public class func post(url: String, data: AnyObject) -> Agent {
return Agent.post(url).send(data)
}
public class func post(url: String, data: AnyObject, done: Response) -> Agent {
return Agent.post(url, data: data).send(data).end(done)
}
public class func post(url: String, headers: Headers, data: AnyObject, done: Response) -> Agent {
return Agent.post(url, headers: headers, data: data).send(data).end(done)
}
public func POST(url: String, data: AnyObject, done: Response) -> Agent {
return self.request("POST", path: url).send(data).end(done)
}
/**
* PUT
*/
public class func put(url: String) -> Agent {
return Agent(method: "PUT", url: url, headers: nil)
}
public class func put(url: String, headers: Headers) -> Agent {
return Agent(method: "PUT", url: url, headers: headers)
}
public class func put(url: String, done: Response) -> Agent {
return Agent.put(url).end(done)
}
public class func put(url: String, headers: Headers, data: AnyObject) -> Agent {
return Agent.put(url, headers: headers).send(data)
}
public class func put(url: String, data: AnyObject) -> Agent {
return Agent.put(url).send(data)
}
public class func put(url: String, data: AnyObject, done: Response) -> Agent {
return Agent.put(url, data: data).send(data).end(done)
}
public class func put(url: String, headers: Headers, data: AnyObject, done: Response) -> Agent {
return Agent.put(url, headers: headers, data: data).send(data).end(done)
}
public func PUT(url: String, data: AnyObject, done: Response) -> Agent {
return self.request("PUT", path: url).send(data).end(done)
}
/**
* DELETE
*/
public class func delete(url: String) -> Agent {
return Agent(method: "DELETE", url: url, headers: nil)
}
public class func delete(url: String, headers: Headers) -> Agent {
return Agent(method: "DELETE", url: url, headers: headers)
}
public class func delete(url: String, done: Response) -> Agent {
return Agent.delete(url).end(done)
}
public class func delete(url: String, headers: Headers, done: Response) -> Agent {
return Agent.delete(url, headers: headers).end(done)
}
public func delete(url: String, done: Response) -> Agent {
return self.request("DELETE", path: url).end(done)
}
/**
* Methods
*/
public func data(data: NSData?, mime: String) -> Agent {
self.set("Content-Type", value: mime)
self.request!.HTTPBody = data
return self
}
public func send(data: AnyObject) -> Agent {
do {
let json = try NSJSONSerialization.dataWithJSONObject(data, options: [])
return self.data(json, mime: "application/json")
} catch let error {
print("error while extracting data from JSON: \(error)");
return self.data(nil, mime: "application/json")
}
}
public func set(header: String, value: String) -> Agent {
self.request!.setValue(value, forHTTPHeaderField: header)
return self
}
public func end(done: Response) -> Agent {
let completion = { (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if error != .None {
done(.None, data, error)
return
}
var json: AnyObject!
if data != .None {
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
} catch let error {
print("error while extracting data from JSON: \(error)");
}
}
let res = response as! NSHTTPURLResponse
done(res, json, error)
}
NSURLConnection.sendAsynchronousRequest(self.request!, queue: self.queue, completionHandler: completion)
return self
}
public func raw(done: RawResponse) -> Agent {
let completion = { (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if error != .None {
done(.None, data, error)
return
}
done(response as? NSHTTPURLResponse, data, error)
}
NSURLConnection.sendAsynchronousRequest(self.request!, queue: self.queue, completionHandler: completion)
return self
}
} | c78fcaace62bfad0ff8e4e48de08072b | 29.427419 | 112 | 0.572697 | false | false | false | false |
liuxianghong/SmartLight | refs/heads/master | Code/SmartLight/SmartLight/AppUIKIt/LoadingView.swift | apache-2.0 | 1 | //
// LoadingView.swift
// Drone
//
// Created by BC600 on 16/1/19.
// Copyright © 2016年 fimi. All rights reserved.
//
import UIKit
class LoadingView: UIView {
fileprivate var delayHideTimer: Timer?
fileprivate var isShow = true
fileprivate var activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initView()
}
deinit {
}
fileprivate func initView() {
self.backgroundColor = UIColor(white: 0, alpha: 0.5)
self.addSubview(activity)
activity.snp.makeConstraints { (make) -> Void in
make.center.equalToSuperview()
}
show(false)
}
func show(_ animated: Bool) {
delayHideTimer?.invalidate()
delayHideTimer = nil
guard !isShow else {return}
isShow = true
self.activity.startAnimating()
superview?.bringSubview(toFront: self)
alpha = 0
UIView.animate(withDuration: animated ? 0.3 : 0, animations: {
self.alpha = 1
})
}
func hide(_ animated: Bool) {
delayHideTimer?.invalidate()
delayHideTimer = nil
isShow = false
UIView.animate(
withDuration: animated ? 0.3 : 0,
animations: { () -> Void in
self.alpha = 0
},
completion: { (finished) -> Void in
// 隐藏中才需要停止动画
if !self.isShow {
self.activity.stopAnimating()
}
}
)
}
func hide(_ animated: Bool, afterDelay delay: Foundation.TimeInterval) {
delayHideTimer?.invalidate()
delayHideTimer = Timer.scheduledTimer(
timeInterval: delay,
target: self,
selector: #selector(delayHideTimerTimeout(_:)),
userInfo: ["animated": animated],
repeats: false
)
}
func delayHideTimerTimeout(_ sender: Timer) {
guard let animated = (sender.userInfo as? [String: Any])?["animated"] as? Bool else {
return
}
hide(animated)
}
}
| 09e230faefd035c94c4d32c58c5bebc6 | 23.186275 | 119 | 0.522497 | false | false | false | false |
BeitIssieShapira/IssieBoard | refs/heads/master | ConfigurableKeyboard/KeyboardModel.swift | apache-2.0 | 2 |
import Foundation
var counter = 0
class Keyboard {
var pages: [Page]
init() {
self.pages = []
}
func addKey(_ key: Key, row: Int, page: Int) {
if self.pages.count <= page {
for _ in self.pages.count...page {
self.pages.append(Page())
}
}
self.pages[page].addKey(key, row: row)
}
}
class Page {
var rows: [[Key]]
init() {
self.rows = []
}
func addKey(_ key: Key, row: Int) {
if self.rows.count <= row {
for _ in self.rows.count...row {
self.rows.append([])
}
}
self.rows[row].append(key)
}
/*
Keyboard Pages
0 - Hebrew
1 - Numbers
2 - Symbols
3 - English Lower
4 - English Upper
5 - Numbers
6 - Symbols
*/
enum PagesIndex : Int {
case hebrewLetters = 0
case hebrewNumbers
case hebrewSymbols
case englishLower
case englishUpper
case englishNumbers
case englishSymbols
case arabicLetters
case arabicNumbers
case arabicSymbols
}
}
class Key: Hashable {
enum KeyType {
case character
case backspace
case modeChange
case keyboardChange
case space
case shift
case `return`
case undo
case restore
case dismissKeyboard
case customCharSetOne
case customCharSetTwo
case customCharSetThree
case specialKeys
case hiddenKey
case punctuation
case other
}
var type: KeyType
var keyTitle : String?
var keyOutput : String?
var pageNum: Int
var toMode: Int? //if type is ModeChange toMode holds the page it links to
var hasOutput : Bool {return (keyOutput != nil)}
var hasTitle : Bool {return (keyTitle != nil)}
var isCharacter: Bool {
get {
switch self.type {
case
.character,
.customCharSetOne,
.customCharSetTwo,
.customCharSetThree,
.hiddenKey,
.specialKeys:
return true
default:
return false
}
}
}
var isSpecial: Bool {
get {
switch self.type {
case
.backspace,
.modeChange,
.keyboardChange,
.space,
.punctuation,
.shift,
.dismissKeyboard,
.return,
.undo,
.restore :
return true
default:
return false
}
}
}
var hashValue: Int
init(_ type: KeyType) {
self.type = type
self.hashValue = counter
counter += 1
pageNum = -1
}
convenience init(_ key: Key) {
self.init(key.type)
self.keyTitle = key.keyTitle
self.keyOutput = key.keyOutput
self.toMode = key.toMode
self.pageNum = key.getPage()
}
func setKeyTitle(_ keyTitle: String) {
self.keyTitle = keyTitle
}
func getKeyTitle () -> String {
if (keyTitle != nil) {
return keyTitle!
}
else {
return ""
}
}
func setKeyOutput(_ keyOutput: String) {
self.keyOutput = keyOutput
}
func getKeyOutput () -> String {
if (keyOutput != nil) {
return keyOutput!
}
else {
return ""
}
}
func setPage(_ pageNum : Int) {
self.pageNum = pageNum
}
func getPage() -> Int {
return self.pageNum
}
}
func ==(lhs: Key, rhs: Key) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| 793e6b47f0e19a405e7d7889106c85c7 | 19.436842 | 78 | 0.480556 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/IRGen/Inputs/ObjectiveC.swift | apache-2.0 | 6 | // This is an overlay Swift module.
@_exported import ObjectiveC
public struct ObjCBool : CustomStringConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
private var value: Int8
public init(_ value: Bool) {
self.value = value ? 1 : 0
}
/// \brief Allow use in a Boolean context.
public var boolValue: Bool {
return value != 0
}
#else
// Everywhere else it is C/C++'s "Bool"
private var value: Bool
public init(_ value: Bool) {
self.value = value
}
public var boolValue: Bool {
return value
}
#endif
public var description: String {
// Dispatch to Bool.
return self.boolValue.description
}
}
public struct Selector {
private var ptr : OpaquePointer
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
public func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool {
return ObjCBool(x)
}
public func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool {
return x.boolValue
}
extension NSObject : Hashable {
public var hashValue: Int { return 0 }
}
public func ==(x: NSObject, y: NSObject) -> Bool { return x === y }
| f1319b5d774429da1a6c5d14906cdd43 | 21.433962 | 75 | 0.666947 | false | false | false | false |
ZJJeffery/PhotoBrowser | refs/heads/master | PhotoBrowser/PhotoBrowser/DemoTableViewController.swift | mit | 1 | //
// DemoTableViewController.swift
// 照片查看器
//
// Created by Jiajun Zheng on 15/5/24.
// Copyright (c) 2015年 hgProject. All rights reserved.
//
import UIKit
private let reusedId = "demoCell"
class DemoTableViewController: UITableViewController {
lazy var heightCache : NSCache = {
return NSCache()
}()
/// 图片资源
lazy var photoes : [Picture] = {
let pList = Picture.picturesList()
return pList
}()
/// 测试数组
lazy var dataList : [[Picture]] = {
var result = [[Picture]]()
for i in 0..<10 {
var list = [Picture]()
for x in 0..<i {
list.append(self.photoes[x])
}
result.append(list)
}
return result
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reusedId, forIndexPath: indexPath) as! DemoCell
if !(childViewControllers as NSArray).containsObject(cell.photoVC!) {
addChildViewController(cell.photoVC!)
}
cell.photoes = self.dataList[indexPath.row] as [Picture]
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if heightCache.objectForKey(indexPath.row) == nil {
let photoes = self.dataList[indexPath.row] as [Picture]
let cell = tableView.dequeueReusableCellWithIdentifier(reusedId) as! DemoCell
let rowHeight = cell.rowHeight(photoes)
heightCache.setObject(rowHeight, forKey: indexPath.row)
return rowHeight
}
return heightCache.objectForKey(indexPath.row) as! CGFloat
}
}
| 5890d245e65b4d0515ccd432beb4c312 | 31.144928 | 118 | 0.63165 | false | false | false | false |
jacobwhite/firefox-ios | refs/heads/master | Client/Frontend/Browser/TopTabsViewController.swift | mpl-2.0 | 1 | /* 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 Shared
import Storage
import WebKit
struct TopTabsUX {
static let TopTabsViewHeight: CGFloat = 44
static let TopTabsBackgroundShadowWidth: CGFloat = 12
static let TabWidth: CGFloat = 190
static let FaderPading: CGFloat = 8
static let SeparatorWidth: CGFloat = 1
static let HighlightLineWidth: CGFloat = 3
static let TabNudge: CGFloat = 1 // Nudge the favicon and close button by 1px
static let TabTitlePadding: CGFloat = 10
static let AnimationSpeed: TimeInterval = 0.1
static let SeparatorYOffset: CGFloat = 7
static let SeparatorHeight: CGFloat = 32
}
protocol TopTabsDelegate: class {
func topTabsDidPressTabs()
func topTabsDidPressNewTab(_ isPrivate: Bool)
func topTabsDidTogglePrivateMode()
func topTabsDidChangeTab()
}
protocol TopTabCellDelegate: class {
func tabCellDidClose(_ cell: TopTabCell)
}
class TopTabsViewController: UIViewController {
let tabManager: TabManager
weak var delegate: TopTabsDelegate?
fileprivate var isPrivate = false
fileprivate var isDragging = false
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout())
collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.clipsToBounds = false
collectionView.accessibilityIdentifier = "Top Tabs View"
collectionView.semanticContentAttribute = .forceLeftToRight
return collectionView
}()
fileprivate lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton.tabTrayButton()
tabsButton.semanticContentAttribute = .forceLeftToRight
tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: .touchUpInside)
tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton"
return tabsButton
}()
fileprivate lazy var newTab: UIButton = {
let newTab = UIButton.newTabButton()
newTab.semanticContentAttribute = .forceLeftToRight
newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: .touchUpInside)
return newTab
}()
lazy var privateModeButton: PrivateModeButton = {
let privateModeButton = PrivateModeButton()
privateModeButton.semanticContentAttribute = .forceLeftToRight
privateModeButton.light = true
privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: .touchUpInside)
return privateModeButton
}()
fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = {
let delegate = TopTabsLayoutDelegate()
delegate.tabSelectionDelegate = self
return delegate
}()
fileprivate var tabsToDisplay: [Tab] {
return self.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
}
// Handle animations.
fileprivate var tabStore: [Tab] = [] //the actual datastore
fileprivate var pendingUpdatesToTabs: [Tab] = [] //the datastore we are transitioning to
fileprivate var needReloads: [Tab?] = [] // Tabs that need to be reloaded
fileprivate var isUpdating = false
fileprivate var pendingReloadData = false
fileprivate var oldTabs: [Tab]? // The last state of the tabs before an animation
fileprivate weak var oldSelectedTab: Tab? // Used to select the right tab when transitioning between private/normal tabs
private var tabObservers: TabObservers!
init(tabManager: TabManager) {
self.tabManager = tabManager
super.init(nibName: nil, bundle: nil)
collectionView.dataSource = self
collectionView.delegate = tabLayoutDelegate
[UICollectionElementKindSectionHeader, UICollectionElementKindSectionFooter].forEach {
collectionView.register(TopTabsHeaderFooter.self, forSupplementaryViewOfKind: $0, withReuseIdentifier: "HeaderFooter")
}
self.tabObservers = registerFor(.didLoadFavicon, .didChangeURL, queue: .main)
}
deinit {
self.tabManager.removeDelegate(self)
unregister(tabObservers)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.tabsToDisplay != self.tabStore {
performTabUpdates()
}
}
override func viewDidLoad() {
super.viewDidLoad()
tabManager.addDelegate(self)
self.tabStore = self.tabsToDisplay
if #available(iOS 11.0, *) {
collectionView.dragDelegate = self
collectionView.dropDelegate = self
}
let topTabFader = TopTabFader()
topTabFader.semanticContentAttribute = .forceLeftToRight
view.addSubview(topTabFader)
topTabFader.addSubview(collectionView)
view.addSubview(tabsButton)
view.addSubview(newTab)
view.addSubview(privateModeButton)
// Setup UIDropInteraction to handle dragging and dropping
// links onto the "New Tab" button.
if #available(iOS 11, *) {
let dropInteraction = UIDropInteraction(delegate: self)
newTab.addInteraction(dropInteraction)
}
newTab.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(tabsButton.snp.leading).offset(-10)
make.size.equalTo(view.snp.height)
}
tabsButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(view).offset(-10)
make.size.equalTo(view.snp.height)
}
privateModeButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.leading.equalTo(view).offset(10)
make.size.equalTo(view.snp.height)
}
topTabFader.snp.makeConstraints { make in
make.top.bottom.equalTo(view)
make.leading.equalTo(privateModeButton.snp.trailing)
make.trailing.equalTo(newTab.snp.leading)
}
collectionView.snp.makeConstraints { make in
make.edges.equalTo(topTabFader)
}
view.backgroundColor = UIColor.Photon.Grey80
tabsButton.applyTheme(.Normal)
if let currentTab = tabManager.selectedTab {
applyTheme(currentTab.isPrivate ? .Private : .Normal)
}
updateTabCount(tabStore.count, animated: false)
}
func switchForegroundStatus(isInForeground reveal: Bool) {
// Called when the app leaves the foreground to make sure no information is inadvertently revealed
if let cells = self.collectionView.visibleCells as? [TopTabCell] {
let alpha: CGFloat = reveal ? 1 : 0
for cell in cells {
cell.titleText.alpha = alpha
cell.favicon.alpha = alpha
}
}
}
func updateTabCount(_ count: Int, animated: Bool = true) {
self.tabsButton.updateTabCount(count, animated: animated)
}
@objc func tabsTrayTapped() {
delegate?.topTabsDidPressTabs()
}
@objc func newTabTapped() {
if pendingReloadData {
return
}
self.delegate?.topTabsDidPressNewTab(self.isPrivate)
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Add tab button in the URL Bar on iPad" as AnyObject])
}
@objc func togglePrivateModeTapped() {
if isUpdating || pendingReloadData {
return
}
let isPrivate = self.isPrivate
delegate?.topTabsDidTogglePrivateMode()
self.pendingReloadData = true // Stops animations from happening
let oldSelectedTab = self.oldSelectedTab
self.oldSelectedTab = tabManager.selectedTab
self.privateModeButton.setSelected(!isPrivate, animated: true)
//if private tabs is empty and we are transitioning to it add a tab
if tabManager.privateTabs.isEmpty && !isPrivate {
tabManager.addTab(isPrivate: true)
}
//get the tabs from which we will select which one to nominate for tribute (selection)
//the isPrivate boolean still hasnt been flipped. (It'll be flipped in the BVC didSelectedTabChange method)
let tabs = !isPrivate ? tabManager.privateTabs : tabManager.normalTabs
if let tab = oldSelectedTab, tabs.index(of: tab) != nil {
tabManager.selectTab(tab)
} else {
tabManager.selectTab(tabs.last)
}
}
func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) {
assertIsMainThread("Only animate on the main thread")
guard let currentTab = tabManager.selectedTab, let index = tabStore.index(of: currentTab), !collectionView.frame.isEmpty else {
return
}
if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame {
if centerCell {
collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false)
} else {
// Padding is added to ensure the tab is completely visible (none of the tab is under the fader)
let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0)
if animated {
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.scrollRectToVisible(padFrame, animated: true)
})
} else {
collectionView.scrollRectToVisible(padFrame, animated: false)
}
}
}
}
}
@available(iOS 11.0, *)
extension TopTabsViewController: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
// Prevent tabs from being dragged and dropped onto the "New Tab" button.
if let localDragSession = session.localDragSession, let item = localDragSession.items.first, let _ = item.localObject as? Tab {
return false
}
return session.canLoadObjects(ofClass: URL.self)
}
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
return UIDropProposal(operation: .copy)
}
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
UnifiedTelemetry.recordEvent(category: .action, method: .drop, object: .url, value: .topTabs)
_ = session.loadObjects(ofClass: URL.self) { urls in
guard let url = urls.first else {
return
}
self.tabManager.addTab(URLRequest(url: url), isPrivate: self.isPrivate)
}
}
}
extension TopTabsViewController: Themeable {
func applyTheme(_ theme: Theme) {
tabsButton.applyTheme(theme)
tabsButton.titleBackgroundColor = view.backgroundColor ?? UIColor.Photon.Grey80
tabsButton.textColor = UIColor.Photon.Grey40
isPrivate = (theme == Theme.Private)
privateModeButton.applyTheme(theme)
privateModeButton.tintColor = UIColor.TopTabs.PrivateModeTint.colorFor(theme)
privateModeButton.imageView?.tintColor = privateModeButton.tintColor
newTab.tintColor = UIColor.Photon.Grey40
collectionView.backgroundColor = view.backgroundColor
}
}
extension TopTabsViewController: TopTabCellDelegate {
func tabCellDidClose(_ cell: TopTabCell) {
// Trying to remove tabs while animating can lead to crashes as indexes change. If updates are happening don't allow tabs to be removed.
guard let index = collectionView.indexPath(for: cell)?.item else {
return
}
let tab = tabStore[index]
if tabsToDisplay.index(of: tab) != nil {
tabManager.removeTab(tab)
}
}
}
extension TopTabsViewController: UICollectionViewDataSource {
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let index = indexPath.item
let tabCell = collectionView.dequeueReusableCell(withReuseIdentifier: TopTabCell.Identifier, for: indexPath) as! TopTabCell
tabCell.delegate = self
let tab = tabStore[index]
tabCell.style = tab.isPrivate ? .dark : .light
tabCell.titleText.text = tab.displayTitle
if tab.displayTitle.isEmpty {
if tab.webView?.url?.isLocalUtility ?? true {
tabCell.titleText.text = Strings.AppMenuNewTabTitleString
} else {
tabCell.titleText.text = tab.webView?.url?.absoluteDisplayString
}
tabCell.accessibilityLabel = tab.url?.aboutComponent ?? ""
tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tabCell.titleText.text ?? "")
} else {
tabCell.accessibilityLabel = tab.displayTitle
tabCell.closeButton.accessibilityLabel = String(format: Strings.TopSitesRemoveButtonAccessibilityLabel, tab.displayTitle)
}
tabCell.selectedTab = (tab == tabManager.selectedTab)
if let siteURL = tab.url?.displayURL {
tabCell.favicon.setIcon(tab.displayFavicon, forURL: siteURL, completed: { (color, url) in
if siteURL == url {
tabCell.favicon.image = tabCell.favicon.image?.createScaled(CGSize(width: 15, height: 15))
tabCell.favicon.backgroundColor = color == .clear ? .white : color
tabCell.favicon.contentMode = .center
}
})
} else {
tabCell.favicon.image = UIImage(named: "defaultFavicon")
tabCell.favicon.contentMode = .scaleAspectFit
tabCell.favicon.backgroundColor = .clear
}
return tabCell
}
@objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabStore.count
}
@objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderFooter", for: indexPath) as! TopTabsHeaderFooter
view.arrangeLine(kind)
return view
}
}
@available(iOS 11.0, *)
extension TopTabsViewController: UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, dragSessionWillBegin session: UIDragSession) {
isDragging = true
}
func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) {
isDragging = false
}
func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
// We need to store the earliest oldTabs. So if one already exists use that.
self.oldTabs = self.oldTabs ?? tabStore
let tab = tabStore[indexPath.item]
// Get the tab's current URL. If it is `nil`, check the `sessionData` since
// it may be a tab that has not been restored yet.
var url = tab.url
if url == nil, let sessionData = tab.sessionData {
let urls = sessionData.urls
let index = sessionData.currentPage + urls.count - 1
if index < urls.count {
url = urls[index]
}
}
// Ensure we actually have a URL for the tab being dragged and that the URL is not local.
// If not, just create an empty `NSItemProvider` so we can create a drag item with the
// `Tab` so that it can at still be re-ordered.
var itemProvider: NSItemProvider
if url != nil, !(url?.isLocal ?? true) {
itemProvider = NSItemProvider(contentsOf: url) ?? NSItemProvider()
} else {
itemProvider = NSItemProvider()
}
UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .tab, value: .topTabs)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = tab
return [dragItem]
}
}
@available(iOS 11.0, *)
extension TopTabsViewController: UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
guard let destinationIndexPath = coordinator.destinationIndexPath, let dragItem = coordinator.items.first?.dragItem, let tab = dragItem.localObject as? Tab, let sourceIndex = tabStore.index(of: tab) else {
return
}
UnifiedTelemetry.recordEvent(category: .action, method: .drop, object: .tab, value: .topTabs)
coordinator.drop(dragItem, toItemAt: destinationIndexPath)
isDragging = false
self.tabManager.moveTab(isPrivate: self.isPrivate, fromIndex: sourceIndex, toIndex: destinationIndexPath.item)
self.performTabUpdates()
}
func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
guard let localDragSession = session.localDragSession, let item = localDragSession.items.first, let tab = item.localObject as? Tab else {
return UICollectionViewDropProposal(operation: .forbidden)
}
// If the `isDragging` is not `true` by the time we get here, we've had other
// add/remove operations happen while the drag was going on. We must return a
// `.cancel` operation continuously until `isDragging` can be reset.
guard tabStore.index(of: tab) != nil, isDragging else {
return UICollectionViewDropProposal(operation: .cancel)
}
return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
}
extension TopTabsViewController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
let tab = tabStore[index]
if tabsToDisplay.index(of: tab) != nil {
tabManager.selectTab(tab)
}
}
}
extension TopTabsViewController: TabEventHandler {
func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) {
assertIsMainThread("UICollectionView changes can only be performed from the main thread")
if tabStore.index(of: tab) != nil {
needReloads.append(tab)
performTabUpdates()
}
}
func tab(_ tab: Tab, didChangeURL url: URL) {
assertIsMainThread("UICollectionView changes can only be performed from the main thread")
if tabStore.index(of: tab) != nil {
needReloads.append(tab)
performTabUpdates()
}
}
}
// Collection Diff (animations)
extension TopTabsViewController {
struct TopTabMoveChange: Hashable {
let from: IndexPath
let to: IndexPath
var hashValue: Int {
return from.hashValue + to.hashValue
}
// Consider equality when from/to are equal as well as swapped. This is because
// moving a tab from index 2 to index 1 will result in TWO changes: 2 -> 1 and 1 -> 2
// We only need to keep *one* of those two changes when dealing with a move.
static func ==(lhs: TopTabsViewController.TopTabMoveChange, rhs: TopTabsViewController.TopTabMoveChange) -> Bool {
return (lhs.from == rhs.from && lhs.to == rhs.to) || (lhs.from == rhs.to && lhs.to == rhs.from)
}
}
struct TopTabChangeSet {
let reloads: Set<IndexPath>
let inserts: Set<IndexPath>
let deletes: Set<IndexPath>
let moves: Set<TopTabMoveChange>
init(reloadArr: [IndexPath], insertArr: [IndexPath], deleteArr: [IndexPath], moveArr: [TopTabMoveChange]) {
reloads = Set(reloadArr)
inserts = Set(insertArr)
deletes = Set(deleteArr)
moves = Set(moveArr)
}
var isEmpty: Bool {
return reloads.isEmpty && inserts.isEmpty && deletes.isEmpty && moves.isEmpty
}
}
// create a TopTabChangeSet which is a snapshot of updates to perfrom on a collectionView
func calculateDiffWith(_ oldTabs: [Tab], to newTabs: [Tab], and reloadTabs: [Tab?]) -> TopTabChangeSet {
let inserts: [IndexPath] = newTabs.enumerated().compactMap { index, tab in
if oldTabs.index(of: tab) == nil {
return IndexPath(row: index, section: 0)
}
return nil
}
let deletes: [IndexPath] = oldTabs.enumerated().compactMap { index, tab in
if newTabs.index(of: tab) == nil {
return IndexPath(row: index, section: 0)
}
return nil
}
let moves: [TopTabMoveChange] = newTabs.enumerated().compactMap { newIndex, tab in
if let oldIndex = oldTabs.index(of: tab), oldIndex != newIndex {
return TopTabMoveChange(from: IndexPath(row: oldIndex, section: 0), to: IndexPath(row: newIndex, section: 0))
}
return nil
}
// Create based on what is visibile but filter out tabs we are about to insert/delete.
let reloads: [IndexPath] = reloadTabs.compactMap { tab in
guard let tab = tab, newTabs.index(of: tab) != nil else {
return nil
}
return IndexPath(row: newTabs.index(of: tab)!, section: 0)
}.filter { return inserts.index(of: $0) == nil && deletes.index(of: $0) == nil }
return TopTabChangeSet(reloadArr: reloads, insertArr: inserts, deleteArr: deletes, moveArr: moves)
}
func updateTabsFrom(_ oldTabs: [Tab]?, to newTabs: [Tab], on completion: (() -> Void)? = nil) {
assertIsMainThread("Updates can only be performed from the main thread")
guard let oldTabs = oldTabs, !self.isUpdating, !self.pendingReloadData, !self.isDragging else {
return
}
// Lets create our change set
let update = self.calculateDiffWith(oldTabs, to: newTabs, and: needReloads)
flushPendingChanges()
// If there are no changes. We have nothing to do
if update.isEmpty {
completion?()
return
}
// The actual update block. We update the dataStore right before we do the UI updates.
let updateBlock = {
self.tabStore = newTabs
// Only consider moves if no other operations are pending.
if update.deletes.count == 0, update.inserts.count == 0, update.reloads.count == 0 {
for move in update.moves {
self.collectionView.moveItem(at: move.from, to: move.to)
}
} else {
self.collectionView.deleteItems(at: Array(update.deletes))
self.collectionView.insertItems(at: Array(update.inserts))
self.collectionView.reloadItems(at: Array(update.reloads))
}
}
//Lets lock any other updates from happening.
self.isUpdating = true
self.isDragging = false
self.pendingUpdatesToTabs = newTabs // This var helps other mutations that might happen while updating.
let onComplete: () -> Void = {
self.isUpdating = false
self.pendingUpdatesToTabs = []
// Sometimes there might be a pending reload. Lets do that.
if self.pendingReloadData {
return self.reloadData()
}
// There can be pending animations. Run update again to clear them.
let tabs = self.oldTabs ?? self.tabStore
self.updateTabsFrom(tabs, to: self.tabsToDisplay, on: {
if !update.inserts.isEmpty || !update.reloads.isEmpty {
self.scrollToCurrentTab()
}
})
}
// The actual update. Only animate the changes if no tabs have moved
// as a result of drag-and-drop.
if update.moves.count == 0 {
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.performBatchUpdates(updateBlock)
}) { (_) in
onComplete()
}
} else {
self.collectionView.performBatchUpdates(updateBlock) { _ in
onComplete()
}
}
}
fileprivate func flushPendingChanges() {
oldTabs = nil
needReloads.removeAll()
}
func reloadData() {
assertIsMainThread("reloadData must only be called from main thread")
if self.isUpdating || self.collectionView.frame == CGRect.zero {
self.pendingReloadData = true
return
}
isUpdating = true
isDragging = false
self.tabStore = self.tabsToDisplay
self.newTab.isUserInteractionEnabled = false
self.flushPendingChanges()
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.layoutIfNeeded()
self.scrollToCurrentTab(true, centerCell: true)
}, completion: { (_) in
self.isUpdating = false
self.pendingReloadData = false
self.performTabUpdates()
self.newTab.isUserInteractionEnabled = true
})
}
}
extension TopTabsViewController: TabManagerDelegate {
// Because we don't know when we are about to transition to private mode
// check to make sure that the tab we are trying to add is being added to the right tab group
fileprivate func tabsMatchDisplayGroup(_ a: Tab?, b: Tab?) -> Bool {
if let a = a, let b = b, a.isPrivate == b.isPrivate {
return true
}
return false
}
func performTabUpdates() {
guard !isUpdating, view.window != nil else {
return
}
let fromTabs = !self.pendingUpdatesToTabs.isEmpty ? self.pendingUpdatesToTabs : self.oldTabs
self.oldTabs = fromTabs ?? self.tabStore
if self.pendingReloadData && !isUpdating {
self.reloadData()
} else {
self.updateTabsFrom(self.oldTabs, to: self.tabsToDisplay)
}
}
// This helps make sure animations don't happen before the view is loaded.
fileprivate var isRestoring: Bool {
return self.tabManager.isRestoring || self.collectionView.frame == CGRect.zero
}
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) {
if isRestoring {
return
}
if !tabsMatchDisplayGroup(selected, b: previous) {
self.reloadData()
} else {
self.needReloads.append(selected)
self.needReloads.append(previous)
performTabUpdates()
delegate?.topTabsDidChangeTab()
}
}
func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) {
// We need to store the earliest oldTabs. So if one already exists use that.
self.oldTabs = self.oldTabs ?? tabStore
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) {
if isRestoring || (tabManager.selectedTab != nil && !tabsMatchDisplayGroup(tab, b: tabManager.selectedTab)) {
return
}
performTabUpdates()
}
func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) {
// We need to store the earliest oldTabs. So if one already exists use that.
self.oldTabs = self.oldTabs ?? tabStore
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) {
if isRestoring {
return
}
// If we deleted the last private tab. We'll be switching back to normal browsing. Pause updates till then
if self.tabsToDisplay.isEmpty {
self.pendingReloadData = true
return
}
// dont want to hold a ref to a deleted tab
if tab === oldSelectedTab {
oldSelectedTab = nil
}
performTabUpdates()
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
self.reloadData()
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {
self.reloadData()
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
self.reloadData()
}
}
| e30a05f88686c63506af966423fe917d | 38.894022 | 213 | 0.646278 | false | false | false | false |
NUKisZ/MyTools | refs/heads/master | MyTools/MyTools/ThirdLibrary/ProgressHUD/ProgressHUD.swift | mit | 1 | //
// ProgressHUD.swift
// LimitFree1606
//
// Created by gaokunpeng on 16/7/28.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
public let kProgressImageName = "提示底.png"
public let kProgressHUDTag = 10000
public let kProgressActivityTag = 20000
class ProgressHUD: UIView {
var textLabel: UILabel?
init(center: CGPoint){
super.init(frame: CGRect.zero)
let bgImage = UIImage(named: kProgressImageName)
self.bounds = CGRect(x: 0, y: 0, width: bgImage!.size.width, height: bgImage!.size.height)
self.center = center
let imageView = UIImageView(image: bgImage)
imageView.frame = self.bounds
self.addSubview(imageView)
//self.backgroundColor = UIColor.grayColor()
self.layer.cornerRadius = 6
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func show(){
let uaiView = UIActivityIndicatorView(activityIndicatorStyle: .white)
uaiView.tag = kProgressActivityTag
uaiView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
uaiView.backgroundColor = UIColor.clear
uaiView.startAnimating()
self.addSubview(uaiView)
self.textLabel = UILabel(frame: CGRect.zero)
self.textLabel!.backgroundColor = UIColor.clear
self.textLabel!.textColor = UIColor.white
self.textLabel!.text = "加载中..."
self.textLabel!.font = UIFont.systemFont(ofSize: 15)
self.textLabel?.sizeToFit()
self.textLabel!.center = CGPoint(x: uaiView.center.x, y: uaiView.frame.origin.y+uaiView.frame.size.height+5+self.textLabel!.bounds.size.height/2)
self.addSubview(self.textLabel!)
}
fileprivate func hideActivityView(){
let tmpView = self.viewWithTag(kProgressActivityTag)
if tmpView != nil {
let uiaView = tmpView as! UIActivityIndicatorView
uiaView.stopAnimating()
uiaView.removeFromSuperview()
}
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
}, completion: { (finished) in
self.superview?.isUserInteractionEnabled = true
self.removeFromSuperview()
})
}
fileprivate func hideAfterSuccess(){
let successImage = UIImage(named: "保存成功.png")
let successImageView = UIImageView(image: successImage)
successImageView.sizeToFit()
successImageView.center = CGPoint(x: self.frame.size.width/2,
y: self.frame.size.height/2)
self.addSubview(successImageView)
self.textLabel!.text = "加载成功"
self.textLabel!.sizeToFit()
self.hideActivityView()
}
fileprivate func hideAfterFail(){
self.textLabel?.text = "加载失败"
self.textLabel?.sizeToFit()
self.hideActivityView()
}
class func showOnView(_ view: UIView){
let oldHud = view.viewWithTag(kProgressHUDTag)
if (oldHud != nil) {
oldHud?.removeFromSuperview()
}
let hud = ProgressHUD(center: view.center)
hud.tag = kProgressHUDTag
hud.show()
view.isUserInteractionEnabled = false
view.addSubview(hud)
}
class func hideAfterSuccessOnView(_ view: UIView){
let tmpView = view.viewWithTag(kProgressHUDTag)
if tmpView != nil {
let hud = tmpView as! ProgressHUD
hud.hideAfterSuccess()
}
}
class func hideAfterFailOnView(_ view: UIView){
let tmpView = view.viewWithTag(kProgressHUDTag)
if tmpView != nil {
let hud = tmpView as! ProgressHUD
hud.hideAfterFail()
}
}
fileprivate class func hideOnView(_ view: UIView){
let tmpView = view.viewWithTag(kProgressHUDTag)
if tmpView != nil {
let hud = tmpView as! ProgressHUD
hud.hideActivityView()
}
}
}
| 361ff445c4bbf0d0380f379e9634c553 | 24.142045 | 153 | 0.567232 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/SILGen/generic_tuples.swift | apache-2.0 | 14 | // RUN: %target-swift-frontend -emit-silgen -parse-as-library %s | %FileCheck %s
func dup<T>(_ x: T) -> (T, T) { return (x,x) }
// CHECK-LABEL: sil hidden @_T014generic_tuples3dup{{[_0-9a-zA-Z]*}}F
// CHECK: ([[RESULT_0:%.*]] : $*T, [[RESULT_1:%.*]] : $*T, [[XVAR:%.*]] : $*T):
// CHECK-NEXT: debug_value_addr [[XVAR]] : $*T, let, name "x"
// CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_0]]
// CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_1]]
// CHECK-NEXT: destroy_addr [[XVAR]]
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]]
// <rdar://problem/13822463>
// Specializing a generic function on a tuple type changes the number of
// SIL parameters, which caused a failure in the ownership conventions code.
struct Blub {}
// CHECK-LABEL: sil hidden @_T014generic_tuples3foo{{[_0-9a-zA-Z]*}}F
func foo<T>(_ x: T) {}
// CHECK-LABEL: sil hidden @_T014generic_tuples3bar{{[_0-9a-zA-Z]*}}F
func bar(_ x: (Blub, Blub)) { foo(x) }
// rdar://26279628
// A type parameter constrained to be a concrete type must be handled
// as that concrete type throughout SILGen. That's especially true
// if it's constrained to be a tuple.
protocol HasAssoc {
associatedtype A
}
extension HasAssoc where A == (Int, Int) {
func returnTupleAlias() -> A {
return (0, 0)
}
}
// CHECK-LABEL: sil hidden @_T014generic_tuples8HasAssocPA2aBRzSi_Sit1ARtzlE16returnTupleAliasSi_SityF : $@convention(method) <Self where Self : HasAssoc, Self.A == (Int, Int)> (@in_guaranteed Self) -> (Int, Int) {
// CHECK: return {{.*}} : $(Int, Int)
| b455c61c59d2461c3b4856500dff74e3 | 39.794872 | 214 | 0.637335 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.