repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hweetty/EasyTransitioning | EasyTransitioning/Classes/Actions/ETFadeAction.swift | 1 | 836 | //
// ETFadeAction.swift
// EasyTransitioning
//
// Created by Jerry Yu on 2016-11-12.
// Copyright © 2016 Jerry Yu. All rights reserved.
//
import UIKit
public struct ETFadeAction: ETAction {
public let toAlpha: CGFloat
public let fromAlpha: CGFloat
public init(toAlpha: CGFloat, fromAlpha: CGFloat) {
self.toAlpha = toAlpha
self.fromAlpha = fromAlpha
}
public func setup(snapshotView: UIView?, in containerView: UIView) {
guard let snapshotView = snapshotView else { return }
snapshotView.alpha = fromAlpha
}
public func animate(snapshotView: UIView?, in containerView: UIView, animationDuration: TimeInterval) {
guard let snapshotView = snapshotView else { return }
snapshotView.alpha = toAlpha
}
public func reversed() -> ETAction {
return ETFadeAction(toAlpha: fromAlpha, fromAlpha: toAlpha)
}
}
| mit | 6972ff0f01719f86520d9b2d8315e138 | 24.30303 | 104 | 0.738922 | 3.678414 | false | false | false | false |
bugitapp/bugit | bugit/Extensions/xUIBezierPath.swift | 1 | 1363 | //
// xUIBezierPath.swift
// bugit
//
// Created by Ernest on 11/12/16.
// Copyright © 2016 BugIt App. All rights reserved.
//
import UIKit
extension UIBezierPath {
// let arrow = UIBezierPath.arrow(from: CGPointMake(50, 100), to: CGPointMake(200, 50), tailWidth: 10, headWidth: 25, headLength: 40)
class func arrow(from start: CGPoint, to end: CGPoint, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat) -> Self {
let length = hypot(end.x - start.x, end.y - start.y)
let tailLength = length - headLength
func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) }
let points: [CGPoint] = [
p(0, tailWidth / 2),
p(tailLength, tailWidth / 2),
p(tailLength, headWidth / 2),
p(length, 0),
p(tailLength, -headWidth / 2),
p(tailLength, -tailWidth / 2),
p(0, -tailWidth / 2)
]
let cosine = (end.x - start.x) / length
let sine = (end.y - start.y) / length
let transform = CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: start.x, ty: start.y)
let path = CGMutablePath()
path.addLines(between: points, transform: transform )
path.closeSubpath()
return self.init(cgPath: path)
}
}
| apache-2.0 | 7d62a8f2df96ec44cc2f6bdaf8b62aec | 32.219512 | 137 | 0.563877 | 3.632 | false | false | false | false |
lpniuniu/bookmark | bookmark/bookmark/BookReadShowViewController/BookCalendarHeadView.swift | 1 | 2670 | //
// BookCalendarHeadView.swift
// bookmark
//
// Created by familymrfan on 17/1/10.
// Copyright © 2017年 niuniu. All rights reserved.
//
import UIKit
import JTAppleCalendar
import SnapKit
import Bulb
class BookCalendarHeadView: JTAppleHeaderView {
let monthLabel:UILabel = UILabel()
let headTitles:[String] = ["日", "一", "二", "三", "四", "五", "六"]
var titleLabels:[UILabel] = []
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(monthLabel)
var i = 0
for _ in 1...7 {
let label = UILabel()
label.text = headTitles[i]
label.textAlignment = .center
titleLabels.append(label)
addSubview(label)
i = i + 1
}
monthLabel.textAlignment = .center
monthLabel.font = monthLabel.font.withSize(20)
weak var weakSelf = self
Bulb.bulbGlobal().register(BookCalendarChangeMonthSignal.signalDefault()) { (data:Any?, identifier2Signal:[String : BulbSignal]?) -> Bool in
let date:Date = (data as? Date)!
let month = Calendar.current.dateComponents([.month], from: date).month!
let monthName = DateFormatter().monthSymbols[(month-1) % 12]
// 0 indexed array
let year = Calendar.current.component(.year, from: date)
if let monthLabel = weakSelf?.monthLabel {
monthLabel.text = monthName + " " + String(year)
} else {
return false
}
return true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
monthLabel.snp.makeConstraints { (maker:ConstraintMaker) in
maker.top.equalToSuperview().offset(30)
maker.left.equalToSuperview().offset(10)
maker.right.equalToSuperview().offset(-10)
maker.height.equalTo(15)
}
var preLabel:UILabel? = nil
for label:UILabel in titleLabels {
label.snp.remakeConstraints({ (maker:ConstraintMaker) in
if preLabel == nil {
maker.left.equalToSuperview()
} else {
maker.left.equalTo((preLabel?.snp.right)!)
}
maker.width.equalTo(frame.width/7.0)
maker.height.equalTo(60)
maker.top.equalTo(monthLabel.snp.bottom)
})
preLabel = label
}
}
}
| mit | c02c9ba9937fa67df515c9003cc5cc2b | 30.211765 | 148 | 0.54919 | 4.646235 | false | false | false | false |
galalmounir/WWDC-2017-Entry | So You Want To Be A Computer Scientist?.playground/Pages/Welcome.xcplaygroundpage/Sources/Welcome.swift | 1 | 407 | import Foundation
import SpriteKit
import PlaygroundSupport
let frame = CGRect(x: 0, y: 250, width: 500, height: 300)
let view = SKView(frame: frame)
let scene = MainScene(size: frame.size)
public func loadPage(){
scene.scaleMode = .aspectFit
scene.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
view.presentScene(scene)
PlaygroundPage.current.liveView = view
}
| mit | 215164e579bab91cc01a62bfa2199b4c | 26.133333 | 78 | 0.717445 | 3.7 | false | false | false | false |
linbin00303/Dotadog | DotaDog/DotaDog/Classes/Other/Tools/LBQRCodeTool.swift | 1 | 14630 | //
// LBQRCodeTool.swift
// 二维码
//
// Created by 林彬 on 16/5/5.
// Copyright © 2016年 linbin. All rights reserved.
//
/**
*二维码的生成,扫描和识别的工具类
*
*提供类方法
*开始扫描方法: LBQRCodeTool.shareInstance.startScan
*关闭扫描方法: LBQRCodeTool.shareInstance.stopScan
***/
import UIKit
import AVFoundation
import CoreFoundation
// 闭包
typealias ScanResult = (resultStrs: String)->()
class LBQRCodeTool: NSObject {
// 判断当前扫描的状态
var isScan : Bool = false
// 保存上一次扫到的结果
var perResult :String?
// 单例
static let shareInstance = LBQRCodeTool()
// 扫描结果的闭包
private var scanResultBlock: ScanResult?
// 懒加载输入
private lazy var input: AVCaptureDeviceInput? = {
// 1. 获取摄像头设备
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
// 1.1 设置为输入设备
var input: AVCaptureDeviceInput?
do {
input = try AVCaptureDeviceInput(device: device)
}catch {
print(error)
return nil
}
return input
}()
// 懒加载输出
private lazy var output: AVCaptureMetadataOutput = {
// 2. 创建元数据输出处理对象
let output = AVCaptureMetadataOutput()
// 2.1 设置元数据输出处理的代理, 来接收输出的数据内容
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
return output
}()
// 会话
private lazy var session: AVCaptureSession = {
// 3. 创建会话, 连接输入和输出
let session = AVCaptureSession()
return session
}()
// 预览图层
private lazy var layer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
return layer
}()
// 扫描二维码的时候是否给二维码加上边框
var isDraw: Bool = false
// 全局的path
var framePath : UIBezierPath?
}
// MARK:- 生成和识别二维码
extension LBQRCodeTool {
// MARK:- 生成二维码
class func generatorQRCode(contentStr : String , centerImage :UIImage?) -> UIImage {
// 1:新建一个二维码滤镜
let fiter = CIFilter(name: "CIQRCodeGenerator")
// 1.1:先让这个滤镜恢复默认设置,避免以前的一些配置影响现在的程序
fiter?.setDefaults()
// 2:利用KVC,设置滤镜的输入内容
// 要注意的是,输入内容必须是NSData,需要先把String转成NSData
let inputStr = contentStr
let inputData = inputStr.dataUsingEncoding(NSUTF8StringEncoding)
// 利用KVC设置输入内容
fiter?.setValue(inputData, forKey: "inputMessage")
// 2.1 :设置滤镜的纠错率.纠错率越高,二维码越复杂,中间可遮挡区域越多.一般M即可
fiter?.setValue("M", forKey: "inputCorrectionLevel")
// 3:取出生成的图片
var outImage = fiter?.outputImage
// 生成的图片默认大小是23,23.需要放大,放大20倍,让它清晰起来
let transform = CGAffineTransformMakeScale(20, 20)
outImage = outImage?.imageByApplyingTransform(transform)
// 4:展示生成的图片
// 先转换类型
var QRCodeImage = UIImage(CIImage: outImage!)
// 5:在生成的图片上覆盖一张小图片
if centerImage != nil {
QRCodeImage = creatCoverImage(QRCodeImage, coverImage: centerImage!)
}
return QRCodeImage
}
// MARK:- 识别图片中的二维码
class func detectorQRCode( sourceImage :UIImage , isDrawFrame : Bool) -> (resultImage :UIImage, resultStrings : [String] ) {
// 1: 创建二维码探测器
/*
CIDetectorTypeQRCode:扫描类型.还可以扫描人脸和文字
CIDetectorAccuracy : 准确性
*/
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
// 2:探测图片特征
let image = sourceImage
let imageCI = CIImage(image: image) // 类型转换
// 获取到的是识别出来的二维码特征,是个数组
let result = detector.featuresInImage(imageCI!)
// 3:遍历特征,打印结果
var strs = [String]()
var tempImage = image
for feature in result {
// 数组result里保存的都是CIQRCodeFeature类型的数据
let qrCodeFeature = feature as! CIQRCodeFeature
// 把信息放到字符串数组中
strs.append(qrCodeFeature.messageString)
// 判断要不要边框
if isDrawFrame {
tempImage = drawFrame(tempImage, feature: qrCodeFeature)
}
}
// sourceImage = tempImage
return (tempImage , strs)
}
}
extension LBQRCodeTool {
// 在生成的二维码上再添加一张图片
class private func creatCoverImage(sourceImage :UIImage , coverImage : UIImage) -> UIImage {
let size = sourceImage.size
// 1:开启图片上下文
UIGraphicsBeginImageContext(size)
// 2:绘制源图片
sourceImage.drawInRect(CGRectMake(0, 0, size.width, size.height))
// 3:绘制覆盖图片
let w : CGFloat = 80
let h : CGFloat = 80
let x = (size.width - 80) * 0.5
let y = (size.height - 80) * 0.5
coverImage.drawInRect(CGRectMake(x, y, w, h))
// 4:获得结果图片
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
// 5:关闭上下文
UIGraphicsEndImageContext()
// 6:返回结果图片
return resultImage
}
// 给识别出来的二维码加上边框
class private func drawFrame(sourceImage : UIImage , feature : CIQRCodeFeature) -> UIImage{
let size = sourceImage.size
// 1:开启上下文
UIGraphicsBeginImageContext(size)
// 2:绘制图片
sourceImage.drawInRect(CGRectMake(0, 0, size.width, size.height))
// 修改坐标(上下颠倒)
/*
为什么要上下颠倒?
因为图片特征feature的bounds,是依照图片的坐标来算的.
我们原先都是以屏幕坐标系来算的,屏幕坐标系的原点在左上角.
而图片坐标系的原点是在图片的左下角.刚好上下颠倒.
所以如果不做坐标上下颠倒处理,那么绘制的边框正好和识别出来的二维码呈上下颠倒姿态.
*/
// 获取当前上下文
let context = UIGraphicsGetCurrentContext()
// 上下文的y方向缩放-1,就相当于上下文上下翻了个个.
CGContextScaleCTM(context, 1, -1)
// 翻转完后,要把上下文移回到原来的位置.因为前面把坐标系的y值改成负的了,这里也要改成负的
CGContextTranslateCTM(context, 0, -size.height)
// 3:绘制线宽
let path = UIBezierPath(rect: feature.bounds)
UIColor.orangeColor().setStroke() // 线的颜色
path.lineWidth = 6
path.stroke() // 样式是边框
// 4:取出合成后的图片
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
// 5:关闭上下文
UIGraphicsEndImageContext()
// 6:返回图片
return resultImage
}
}
// MARK:- 扫描二维码
extension LBQRCodeTool {
// MARK:- 扫描二维码
func startScan(inView: UIView, isDraw: Bool, interestRect : CGRect , resultBlock: ScanResult?) {
// 1. 记录block, 在合适的地方执行
scanResultBlock = resultBlock
self.isDraw = isDraw
// 2. 创建会话, 连接输入和输出
if session.canAddInput(input) && session.canAddOutput(output)
{
session.addInput(input)
session.addOutput(output)
}
// 2.1 设置扫描识别的类型
// output.availableMetadataObjectTypes, 识别所有的类型
// 如果设置这个属性, 在添加到session之前会崩溃
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
// 2.2 添加视频预览图层
let sublayers = inView.layer.sublayers
if sublayers == nil || !sublayers!.contains(layer)
{
layer.frame = inView.bounds
inView.layer.insertSublayer(layer, atIndex: 0)
}
// 3. 设置扫描区域
setInterestRect(interestRect)
// 4. 启动会话, 开始扫描
session.startRunning()
}
func stopScan() {
// 停止扫描后,需要关闭会话
isScan = false
removeQRCodeFrameLayer()
session.stopRunning()
}
// 3 设置扫描区域
func setInterestRect(rect: CGRect) -> () {
// 1. 这个矩形, 是一个比例(0.0 - 1.0)
// 2. 这个矩形, 是横屏状态下的矩形
let size = UIScreen.mainScreen().bounds
let x: CGFloat = rect.origin.x / size.width
let y: CGFloat = rect.origin.y / size.height
let w: CGFloat = rect.size.width / size.width
let h: CGFloat = rect.size.height / size.height
output.rectOfInterest = CGRectMake(y, x, h, w)
}
}
extension LBQRCodeTool {
// 扫描二维码的时候添加边框
private func drawQRCodeFrame(codeObj: AVMetadataMachineReadableCodeObject) -> () {
// 绘制边框
// 1. 创建图形的图层
let shapLayer = CAShapeLayer()
shapLayer.fillColor = UIColor.clearColor().CGColor
shapLayer.strokeColor = UIColor.orangeColor().CGColor
shapLayer.lineWidth = 6
// 2. 设置需要显示的图形路径
let corners = codeObj.corners
// 2.1 创建一个路径
let path = UIBezierPath()
var index = 0
// 获取二维码4个角的4个点
for corner in corners {
// 转换成为一个CGPoint
var point = CGPointZero
CGPointMakeWithDictionaryRepresentation((corner as! CFDictionary), &point)
if index == 0 {
path.moveToPoint(point)
}else {
path.addLineToPoint(point)
}
index += 1
}
// 让线闭合
path.closePath()
path.lineWidth = 1
framePath = path
shapLayer.path = path.CGPath
// 3. 添加到需要展示的图层
layer.addSublayer(shapLayer)
}
private func removeQRCodeFrameLayer() -> () {
guard let subLayers = layer.sublayers else { return }
for subLayer in subLayers {
if subLayer.isKindOfClass(CAShapeLayer) {
subLayer.removeFromSuperlayer()
}
}
}
}
// MARK:- 代理方法
extension LBQRCodeTool : AVCaptureMetadataOutputObjectsDelegate {
// 扫描到结果之后, 调用
// 最后一次也会调用
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
if isDraw {
removeQRCodeFrameLayer()
}
var strs = [String]()
for obj in metadataObjects {
// AVMetadataMachineReadableCodeObject, 二维码的数据模型
if obj.isKindOfClass(AVMetadataMachineReadableCodeObject)
{
// 借助layer来转换,,四个角的坐标
let resultObj = layer.transformedMetadataObjectForMetadataObject(obj as! AVMetadataObject)
let codeObj = resultObj as! AVMetadataMachineReadableCodeObject
strs.append(codeObj.stringValue)
// 描绘边框
if isDraw {
drawQRCodeFrame(codeObj)
}
}
}
// 把数组转换成string,进行编码转换
var resultString : String
if strs != [] {
resultString = strs[0]
}else {
resultString = ""
}
if perResult == resultString { return }
// 做判断,防止在一次扫描成功的情况下多次输出同一个结果.扫描成功一次就输出一次.
if scanResultBlock != nil {
if resultString == "" {
perResult = resultString
return
}
let sss = startEncoding(resultString)
scanResultBlock!(resultStrs: sss as String)
}
perResult = resultString
}
}
extension LBQRCodeTool {
func startEncoding(str : String) -> NSString {
var resultStr :NSString?
if str.canBeConvertedToEncoding(NSShiftJISStringEncoding) {
resultStr = NSString(CString: str.cStringUsingEncoding(NSShiftJISStringEncoding)!, encoding: NSUTF8StringEncoding)
//如果转化成utf-8失败,再尝试转化为gbk
if resultStr == nil {
let enc = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
resultStr = NSString(CString: str.cStringUsingEncoding(NSShiftJISStringEncoding)!, encoding: enc)
}
}else if str.canBeConvertedToEncoding(NSISOLatin1StringEncoding) {
resultStr = NSString(CString: str.cStringUsingEncoding(NSISOLatin1StringEncoding)!, encoding: NSUTF8StringEncoding)
//如果转化成utf-8失败,再尝试转化为gbk
if resultStr == nil {
let enc = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
resultStr = NSString(CString: str.cStringUsingEncoding(NSISOLatin1StringEncoding)!, encoding: enc)
}
}
if resultStr == nil {
return str
}
return resultStr!
}
}
| mit | db8dc462d886a3727eb44fd738d18c7d | 27.614155 | 162 | 0.569856 | 4.449059 | false | false | false | false |
collinhundley/APCustomBlurView | Example/Blur/APSpringButton.swift | 1 | 3375 | //
// APSpringButton.swift
// Copyright © 2015 Appsidian. All rights reserved.
//
import UIKit
/// A UIButton subclass that renders a springy animation when tapped.
/// If the damping parameters are set to 1.0, this class may be used to provide subtle feedback to buttons with no elsasticity.
/// - parameter minimumScale: The minimum scale that the button may reach while pressed. Default 0.95
/// - parameter pressSpringDamping: The damping parameter for the spring animation used when the button is pressed. Default 0.4
/// - parameter releaseSpringDamping: The damping parameter for the spring animation used when the button is released. Default 0.35
/// - parameter pressSpringDuration: The duration of the spring animation used when the button is pressed. Default 0.4
/// - parameter releaseSpringDuration: The duration of the spring animation used when the button is reloeased. Default 0.5
public class APSpringButton: UIButton {
public var minimumScale: CGFloat = 0.95
public var pressSpringDamping: CGFloat = 0.4
public var releaseSpringDamping: CGFloat = 0.35
public var pressSpringDuration = 0.4
public var releaseSpringDuration = 0.5
public init() {
super.init(frame: CGRectZero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
UIView.animateWithDuration(self.pressSpringDuration, delay: 0, usingSpringWithDamping: self.pressSpringDamping, initialSpringVelocity: 0, options: [.CurveLinear, .AllowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransformMakeScale(self.minimumScale, self.minimumScale)
}, completion: nil)
}
override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
UIView.animateWithDuration(self.releaseSpringDuration, delay: 0, usingSpringWithDamping: self.releaseSpringDamping, initialSpringVelocity: 0, options: [.CurveLinear, .AllowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransformIdentity
}, completion: nil)
}
override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touches.first!.locationInView(self)
if !CGRectContainsPoint(self.bounds, location) {
UIView.animateWithDuration(self.releaseSpringDuration, delay: 0, usingSpringWithDamping: self.releaseSpringDamping, initialSpringVelocity: 0, options: [.CurveLinear, .AllowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransformIdentity
}, completion: nil)
}
}
override public func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
UIView.animateWithDuration(self.releaseSpringDuration, delay: 0, usingSpringWithDamping: self.releaseSpringDamping, initialSpringVelocity: 0, options: [.CurveLinear, .AllowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransformIdentity
}, completion: nil)
}
} | mit | e27957b9b0bcb89f986043c5ac3334e8 | 54.327869 | 229 | 0.721399 | 5.088989 | false | false | false | false |
lorentey/swift | test/stdlib/ErrorBridged.swift | 2 | 25536 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -o %t/ErrorBridged -DPTR_SIZE_%target-ptrsize -module-name main %s
// RUN: %target-run %t/ErrorBridged
// REQUIRES: executable_test
// REQUIRES: objc_interop
import StdlibUnittest
import Foundation
import CoreLocation
import Darwin
var ErrorBridgingTests = TestSuite("ErrorBridging")
var NoisyErrorLifeCount = 0
var NoisyErrorDeathCount = 0
var CanaryHandle = 0
protocol OtherProtocol {
var otherProperty: String { get }
}
protocol OtherClassProtocol : class {
var otherClassProperty: String { get }
}
class NoisyError : Error, OtherProtocol, OtherClassProtocol {
init() { NoisyErrorLifeCount += 1 }
deinit { NoisyErrorDeathCount += 1 }
let _domain = "NoisyError"
let _code = 123
let otherProperty = "otherProperty"
let otherClassProperty = "otherClassProperty"
}
@objc enum EnumError : Int, Error {
case BadError = 9000
case ReallyBadError = 9001
}
ErrorBridgingTests.test("NSError") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
autoreleasepool {
let ns = NSError(domain: "SomeDomain", code: 321, userInfo: nil)
objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let e: Error = ns
expectEqual(e._domain, "SomeDomain")
expectEqual(e._code, 321)
let ns2 = e as NSError
expectTrue(ns === ns2)
expectEqual(ns2._domain, "SomeDomain")
expectEqual(ns2._code, 321)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorBridgingTests.test("NSCopying") {
autoreleasepool {
let orig = EnumError.ReallyBadError as NSError
let copy = orig.copy() as! NSError
expectEqual(orig, copy)
}
}
// Gated on the availability of NSKeyedArchiver.archivedData(withRootObject:).
@available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)
func archiveAndUnarchiveObject<T: NSCoding>(
_ object: T
) -> T?
where T: NSObject {
let unarchiver = NSKeyedUnarchiver(forReadingWith:
NSKeyedArchiver.archivedData(withRootObject: object)
)
unarchiver.requiresSecureCoding = true
return unarchiver.decodeObject(of: T.self, forKey: "root")
}
ErrorBridgingTests.test("NSCoding") {
if #available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
autoreleasepool {
let orig = EnumError.ReallyBadError as NSError
let unarchived = archiveAndUnarchiveObject(orig)!
expectEqual(orig, unarchived)
expectTrue(type(of: unarchived) == NSError.self)
}
}
}
ErrorBridgingTests.test("NSError-to-enum bridging") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
let testURL = URL(string: "https://swift.org")!
autoreleasepool {
let underlyingError = CocoaError(.fileLocking)
as Error as NSError
let ns = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: [
NSFilePathErrorKey: "/dev/null",
NSStringEncodingErrorKey: /*ASCII=*/1,
NSUnderlyingErrorKey: underlyingError,
NSURLErrorKey: testURL
])
objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let e: Error = ns
let cocoaCode: Int?
switch e {
case let x as CocoaError:
cocoaCode = x._code
expectTrue(x.isFileError)
expectEqual(x.code, .fileNoSuchFile)
default:
cocoaCode = nil
}
expectEqual(NSFileNoSuchFileError, cocoaCode)
let cocoaCode2: Int? = (ns as? CocoaError)?._code
expectEqual(NSFileNoSuchFileError, cocoaCode2)
let isNoSuchFileError: Bool
switch e {
case CocoaError.fileNoSuchFile:
isNoSuchFileError = true
default:
isNoSuchFileError = false
}
expectTrue(isNoSuchFileError)
// Check the contents of the error.
let cocoaError = e as! CocoaError
expectEqual("/dev/null", cocoaError.filePath)
expectEqual(String.Encoding.ascii, cocoaError.stringEncoding)
expectEqual(underlyingError, cocoaError.underlying.map { $0 as NSError })
expectEqual(testURL, cocoaError.url)
// URLError domain
let nsURL = NSError(domain: NSURLErrorDomain,
code: NSURLErrorBadURL,
userInfo: [NSURLErrorFailingURLErrorKey: testURL])
let eURL: Error = nsURL
let isBadURLError: Bool
switch eURL {
case URLError.badURL:
isBadURLError = true
default:
isBadURLError = false
}
expectTrue(isBadURLError)
let urlError = eURL as! URLError
expectEqual(testURL, urlError.failingURL)
expectNil(urlError.failureURLPeerTrust)
// CoreLocation error domain
let nsCL = NSError(domain: kCLErrorDomain,
code: CLError.headingFailure.rawValue,
userInfo: [NSURLErrorKey: testURL])
let eCL: Error = nsCL
let isHeadingFailure: Bool
switch eCL {
case CLError.headingFailure:
isHeadingFailure = true
default:
isHeadingFailure = false
}
let isCLError: Bool
switch eCL {
case let error as CLError:
isCLError = true
expectEqual(testURL, (error as NSError).userInfo[NSURLErrorKey] as? URL)
expectEqual(testURL, error.userInfo[NSURLErrorKey] as? URL)
default:
isCLError = false
}
expectTrue(isCLError)
// NSPOSIXError domain
let nsPOSIX = NSError(domain: NSPOSIXErrorDomain,
code: Int(EDEADLK),
userInfo: [:])
let ePOSIX: Error = nsPOSIX
let isDeadlock: Bool
switch ePOSIX {
case POSIXError.EDEADLK:
isDeadlock = true
default:
isDeadlock = false
}
expectTrue(isDeadlock)
// NSMachError domain
let nsMach = NSError(domain: NSMachErrorDomain,
code: Int(KERN_MEMORY_FAILURE),
userInfo: [:])
let eMach: Error = nsMach
let isMemoryFailure: Bool
switch eMach {
case MachError.memoryFailure:
isMemoryFailure = true
default:
isMemoryFailure = false
}
expectTrue(isMemoryFailure)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
func opaqueUpcastToAny<T>(_ x: T) -> Any {
return x
}
struct StructError: Error {
var _domain: String { return "StructError" }
var _code: Int { return 4812 }
}
ErrorBridgingTests.test("Error-to-NSError bridging") {
NoisyErrorLifeCount = 0
NoisyErrorDeathCount = 0
autoreleasepool {
let e: Error = NoisyError()
let ns = e as NSError
let ns2 = e as NSError
expectTrue(ns === ns2)
expectEqual(ns._domain, "NoisyError")
expectEqual(ns._code, 123)
let e3: Error = ns
expectEqual(e3._domain, "NoisyError")
expectEqual(e3._code, 123)
let ns3 = e3 as NSError
expectTrue(ns === ns3)
let nativeNS = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: nil)
objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
let nativeE: Error = nativeNS
let nativeNS2 = nativeE as NSError
expectTrue(nativeNS === nativeNS2)
expectEqual(nativeNS2._domain, NSCocoaErrorDomain)
expectEqual(nativeNS2._code, NSFileNoSuchFileError)
let any: Any = NoisyError()
let ns4 = any as! NSError
expectEqual(ns4._domain, "NoisyError")
expectEqual(ns4._code, 123)
let ao: AnyObject = NoisyError()
let ns5 = ao as! NSError
expectEqual(ns5._domain, "NoisyError")
expectEqual(ns5._code, 123)
let any2: Any = StructError()
let ns6 = any2 as! NSError
expectEqual(ns6._domain, "StructError")
expectEqual(ns6._code, 4812)
}
expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount)
}
ErrorBridgingTests.test("NSError-to-error bridging in bridged container") {
autoreleasepool {
let error = NSError(domain: "domain", code: 42, userInfo: nil)
let nsdictionary = ["error": error] as NSDictionary
let dictionary = nsdictionary as? Dictionary<String, Error>
expectNotNil(dictionary)
expectEqual(error, dictionary?["error"] as NSError?)
}
}
ErrorBridgingTests.test("enum-to-NSError round trip") {
autoreleasepool {
// Emulate throwing an error from Objective-C.
func throwNSError(_ error: EnumError) throws {
throw NSError(domain: "main.EnumError", code: error.rawValue,
userInfo: [:])
}
var caughtError: Bool
caughtError = false
do {
try throwNSError(.BadError)
expectUnreachable()
} catch let error as EnumError {
expectEqual(.BadError, error)
caughtError = true
} catch _ {
expectUnreachable()
}
expectTrue(caughtError)
caughtError = false
do {
try throwNSError(.ReallyBadError)
expectUnreachable()
} catch EnumError.BadError {
expectUnreachable()
} catch EnumError.ReallyBadError {
caughtError = true
} catch _ {
expectUnreachable()
}
expectTrue(caughtError)
}
}
class SomeNSErrorSubclass: NSError {}
ErrorBridgingTests.test("Thrown NSError identity is preserved") {
do {
let e = NSError(domain: "ClericalError", code: 219,
userInfo: ["yeah": "yeah"])
do {
throw e
} catch let e2 as NSError {
expectTrue(e === e2)
expectTrue(e2.userInfo["yeah"] as? String == "yeah")
} catch {
expectUnreachable()
}
}
do {
let f = SomeNSErrorSubclass(domain: "ClericalError", code: 219,
userInfo: ["yeah": "yeah"])
do {
throw f
} catch let f2 as NSError {
expectTrue(f === f2)
expectTrue(f2.userInfo["yeah"] as? String == "yeah")
} catch {
expectUnreachable()
}
}
}
// Check errors customized via protocol.
struct MyCustomizedError : Error {
let code: Int
}
extension MyCustomizedError : LocalizedError {
var errorDescription: String? {
return NSLocalizedString("something went horribly wrong", comment: "")
}
var failureReason: String? {
return NSLocalizedString("because someone wrote 'throw'", comment: "")
}
var recoverySuggestion: String? {
return NSLocalizedString("delete the 'throw'", comment: "")
}
var helpAnchor: String? {
return NSLocalizedString("there is no help when writing tests", comment: "")
}
}
extension MyCustomizedError : CustomNSError {
static var errorDomain: String {
return "custom"
}
/// The error code within the given domain.
var errorCode: Int {
return code
}
/// The user-info dictionary.
var errorUserInfo: [String : Any] {
return [NSURLErrorKey : URL(string: "https://swift.org")!]
}
}
extension MyCustomizedError : RecoverableError {
var recoveryOptions: [String] {
return ["Delete 'throw'", "Disable the test" ]
}
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool {
return recoveryOptionIndex == 0
}
}
/// An error type that provides localization and recovery, but doesn't
/// customize NSError directly.
enum MySwiftCustomizedError : Error {
case failed
static var errorDescriptionCount = 0
}
extension MySwiftCustomizedError : LocalizedError {
var errorDescription: String? {
MySwiftCustomizedError.errorDescriptionCount =
MySwiftCustomizedError.errorDescriptionCount + 1
return NSLocalizedString("something went horribly wrong", comment: "")
}
var failureReason: String? {
return NSLocalizedString("because someone wrote 'throw'", comment: "")
}
var recoverySuggestion: String? {
return NSLocalizedString("delete the 'throw'", comment: "")
}
var helpAnchor: String? {
return NSLocalizedString("there is no help when writing tests", comment: "")
}
}
extension MySwiftCustomizedError : RecoverableError {
var recoveryOptions: [String] {
return ["Delete 'throw'", "Disable the test" ]
}
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool {
return recoveryOptionIndex == 0
}
}
/// Fake definition of the informal protocol
/// "NSErrorRecoveryAttempting" that we use to poke at the object
/// produced for a RecoverableError.
@objc protocol FakeNSErrorRecoveryAttempting {
@objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:)
func attemptRecovery(fromError nsError: Error,
optionIndex recoveryOptionIndex: Int,
delegate: AnyObject?,
didRecoverSelector: Selector,
contextInfo: UnsafeMutableRawPointer?)
@objc(attemptRecoveryFromError:optionIndex:)
func attemptRecovery(fromError nsError: Error,
optionIndex recoveryOptionIndex: Int) -> Bool
}
class RecoveryDelegate {
let expectedSuccess: Bool
let expectedContextInfo: UnsafeMutableRawPointer?
var called = false
init(expectedSuccess: Bool,
expectedContextInfo: UnsafeMutableRawPointer?) {
self.expectedSuccess = expectedSuccess
self.expectedContextInfo = expectedContextInfo
}
@objc func recover(success: Bool, contextInfo: UnsafeMutableRawPointer?) {
expectEqual(expectedSuccess, success)
expectEqual(expectedContextInfo, contextInfo)
called = true
}
}
/// Helper for testing a customized error.
func testCustomizedError(error: Error, nsError: NSError) {
// LocalizedError
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSLocalizedDescriptionKey])
expectNil(nsError.userInfo[NSLocalizedFailureReasonErrorKey])
expectNil(nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey])
expectNil(nsError.userInfo[NSHelpAnchorErrorKey])
} else {
expectEqual("something went horribly wrong",
nsError.userInfo[NSLocalizedDescriptionKey] as? String)
expectEqual("because someone wrote 'throw'",
nsError.userInfo[NSLocalizedFailureReasonErrorKey] as? String)
expectEqual("delete the 'throw'",
nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String)
expectEqual("there is no help when writing tests",
nsError.userInfo[NSHelpAnchorErrorKey] as? String)
}
expectEqual("something went horribly wrong", error.localizedDescription)
expectEqual("something went horribly wrong", nsError.localizedDescription)
expectEqual("because someone wrote 'throw'", nsError.localizedFailureReason)
expectEqual("delete the 'throw'", nsError.localizedRecoverySuggestion)
expectEqual("there is no help when writing tests", nsError.helpAnchor)
// RecoverableError
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey])
} else {
expectEqual(["Delete 'throw'", "Disable the test" ],
nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String])
}
expectEqual(["Delete 'throw'", "Disable the test" ],
nsError.localizedRecoveryOptions)
// Directly recover.
let ctx = UnsafeMutableRawPointer(bitPattern:0x1234567)
let attempter: AnyObject
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSRecoveryAttempterErrorKey])
attempter = nsError.recoveryAttempter! as AnyObject
} else {
attempter = nsError.userInfo[NSRecoveryAttempterErrorKey]! as AnyObject
}
expectEqual(attempter.attemptRecovery(fromError: nsError, optionIndex: 0), true)
expectEqual(attempter.attemptRecovery(fromError: nsError, optionIndex: 1), false)
// Recover through delegate.
let rd1 = RecoveryDelegate(expectedSuccess: true, expectedContextInfo: ctx)
expectEqual(false, rd1.called)
attempter.attemptRecovery(
fromError: nsError,
optionIndex: 0,
delegate: rd1,
didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)),
contextInfo: ctx)
expectEqual(true, rd1.called)
let rd2 = RecoveryDelegate(expectedSuccess: false, expectedContextInfo: nil)
expectEqual(false, rd2.called)
attempter.attemptRecovery(
fromError: nsError,
optionIndex: 1,
delegate: rd2,
didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)),
contextInfo: nil)
expectEqual(true, rd2.called)
}
ErrorBridgingTests.test("Customizing NSError via protocols") {
let error = MyCustomizedError(code: 12345)
let nsError = error as NSError
// CustomNSError
expectEqual("custom", nsError.domain)
expectEqual(12345, nsError.code)
expectEqual(URL(string: "https://swift.org"),
nsError.userInfo[NSURLErrorKey] as? URL)
testCustomizedError(error: error, nsError: nsError)
}
ErrorBridgingTests.test("Customizing localization/recovery via protocols") {
let error = MySwiftCustomizedError.failed
let nsError = error as NSError
testCustomizedError(error: error, nsError: nsError)
}
ErrorBridgingTests.test("Customizing localization/recovery laziness") {
let countBefore = MySwiftCustomizedError.errorDescriptionCount
let error = MySwiftCustomizedError.failed
let nsError = error as NSError
// RecoverableError
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey])
} else {
expectEqual(["Delete 'throw'", "Disable the test" ],
nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String])
}
expectEqual(["Delete 'throw'", "Disable the test" ], nsError.localizedRecoveryOptions)
// None of the operations above should affect the count
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectEqual(countBefore, MySwiftCustomizedError.errorDescriptionCount)
}
// This one does affect the count.
expectEqual("something went horribly wrong", error.localizedDescription)
// Check that we did get a call to errorDescription.
if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) {
expectEqual(countBefore+1, MySwiftCustomizedError.errorDescriptionCount)
}
}
enum DefaultCustomizedError1 : CustomNSError {
case bad
case worse
}
enum DefaultCustomizedError2 : Int, CustomNSError {
case bad = 7
case worse = 13
}
enum DefaultCustomizedError3 : UInt, CustomNSError {
case bad = 9
case worse = 115
#if PTR_SIZE_64
case dreadful = 0xFFFFFFFFFFFFFFFF
#elseif PTR_SIZE_32
case dreadful = 0xFFFFFFFF
#else
#error ("Unknown pointer size")
#endif
static var errorDomain: String {
return "customized3"
}
}
enum DefaultCustomizedParent {
enum ChildError: CustomNSError {
case foo
}
}
ErrorBridgingTests.test("Default-customized via CustomNSError") {
expectEqual(1, (DefaultCustomizedError1.worse as NSError).code)
expectEqual(13, (DefaultCustomizedError2.worse as NSError).code)
expectEqual(115, (DefaultCustomizedError3.worse as NSError).code)
expectEqual(-1, (DefaultCustomizedError3.dreadful as NSError).code)
expectEqual("main.DefaultCustomizedError1", (DefaultCustomizedError1.worse as NSError).domain)
expectEqual("customized3", (DefaultCustomizedError3.worse as NSError).domain)
expectEqual("main.DefaultCustomizedParent.ChildError", (DefaultCustomizedParent.ChildError.foo as NSError).domain)
}
class MyNSError : NSError { }
ErrorBridgingTests.test("NSError subclass identity") {
let myNSError: Error = MyNSError(domain: "MyNSError", code: 0, userInfo: [:])
let nsError = myNSError as NSError
expectTrue(type(of: nsError) == MyNSError.self)
}
ErrorBridgingTests.test("Wrapped NSError identity") {
let nsError = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: [
NSFilePathErrorKey : "/dev/null",
NSStringEncodingErrorKey : /*ASCII=*/1,
])
let error: Error = nsError
let nsError2: NSError = error as NSError
expectTrue(nsError === nsError2)
// Extracting the NSError via the runtime.
let cocoaErrorAny: Any = error as! CocoaError
let nsError3: NSError = cocoaErrorAny as! NSError
expectTrue(nsError === nsError3)
if let cocoaErrorAny2: Any = error as? CocoaError {
let nsError4: NSError = cocoaErrorAny2 as! NSError
expectTrue(nsError === nsError4)
} else {
expectUnreachable()
}
// Extracting the NSError via direct call.
let cocoaError = error as! CocoaError
let nsError5: NSError = cocoaError as NSError
expectTrue(nsError === nsError5)
if error is CocoaError {
let nsError6: NSError = cocoaError as NSError
expectTrue(nsError === nsError6)
} else {
expectUnreachable()
}
}
extension Error {
func asNSError() -> NSError {
return self as NSError
}
}
func unconditionalCast<T>(_ x: Any, to: T.Type) -> T {
return x as! T
}
func conditionalCast<T>(_ x: Any, to: T.Type) -> T? {
return x as? T
}
// SR-1562
ErrorBridgingTests.test("Error archetype identity") {
let myError = NSError(domain: "myErrorDomain", code: 0,
userInfo: [ "one" : 1 ])
expectTrue(myError === myError.asNSError())
expectTrue(unconditionalCast(myError, to: Error.self) as NSError
=== myError)
expectTrue(conditionalCast(myError, to: Error.self)! as NSError
=== myError)
let nsError = NSError(domain: NSCocoaErrorDomain,
code: NSFileNoSuchFileError,
userInfo: [
NSFilePathErrorKey : "/dev/null",
NSStringEncodingErrorKey : /*ASCII=*/1,
])
let cocoaError = nsError as Error as! CocoaError
expectTrue(cocoaError.asNSError() === nsError)
expectTrue(unconditionalCast(cocoaError, to: Error.self) as NSError
=== nsError)
expectTrue(conditionalCast(cocoaError, to: Error.self)! as NSError
=== nsError)
}
// SR-9389
class ParentA: NSObject {
@objc(ParentAError) enum Error: Int, Swift.Error {
case failed
}
}
class ParentB: NSObject {
@objc(ParentBError) enum Error: Int, Swift.Error {
case failed
}
}
private class NonPrintAsObjCClass: NSObject {
@objc enum Error: Int, Swift.Error {
case foo
}
}
@objc private enum NonPrintAsObjCError: Int, Error {
case bar
}
ErrorBridgingTests.test("@objc error domains for nested types") {
// Domain strings should correspond to Swift types, including parent types.
expectEqual(ParentA.Error.failed._domain, "main.ParentA.Error")
expectEqual(ParentB.Error.failed._domain, "main.ParentB.Error")
func makeNSError(like error: Error) -> NSError {
return NSError(domain: error._domain, code: error._code)
}
// NSErrors corresponding to Error types with the same name but nested in
// different enclosing types should not be castable to the wrong error type.
expectTrue(makeNSError(like: ParentA.Error.failed) is ParentA.Error)
expectFalse(makeNSError(like: ParentA.Error.failed) is ParentB.Error)
expectFalse(makeNSError(like: ParentB.Error.failed) is ParentA.Error)
expectTrue(makeNSError(like: ParentB.Error.failed) is ParentB.Error)
// If an @objc enum error is not eligible for PrintAsObjC, we should treat it
// as though it inherited the default implementation, which calls
// String(reflecting:).
expectEqual(NonPrintAsObjCClass.Error.foo._domain,
String(reflecting: NonPrintAsObjCClass.Error.self))
expectEqual(NonPrintAsObjCError.bar._domain,
String(reflecting: NonPrintAsObjCError.self))
}
ErrorBridgingTests.test("error-to-NSObject casts") {
let error = MyCustomizedError(code: 12345)
if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) {
// Unconditional cast
let nsErrorAsObject1 = unconditionalCast(error, to: NSObject.self)
let nsError1 = unconditionalCast(nsErrorAsObject1, to: NSError.self)
expectEqual("custom", nsError1.domain)
expectEqual(12345, nsError1.code)
// Conditional cast
let nsErrorAsObject2 = conditionalCast(error, to: NSObject.self)!
let nsError2 = unconditionalCast(nsErrorAsObject2, to: NSError.self)
expectEqual("custom", nsError2.domain)
expectEqual(12345, nsError2.code)
// "is" check
expectTrue(error is NSObject)
// Unconditional cast to a dictionary.
let dict = ["key" : NoisyError()]
let anyOfDict = dict as AnyObject
let dict2 = anyOfDict as! [String: NSObject]
}
}
// SR-7732: Casting CFError or NSError to Error results in a memory leak
ErrorBridgingTests.test("NSError-to-Error casts") {
func should_not_leak_nserror() {
let something: Any? = NSError(domain: "Foo", code: 1)
expectTrue(something is Error)
}
if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) {
// TODO: Wrap some leak checking around this
// Until then, this is a helpful debug tool
should_not_leak_nserror()
}
}
ErrorBridgingTests.test("CFError-to-Error casts") {
func should_not_leak_cferror() {
let something: Any? = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainCocoa, 1, [:] as CFDictionary)
expectTrue(something is Error)
}
if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) {
// TODO: Wrap some leak checking around this
// Until then, this is a helpful debug tool
should_not_leak_cferror()
}
}
enum MyError: Error {
case someThing
}
ErrorBridgingTests.test("SR-9207 crash in failed cast to NSError") {
if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) {
let error = MyError.someThing
let foundationError = error as NSError
if let urlError = foundationError as? URLError {
expectUnreachable()
}
}
}
runAllTests()
| apache-2.0 | 335685fc8cedc817960d40d1342b41c1 | 29.436234 | 116 | 0.691925 | 4.302612 | false | true | false | false |
ringohub/swift-todo | ToDo/AppDelegate.swift | 1 | 5710 | import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
MagicalRecord.setupCoreDataStack(withAutoMigratingSqliteStoreNamed: "ToDo.sqlite")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
MagicalRecord.cleanUp()
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.ringohub.ToDo" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "ToDo", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("ToDo.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext!.hasChanges {
do {
try managedObjectContext!.save()
} catch {
let nserror = error as NSError
NSLog("Unresolved error \(error), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 84cb0b88a40e2d3e3ab8f8f180d58422 | 52.867925 | 288 | 0.742207 | 5.698603 | false | false | false | false |
PjGeeroms/IOSRecipeDB | Pods/Diff/Sources/Diff+UIKit.swift | 2 | 18495 | #if !os(macOS) && !os(watchOS)
import UIKit
struct BatchUpdate {
let deletions: [IndexPath]
let insertions: [IndexPath]
let moves: [(from: IndexPath, to: IndexPath)]
init(diff: ExtendedDiff) {
deletions = diff.flatMap { element -> IndexPath? in
switch element {
case .delete(let at):
return IndexPath(row: at, section: 0)
default: return nil
}
}
insertions = diff.flatMap { element -> IndexPath? in
switch element {
case .insert(let at):
return IndexPath(row: at, section: 0)
default: return nil
}
}
moves = diff.flatMap { element -> (IndexPath, IndexPath)? in
switch element {
case let .move(from, to):
return (IndexPath(row: from, section: 0), IndexPath(row: to, section: 0))
default: return nil
}
}
}
}
struct NestedBatchUpdate {
let itemDeletions: [IndexPath]
let itemInsertions: [IndexPath]
let itemMoves: [(from: IndexPath, to: IndexPath)]
let sectionDeletions: IndexSet
let sectionInsertions: IndexSet
let sectionMoves: [(from: Int, to: Int)]
init(diff: NestedExtendedDiff) {
var itemDeletions: [IndexPath] = []
var itemInsertions: [IndexPath] = []
var itemMoves: [(IndexPath, IndexPath)] = []
var sectionDeletions: IndexSet = []
var sectionInsertions: IndexSet = []
var sectionMoves: [(from: Int, to: Int)] = []
diff.forEach { element in
switch element {
case let .deleteElement(at, section):
itemDeletions.append(IndexPath(item: at, section: section))
case let .insertElement(at, section):
itemInsertions.append(IndexPath(item: at, section: section))
case let .moveElement(from, to):
itemMoves.append((IndexPath(item: from.item, section: from.section), IndexPath(item: to.item, section: to.section)))
case let .deleteSection(at):
sectionDeletions.insert(at)
case let .insertSection(at):
sectionInsertions.insert(at)
case let .moveSection(move):
sectionMoves.append(move)
}
}
self.itemInsertions = itemInsertions
self.itemDeletions = itemDeletions
self.itemMoves = itemMoves
self.sectionMoves = sectionMoves
self.sectionInsertions = sectionInsertions
self.sectionDeletions = sectionDeletions
}
}
public extension UITableView {
/// Animates rows which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateRowChanges<T: Collection>(
oldData: T,
newData: T,
deletionAnimation: UITableViewRowAnimation = .automatic,
insertionAnimation: UITableViewRowAnimation = .automatic
) where T.Iterator.Element: Equatable {
apply(
oldData.extendedDiff(newData),
deletionAnimation: deletionAnimation,
insertionAnimation: insertionAnimation
)
}
/// Animates rows which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter isEqual: A function comparing two elements of `T`
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateRowChanges<T: Collection>(
oldData: T,
newData: T,
// https://twitter.com/dgregor79/status/570068545561735169
isEqual: (EqualityChecker<T>),
deletionAnimation: UITableViewRowAnimation = .automatic,
insertionAnimation: UITableViewRowAnimation = .automatic
) {
apply(
oldData.extendedDiff(newData, isEqual: isEqual),
deletionAnimation: deletionAnimation,
insertionAnimation: insertionAnimation
)
}
private func apply(
_ diff: ExtendedDiff,
deletionAnimation: UITableViewRowAnimation = .automatic,
insertionAnimation: UITableViewRowAnimation = .automatic
) {
let update = BatchUpdate(diff: diff)
beginUpdates()
deleteRows(at: update.deletions, with: deletionAnimation)
insertRows(at: update.insertions, with: insertionAnimation)
update.moves.forEach { moveRow(at: $0.from, to: $0.to) }
endUpdates()
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(to: newData),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`) /// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
// https://twitter.com/dgregor79/status/570068545561735169
isEqualElement: (NestedElementEqualityChecker<T>),
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualElement: isEqualElement
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter insertionAnimation: Animation type for insertions
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
// https://twitter.com/dgregor79/status/570068545561735169
isEqualSection: (EqualityChecker<T>),
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic
)
where T.Iterator.Element: Collection,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableVie
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
// https://twitter.com/dgregor79/status/570068545561735169
isEqualElement: (NestedElementEqualityChecker<T>),
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic
)
where T.Iterator.Element: Collection {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection,
isEqualElement: isEqualElement
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation
)
}
public func apply(
_ diff: NestedExtendedDiff,
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic
) {
let update = NestedBatchUpdate(diff: diff)
beginUpdates()
deleteRows(at: update.itemDeletions, with: rowDeletionAnimation)
insertRows(at: update.itemInsertions, with: rowInsertionAnimation)
update.itemMoves.forEach { moveRow(at: $0.from, to: $0.to) }
deleteSections(update.sectionDeletions, with: sectionDeletionAnimation)
insertSections(update.sectionInsertions, with: sectionInsertionAnimation)
update.sectionMoves.forEach { moveSection($0.from, toSection: $0.to) }
endUpdates()
}
}
public extension UICollectionView {
/// Animates items which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
public func animateItemChanges<T: Collection>(
oldData: T,
newData: T,
completion: ((Bool) -> Void)? = nil
) where T.Iterator.Element: Equatable {
let diff = oldData.extendedDiff(newData)
apply(diff, completion: completion)
}
/// Animates items which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter isEqual: A function comparing two elements of `T`
public func animateItemChanges<T: Collection>(
oldData: T,
newData: T,
isEqual: EqualityChecker<T>,
completion: ((Bool) -> Swift.Void)? = nil
) {
let diff = oldData.extendedDiff(newData, isEqual: isEqual)
apply(diff, completion: completion)
}
public func apply(
_ diff: ExtendedDiff,
completion: ((Bool) -> Swift.Void)? = nil
) {
performBatchUpdates({
let update = BatchUpdate(diff: diff)
self.deleteItems(at: update.deletions)
self.insertItems(at: update.insertions)
update.moves.forEach { self.moveItem(at: $0.from, to: $0.to) }
}, completion: completion)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(to: newData),
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualElement: NestedElementEqualityChecker<T>,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualElement: isEqualElement
),
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection
),
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of UITableView
/// - parameter newData: Data which reflects the current state of UITableView
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
isEqualElement: NestedElementEqualityChecker<T>,
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection,
isEqualElement: isEqualElement
),
completion: completion
)
}
public func apply(
_ diff: NestedExtendedDiff,
completion: ((Bool) -> Void)? = nil
) {
performBatchUpdates({
let update = NestedBatchUpdate(diff: diff)
self.insertSections(update.sectionInsertions)
self.deleteSections(update.sectionDeletions)
update.sectionMoves.forEach { self.moveSection($0.from, toSection: $0.to) }
self.deleteItems(at: update.itemDeletions)
self.insertItems(at: update.itemInsertions)
update.itemMoves.forEach { self.moveItem(at: $0.from, to: $0.to) }
}, completion: completion)
}
}
#endif
| mit | 6d8560194fe08080fecd07b974d1dea5 | 42.212617 | 173 | 0.63136 | 5.747359 | false | false | false | false |
dnadri/SwiftStructures | SwiftTests/GraphTest.swift | 11 | 4877 | //
// GraphsTest.swift
// SwiftStructures
//
// Created by Wayne Bishop on 9/19/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import UIKit
import XCTest
@testable import SwiftStructures
/*
unit test cases specific to graph algorithms
to test your own graph, replace the vertices and edges.
*/
class GraphTest: XCTestCase {
var testGraph: SwiftGraph = SwiftGraph()
var vertexA: Vertex!
var vertexB: Vertex!
var vertexC: Vertex!
var vertexD: Vertex!
var vertexE: Vertex!
//called before each test invocation
override func setUp() {
super.setUp()
/* build the vertices */
vertexA = testGraph.addVertex(key: "A")
vertexB = testGraph.addVertex(key: "B")
vertexC = testGraph.addVertex(key: "C")
vertexD = testGraph.addVertex(key: "D")
vertexE = testGraph.addVertex(key: "E")
/* connect the vertices with weighted edges */
testGraph.addEdge(source: vertexA, neighbor: vertexD, weight: 4)
testGraph.addEdge(source: vertexA, neighbor: vertexB, weight: 1)
testGraph.addEdge(source: vertexB, neighbor: vertexD, weight: 5)
testGraph.addEdge(source: vertexB, neighbor: vertexC, weight: 2)
testGraph.addEdge(source: vertexD, neighbor: vertexE, weight: 8)
}
//validate neighbor association
func testVertexNeighbors() {
neighborTest(vertexA, neighbor: vertexD)
neighborTest(vertexA, neighbor: vertexB)
neighborTest(vertexB, neighbor: vertexD)
neighborTest(vertexB, neighbor: vertexC)
neighborTest(vertexD, neighbor: vertexE)
}
//find the shortest path using heapsort operations - O(1)
func testDijkstraWithHeaps() {
let sourceVertex = vertexA
let destinationVertex = vertexE
let shortestPath: Path! = testGraph.processDijkstraWithHeap(sourceVertex, destination: destinationVertex)
XCTAssertNotNil(shortestPath, "shortest path not found..")
printPath(shortestPath)
}
//find the shortest path based on two non-negative edge weights - O(n)
func testDijkstra() {
let sourceVertex = vertexA
let destinationVertex = vertexE
let shortestPath: Path! = testGraph.processDijkstra(sourceVertex, destination: destinationVertex)
XCTAssertNotNil(shortestPath, "shortest path not found..")
printPath(shortestPath)
}
//MARK: Closures and traversals
//breadth-first search
func testBFSTraverse() {
testGraph.traverse(vertexA)
}
//breadth-first search with function
func testBFSTraverseFunction() {
testGraph.traverse(vertexA, formula: traverseFormula)
}
//breadth-first search with closure expression
func testBFSTraverseExpression() {
/*
notes: the inout parameter is passed by reference.
As a result, no return type is required. Also note the trailing closure syntax.
*/
testGraph.traverse(vertexA) { (inout node: Vertex) -> () in
node.visited = true
print("traversed vertex: \(node.key!)..")
}
}
//closure function passed as parameter
func traverseFormula(inout node: Vertex) -> () {
/*
notes: the inout parameter is passed by reference.
As a result, no return type is required.
*/
node.visited = true
print("traversed vertex: \(node.key!)..")
}
//MARK: - Helper function
//check for neighbor membership
func neighborTest(source: Vertex, neighbor: Vertex) -> Bool! {
//add unvisited vertices to the queue
for e in source.neighbors {
if (e.neighbor.key == neighbor.key) {
return true
}
}
XCTFail("vertex \(neighbor.key!) is not a neighbor of vertex \(source.key!)")
return nil
}
//reverse a path data structure
func printPath(shortestPath: Path!) {
var reversedPath: Path! = Path()
var current: Path! = Path()
//reverse the sequence of paths
reversedPath = testGraph.reversePath(shortestPath, source: vertexA)
current = reversedPath
//iterate and print each path sequence
while (current != nil) {
print("The path is : \(current.destination.key!) with a total of : \(current.total)..")
current = current.previous
}
}
} //end class
| mit | 275a8a7d899586094ec437a926716e65 | 23.756345 | 113 | 0.58335 | 4.725775 | false | true | false | false |
obrichak/discounts | discounts/Classes/BarCodeGenerator/RSCodeReaderViewController.swift | 1 | 4885 | //
// RSCodeReaderViewController.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/12/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
import AVFoundation
class RSCodeReaderViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let session = AVCaptureSession()
let focusMarkLayer = RSFocusMarkLayer()
let cornersLayer = RSCornersLayer()
var layer: AVCaptureVideoPreviewLayer?
var tapHandler: ((CGPoint) -> Void)?
var barcodesHandler: ((Array<AVMetadataMachineReadableCodeObject>) -> Void)?
func tap(gesture: UITapGestureRecognizer) {
let tapPoint = gesture.locationInView(self.view)
let focusPoint = CGPointMake(
tapPoint.x / self.view.bounds.size.width,
tapPoint.y / self.view.bounds.size.height)
if device == nil
|| !device.focusPointOfInterestSupported
|| !device.isFocusModeSupported(.AutoFocus) {
return
} else if device.lockForConfiguration(nil) {
device.focusPointOfInterest = focusPoint
device.focusMode = .AutoFocus
device.unlockForConfiguration()
focusMarkLayer.point = tapPoint
if tapHandler != nil {
tapHandler!(tapPoint)
}
}
}
func appWillEnterForeground() {
session.startRunning()
}
func appDidEnterBackground() {
session.stopRunning()
}
override func viewDidLoad() {
super.viewDidLoad()
var error : NSError?
let input = AVCaptureDeviceInput(device: device, error: &error)
if error != nil {
println(error!.description)
return
}
if session.canAddInput(input) {
session.addInput(input)
}
layer = AVCaptureVideoPreviewLayer(session: session)
layer!.videoGravity = AVLayerVideoGravityResizeAspectFill
layer!.frame = self.view.bounds
self.view.layer.addSublayer(layer!)
let output = AVCaptureMetadataOutput()
let queue = dispatch_queue_create("com.pdq.rsbarcodes.metadata", DISPATCH_QUEUE_CONCURRENT)
output.setMetadataObjectsDelegate(self, queue: queue)
if session.canAddOutput(output) {
session.addOutput(output)
output.metadataObjectTypes = output.availableMetadataObjectTypes
}
let gesture = UITapGestureRecognizer(target: self, action: "tap:")
self.view.addGestureRecognizer(gesture)
focusMarkLayer.frame = self.view.bounds
self.view.layer.addSublayer(focusMarkLayer)
cornersLayer.frame = self.view.bounds
self.view.layer.addSublayer(cornersLayer)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "appWillEnterForeground", name:UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "appDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
session.startRunning()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil)
session.stopRunning()
}
// AVCaptureMetadataOutputObjectsDelegate
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
var barcodeObjects : Array<AVMetadataMachineReadableCodeObject> = []
var cornersArray : Array<[AnyObject]> = []
for metadataObject : AnyObject in metadataObjects {
let transformedMetadataObject = layer!.transformedMetadataObjectForMetadataObject(metadataObject as AVMetadataObject)
if transformedMetadataObject.isKindOfClass(AVMetadataMachineReadableCodeObject.self) {
let barcodeObject = transformedMetadataObject as AVMetadataMachineReadableCodeObject
barcodeObjects.append(barcodeObject)
cornersArray.append(barcodeObject.corners)
}
}
cornersLayer.cornersArray = cornersArray
if barcodeObjects.count > 0 && barcodesHandler != nil {
barcodesHandler!(barcodeObjects)
}
}
}
| gpl-3.0 | 33601fee63fca5a6cc218e6fe4e7e9a1 | 36.576923 | 162 | 0.662231 | 5.921212 | false | false | false | false |
esttorhe/MammutAPI | Tests/MammutAPITests/Mocks/MockURLSession.swift | 1 | 729 | //
// Created by Esteban Torres on 10/04/2017.
// Copyright (c) 2017 Esteban Torres. All rights reserved.
//
import Foundation
@testable import MammutAPI
internal class MockURLSession: DataTaskCreating {
var didCallDataTask = false
var dataTask: DataTask? = nil
var completion: DataTaskCreating.CompletionHandler? = nil
var dataTaskArgs: ((URLRequest, (Data?, URLResponse?, Error?) -> Void) -> Void)? = nil
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTask {
dataTaskArgs?(request, completionHandler)
completion = completionHandler
didCallDataTask = true
return dataTask ?? URLSessionDataTask()
}
}
| mit | d81205cb1ff7abb377d3b90b95d1190c | 32.136364 | 125 | 0.702332 | 4.703226 | false | false | false | false |
ioscreator/ioscreator | IOS12SceneKitTutorial/IOS12SceneKitTutorial/MyScene.swift | 1 | 2749 | //
// MyScene.swift
// IOS12SceneKitTutorial
//
// Created by Arthur Knopper on 26/08/2018.
// Copyright © 2018 Arthur Knopper. All rights reserved.
//
import UIKit
import SceneKit
class MyScene: SCNScene {
override init() {
super.init()
let plane = SCNPlane(width: 1.0, height: 1.0)
plane.firstMaterial?.diffuse.contents = UIColor.blue
let planeNode = SCNNode(geometry: plane)
rootNode.addChildNode(planeNode)
let sphere = SCNSphere(radius: 1.0)
sphere.firstMaterial?.diffuse.contents = UIColor.red
let sphereNode = SCNNode(geometry: sphere)
sphereNode.position = SCNVector3(x: 0.0, y: 3.0, z: 0.0)
rootNode.addChildNode(sphereNode)
let box = SCNBox(width: 1.0, height: 1.0, length: 1.0, chamferRadius: 0.2)
box.firstMaterial?.diffuse.contents = UIColor.green
let boxNode = SCNNode(geometry: box)
boxNode.position = SCNVector3(x: 0.0, y: -3.0, z: 0.0)
rootNode.addChildNode(boxNode)
let cylinder = SCNCylinder(radius: 1.0, height: 1.0)
cylinder.firstMaterial?.diffuse.contents = UIColor.yellow
let cylinderNode = SCNNode(geometry: cylinder)
cylinderNode.position = SCNVector3(x: -3.0, y: 3.0, z: 0.0)
rootNode.addChildNode(cylinderNode)
let torus = SCNTorus(ringRadius: 1.0, pipeRadius: 0.3)
torus.firstMaterial?.diffuse.contents = UIColor.white
let torusNode = SCNNode(geometry: torus)
torusNode.position = SCNVector3(x: -3.0, y: 0.0, z: 0.0)
rootNode.addChildNode(torusNode)
let capsule = SCNCapsule(capRadius: 0.3, height: 1.0)
capsule.firstMaterial?.diffuse.contents = UIColor.gray
let capsuleNode = SCNNode(geometry: capsule)
capsuleNode.position = SCNVector3(x: -3.0, y: -3.0, z: 0.0)
rootNode.addChildNode(capsuleNode)
let cone = SCNCone(topRadius: 1.0, bottomRadius: 2.0, height: 1.0)
cone.firstMaterial?.diffuse.contents = UIColor.magenta
let coneNode = SCNNode(geometry: cone)
coneNode.position = SCNVector3(x: 3.0, y: -2.0, z: 0.0)
rootNode.addChildNode(coneNode)
let tube = SCNTube(innerRadius: 1.0, outerRadius: 2.0, height: 1.0)
tube.firstMaterial?.diffuse.contents = UIColor.brown
let tubeNode = SCNNode(geometry: tube)
tubeNode.position = SCNVector3(x: 3.0, y: 2.0, z: 0.0)
rootNode.addChildNode(tubeNode)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 74bd080f50d610ed87785565a937d549 | 34.230769 | 82 | 0.60917 | 3.723577 | false | false | false | false |
dsay/POPDataSources | Example/POPDataSource/Example/ViewControllers/TableViewController.swift | 1 | 632 | import UIKit
import POPDataSource
class TableViewController: UITableViewController {
var shim: TableViewDataSourceShim! {
didSet {
let emptyView = UIView()
emptyView.backgroundColor = .red
shim.emptyView = emptyView
shim.tableView = tableView
tableView.dataSource = shim
tableView.delegate = shim
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CustomeSection.self)
tableView.register(cell: TableViewCell.self)
tableView.register(cell: CustomeCell.self)
}
}
| mit | e11c5db2418bb1d91ff5ed049ff4ebbe | 24.28 | 52 | 0.620253 | 5.448276 | false | false | false | false |
stone-payments/onestap-sdk-ios | OnestapSDK/Core/API/ApiReport.swift | 1 | 1104 | //
// ApiReport.swift
// OnestapSDK
//
// Created by Munir Wanis on 17/08/17.
// Copyright © 2017 Stone Payments. All rights reserved.
//
import Foundation
/// Returns in every response of the API
public struct ApiReport: InitializableWithData, InitializableWithJson {
/// Field where the Report is about
var field: String
/// Message explaining Field
var message: String
init(data: Data?) throws {
guard let data = data,
let jsonObject = try? JSONSerialization.jsonObject(with: data),
let json = jsonObject as? JSON else {
throw NSError.createParseError()
}
try self.init(json: json)
}
init(json: JSON) throws {
guard let field = json["field"] as? String,
let message = json["message"] as? String
else {
throw NSError.createParseError()
}
self.field = field
self.message = message
}
}
extension ApiReport {
var report: Report {
return Report(field: field, message: message)
}
}
| apache-2.0 | 857cfcd16d905f717407d1e27f1b59c4 | 23.511111 | 75 | 0.589302 | 4.557851 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Internal/Link/Elements/LinkEmailElement.swift | 1 | 2725 | //
// LinkEmailElement.swift
// StripePaymentSheet
//
// Created by Cameron Sabol on 1/13/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripeUICore
class LinkEmailElement: Element {
weak var delegate: ElementDelegate? = nil
private let emailAddressElement: TextFieldElement
private let activityIndicator: ActivityIndicator = {
// TODO: Consider adding the activity indicator to TextFieldView
let activityIndicator = ActivityIndicator(size: .medium)
activityIndicator.setContentCompressionResistancePriority(.required, for: .horizontal)
return activityIndicator
}()
private lazy var stackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [emailAddressElement.view, activityIndicator])
stackView.spacing = 0
stackView.axis = .horizontal
stackView.alignment = .center
stackView.isLayoutMarginsRelativeArrangement = true
stackView.directionalLayoutMargins = .insets(
top: 0,
leading: 0,
bottom: 0,
trailing: ElementsUI.contentViewInsets.trailing
)
return stackView
}()
var view: UIView {
return stackView
}
public var emailAddressString: String? {
return emailAddressElement.text
}
public var validationState: ElementValidationState {
return emailAddressElement.validationState
}
public var indicatorTintColor: UIColor {
get {
return activityIndicator.color
}
set {
activityIndicator.color = newValue
}
}
public func startAnimating() {
UIView.performWithoutAnimation {
activityIndicator.startAnimating()
stackView.setNeedsLayout()
stackView.layoutSubviews()
}
}
public func stopAnimating() {
UIView.performWithoutAnimation {
activityIndicator.stopAnimating()
stackView.setNeedsLayout()
stackView.layoutSubviews()
}
}
public init(defaultValue: String? = nil, theme: ElementsUITheme = .default) {
emailAddressElement = TextFieldElement.makeEmail(defaultValue: defaultValue, theme: theme)
emailAddressElement.delegate = self
}
@discardableResult
func beginEditing() -> Bool {
return emailAddressElement.beginEditing()
}
}
extension LinkEmailElement: ElementDelegate {
func didUpdate(element: Element) {
delegate?.didUpdate(element: self)
}
func continueToNextField(element: Element) {
delegate?.continueToNextField(element: self)
}
}
| mit | 09d8b0db1078aee30fee4955e9f79259 | 27.375 | 100 | 0.651248 | 5.663202 | false | false | false | false |
hirohitokato/SimpleGaplessPlayer | HKLAVGaplessPlayer/misc/HKLAVFoundationUtils.swift | 1 | 6756 | //
// HKLAVFoundationUtils.swift
// SimpleGaplessPlayer
//
// Created by Hirohito Kato on 2014/12/23.
// Copyright (c) 2014年 Hirohito Kato. All rights reserved.
//
import Foundation
import AVFoundation
extension AVURLAsset {
open override var description: String {
var str: String = ""
str += "---------------------\n"
str += "<file : \(url.lastPathComponent)>\n"
str += "[Availability]\n"
str += " isPlayable : \(isPlayable)\n"
str += " isExportable : \(isExportable)\n"
str += " isReadable : \(isReadable)\n"
str += " isComposable : \(isComposable)\n"
str += " hasProtectedContent : \(hasProtectedContent)\n"
str += " isCompatibleWithSavedPhotosAlbum: \(isCompatibleWithSavedPhotosAlbum)\n"
str += "[Asset Information]\n"
str += " creationDate : \(String(describing: creationDate))\n"
str += " duration : \(duration.description)\n"
str += " lyrics : \(String(describing: lyrics))\n"
str += " preferredRate : \(preferredRate)\n"
str += " preferredVolume : \(preferredVolume)\n"
str += " preferredTransform : \(preferredTransform.description)\n"
str += " referenceRestrictions : \(referenceRestrictions.description)\n"
str += "[Track Information] (\(tracks.count) tracks)\n"
for (_, track) in tracks.enumerated() {
str += "\(track.description)\n"
}
str += " trackGroups:\(trackGroups)\n"
str += "[Metadata]\n"
str += " commonMetadata: \(commonMetadata.count)\n"
for (_, md) in commonMetadata.enumerated() {
str += " | \(md.description),\n"
}
str += " metadata: \(metadata.count)\n"
for (_, md) in metadata.enumerated() {
str += " | \(md.description),\n"
}
str += " availableMetadataFormats : \(availableMetadataFormats)\n"
str += " availableChapterLocales : \(availableChapterLocales)\n"
str += " availableMediaCharacteristicsWithMediaSelectionOptions: \(availableMediaCharacteristicsWithMediaSelectionOptions)\n"
str += "---------------------"
return str
}
open override var debugDescription: String {
return description
}
}
extension AVAssetReferenceRestrictions : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
switch self.rawValue {
case 0:
return "RestrictionForbidNone"
case 1:
return "RestrictionForbidRemoteReferenceToLocal"
case 2:
return "RestrictionForbidLocalReferenceToRemote"
case 3:
return "RestrictionForbidCrossSiteReference"
case 4:
return "RestrictionForbidLocalReferenceToLocal"
case 5:
return "RestrictionForbidAll"
default:
return "Unknown value(\(self.rawValue))"
}
}
public var debugDescription: String {
return description
}
}
extension AVAssetTrack {
open override var description: String {
var str = ""
str += " [track #\(trackID)]\n"
str += " | mediaType : \(media(type: mediaType))\n"
str += " | isPlayable : \(isPlayable)\n"
str += " | isEnabled : \(isEnabled)\n"
str += " | selfContained : \(isSelfContained)\n"
str += " | totalSampleDataLength : \(totalSampleDataLength)\n"
str += " | timeRange : \(timeRange.description)\n"
str += " | naturalTimeScale : \(naturalTimeScale)\n"
str += " | estimatedDataRate : \(estimatedDataRate/1_000_000) Mbps\n"
str += " | naturalSize : {\(naturalSize.width), \(naturalSize.height)}\n"
str += " | preferredTransform : \(preferredTransform.description)\n"
str += " | nominalFrameRate : \(nominalFrameRate)\n"
str += " | minFrameDuration : \(minFrameDuration.description)\n"
str += " | requiresFrameReordering: \(requiresFrameReordering)\n"
str += " | availableTrackAssociationTypes: \(availableTrackAssociationTypes)\n"
str += " | segments : \(segments.count)\n"
for (_, segment) in segments.enumerated() {
str += " | | \(segment.description)"
}
return str
}
open override var debugDescription: String {
return description
}
func media(type: AVMediaType)-> String {
switch type {
case .video: return "video"
case .audio: return "audio"
case .text: return "text"
case .closedCaption: return "closed caption"
case .subtitle: return "subtitle"
case .timecode: return "timecode"
case .metadata: return "metadata"
case .muxed: return "muxed"
default:
return "Unknown"
}
}
}
extension AVMetadataItem {
open override var description: String {
var str = "[\(String(describing: key))"
if self.dateValue != nil {
str += "(date) : \(String(describing: self.dateValue))]"
} else if self.stringValue != nil {
str += "(str) : \(String(describing: self.stringValue))]"
} else if self.numberValue != nil {
str += "(num) : \(String(describing: self.numberValue))]"
}
return str
}
open override var debugDescription: String {
var str = ""
str += " | key : \(String(describing: key))\n"
str += " | keySpace : \(String(describing: keySpace))\n"
str += " | identifier : \(String(describing: identifier))\n"
if dataType != nil {
str += " | dataType : \(String(describing: dataType))\n"
}
if time.flags.contains(.valid) {
str += " | time : \(time.description)\n"
}
if self.dateValue != nil {
str += " | value(date) : \(String(describing: self.dateValue))\n"
} else if self.stringValue != nil {
str += " | value(str) : \(String(describing: self.stringValue))\n"
} else if self.numberValue != nil {
str += " | value(num) : \(String(describing: self.numberValue))\n"
}
str += " | extraAttributes : \(String(describing: extraAttributes))\n"
return str
}
}
extension AVAssetTrackSegment {
open override var description: String {
return "{ empty:\(isEmpty), timeMapping:\(timeMapping.description)}"
}
open override var debugDescription: String {
return description
}
}
| bsd-3-clause | 49976f068e68c51d84bdf82fe6e4fb36 | 39.443114 | 133 | 0.557299 | 4.42595 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Internal/Link/Views/LinkLegalTermsView.swift | 1 | 4393 | //
// LinkLegalTermsView.swift
// StripePaymentSheet
//
// Created by Ramon Torres on 1/26/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripeUICore
@_spi(STP) import StripePaymentsUI
protocol LinkLegalTermsViewDelegate: AnyObject {
/// Called when the user taps on a legal link.
///
/// Implementation must return `true` if the link was handled. Returning `false`results in the link
/// to open in the default browser.
///
/// - Parameters:
/// - legalTermsView: The view that the user interacted with.
/// - url: URL of the link.
/// - Returns: `true` if the link was handled by the delegate.
func legalTermsView(_ legalTermsView: LinkLegalTermsView, didTapOnLinkWithURL url: URL) -> Bool
}
/// For internal SDK use only
@objc(STP_Internal_LinkLegalTermsView)
final class LinkLegalTermsView: UIView {
struct Constants {
static let lineHeight: CGFloat = 1.5
}
private let links: [String: URL] = [
"terms": URL(string: "https://link.co/terms")!,
"privacy": URL(string: "https://link.co/privacy")!
]
weak var delegate: LinkLegalTermsViewDelegate?
var textColor: UIColor? {
get {
return textView.textColor
}
set {
textView.textColor = newValue
}
}
var font: UIFont? {
get {
return textView.font
}
set {
textView.font = newValue
}
}
private lazy var textView: UITextView = {
let textView = UITextView()
textView.isScrollEnabled = false
textView.isEditable = false
textView.backgroundColor = .clear
textView.attributedText = formattedLegalText()
textView.textColor = .linkSecondaryText
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.delegate = self
textView.clipsToBounds = false
textView.adjustsFontForContentSizeCategory = true
textView.font = LinkUI.font(forTextStyle: .caption)
return textView
}()
init(textAlignment: NSTextAlignment = .left, delegate: LinkLegalTermsViewDelegate? = nil) {
super.init(frame: .zero)
self.textView.textAlignment = textAlignment
self.delegate = delegate
addAndPinSubview(textView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func formattedLegalText() -> NSAttributedString {
let string = STPLocalizedString(
"By joining Link, you agree to the <terms>Terms</terms> and <privacy>Privacy Policy</privacy>.",
"Legal text shown when creating a Link account."
)
let formattedString = NSMutableAttributedString()
STPStringUtils.parseRanges(from: string, withTags: Set<String>(links.keys)) { string, matches in
formattedString.append(NSAttributedString(string: string))
for (tag, range) in matches {
guard range.rangeValue.location != NSNotFound else {
assertionFailure("Tag '<\(tag)>' not found")
continue
}
if let url = links[tag] {
formattedString.addAttributes([.link: url], range: range.rangeValue)
}
}
}
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = LinkUI.lineSpacing(
fromRelativeHeight: Constants.lineHeight,
textStyle: .caption
)
formattedString.addAttributes([.paragraphStyle: paragraphStyle], range: formattedString.extent)
return formattedString
}
}
extension LinkLegalTermsView: UITextViewDelegate {
func textView(
_ textView: UITextView,
shouldInteractWith URL: URL,
in characterRange: NSRange,
interaction: UITextItemInteraction
) -> Bool {
guard interaction == .invokeDefaultAction else {
// Disable preview and actions
return false
}
let handled = delegate?.legalTermsView(self, didTapOnLinkWithURL: URL) ?? false
assert(handled, "Link not handled by delegate")
// If not handled by the delegate, let the system handle the link.
return !handled
}
}
| mit | cab6be70553cabedb339251abea7705d | 30.148936 | 108 | 0.625683 | 4.951522 | false | false | false | false |
overtake/TelegramSwift | packages/TGUIKit/Sources/InvisibleInkDustView.swift | 1 | 8165 | //
// File.swift
//
//
// Created by Mike Renoir on 18.01.2022.
//
import Foundation
import AppKit
public func createEmitterBehavior(type: String) -> NSObject {
let selector = ["behaviorWith", "Type:"].joined(separator: "")
let behaviorClass = NSClassFromString(["CA", "Emitter", "Behavior"].joined(separator: "")) as! NSObject.Type
let behaviorWithType = behaviorClass.method(for: NSSelectorFromString(selector))!
let castedBehaviorWithType = unsafeBitCast(behaviorWithType, to:(@convention(c)(Any?, Selector, Any?) -> NSObject).self)
return castedBehaviorWithType(behaviorClass, NSSelectorFromString(selector), type)
}
private func generateMaskImage(size originalSize: CGSize, position: CGPoint, inverse: Bool) -> CGImage? {
var size = originalSize
var position = position
var scale: CGFloat = 1.0
if max(size.width, size.height) > 640.0 {
size = size.aspectFitted(CGSize(width: 640.0, height: 640.0))
scale = size.width / originalSize.width
position = CGPoint(x: position.x * scale, y: position.y * scale)
}
return generateImage(size, rotatedContext: { size, context in
let bounds = CGRect(origin: CGPoint(), size: size)
context.clear(bounds)
let startAlpha: CGFloat = inverse ? 0.0 : 1.0
let endAlpha: CGFloat = inverse ? 1.0 : 0.0
var locations: [CGFloat] = [0.0, 0.7, 0.95, 1.0]
let colors: [CGColor] = [NSColor(rgb: 0xffffff, alpha: startAlpha).cgColor, NSColor(rgb: 0xffffff, alpha: startAlpha).cgColor, NSColor(rgb: 0xffffff, alpha: endAlpha).cgColor, NSColor(rgb: 0xffffff, alpha: endAlpha).cgColor]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: &locations)!
let center = position
context.drawRadialGradient(gradient, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: min(10.0, min(size.width, size.height) * 0.4) * scale, options: .drawsAfterEndLocation)
})
}
public class InvisibleInkDustView: View {
private var currentParams: (size: CGSize, color: NSColor, textColor: NSColor, rects: [CGRect], wordRects: [CGRect])?
private var animColor: CGColor?
private weak var textView: TextView?
private let textMaskView: View
private let textSpotView: ImageView
private var emitterView: View
private var emitter: CAEmitterCell?
private var emitterLayer: CAEmitterLayer?
private let emitterMaskView: View
private let emitterSpotView: ImageView
private let emitterMaskFillView: View
public var isRevealed = false
public init(textView: TextView?) {
self.textView = textView
self.emitterView = View()
self.textMaskView = View()
self.textSpotView = ImageView()
self.emitterMaskView = View()
self.emitterSpotView = ImageView()
self.emitterMaskFillView = View()
self.emitterMaskFillView.backgroundColor = .white
super.init()
self.addSubview(self.emitterView)
self.textMaskView.addSubview(self.textSpotView)
self.emitterMaskView.addSubview(self.emitterSpotView)
self.emitterMaskView.addSubview(self.emitterMaskFillView)
initialize()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required public init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
private func initialize() {
let emitter = CAEmitterCell()
emitter.contents = NSImage(named: "textSpeckle_Normal")?.cgImage(forProposedRect: nil, context: nil, hints: nil)
emitter.contentsScale = 1.8
emitter.emissionRange = .pi * 2.0
emitter.lifetime = 1.0
emitter.scale = 0.5
emitter.velocityRange = 20.0
emitter.name = "dustCell"
emitter.alphaRange = 1.0
emitter.setValue("point", forKey: "particleType")
emitter.setValue(3.0, forKey: "mass")
emitter.setValue(2.0, forKey: "massRange")
self.emitter = emitter
let fingerAttractor = createEmitterBehavior(type: "simpleAttractor")
fingerAttractor.setValue("fingerAttractor", forKey: "name")
let alphaBehavior = createEmitterBehavior(type: "valueOverLife")
alphaBehavior.setValue("color.alpha", forKey: "keyPath")
alphaBehavior.setValue([0.0, 0.0, 1.0, 0.0, -1.0], forKey: "values")
alphaBehavior.setValue(true, forKey: "additive")
let behaviors = [fingerAttractor, alphaBehavior]
let emitterLayer = CAEmitterLayer()
emitterLayer.masksToBounds = true
emitterLayer.allowsGroupOpacity = true
emitterLayer.lifetime = 1
emitterLayer.emitterCells = [emitter]
emitterLayer.emitterPosition = CGPoint(x: 0, y: 0)
emitterLayer.seed = arc4random()
emitterLayer.emitterSize = CGSize(width: 1, height: 1)
emitterLayer.emitterShape = CAEmitterLayerEmitterShape(rawValue: "rectangles")
emitterLayer.setValue(behaviors, forKey: "emitterBehaviors")
emitterLayer.setValue(4.0, forKeyPath: "emitterBehaviors.fingerAttractor.stiffness")
emitterLayer.setValue(false, forKeyPath: "emitterBehaviors.fingerAttractor.enabled")
self.emitterLayer = emitterLayer
self.emitterView.layer?.addSublayer(emitterLayer)
self.updateEmitter()
}
public func update(revealed: Bool) {
guard self.isRevealed != revealed, let textView = self.textView else {
return
}
self.isRevealed = revealed
if revealed {
let transition = ContainedViewLayoutTransition.animated(duration: 0.3, curve: .linear)
transition.updateAlpha(view: self, alpha: 0.0)
transition.updateAlpha(view: textView, alpha: 1.0)
} else {
let transition = ContainedViewLayoutTransition.animated(duration: 0.4, curve: .linear)
transition.updateAlpha(view: self, alpha: 1.0)
transition.updateAlpha(view: textView, alpha: 0.0)
}
}
private func updateEmitter() {
guard let (size, color, _, _, wordRects) = self.currentParams else {
return
}
self.emitter?.color = self.animColor ?? color.cgColor
self.emitterLayer?.setValue(wordRects, forKey: "emitterRects")
self.emitterLayer?.frame = CGRect(origin: CGPoint(), size: size)
let radius = max(size.width, size.height)
self.emitterLayer?.setValue(max(size.width, size.height), forKeyPath: "emitterBehaviors.fingerAttractor.radius")
self.emitterLayer?.setValue(radius * -0.5, forKeyPath: "emitterBehaviors.fingerAttractor.falloff")
var square: Float = 0.0
for rect in wordRects {
square += Float(rect.width * rect.height)
}
self.emitter?.birthRate = min(100000, square * 0.35)
}
public func update(size: CGSize, color: NSColor, textColor: NSColor, rects: [CGRect], wordRects: [CGRect]) {
self.currentParams = (size, color, textColor, rects, wordRects)
self.emitterView.frame = CGRect(origin: CGPoint(), size: size)
self.emitterMaskView.frame = self.emitterView.bounds
self.emitterMaskFillView.frame = self.emitterView.bounds
self.textMaskView.frame = CGRect(origin: CGPoint(x: 3.0, y: 3.0), size: size)
self.updateEmitter()
}
public func point(inside point: CGPoint, with event: NSEvent?) -> Bool {
if let (_, _, _, rects, _) = self.currentParams, !self.isRevealed {
for rect in rects {
if rect.contains(point) {
return true
}
}
return false
} else {
return false
}
}
}
| gpl-2.0 | 413ec5816f0e1d671e0c7d89112c3252 | 37.696682 | 232 | 0.63466 | 4.459312 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/StorageUsageCleanProgressRowItem.swift | 1 | 2471 | //
// StorageUsageCleanProgressRowItem.swift
// Telegram
//
// Created by Mikhail Filimonov on 03/08/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
class StorageUsageCleanProgressRowItem: GeneralRowItem {
private let task: CCTaskData
fileprivate var currentProgress: Float
init(_ initialSize: NSSize, stableId: AnyHashable, task: CCTaskData, viewType: GeneralViewType) {
self.task = task
self.currentProgress = task.currentProgress
super.init(initialSize, height: 40, stableId: stableId, viewType: viewType)
}
override func viewClass() -> AnyClass {
return StorageUsageCleanProgressRowView.self
}
fileprivate var progress: Signal<Float, NoError> {
return self.task.progress |> deliverOnMainQueue
}
}
private final class StorageUsageCleanProgressRowView : GeneralContainableRowView {
private let disposable = MetaDisposable()
private let progressView: LinearProgressControl = LinearProgressControl(progressHeight: 4)
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(progressView)
}
override func layout() {
super.layout()
guard let item = item as? StorageUsageCleanProgressRowItem else {
return
}
progressView.setFrameSize(NSMakeSize(item.blockWidth - item.viewType.innerInset.left - item.viewType.innerInset.right, 4))
progressView.center()
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? StorageUsageCleanProgressRowItem else {
return
}
progressView.style = ControlStyle(foregroundColor: theme.colors.accent, backgroundColor: theme.colors.grayUI)
progressView.set(progress: CGFloat(item.currentProgress), animated: animated, duration: 0.2, timingFunction: .linear)
progressView.cornerRadius = 2
disposable.set(item.progress.start(next: { [weak self] value in
self?.progressView.set(progress: CGFloat(value), animated: true, duration: 0.2, timingFunction: .linear)
}))
}
deinit {
disposable.dispose()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | 81246246697d7322acac8991afa9f37e | 30.666667 | 131 | 0.668826 | 4.814815 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Sources/EurofurenceApplication/Content Router/Routes/News/ResetNewsAfterLogout.swift | 1 | 2253 | import ComponentBase
import UIKit
struct ResetNewsAfterLogout: NewsPresentation {
var window: UIWindow
func showNews() {
guard let tabBarController = window.rootViewController as? UITabBarController else { return }
guard let newsNavigationController = tabBarController
.viewControllers?
.compactMap({ $0 as? UISplitViewController })
.compactMap({ $0.viewControllers.first as? UINavigationController })
.first(where: { $0.viewControllers.contains(where: { $0 is CompositionalNewsViewController }) }) else {
return
}
guard let newsControllerIndex = tabBarController
.viewControllers?
.compactMap({ $0 as? UISplitViewController })
.compactMap({ $0.viewControllers.first as? UINavigationController })
.firstIndex(of: newsNavigationController) else { return }
guard let newsSplitViewController = tabBarController
.viewControllers?[newsControllerIndex] as? UISplitViewController else { return }
tabBarController.selectedIndex = newsControllerIndex
newsNavigationController.popToRootViewController(animated: UIView.areAnimationsEnabled)
let secondaryViewController = newsSplitViewController.viewControllers.last
guard let detailNavigation = secondaryViewController as? UINavigationController else { return }
let navigationStack = detailNavigation.viewControllers
let nonMessageControllers = navigationStack.filter({ (viewController) in
(viewController is MessageDetailViewController || viewController is MessagesViewController) == false
})
if nonMessageControllers.isEmpty {
let placeholderController = NoContentPlaceholderViewController.fromStoryboard()
let placeholderNavigationController = UINavigationController(rootViewController: placeholderController)
newsSplitViewController.viewControllers = [newsNavigationController, placeholderNavigationController]
} else {
detailNavigation.setViewControllers(nonMessageControllers, animated: UIView.areAnimationsEnabled)
}
}
}
| mit | c74f46ec47785bb24c5aaedb5dbdf891 | 46.93617 | 115 | 0.700399 | 6.705357 | false | false | false | false |
karthikprabhuA/SwiftMediaBrowser | SwiftMediaBrowserframework/KPAImageViewController.swift | 1 | 7502 | //
// KPAImageViewController.swift
// SwiftMediaBrowser
//
// Created by Karthik Prabhu Alagu on 27/08/15.
// Copyright © 2015 KPAlagu. All rights reserved.
//
import UIKit
import AVFoundation
class ImageScrollView: UIScrollView
{
var imageView:UIImageView?;
override init(frame: CGRect) {
super.init(frame: frame)
let tapOnce:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageScrollView.tapOnce))
tapOnce.numberOfTapsRequired = 1;
self.addGestureRecognizer(tapOnce);
let tapTwice:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageScrollView.tapTwice))
tapTwice.numberOfTapsRequired = 2;
self.addGestureRecognizer(tapTwice);
}
@objc func tapOnce()
{
print("tappedonce");
self.zoomScale = 1.0;
}
@objc func tapTwice()
{
print("tappedTwice");
self.zoomScale = 2.0;
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews()
{
super.layoutSubviews()
// center the zoom view as it becomes smaller than the size of the screen
let boundsSize:CGSize = self.bounds.size;
if let imageView = imageView {
var frameToCenter:CGRect = imageView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
{
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
}
else
{
frameToCenter.origin.x = 0;
}
// center vertically
if (frameToCenter.size.height < boundsSize.height)
{
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
}
else
{
frameToCenter.origin.y = 0;
}
imageView.frame = frameToCenter;
}
}
func setMaxMinZoomScalesForCurrentBounds() {
// Reset
self.maximumZoomScale = 1;
self.minimumZoomScale = 1;
self.zoomScale = 1;
// Bail if no image
if (self.imageView != nil && self.imageView!.image == nil)
{
return;
}
// Reset position
self.imageView!.frame = CGRect(x:0, y:0, width:self.imageView!.frame.size.width, height:self.imageView!.frame.size.height);
// Sizes
let boundsSize:CGSize = self.bounds.size;
let imageSize:CGSize = self.imageView!.image!.size;
// Calculate Min
let xScale:CGFloat = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise
let yScale:CGFloat = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise
var minScale:CGFloat = min(xScale, yScale); // use minimum of these to allow the image to become fully visible
// Calculate Max
var maxScale:CGFloat = 3;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) {
// Let them go a bit bigger on a bigger screen!
maxScale = 4;
}
// Image is smaller than screen so no zooming!
if (xScale >= 1 && yScale >= 1) {
minScale = 1.0;
}
// Set min/max zoom
self.maximumZoomScale = maxScale;
self.minimumZoomScale = minScale;
// Initial zoom
//self.zoomScale = [self initialZoomScaleWithMinScale];
// If we're zooming to fill then centralise
if (self.zoomScale != minScale) {
// Centralise
self.contentOffset = CGPoint(x:(imageSize.width * self.zoomScale - boundsSize.width) / 2.0,
y:(imageSize.height * self.zoomScale - boundsSize.height) / 2.0);
}
// Disable scrolling initially until the first pinch to fix issues with swiping on an initally zoomed in photo
self.isScrollEnabled = true;
// Layout
self.setNeedsLayout();
}
}
class KPAImageViewController: UIViewController,UIScrollViewDelegate {
var imageView:UIImageView!;
var scrollView: ImageScrollView!;
var pageIndex : Int = 0;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
}
override func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
scrollView.frame = UIScreen.main.bounds;
}
func initializeImageViewForZoomingWithImage(image:UIImage)
{
let rect = self.view.frame;
self.view.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight,UIView.AutoresizingMask.flexibleWidth];
scrollView = ImageScrollView(frame: rect)
scrollView.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight,UIView.AutoresizingMask.flexibleWidth];
scrollView.delegate = self
scrollView.backgroundColor = UIColor.white;
scrollView.alwaysBounceVertical = false
scrollView.alwaysBounceHorizontal = false
scrollView.showsVerticalScrollIndicator = false
scrollView.flashScrollIndicators()
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 4.0
self.view.addSubview(scrollView)
imageView = UIImageView(frame: CGRect.zero);
scrollView.imageView = imageView
scrollView.imageView!.image = image;
scrollView.imageView!.frame.size = CGSizeAspectFit(aspectRatio: scrollView.imageView!.image!.size, boundingSize: rect.size);
scrollView.contentSize = (scrollView.imageView!.frame.size);
imageView!.layer.cornerRadius = 11.0
imageView!.clipsToBounds = false
scrollView.addSubview(imageView!)
}
func CGSizeAspectFit( aspectRatio:CGSize, boundingSize:CGSize) -> CGSize
{
var size = boundingSize
let mW = size.width / aspectRatio.width;
let mH = size.height / aspectRatio.height;
if( mH < mW )
{
size.width = size.height / aspectRatio.height * aspectRatio.width;
}
else if( mW < mH )
{
size.height = size.width / aspectRatio.width * aspectRatio.height;
}
return size;
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 251abe4bf7ae57a2c19ca3be8cf6c1d0 | 33.56682 | 134 | 0.614585 | 5.078538 | false | false | false | false |
LuigiAndMario/Informant | Informant/GeneralViewController.swift | 1 | 2977 | //
// ViewController.swift
// Informant
//
// Created by Luigi Sansonetti on 11.05.17.
// Copyright © 2017 Luigi Sansonetti. All rights reserved.
//
import Cocoa
import Foundation
class GeneralViewController: NSViewController {
// MARK: Variables and constants
let mask: String = "/24"
// MARK:- Properties
// MARK: Interface
@IBOutlet weak var interfaceLabel: NSTextField!
@IBOutlet weak var interfaceSelector: NSPopUpButton!
@IBAction func changeInterface(_ sender: NSPopUpButton) {
refresh(self)
}
// MARK: Addresses
@IBOutlet weak var IPLabel: NSTextField!
@IBOutlet weak var IPAddress: NSTextField!
@IBOutlet weak var MACLabel: NSTextField!
@IBOutlet weak var MACAddress: NSTextField!
@IBOutlet weak var scanButton: NSButton!
@IBAction func scanRequested(_ sender: NSButton) {
scan(IP: IPAddress.stringValue, mask: mask, populate: self)
}
// MARK: Scan
@IBOutlet weak var MACAddressesFieldTitle: NSTextField!
@IBOutlet weak var MACAddresses: NSTextView!
@IBOutlet weak var IPAddressesFieldTitle: NSTextField!
@IBOutlet weak var IPAddresses: NSTextView!
// MARK: Ping
@IBOutlet weak var PingButton: NSButton!
@IBAction func pingRequested(_ sender: NSButton) {
ping(self)
}
@IBOutlet weak var PingResult: NSTextField!
// MARK: Lookup
@IBOutlet weak var IPAddressForLookup: NSTextField!
@IBOutlet weak var LookupButton: NSButton!
@IBAction func lookupRequested(_ sender: NSButton) {
lookup(IPAddressForLookup.stringValue)
}
// MARK:- Initialisation
override func viewDidLoad() {
super.viewDidLoad()
// Filling the interface menu.
interfaceSelector.removeAllItems()
bash("ifconfig -a | cut -f1") // Getting the interfaces names.
.components(separatedBy: "\n") // Separating the string into an array.
.filter { $0 != "" } // removing empty lines.
.map { $0.components(separatedBy: ":")[0] } // Keeping the interface names only.
.forEach { interfaceSelector.addItem(withTitle: $0) } // Adding them to the selector.
interfaceSelector.selectItem(at: 3)
// Getting the IP and MAC addresses.
refresh(self)
// Setting the visibility and editability of the scan results fields.
MACAddressesFieldTitle.isHidden = true
MACAddresses.enclosingScrollView?.isHidden = true
MACAddresses.isEditable = false
IPAddressesFieldTitle.isHidden = true
IPAddresses.enclosingScrollView?.isHidden = true
IPAddresses.isEditable = false
// Setting the visibility of the ping button.
PingResult.isHidden = true
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit | a0dbf2cc1d0dd9faae0bcc8eb146d333 | 30 | 97 | 0.644153 | 4.815534 | false | false | false | false |
chayelheinsen/GamingStreams-tvOS-App | StreamCenter/SSLSecurity.swift | 3 | 8313 | // Copyright 2015 Dalton Cherry
//
// 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.
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// SSLSecurity.swift
// Starscream
//
// Created by Dalton Cherry on 5/16/15.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import Security
public class SSLCert {
var certData: NSData?
var key: SecKeyRef?
/**
Designated init for certificates
- parameter data: is the binary data of the certificate
- returns: a representation security object to be used with
*/
public init(data: NSData) {
self.certData = data
}
/**
Designated init for public keys
- parameter key: is the public key to be used
- returns: a representation security object to be used with
*/
public init(key: SecKeyRef) {
self.key = key
}
}
public class SSLSecurity {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
var certificates: [NSData]? //the certificates
var pubKeys: [SecKeyRef]? //the public keys
var usePublicKeys = false //use public keys or certificate validation?
/**
Use certs from main app bundle
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
- returns: a representation security object to be used with
*/
public convenience init(usePublicKeys: Bool = false) {
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
var collect = Array<SSLCert>()
for path in paths {
if let d = NSData(contentsOfFile: path as String) {
collect.append(SSLCert(data: d))
}
}
self.init(certs:collect, usePublicKeys: usePublicKeys)
}
/**
Designated init
- parameter keys: is the certificates or public keys to use
- parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation
- returns: a representation security object to be used with
*/
public init(certs: [SSLCert], usePublicKeys: Bool) {
self.usePublicKeys = usePublicKeys
if self.usePublicKeys {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
var collect = Array<SecKeyRef>()
for cert in certs {
if let data = cert.certData where cert.key == nil {
cert.key = self.extractPublicKey(data)
}
if let k = cert.key {
collect.append(k)
}
}
self.pubKeys = collect
self.isReady = true
})
} else {
var collect = Array<NSData>()
for cert in certs {
if let d = cert.certData {
collect.append(d)
}
}
self.certificates = collect
self.isReady = true
}
}
/**
Valid the trust and domain name.
- parameter trust: is the serverTrust to validate
- parameter domain: is the CN domain to validate
- returns: if the key was successfully validated
*/
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicyRef
if self.validatedDN {
policy = SecPolicyCreateSSL(true, domain)
} else {
policy = SecPolicyCreateBasicX509()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
let serverPubKeys = publicKeyChainForTrust(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
return true
}
}
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChainForTrust(trust)
var collect = Array<SecCertificate>()
for cert in certs {
collect.append(SecCertificateCreateWithData(nil,cert)!)
}
SecTrustSetAnchorCertificates(trust,collect)
var result: SecTrustResultType = 0
SecTrustEvaluate(trust,&result)
let r = Int(result)
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount++
break
}
}
}
if trustedCount == serverCerts.count {
return true
}
}
}
return false
}
/**
Get the public key from a certificate data
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKey(data: NSData) -> SecKeyRef? {
let possibleCert = SecCertificateCreateWithData(nil,data)
if let cert = possibleCert {
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
}
return nil
}
/**
Get the public key from a certificate
- parameter data: is the certificate to pull the public key from
- returns: a public key
*/
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
var possibleTrust: SecTrust?
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
if let trust = possibleTrust {
var result: SecTrustResultType = 0
SecTrustEvaluate(trust, &result)
return SecTrustCopyPublicKey(trust)
}
return nil
}
/**
Get the certificate chain for the trust
- parameter trust: is the trust to lookup the certificate chain for
- returns: the certificate chain for the trust
*/
func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> {
var collect = Array<NSData>()
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
let cert = SecTrustGetCertificateAtIndex(trust,i)
collect.append(SecCertificateCopyData(cert!))
}
return collect
}
/**
Get the public key chain for the trust
- parameter trust: is the trust to lookup the certificate chain and extract the public keys
- returns: the public keys from the certifcate chain for the trust
*/
func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> {
var collect = Array<SecKeyRef>()
let policy = SecPolicyCreateBasicX509()
for var i = 0; i < SecTrustGetCertificateCount(trust); i++ {
let cert = SecTrustGetCertificateAtIndex(trust,i)
if let key = extractPublicKeyFromCert(cert!, policy: policy) {
collect.append(key)
}
}
return collect
}
} | mit | 6cef6e71c0753bb382381771aac2bf7f | 32.256 | 122 | 0.558884 | 5.472679 | false | false | false | false |
huonw/swift | test/Serialization/objc.swift | 3 | 1674 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_objc.swift -disable-objc-attr-requires-foundation-module -enable-objc-interop
// RUN: llvm-bcanalyzer %t/def_objc.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -module-name objc -emit-silgen -I %t %s -o - | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: UnknownCode
import def_objc
// SIL: sil hidden @$S4objc9testProto3objy04def_A09ObjCProto_p_tF : $@convention(thin) (@guaranteed ObjCProto) -> () {
func testProto(obj obj: ObjCProto) {
// SIL: = objc_method {{%.*}} : $@opened({{.*}}) ObjCProto, #ObjCProto.doSomething!1.foreign
obj.doSomething()
}
// SIL: sil hidden @$S4objc9testClass3objy04def_A09ObjCClassC_tF : $@convention(thin) (@guaranteed ObjCClass) -> () {
func testClass(obj obj: ObjCClass) {
// SIL: = objc_method %{{.+}} : $ObjCClass, #ObjCClass.implicitlyObjC!1.foreign
obj.implicitlyObjC()
// SIL: = objc_method %{{.+}} : $@objc_metatype ObjCClass.Type, #ObjCClass.classMethod!1.foreign
ObjCClass.classMethod()
}
// SIL: sil hidden @$S4objc15testNativeClass3objy04def_A012NonObjCClassC_tF : $@convention(thin) (@guaranteed NonObjCClass) -> () {
func testNativeClass(obj obj: NonObjCClass) {
// SIL: = objc_method %{{.+}} : $NonObjCClass, #NonObjCClass.doSomething!1.foreign
// SIL: = objc_method %{{.+}} : $NonObjCClass, #NonObjCClass.objcMethod!1.foreign
obj.doSomething()
obj.objcMethod()
// SIL: objc_method [[OBJ:%[0-9]+]] : $NonObjCClass, #NonObjCClass.objcProp!getter.1.foreign
var x = obj.objcProp
// SIL: objc_method [[OBJ:%[0-9]+]] : $NonObjCClass, #NonObjCClass.subscript!getter.1.foreign
_ = obj[42]
}
| apache-2.0 | 48c82720e94bcb88aa1ff547817167c7 | 43.052632 | 141 | 0.691159 | 3.334661 | false | true | false | false |
Alamofire/Alamofire | Source/ParameterEncoding.swift | 4 | 14103 | //
// ParameterEncoding.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
/// A type used to define how a set of parameters are applied to a `URLRequest`.
public protocol ParameterEncoding {
/// Creates a `URLRequest` by encoding parameters and applying them on the passed request.
///
/// - Parameters:
/// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded.
/// - parameters: `Parameters` to encode onto the request.
///
/// - Returns: The encoded `URLRequest`.
/// - Throws: Any `Error` produced during parameter encoding.
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
// MARK: -
/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
/// the HTTP body depends on the destination of the encoding.
///
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
/// `application/x-www-form-urlencoded; charset=utf-8`.
///
/// There is no published specification for how to encode collection types. By default the convention of appending
/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
/// square brackets appended to array keys.
///
/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
/// `true` as 1 and `false` as 0.
public struct URLEncoding: ParameterEncoding {
// MARK: Helper Types
/// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
/// resulting URL request.
public enum Destination {
/// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and
/// sets as the HTTP body for requests with any other HTTP method.
case methodDependent
/// Sets or appends encoded query string result to existing query string.
case queryString
/// Sets encoded query string result as the HTTP body of the URL request.
case httpBody
func encodesParametersInURL(for method: HTTPMethod) -> Bool {
switch self {
case .methodDependent: return [.get, .head, .delete].contains(method)
case .queryString: return true
case .httpBody: return false
}
}
}
/// Configures how `Array` parameters are encoded.
public enum ArrayEncoding {
/// An empty set of square brackets is appended to the key for every value. This is the default behavior.
case brackets
/// No brackets are appended. The key is encoded as is.
case noBrackets
/// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior.
case indexInBrackets
func encode(key: String, atIndex index: Int) -> String {
switch self {
case .brackets:
return "\(key)[]"
case .noBrackets:
return key
case .indexInBrackets:
return "\(key)[\(index)]"
}
}
}
/// Configures how `Bool` parameters are encoded.
public enum BoolEncoding {
/// Encode `true` as `1` and `false` as `0`. This is the default behavior.
case numeric
/// Encode `true` and `false` as string literals.
case literal
func encode(value: Bool) -> String {
switch self {
case .numeric:
return value ? "1" : "0"
case .literal:
return value ? "true" : "false"
}
}
}
// MARK: Properties
/// Returns a default `URLEncoding` instance with a `.methodDependent` destination.
public static var `default`: URLEncoding { URLEncoding() }
/// Returns a `URLEncoding` instance with a `.queryString` destination.
public static var queryString: URLEncoding { URLEncoding(destination: .queryString) }
/// Returns a `URLEncoding` instance with an `.httpBody` destination.
public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) }
/// The destination defining where the encoded query string is to be applied to the URL request.
public let destination: Destination
/// The encoding to use for `Array` parameters.
public let arrayEncoding: ArrayEncoding
/// The encoding to use for `Bool` parameters.
public let boolEncoding: BoolEncoding
// MARK: Initialization
/// Creates an instance using the specified parameters.
///
/// - Parameters:
/// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by
/// default.
/// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default.
/// - boolEncoding: `BoolEncoding` to use. `.numeric` by default.
public init(destination: Destination = .methodDependent,
arrayEncoding: ArrayEncoding = .brackets,
boolEncoding: BoolEncoding = .numeric) {
self.destination = destination
self.arrayEncoding = arrayEncoding
self.boolEncoding = boolEncoding
}
// MARK: Encoding
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if let method = urlRequest.method, destination.encodesParametersInURL(for: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.headers["Content-Type"] == nil {
urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
}
urlRequest.httpBody = Data(query(parameters).utf8)
}
return urlRequest
}
/// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.
///
/// - Parameters:
/// - key: Key of the query component.
/// - value: Value of the query component.
///
/// - Returns: The percent-escaped, URL encoded query string components.
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
switch value {
case let dictionary as [String: Any]:
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
case let array as [Any]:
for (index, value) in array.enumerated() {
components += queryComponents(fromKey: arrayEncoding.encode(key: key, atIndex: index), value: value)
}
case let number as NSNumber:
if number.isBool {
components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue))))
} else {
components.append((escape(key), escape("\(number)")))
}
case let bool as Bool:
components.append((escape(key), escape(boolEncoding.encode(value: bool))))
default:
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Creates a percent-escaped string following RFC 3986 for a query string key or value.
///
/// - Parameter string: `String` to be percent-escaped.
///
/// - Returns: The percent-escaped `String`.
public func escape(_ string: String) -> String {
string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
}
// MARK: -
/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
public struct JSONEncoding: ParameterEncoding {
public enum Error: Swift.Error {
case invalidJSONObject
}
// MARK: Properties
/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncoding { JSONEncoding() }
/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) }
/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions
// MARK: Initialization
/// Creates an instance using the specified `WritingOptions`.
///
/// - Parameter options: `JSONSerialization.WritingOptions` to use.
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
// MARK: Encoding
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
guard JSONSerialization.isValidJSONObject(parameters) else {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject))
}
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.headers["Content-Type"] == nil {
urlRequest.headers.update(.contentType("application/json"))
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
/// Encodes any JSON compatible object into a `URLRequest`.
///
/// - Parameters:
/// - urlRequest: `URLRequestConvertible` value into which the object will be encoded.
/// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default.
///
/// - Returns: The encoded `URLRequest`.
/// - Throws: Any `Error` produced during encoding.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let jsonObject = jsonObject else { return urlRequest }
guard JSONSerialization.isValidJSONObject(jsonObject) else {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: Error.invalidJSONObject))
}
do {
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
if urlRequest.headers["Content-Type"] == nil {
urlRequest.headers.update(.contentType("application/json"))
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}
extension JSONEncoding.Error {
public var localizedDescription: String {
"""
Invalid JSON object provided for parameter or object encoding. \
This is most likely due to a value which can't be represented in Objective-C.
"""
}
}
// MARK: -
extension NSNumber {
fileprivate var isBool: Bool {
// Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of
// swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22).
String(cString: objCType) == "c"
}
}
| mit | 8cc51f46033904840fbb3cd68975ec54 | 40.236842 | 167 | 0.651705 | 4.932844 | false | false | false | false |
btanner/Eureka | Source/Validations/RuleLength.swift | 6 | 3078 | // RuleLength.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct RuleMinLength: RuleType {
let min: UInt
public var id: String?
public var validationError: ValidationError
public init(minLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have at least \(minLength) characters"
min = minLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value, !value.isEmpty else { return nil }
return value.count < Int(min) ? validationError : nil
}
}
public struct RuleMaxLength: RuleType {
let max: UInt
public var id: String?
public var validationError: ValidationError
public init(maxLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have less than \(maxLength) characters"
max = maxLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value, !value.isEmpty else { return nil }
return value.count > Int(max) ? validationError : nil
}
}
public struct RuleExactLength: RuleType {
let length: UInt
public var id: String?
public var validationError: ValidationError
public init(exactLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have exactly \(exactLength) characters"
length = exactLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value, !value.isEmpty else { return nil }
return value.count != Int(length) ? validationError : nil
}
}
| mit | 73e7396bd5ea99fc5c656f3fa1c23aba | 35.642857 | 86 | 0.687459 | 4.480349 | false | false | false | false |
society2012/PGDBK | PGDBK/PGDBK/Code/Member/Controller/RegisterViewController.swift | 1 | 2800 | //
// RegisterViewController.swift
// PGDBK
//
// Created by hupeng on 2017/7/5.
// Copyright © 2017年 m.zintao. All rights reserved.
//
import UIKit
import SVProgressHUD
class RegisterViewController: BaseViewController {
@IBOutlet var confirmFild: UITextField!
@IBOutlet var pwdFild: UITextField!
@IBOutlet var userNameFild: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "注册"
// Do any additional setup after loading the view.
}
@IBAction func registerAction(_ sender: UIButton) {
if(self.userNameFild.text == nil || self.userNameFild.text == ""){
SVProgressHUD.showError(withStatus: "用户名不能为空")
return
}
if(self.pwdFild.text == nil || self.pwdFild.text == ""){
SVProgressHUD.showError(withStatus: "密码不能为空")
return
}
if(self.confirmFild.text == nil || self.confirmFild.text == ""){
SVProgressHUD.showError(withStatus: "确认密码不能为空")
return
}
if(self.pwdFild.text != self.confirmFild.text){
SVProgressHUD.showError(withStatus: "两次输入的密码不同")
return
}
goRegister()
}
func goRegister() -> Void {
SVProgressHUD.show(withStatus: "注册中")
SVProgressHUD.setDefaultStyle(.dark)
let url = SERVER_IP + "/index.php/api/AppInterface/registerApp"
let parmertas = ["username":self.userNameFild.text!,"password":self.pwdFild.text!]
NetWorkTools.requestData(URLString: url, type: .post, parmertas: parmertas) { (response) in
SVProgressHUD.dismiss()
guard let data = response as? [String:Any] else{return}
let code = data["code"] as?Int
let message = data["message"] as?String
if(code == 200){
SVProgressHUD.showSuccess(withStatus: "注册成功")
}else{
SVProgressHUD.showError(withStatus: message)
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let first = (touches as NSSet).allObjects.first as!UITouch
if(first.tapCount == 1){
self.view.endEditing(true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 1709675791172c22a7a82e6b47021f4b | 27.621053 | 106 | 0.587716 | 4.516611 | false | false | false | false |
sodascourse/swift-introduction | Swift-Introduction.playground/Pages/Collections - Dictionary.xcplaygroundpage/Contents.swift | 1 | 4142 | /*:
# Collections
Swift provides three primary collection types, known as arrays, sets, and dictionaries,
for storing collections of values.
- Arrays are **ordered** collections of values.
- Sets are **unordered** collections of **unique values**.
- Dictionaries are **unordered** collections of **key-value associations**.
Arrays, sets, and dictionaries in Swift are always clear about
the types of values and keys that they can store.
This means that you cannot insert a value of the wrong type into a collection
by mistake. It also means you can be confident about the type of values you
will retrieve from a collection.
If you create an array, a set, or a dictionary, and assign it to a variable,
the collection that is created will be mutable. You can change the collection
by adding, removing, or changing items in the collection.
If you assign an array, a set, or a dictionary to a constant,
that collection is immutable, and its size and contents cannot be changed.
*/
/*:
## Dictionaries
A dictionary stores associations between **keys** of the same type and
**values** of the same type in a collection with no defined ordering.
Each value is associated with a unique key, which acts as an identifier for
that value within the dictionary.
Unlike items in an array, items in a dictionary do not have a specified order.
You use a dictionary when you need to look up values based on their identifier,
in much the same way that a real-world dictionary is used to look up the
definition for a particular word.
### Dictionary Creation
Dictionary could be created by using Dictionary's initializers or with the
dictionary literals.
A _key-value pair_ is a combination of a key and a value. In a dictionary literal,
the key and value in each key-value pair are separated by **a colon** (`:`).
The key-value pairs are written as _a list_, separated by commas (`,`),
surrounded by a pair of square brackets.
*/
var airports = [
"TPE": "Taipei Taoyuan",
"HND": "Tokyo Haneda",
"NRT": "Tokyo Narita"
]
let emptyStringIntPairDictionary = Dictionary<String, Int>()
let emptyStringFloatPairDictionary = [String: Float]()
let emptyStringBoolPairDictionary: [String: Bool] = [:]
/*:
### Dictionary Type
The type of a Swift dictionary is written in full as `Dictionary<Key, Value>`,
where `Key` is the type of value that can be used as a dictionary key,
and `Value` is the type of value that the dictionary stores for those keys.
You can also write the type of a dictionary in shorthand form as `[Key: Value]`.
Although the two forms are functionally identical, the shorthand form is preferred
and is used throughout this guide when referring to the type of a dictionary.
*/
var fruitsColors: Dictionary<String, String> = [
"apple": "red",
"banana": "yellow",
"orange": "orange",
]
let numberNames: [Int: [String]] = [
1: ["One", "ichi", "いち"],
2: ["Two", "ni", "に"],
4: ["Four", "yon", "よん"],
7: ["Seven", "nana", "なな"],
8: ["Eight", "hachi", "はち"],
]
/*:
### Dictionary and Operators
- We use bracket operator (`[]`) to access the content of a dictionary
by a given key.
*/
let colorOfApple = fruitsColors["apple"]!
let colorOfWatermelon = fruitsColors["watermelon"]
// Try to use "option+click" to see the type of above two constants.
fruitsColors["grape"] = "purple"
fruitsColors
fruitsColors["grape"] = nil
fruitsColors["watermelon"] = nil
fruitsColors
//numberNames[3] = ["Three", "san", "さん"]
// Try to uncomment the above line to see what Xcode yields
/*:
### Properties and Methods of Dictionaries
*/
emptyStringIntPairDictionary.isEmpty
numberNames.count
let numbers = Array(numberNames.keys)
let colors = Set(fruitsColors.values)
/*:
### Dictionaries and Control flows
The `for-in` loop is great to enumerate key-value pairs in a dictionary.
*/
for (fruit, color) in fruitsColors {
"\(fruit) is \(color)."
}
for fruit in fruitsColors.keys {
fruit
}
for color in fruitsColors.values {
color
}
//: ---
//:
//: [<- Previous](@previous) | [Next ->](@next)
//:
| apache-2.0 | 5eddc3c29a698c2661180b81eca81eff | 28.640288 | 88 | 0.707039 | 3.980676 | false | false | false | false |
FranDepascuali/ProyectoAlimentar | ProyectoAlimentar/Resources/FontPalette.swift | 1 | 961 | //
// FontPalette.swift
// ProyectoAlimentar
//
// Created by Francisco Depascuali on 9/21/16.
// Copyright © 2016 Alimentar. All rights reserved.
//
import UIKit
public enum RobotoFont: String {
case Medium = "Roboto-Medium"
case Bold = "Roboto-Bold"
}
public extension UILabel {
public func setFont(_ type: RobotoFont = .Medium, pointSize: Float? = nil) {
let size = pointSize ?? Float(self.font.pointSize)
self.font = UIFont(type: type, pointSize: size)
self.sizeToFit()
}
}
public extension UITextView {
public func setFont(_ type: RobotoFont = .Medium, pointSize: Float? = nil) {
let size = pointSize ?? Float(self.font!.pointSize)
self.font = UIFont(type: type, pointSize: size)
self.sizeToFit()
}
}
public extension UIFont {
public convenience init(type: RobotoFont, pointSize: Float) {
self.init(name: type.rawValue, size: CGFloat(pointSize))!
}
}
| apache-2.0 | 038d509578af5b311df34a3209ff75cc | 21.325581 | 80 | 0.651042 | 3.72093 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/GrouppedTableView/HLCustomPointSelectionVC/HLCustomPointSelectionVC.swift | 1 | 3198 | import UIKit
@objc protocol HLCustomPointSelectionDelegate: NSObjectProtocol {
func didSelectCustomSearchLocationPoint(_ searchLocationPoint: HDKSearchLocationPoint)
}
@objcMembers
class HLCustomPointSelectionVC: HLCommonVC, MKMapViewDelegate, HLLocateMeMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var pinImageView: UIImageView!
@IBOutlet weak var pinBottomShadowImageView: UIImageView!
@IBOutlet weak var pinBigShadowImageView: UIImageView!
@IBOutlet weak var locateMeMapView: HLLocateMeMapView!
weak var delegate: HLCustomPointSelectionDelegate?
var initialSearchInfoLocation: CLLocation?
let spanDegrees: CLLocationDegrees = iPad() ? 0.1 : 0.05
// MARK: - VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = NSLS("HL_LOC_SELECT_POINT_ON_MAP_TITLE")
HLLocationManager.shared().hasUserGrantedLocationAccess(onCompletion: { accessGranted in
self.mapView.showsUserLocation = accessGranted
})
locateMeMapView.delegate = self
let sel = #selector(HLCustomPointSelectionVC.selectSearchLocationPoint)
let doneItem = UIBarButtonItem(title:NSLS("HL_LOC_FILTER_APPLY_BUTTON"), style:.plain, target:self, action:sel)
navigationItem.rightBarButtonItem = doneItem
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let searchInfoLocation = initialSearchInfoLocation {
mapView.region = MKCoordinateRegion.init(center: searchInfoLocation.coordinate, span: MKCoordinateSpan.init(latitudeDelta: spanDegrees, longitudeDelta: spanDegrees))
initialSearchInfoLocation = nil
}
}
@objc func selectSearchLocationPoint() {
let coordinate = mapView.convert(pinBottomShadowImageView.center, toCoordinateFrom: view)
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
goBack()
let point = HLCustomSearchLocationPoint(location: location, nearbyCities: [])
delegate?.didSelectCustomSearchLocationPoint(point)
}
// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let pin = MKAnnotationView()
pin.image = UIImage(named: "userLocationPin")
return pin
}
func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
locateMeMapView.locateMeButton.isSelected = false
}
// MARK: - HLLocateMeMapViewDelegate
func locateMeMapView(_ locateMeMapView: HLLocateMeMapView, shouldShowUserLocation userLocation: CLLocation?) {
guard let coordinate = userLocation?.coordinate else { return }
var point = mapView.convert(coordinate, toPointTo: view)
point.y -= bottomLayoutGuide.length / 2.0
mapView.setCenter(mapView.convert(point, toCoordinateFrom: view), animated: true)
locateMeMapView.locateMeButton.isSelected = true
HLLocationManager.shared().hasUserGrantedLocationAccess(onCompletion: { accessGranted in
self.mapView.showsUserLocation = accessGranted
})
}
}
| mit | 5057780c85c8992e33870739124936c4 | 37.071429 | 177 | 0.726391 | 5.1168 | false | false | false | false |
angmu/SwiftPlayCode | swift练习/playground Test.playground/Contents.swift | 1 | 1947 | //: Playground - noun: a place where people can play
import UIKit
import XCPlayground
let color = UIColor.redColor()
let frame = CGRect(x: 0, y: 0, width: 150, height: 80)
let point = CGPoint(x: 100, y: 100)
let size = CGSize(width: 100, height: 80)
let image = UIImage(named: "me")
let image2 = UIImage(named: "baidu")
let url = NSURL(string: "https://www.baidu.com")
let attrString = NSAttributedString(string: "this is an attributedString", attributes: [NSForegroundColorAttributeName: UIColor.yellowColor(), NSFontAttributeName: UIFont.systemFontOfSize(50.0)])
/* ##3 显示带"+"号按钮的视图 */
let view = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 60))
view.backgroundColor = UIColor.whiteColor()
let addBtn = UIButton(type: .ContactAdd)
addBtn.center = CGPoint(x: view.center.x, y: view.center.y)
view.addSubview(addBtn)
/* ##4 sin(i) = i */
for i in 0..<100
{
let f = Float(i)
sin(f) * f
}
/* ##4 显示结果 */
XCPlaygroundPage.currentPage.liveView = view
XCPlaygroundPage.currentPage.captureValue(frame, withIdentifier: "this is a frame")
XCPlaygroundPage.currentPage.captureValue(color, withIdentifier: "show red color")
XCPlaygroundPage.currentPage.captureValue(attrString, withIdentifier: "this is a string")
/* ##5 图形 */
let triange = Shape(frame: frame, type: .Triangle)
let square = Shape(frame: frame, type: .Square)
let round = Shape(frame: frame, type: .Round)
var path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
path = XCPSharedDataDirectoryPath.stringByAppendingString("/nice.png")
let sharedImage = UIImage(contentsOfFile: path!)
/* ##5 字面量 */
let literImage = [#Image(imageLiteral: "[email protected]")#]
let literalFile = [#FileReference(fileReferenceLiteral: "Info.plist")#]
let literalColor = [#Color(colorLiteralRed: 0.2078431397676468, green: 0.7490196228027344, blue: 0.3333333432674408, alpha: 1)#]
| mit | 1f404acaa613f5c4e7364b8567652966 | 29.822581 | 195 | 0.727368 | 3.487226 | false | false | false | false |
yagiz/Bagel | mac/Bagel/Workers/ContentRepresentation/ContentRepresentation/OverviewRepresentation/OverviewRepresentation.swift | 1 | 3168 | //
// OverviewRepresentation.swift
// Bagel
//
// Created by Yagiz Gurgul on 21.10.2018.
// Copyright © 2018 Yagiz Lab. All rights reserved.
//
import Cocoa
class OverviewRepresentation: ContentRepresentation {
init(requestInfo: BagelRequestInfo?) {
super.init()
if let requestInfo = requestInfo {
var overviewString = ""
overviewString = overviewString + (requestInfo.requestMethod?.rawValue ?? "")
overviewString = overviewString + " "
overviewString = overviewString + (requestInfo.url ?? "")
overviewString = overviewString + "\n\n"
overviewString = overviewString + "Response Code: "
overviewString = overviewString + (requestInfo.statusCode ?? "")
if let requestURLString = requestInfo.url, let requestURL = URL(string: requestURLString) {
let contentRawString = (ContentRepresentationParser.keyValueRepresentation(url: requestURL).rawString ?? "")
if contentRawString.count > 0 {
overviewString = overviewString + "\n\n"
overviewString = overviewString + "URL Parameters:\n"
overviewString = overviewString + contentRawString
}
}
if let requestHeaders = requestInfo.requestHeaders {
let contentRawString = ContentRepresentationParser.keyValueRepresentation(dictionary: requestHeaders).rawString ?? ""
if contentRawString.count > 0 {
overviewString = overviewString + "\n\n"
overviewString = overviewString + "Request Headers:\n"
overviewString = overviewString + contentRawString
}
}
if let requestBodyData = requestInfo.requestBody?.base64Data {
let contentRawString = ContentRepresentationParser.dataRepresentation(data: requestBodyData)?.rawString ?? ""
if contentRawString.count > 0 {
overviewString = overviewString + "\n\n"
overviewString = overviewString + "Request Body:\n"
overviewString = overviewString + contentRawString
}
}
if let responseBodyData = requestInfo.responseData?.base64Data {
let contentRawString = ContentRepresentationParser.dataRepresentation(data: responseBodyData)?.rawString ?? ""
if contentRawString.count > 0 {
overviewString = overviewString + "\n\n"
overviewString = overviewString + "Response Body:\n"
overviewString = overviewString + contentRawString
}
}
self.rawString = overviewString
}
}
}
| apache-2.0 | c4b11e3e4a27c8c3983fd17c57aad742 | 37.621951 | 133 | 0.529207 | 6.334 | false | false | false | false |
goblinr/omim | iphone/Maps/UI/Appearance/ThemeManager.swift | 7 | 1885 | @objc(MWMThemeManager)
final class ThemeManager: NSObject {
private static let autoUpdatesInterval: TimeInterval = 30 * 60 // 30 minutes in seconds
private static let instance = ThemeManager()
private weak var timer: Timer?
private override init() { super.init() }
private func update(theme: MWMTheme) {
let actualTheme: MWMTheme = { theme in
let isVehicleRouting = MWMRouter.isRoutingActive() && (MWMRouter.type() == .vehicle)
switch theme {
case .day: fallthrough
case .vehicleDay: return isVehicleRouting ? .vehicleDay : .day
case .night: fallthrough
case .vehicleNight: return isVehicleRouting ? .vehicleNight : .night
case .auto:
guard isVehicleRouting else { return .day }
switch MWMFrameworkHelper.daytime() {
case .day: return .vehicleDay
case .night: return .vehicleNight
}
}
}(theme)
let nightMode = UIColor.isNightMode()
let newNightMode: Bool = { theme in
switch theme {
case .day: fallthrough
case .vehicleDay: return false
case .night: fallthrough
case .vehicleNight: return true
case .auto: assert(false); return false
}
}(actualTheme)
MWMFrameworkHelper.setTheme(actualTheme)
if nightMode != newNightMode {
UIColor.setNightMode(newNightMode)
(UIViewController.topViewController() as! MWMController).mwm_refreshUI()
}
}
@objc static func invalidate() {
instance.update(theme: MWMSettings.theme())
}
@objc static var autoUpdates: Bool {
get {
return instance.timer != nil
}
set {
if newValue {
instance.timer = Timer.scheduledTimer(timeInterval: autoUpdatesInterval, target: self, selector: #selector(invalidate), userInfo: nil, repeats: true)
} else {
instance.timer?.invalidate()
}
invalidate()
}
}
}
| apache-2.0 | ff03629e11badfe9845704a7890175b2 | 28.920635 | 157 | 0.657825 | 4.404206 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/BitcoinCashKit/Domain/Services/BitcoinCashTxNotesStrategy.swift | 1 | 3308 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import ToolKit
import WalletPayloadKit
public protocol BitcoinCashTxNotesStrategyAPI: TxNoteUpdateProvideStrategyAPI {}
final class BitcoinCashTxNotesStrategy: BitcoinCashTxNotesStrategyAPI {
private let repository: BitcoinCashWalletAccountRepository
private let updater: BitcoinCashEntryFetcherAPI
private let nativeWalletFeatureEnabled: () -> AnyPublisher<Bool, Never>
init(
repository: BitcoinCashWalletAccountRepository,
updater: BitcoinCashEntryFetcherAPI,
nativeWalletFeatureEnabled: @escaping () -> AnyPublisher<Bool, Never> = { nativeWalletFlagEnabled() }
) {
self.repository = repository
self.updater = updater
self.nativeWalletFeatureEnabled = nativeWalletFeatureEnabled
}
func note(
txHash: String
) -> AnyPublisher<String?, TxNotesError> {
nativeWalletFeatureEnabled()
.flatMap { [repository] isEnabled -> AnyPublisher<String?, TxNotesError> in
guard isEnabled else {
return .just(nil) // JS didn't support this
}
return repository.bitcoinCashEntry
.mapError { _ in TxNotesError.unableToRetrieveNote }
.compactMap { $0 }
.map { entry in
entry.txNotes?[txHash]
}
.first()
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
func updateNote(
txHash: String,
note: String?
) -> AnyPublisher<EmptyValue, TxNotesError> {
nativeWalletFeatureEnabled()
.flatMap { [repository, updater] isEnabled -> AnyPublisher<EmptyValue, TxNotesError> in
guard isEnabled else {
return .failure(.unabledToSave) // JS didn't support this
}
return repository.bitcoinCashEntry
.first()
.mapError { _ in TxNotesError.unableToRetrieveNote }
.compactMap { $0 }
.map { entry -> BitcoinCashEntry in
let notes = entry.txNotes
let updatedNotes = transcationNotesUpdate(notes: notes, hash: txHash, note: note)
return BitcoinCashEntry(
payload: entry.payload,
accounts: entry.accounts,
txNotes: updatedNotes
)
}
.flatMap { updatedEntry -> AnyPublisher<EmptyValue, TxNotesError> in
updater.update(entry: updatedEntry)
.mapError { _ in TxNotesError.unabledToSave }
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
.handleEvents(
receiveCompletion: { [repository] completion in
guard case .finished = completion else {
return
}
repository.invalidateCache()
}
)
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | 8537d0325b1f6ffedeac2e6069f12e07 | 37.905882 | 109 | 0.542486 | 5.771379 | false | false | false | false |
calkinssean/TIY-Assignments | Day 37/RealmApp/RealmApp/NotesTableViewController.swift | 1 | 3507 | //
// NotesTableViewController.swift
// RealmApp
//
// Created by Sean Calkins on 3/23/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
import RealmSwift
class NotesTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var currentUser = User()
var arrayOfNotes = [Note]()
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
for n in currentUser.notes {
self.arrayOfNotes.append(n)
}
self.tableView.reloadData()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addTapped")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let n = arrayOfNotes[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("Note Cell", forIndexPath: indexPath)
cell.textLabel?.text = n.noteDescription
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfNotes.count
}
func addTapped() {
print("add tapped")
let ac = UIAlertController(title: "Add", message: "Add a note", preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default) {
(alertAction) -> Void in
let date = NSDate()
let n = Note()
n.createdAt = date
n.user = self.currentUser
if let textField = ac.textFields?.first,
let name = textField.text {
n.noteDescription = name
}
try! self.realm.write {
self.currentUser.notes.append(n)
self.realm.add(n)
}
self.arrayOfNotes.append(n)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
(alertAction) -> Void in
}
ac.addTextFieldWithConfigurationHandler { (textField) -> Void in
}
ac.addAction(saveAction)
ac.addAction(cancelAction)
presentViewController(ac, animated: true, completion: nil)
}
@IBAction func editProfileTapped(sender: BorderButton) {
performSegueWithIdentifier("editProfileSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "editProfileSegue" {
let controller = segue.destinationViewController as! EditProfileViewController
controller.currentUser = self.currentUser
}
}
@IBAction func searchByNameTapped(sender: BorderButton) {
performSegueWithIdentifier("searchByNameSegue", sender: self)
}
@IBAction func searchByDateTapped(sender: BorderButton) {
performSegueWithIdentifier("searchByDateSegue", sender: self)
}
@IBAction func unwindSegue (segue: UIStoryboardSegue) {}
}
| cc0-1.0 | 2a2c166a8e90d5f5ac4c3a525a8ae6f6 | 28.216667 | 121 | 0.581289 | 5.565079 | false | false | false | false |
KoNEW/SwiftyDefaults | Example/SwiftyDefaults/ViewController.swift | 1 | 997 | //
// ViewController.swift
// SwiftDefaults
//
// Created by shimesaba9 on 01/12/2016.
// Copyright (c) 2016 shimesaba9. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let md = MyDefaults()
print("Value1: \(md.value1)") // nil
print("Value2: \(md.value2)") // "Some value"
print("Value3: \(md.value3)") // 1
print("Value4: \(md.value4)") // nil
md.value1 = "Some another value"
md.value2 = "Some another value 2"
md.value3 = 10
md.value4 = Person(firstName: "Elvis", lastName: "Presley", age: 42)
print("Value1: \(md.value1)") // Optional("Some another value")
print("Value2: \(md.value2)") // "Some an0ther value 2"
print("Value3: \(md.value3)") // 10
print("Value4: \(md.value4)") // Optional(Person=(Optional("Elvis"), Optional("Presley"), 42))
}
}
| mit | eee4f3a44fb3d020cdd38232d41bc063 | 28.323529 | 102 | 0.565697 | 3.548043 | false | false | false | false |
krzysztofzablocki/Sourcery | SourceryFramework/Sources/Parsing/SwiftSyntax/AST/EnumCase+SwiftSyntax.swift | 1 | 2824 | import Foundation
import SwiftSyntax
import SourceryRuntime
extension EnumCase {
convenience init(_ node: EnumCaseElementSyntax, parent: EnumCaseDeclSyntax, annotationsParser: AnnotationsParser) {
var associatedValues: [AssociatedValue] = []
if let paramList = node.associatedValue?.parameterList {
let hasManyValues = paramList.count > 1
associatedValues = paramList
.enumerated()
.map { (idx, param) in
let name = param.firstName?.text.trimmed.nilIfNotValidParameterName
let secondName = param.secondName?.text.trimmed
let defaultValue = param.defaultArgument?.value.description.trimmed
var externalName: String? = secondName
if externalName == nil, hasManyValues {
externalName = name ?? "\(idx)"
}
var collectedAnnotations = Annotations()
if let typeSyntax = param.type {
collectedAnnotations = annotationsParser.annotations(fromToken: typeSyntax)
}
return AssociatedValue(localName: name,
externalName: externalName,
typeName: param.type.map { TypeName($0) } ?? TypeName.unknown(description: parent.description.trimmed),
type: nil,
defaultValue: defaultValue,
annotations: collectedAnnotations
)
}
}
let rawValue: String? = {
var value = node.rawValue?.withEqual(nil).description.trimmed
if let unwrapped = value, unwrapped.hasPrefix("\""), unwrapped.hasSuffix("\""), unwrapped.count > 2 {
value = unwrapped.substring(with: unwrapped.index(after: unwrapped.startIndex) ..< unwrapped.index(before: unwrapped.endIndex))
}
return value
}()
let modifiers = parent.modifiers?.map(Modifier.init) ?? []
let indirect = modifiers.contains(where: {
$0.tokenKind == TokenKind.contextualKeyword("indirect")
})
self.init(
name: node.identifier.text.trimmed,
rawValue: rawValue,
associatedValues: associatedValues,
annotations: annotationsParser.annotations(from: node),
documentation: annotationsParser.documentation(from: node),
indirect: indirect
)
}
static func from(_ node: EnumCaseDeclSyntax, annotationsParser: AnnotationsParser) -> [EnumCase] {
node.elements.compactMap {
EnumCase($0, parent: node, annotationsParser: annotationsParser)
}
}
}
| mit | cdf428e515ffd86f43f1955527e792e0 | 41.787879 | 144 | 0.569405 | 5.728195 | false | false | false | false |
QueryKit/QueryKit | Tests/QueryKitTests/QuerySetTests.swift | 1 | 8190 | //
// QuerySetTests.swift
// QueryKit
//
// Created by Kyle Fuller on 06/07/2014.
//
//
import XCTest
import CoreData
import QueryKit
class QuerySetTests: XCTestCase {
var context:NSManagedObjectContext!
var queryset:QuerySet<Person>!
override func setUp() {
super.setUp()
context = NSManagedObjectContext()
context.persistentStoreCoordinator = persistentStoreCoordinator()
let company = Company.create(context)
company.name = "Cocode"
for name in ["Kyle", "Orta", "Ayaka", "Mark", "Scott"] {
let person = Person.create(context)
person.name = name
if name == "Kyle" {
person.company = company
}
}
try! context.save()
queryset = QuerySet(context, "Person")
}
func testEqualQuerySetIsEquatable() {
XCTAssertEqual(queryset, QuerySet(context, "Person"))
}
// MARK: Sorting
func testOrderByKeyPathAscending() {
let qs = queryset.orderBy(\.name, ascending: true)
XCTAssertEqual(qs.sortDescriptors, [
NSSortDescriptor(key: "name", ascending: true),
])
}
func testOrderByKeyPathDecending() {
let qs = queryset.orderBy(\.name, ascending: false)
XCTAssertEqual(qs.sortDescriptors, [
NSSortDescriptor(key: "name", ascending: false),
])
}
func testOrderBySortDescriptor() {
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let qs = queryset.orderBy(sortDescriptor)
XCTAssertTrue(qs.sortDescriptors == [sortDescriptor])
}
func testOrderBySortDescriptors() {
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let qs = queryset.orderBy([sortDescriptor])
XCTAssertTrue(qs.sortDescriptors == [sortDescriptor])
}
func testTypeSafeOrderBySortDescriptor() {
let qs = queryset.orderBy { $0.name.ascending() }
XCTAssertTrue(qs.sortDescriptors == [NSSortDescriptor(key: "name", ascending: true)])
}
func testTypeSafeOrderBySortDescriptors() {
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let qs = queryset.orderBy { [$0.name.ascending() as SortDescriptor<Person>] }
XCTAssertTrue(qs.sortDescriptors == [sortDescriptor])
}
func testReverseOrdering() {
let nameSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let ageSortDescriptor = NSSortDescriptor(key: "age", ascending: true)
let qs = queryset.orderBy([nameSortDescriptor, ageSortDescriptor]).reverse()
XCTAssertEqual(qs.sortDescriptors, [
NSSortDescriptor(key: "name", ascending: false),
NSSortDescriptor(key: "age", ascending: false),
])
}
// MARK: Filtering
func testFilterKeyPath() {
let qs = queryset.filter(\.name == "Kyle")
XCTAssertEqual(qs.predicate?.description, "name == \"Kyle\"")
}
func testFilterPredicate() {
let predicate = NSPredicate(format: "name == Kyle")
let qs = queryset.filter(predicate)
XCTAssertEqual(qs.predicate!, predicate)
}
func testFilterPredicates() {
let predicateName = NSPredicate(format: "name == Kyle")
let predicateAge = NSPredicate(format: "age > 27")
let qs = queryset.filter([predicateName, predicateAge])
XCTAssertEqual(qs.predicate!, NSPredicate(format: "name == Kyle AND age > 27"))
}
func testFilterBooleanAttribute() {
let qs = queryset.filter(Attribute<Bool>("isEmployed"))
XCTAssertEqual(qs.predicate!, NSPredicate(format: "isEmployed == YES"))
}
func testTypeSafeFilter() {
let qs = queryset.filter { $0.name == "Kyle" }
XCTAssertEqual(qs.predicate?.description, "name == \"Kyle\"")
}
func testTypeSafeFilerEqualWithNilRHS() {
let qs = queryset.filter { $0.name == nil }
XCTAssertEqual(qs.predicate?.description, "name == <null>")
}
func testTypeSafeRelatedFilterPredicate() {
let at = Attribute<Company>("company")
XCTAssertEqual(at.name.key, "company.name")
let qs = queryset.filter { $0.company.name == "Cocode" }
XCTAssertEqual(qs.predicate?.description, "company.name == \"Cocode\"")
}
// MARK: Exclusion
func testExcludeKeyPath() {
let qs = queryset.exclude(\.name == "Kyle")
XCTAssertEqual(qs.predicate?.description, "NOT name == \"Kyle\"")
}
func testExcludePredicate() {
let predicate = NSPredicate(format: "name == Kyle")
let qs = queryset.exclude(predicate)
XCTAssertEqual(qs.predicate!, NSPredicate(format: "NOT name == Kyle"))
}
func testExcludePredicates() {
let predicateName = NSPredicate(format: "name == Kyle")
let predicateAge = NSPredicate(format: "age > 27")
let qs = queryset.exclude([predicateName, predicateAge])
XCTAssertEqual(qs.predicate!, NSPredicate(format: "NOT (name == Kyle AND age > 27)"))
}
func testExcludeBooleanAttribute() {
let qs = queryset.exclude(Attribute<Bool>("isEmployed"))
XCTAssertEqual(qs.predicate!, NSPredicate(format: "isEmployed == NO"))
}
func testTypeSafeExclude() {
let qs = queryset.exclude { $0.name == "Kyle" }
XCTAssertEqual(qs.predicate?.description, "NOT name == \"Kyle\"")
}
// Fetch Request
func testConversionToFetchRequest() {
let predicate = NSPredicate(format: "name == Kyle")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let qs = queryset.filter(predicate).orderBy(sortDescriptor)[2..<4]
let fetchRequest = qs.fetchRequest
XCTAssertEqual(fetchRequest.entityName!, "Person")
XCTAssertEqual(fetchRequest.predicate!, predicate)
// XCTAssertEqual(fetchRequest.sortDescriptors!, [sortDescriptor])
XCTAssertEqual(fetchRequest.fetchOffset, 2)
XCTAssertEqual(fetchRequest.fetchLimit, 2)
}
// MARK: Subscripting
func testSubscriptingAtIndex() {
let qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))
let ayaka = try! qs.object(0)
let kyle = try! qs.object(1)
let mark = try! qs.object(2)
let orta = try! qs.object(3)
let scott = try! qs.object(4)
XCTAssertEqual(ayaka!.name, "Ayaka")
XCTAssertEqual(kyle!.name, "Kyle")
XCTAssertEqual(mark!.name, "Mark")
XCTAssertEqual(orta!.name, "Orta")
XCTAssertEqual(scott!.name, "Scott")
}
func testSubscriptingRange() {
let qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))[0...2]
XCTAssertEqual(qs.range!.startIndex, 0)
XCTAssertEqual(qs.range!.endIndex, 3)
}
func testSubscriptingRangeSubscriptsCurrentRange() {
var qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))
qs = qs[2...5]
qs = qs[2...4]
XCTAssertEqual(qs.range!.startIndex, 4)
XCTAssertEqual(qs.range!.endIndex, 5)
}
// MARK: Getters
func testFirst() {
let qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))
let name = try! qs.first()?.name
XCTAssertEqual(name, "Ayaka")
}
func testLast() {
let qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))
let name = try! qs.last()?.name
XCTAssertEqual(name, "Scott")
}
// MARK: Conversion
func testConversionToArray() {
let qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))[0...1]
let people = AssertNotThrow(try qs.array()) ?? []
XCTAssertEqual(people.count, 2)
}
// MARK: Count
func testCount() {
let qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))[0...1]
let count = AssertNotThrow(try qs.count())
XCTAssertEqual(count!, 2)
}
// MARK: Exists
func testExistsReturnsTrueWithMatchingObjects() {
let qs = queryset.filter(NSPredicate(format: "name == %@", "Kyle"))
let exists = AssertNotThrow(try qs.exists()) ?? false
XCTAssertTrue(exists)
}
func testExistsReturnsFalseWithNoMatchingObjects() {
let qs = queryset.filter(NSPredicate(format: "name == %@", "None"))
let exists = AssertNotThrow(try qs.exists()) ?? true
XCTAssertFalse(exists)
}
// MARK: Deletion
func testDelete() {
let qs = queryset.orderBy(NSSortDescriptor(key: "name", ascending: true))
let deletedCount = AssertNotThrow(try qs[0...1].delete()) ?? 0
let count = AssertNotThrow(try qs.count()) ?? 0
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(count, 3)
}
}
| bsd-2-clause | b2656260ddbff5904b03e6fbd39afa35 | 27.939929 | 89 | 0.677534 | 4.046443 | false | true | false | false |
wayfair/brickkit-ios | Source/Bricks/Label/LabelBrick.swift | 1 | 8166 | //
// LabelBrickCell.swift
// BrickApp
//
// Created by Ruben Cagnie on 5/25/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import UIKit
public typealias ConfigureLabelBlock = ((_ cell: LabelBrickCell) -> Void)
// MARK: - Nibs
public struct LabelBrickNibs {
public static let Default = UINib(nibName: LabelBrick.nibName, bundle: LabelBrick.bundle)
public static let Chevron = UINib(nibName: "LabelBrickChevron", bundle: LabelBrick.bundle)
public static let Image = UINib(nibName: "LabelBrickImage", bundle: LabelBrick.bundle)
public static let Button = UINib(nibName: "LabelBrickButton", bundle: LabelBrick.bundle)
}
// MARK: - Brick
open class LabelBrick: GenericBrick<UILabel> {
weak var dataSource: LabelBrickCellDataSource?
weak var delegate: LabelBrickCellDelegate?
open override class var internalIdentifier: String {
return self.nibName
}
open override class var cellClass: UICollectionViewCell.Type? {
return LabelBrickCell.self
}
open override class var bundle: Bundle {
return Bundle(for: Brick.self)
}
open var text: String? {
set {
if let model = dataSource as? LabelBrickCellModel {
model.text = newValue ?? ""
} else {
fatalError("Can't set `text` of a LabelBrick where its dataSource is not a LabelBrickCellModel")
}
}
get {
if let model = dataSource as? LabelBrickCellModel {
return model.text
} else {
fatalError("Can't get `text` of a LabelBrick where its dataSource is not a LabelBrickCellModel")
}
}
}
open var configureCellBlock: ConfigureLabelBlock? {
set {
if let model = dataSource as? LabelBrickCellModel {
model.configureCellBlock = newValue
} else {
fatalError("Can't set `configureCellBlock` of a LabelBrick where its dataSource is not a LabelBrickCellModel")
}
}
get {
if let model = dataSource as? LabelBrickCellModel {
return model.configureCellBlock
} else {
fatalError("Can't get `configureCellBlock` of a LabelBrick where its dataSource is not a LabelBrickCellModel")
}
}
}
fileprivate var dataSourceModel: LabelBrickCellModel?
fileprivate var delegateModel: LabelBrickCellModel?
public convenience init(_ identifier: String = "", width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 50)), backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, text: String, configureCellBlock: ConfigureLabelBlock? = nil) {
let model = LabelBrickCellModel(text: text, configureCellBlock: configureCellBlock)
self.init(identifier, width: width, height: height, backgroundColor: backgroundColor, backgroundView: backgroundView, dataSource: model)
}
public convenience init(_ identifier: String = "", width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 50)), backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, dataSource: LabelBrickCellDataSource, delegate: LabelBrickCellDelegate? = nil) {
self.init(identifier, size: BrickSize(width: width, height: height), backgroundColor: backgroundColor, backgroundView: backgroundView, dataSource: dataSource, delegate: delegate)
}
public convenience init(_ identifier: String = "", size: BrickSize, backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, text: String, configureCellBlock: ConfigureLabelBlock? = nil) {
let model = LabelBrickCellModel(text: text, configureCellBlock: configureCellBlock)
self.init(identifier, size: size, backgroundColor: backgroundColor, backgroundView: backgroundView, dataSource: model)
}
public init(_ identifier: String = "", size: BrickSize, backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, dataSource: LabelBrickCellDataSource, delegate: LabelBrickCellDelegate? = nil) {
self.dataSource = dataSource
self.delegate = delegate
super.init(identifier, size: size, backgroundColor: backgroundColor, backgroundView: backgroundView, configureView: { (label: UILabel, cell: BrickCell) in
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 14)
})
if let delegateModel = delegate as? LabelBrickCellModel {
self.delegateModel = delegateModel
}
if let dataSourceModel = dataSource as? LabelBrickCellModel , delegate !== dataSource {
self.dataSourceModel = dataSourceModel
}
}
}
// MARK: - DataSource
/// An object that adopts the `LabelBrickCellDataSource` protocol is responsible for providing the data required by a `LabelBrick`.
public protocol LabelBrickCellDataSource: class {
func configureLabelBrickCell(_ cell: LabelBrickCell)
}
// MARK: - Delegate
public protocol LabelBrickCellDelegate: class {
func buttonTouchedForLabelBrickCell(_ cell: LabelBrickCell)
}
// MARK: - Models
open class LabelBrickCellModel: LabelBrickCellDataSource {
open var text: String
open var configureCellBlock: ConfigureLabelBlock?
open var textColor: UIColor?
public init(text:String, textColor:UIColor? = nil, configureCellBlock: ConfigureLabelBlock? = nil){
self.text = text
self.textColor = textColor
self.configureCellBlock = configureCellBlock
}
open func configureLabelBrickCell(_ cell: LabelBrickCell) {
let label = cell.label
label?.text = text
if let color = textColor {
label?.textColor = color
}
configureCellBlock?(cell)
}
}
open class LabelWithDecorationImageBrickCellModel: LabelBrickCellModel {
open var image: UIImage
public init(text:String, textColor:UIColor? = nil, image:UIImage, configureCellBlock: ConfigureLabelBlock? = nil) {
self.image = image
super.init(text: text, textColor: textColor, configureCellBlock: configureCellBlock)
}
override open func configureLabelBrickCell(_ cell: LabelBrickCell) {
if let imageView = cell.imageView {
imageView.image = image
}
super.configureLabelBrickCell(cell)
}
}
// MARK: - Cell
open class LabelBrickCell: GenericBrickCell, Bricklike {
public typealias BrickType = LabelBrick
@IBOutlet weak open var label: UILabel!
@IBOutlet weak open var button: UIButton?
@IBOutlet weak open var horizontalRuleLeft: UIView?
@IBOutlet weak open var horizontalRuleRight: UIView?
@IBOutlet weak open var imageView: UIImageView?
override open func updateContent() {
horizontalRuleLeft?.isHidden = true
horizontalRuleRight?.isHidden = true
super.updateContent()
if !fromNib {
self.label = (self.genericContentView as! UILabel)
}
brick.dataSource?.configureLabelBrickCell(self)
}
override open func prepareForReuse() {
super.prepareForReuse()
self.backgroundColor = .clear
self.backgroundView = nil
self.isHidden = false
self.edgeInsets = UIEdgeInsets.zero
self.accessoryView = nil
self.label.text = nil
self.label.attributedText = nil
self.label.textAlignment = .natural
self.label.numberOfLines = 0
self.label.textColor = .black
self.label.isHidden = false
self.label.backgroundColor = .clear
self.horizontalRuleLeft = nil
self.horizontalRuleRight = nil
if !fromNib {
self.button = nil
self.imageView?.image = nil
}
}
@IBAction func buttonTapped(_ sender: UIButton) {
brick.delegate?.buttonTouchedForLabelBrickCell(self)
}
#if os(tvOS)
override public var allowsFocus: Bool {
get {
return true
}
set {
super.allowsFocus = true
}
}
#endif
}
| apache-2.0 | 4464f467ea01fd7d3986aeb70927ad1e | 34.5 | 310 | 0.668953 | 4.92164 | false | true | false | false |
glyuck/GlyuckDataGrid | Source/Cells/DataGridViewBaseCell.swift | 1 | 2968 | //
// DataGridViewBaseCell.swift
// Pods
//
// Created by Vladimir Lyukov on 12/08/15.
//
//
import UIKit
/**
Base class for data grid view cells.
*/
open class DataGridViewBaseCell: UICollectionViewCell {
/// The inset or outset margins for the rectangle around the cell’s text label.
open dynamic var textLabelInsets = UIEdgeInsets.zero
/// Background color for highlighted state.
open dynamic var highlightedBackgroundColor = UIColor(white: 0.9, alpha: 1)
/// Background color for selected state.
open dynamic var selectedBackgroundColor = UIColor(white: 0.8, alpha: 1)
/// Helper object for configuring cell borders.
open lazy var border: BorderHelper = {
BorderHelper(view: self)
}()
/// Returns the label used for the main textual content of the table cell. (read-only)
fileprivate(set) open lazy var textLabel: UILabel = {
let label = UILabel(frame: self.bounds)
self.contentView.addSubview(label)
return label
}()
// MARK: - UICollectionViewCell
open override var isHighlighted: Bool {
didSet {
contentView.backgroundColor = isHighlighted ? highlightedBackgroundColor : UIColor.clear
}
}
open override var isSelected: Bool {
didSet {
contentView.backgroundColor = isSelected ? selectedBackgroundColor : UIColor.clear
}
}
open override func layoutSubviews() {
super.layoutSubviews()
textLabel.frame = UIEdgeInsetsInsetRect(bounds, textLabelInsets)
}
open override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
if layer == self.layer {
border.layoutLayersInFrame(layer.frame)
}
}
}
// Border getters/setters for UIAppearance
extension DataGridViewBaseCell {
public dynamic var borderTopWidth: CGFloat {
get { return border.topWidth }
set { border.topWidth = newValue }
}
public dynamic var borderTopColor: UIColor {
get { return border.topColor }
set { border.topColor = newValue }
}
public dynamic var borderLeftWidth: CGFloat {
get { return border.leftWidth }
set { border.leftWidth = newValue }
}
public dynamic var borderLeftColor: UIColor {
get { return border.leftColor }
set { border.leftColor = newValue }
}
public dynamic var borderBottomWidth: CGFloat {
get { return border.bottomWidth }
set { border.bottomWidth = newValue }
}
public dynamic var borderBottomColor: UIColor {
get { return border.bottomColor }
set { border.bottomColor = newValue }
}
public dynamic var borderRightWidth: CGFloat {
get { return border.rightWidth }
set { border.rightWidth = newValue }
}
public dynamic var borderRightColor: UIColor {
get { return border.rightColor }
set { border.rightColor = newValue }
}
}
| mit | 9d252ca4c25d72411cf763c296eed775 | 29.895833 | 100 | 0.658463 | 4.7456 | false | false | false | false |
thompsonate/Shifty | Pods/AXSwift/Sources/UIElement.swift | 1 | 25670 | import Cocoa
import Foundation
/// Holds and interacts with any accessibility element.
///
/// This class wraps every operation that operates on AXUIElements.
///
/// - seeAlso: [OS X Accessibility Model](https://developer.apple.com/library/mac/documentation/Accessibility/Conceptual/AccessibilityMacOSX/OSXAXmodel.html)
///
/// Note that every operation involves IPC and is tied to the event loop of the target process. This
/// means that operations are synchronous and can hang until they time out. The default timeout is
/// 6 seconds, but it can be changed using `setMessagingTimeout` and `setGlobalMessagingTimeout`.
///
/// Every attribute- or action-related function has an enum version and a String version. This is
/// because certain processes might report attributes or actions not documented in the standard API.
/// These will be ignored by enum functions (and you can't specify them). Most users will want to
/// use the enum-based versions, but if you want to be exhaustive or use non-standard attributes and
/// actions, you can use the String versions.
///
/// ### Error handling
///
/// Unless otherwise specified, during reads, "missing data/attribute" errors are handled by
/// returning optionals as nil. During writes, missing attribute errors are thrown.
///
/// Other failures are all thrown, including if messaging fails or the underlying AXUIElement
/// becomes invalid.
///
/// #### Possible Errors
/// - `Error.APIDisabled`: The accessibility API is disabled. Your application must request and
/// receive special permission from the user to be able to use these APIs.
/// - `Error.InvalidUIElement`: The UI element has become invalid, perhaps because it was destroyed.
/// - `Error.CannotComplete`: There is a problem with messaging, perhaps because the application is
/// being unresponsive. This error will be thrown when a message times
/// out.
/// - `Error.NotImplemented`: The process does not fully support the accessibility API.
/// - Anything included in the docs of the method you are calling.
///
/// Any undocumented errors thrown are bugs and should be reported.
///
/// - seeAlso: [AXUIElement.h reference](https://developer.apple.com/library/mac/documentation/ApplicationServices/Reference/AXUIElement_header_reference/)
open class UIElement {
public let element: AXUIElement
/// Create a UIElement from a raw AXUIElement object.
///
/// The state and role of the AXUIElement is not checked.
public required init(_ nativeElement: AXUIElement) {
// Since we are dealing with low-level C APIs, it never hurts to double check types.
assert(CFGetTypeID(nativeElement) == AXUIElementGetTypeID(),
"nativeElement is not an AXUIElement")
element = nativeElement
}
/// Checks if the current process is a trusted accessibility client. If false, all APIs will
/// throw errors.
///
/// - parameter withPrompt: Whether to show the user a prompt if the process is untrusted. This
/// happens asynchronously and does not affect the return value.
open class func isProcessTrusted(withPrompt showPrompt: Bool = false) -> Bool {
let options = [
kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: showPrompt as CFBoolean
]
return AXIsProcessTrustedWithOptions(options as CFDictionary)
}
/// Timeout in seconds for all UIElement messages. Use this to control how long a method call
/// can delay execution. The default is `0` which means to use the system default.
open class var globalMessagingTimeout: Float {
get { return systemWideElement.messagingTimeout }
set { systemWideElement.messagingTimeout = newValue }
}
// MARK: - Attributes
/// Returns the list of all attributes.
///
/// Does not include parameterized attributes.
open func attributes() throws -> [Attribute] {
let attrs = try attributesAsStrings()
for attr in attrs where Attribute(rawValue: attr) == nil {
print("Unrecognized attribute: \(attr)")
}
return attrs.compactMap({ Attribute(rawValue: $0) })
}
// This version is named differently so the caller doesn't have to specify the return type when
// using the enum version.
open func attributesAsStrings() throws -> [String] {
var names: CFArray?
let error = AXUIElementCopyAttributeNames(element, &names)
if error == .noValue || error == .attributeUnsupported {
return []
}
guard error == .success else {
throw error
}
// We must first convert the CFArray to a native array, then downcast to an array of
// strings.
return names! as [AnyObject] as! [String]
}
/// Returns whether `attribute` is supported by this element.
///
/// The `attribute` method returns nil for unsupported attributes and empty attributes alike,
/// which is more convenient than dealing with exceptions (which are used for more serious
/// errors). However, if you'd like to specifically test an attribute is actually supported, you
/// can use this method.
open func attributeIsSupported(_ attribute: Attribute) throws -> Bool {
return try attributeIsSupported(attribute.rawValue)
}
open func attributeIsSupported(_ attribute: String) throws -> Bool {
// Ask to copy 0 values, since we are only interested in the return code.
var value: CFArray?
let error = AXUIElementCopyAttributeValues(element, attribute as CFString, 0, 0, &value)
if error == .attributeUnsupported {
return false
}
if error == .noValue {
return true
}
guard error == .success else {
throw error
}
return true
}
/// Returns whether `attribute` is writeable.
open func attributeIsSettable(_ attribute: Attribute) throws -> Bool {
return try attributeIsSettable(attribute.rawValue)
}
open func attributeIsSettable(_ attribute: String) throws -> Bool {
var settable: DarwinBoolean = false
let error = AXUIElementIsAttributeSettable(element, attribute as CFString, &settable)
if error == .noValue || error == .attributeUnsupported {
return false
}
guard error == .success else {
throw error
}
return settable.boolValue
}
/// Returns the value of `attribute`, if it exists.
///
/// - parameter attribute: The name of a (non-parameterized) attribute.
///
/// - returns: An optional containing the value of `attribute` as the desired type, or nil.
/// If `attribute` is an array, all values are returned.
///
/// - warning: This method force-casts the attribute to the desired type, which will abort if
/// the cast fails. If you want to check the return type, ask for Any.
open func attribute<T>(_ attribute: Attribute) throws -> T? {
return try self.attribute(attribute.rawValue)
}
open func attribute<T>(_ attribute: String) throws -> T? {
var value: AnyObject?
let error = AXUIElementCopyAttributeValue(element, attribute as CFString, &value)
if error == .noValue || error == .attributeUnsupported {
return nil
}
guard error == .success else {
throw error
}
return (unpackAXValue(value!) as! T)
}
/// Sets the value of `attribute` to `value`.
///
/// - warning: Unlike read-only methods, this method throws if the attribute doesn't exist.
///
/// - throws:
/// - `Error.AttributeUnsupported`: `attribute` isn't supported.
/// - `Error.IllegalArgument`: `value` is an illegal value.
/// - `Error.Failure`: A temporary failure occurred.
open func setAttribute(_ attribute: Attribute, value: Any) throws {
try setAttribute(attribute.rawValue, value: value)
}
open func setAttribute(_ attribute: String, value: Any) throws {
let error = AXUIElementSetAttributeValue(element, attribute as CFString, packAXValue(value))
guard error == .success else {
throw error
}
}
/// Gets multiple attributes of the element at once.
///
/// - parameter attributes: An array of attribute names. Nonexistent attributes are ignored.
///
/// - returns: A dictionary mapping provided parameter names to their values. Parameters which
/// don't exist or have no value will be absent.
///
/// - throws: If there are any errors other than .NoValue or .AttributeUnsupported, it will
/// throw the first one it encounters.
///
/// - note: Presumably you would use this API for performance, though it's not explicitly
/// documented by Apple that there is actually a difference.
open func getMultipleAttributes(_ names: Attribute...) throws -> [Attribute: Any] {
return try getMultipleAttributes(names)
}
open func getMultipleAttributes(_ attributes: [Attribute]) throws -> [Attribute: Any] {
let values = try fetchMultiAttrValues(attributes.map({ $0.rawValue }))
return try packMultiAttrValues(attributes, values: values)
}
open func getMultipleAttributes(_ attributes: [String]) throws -> [String: Any] {
let values = try fetchMultiAttrValues(attributes)
return try packMultiAttrValues(attributes, values: values)
}
// Helper: Gets list of values
fileprivate func fetchMultiAttrValues(_ attributes: [String]) throws -> [AnyObject] {
var valuesCF: CFArray?
let error = AXUIElementCopyMultipleAttributeValues(
element,
attributes as CFArray,
// keep going on errors (particularly NoValue)
AXCopyMultipleAttributeOptions(rawValue: 0),
&valuesCF)
guard error == .success else {
throw error
}
return valuesCF! as [AnyObject]
}
// Helper: Packs names, values into dictionary
fileprivate func packMultiAttrValues<Attr>(_ attributes: [Attr],
values: [AnyObject]) throws -> [Attr: Any] {
var result = [Attr: Any]()
for (index, attribute) in attributes.enumerated() {
if try checkMultiAttrValue(values[index]) {
result[attribute] = unpackAXValue(values[index])
}
}
return result
}
// Helper: Checks if value is present and not an error (throws on nontrivial errors).
fileprivate func checkMultiAttrValue(_ value: AnyObject) throws -> Bool {
// Check for null
if value is NSNull {
return false
}
// Check for error
if CFGetTypeID(value) == AXValueGetTypeID() &&
AXValueGetType(value as! AXValue).rawValue == kAXValueAXErrorType {
var error: AXError = AXError.success
AXValueGetValue(value as! AXValue, AXValueType(rawValue: kAXValueAXErrorType)!, &error)
assert(error != .success)
if error == .noValue || error == .attributeUnsupported {
return false
} else {
throw error
}
}
return true
}
// MARK: Array attributes
/// Returns all the values of the attribute as an array of the given type.
///
/// - parameter attribute: The name of the array attribute.
///
/// - throws: `Error.IllegalArgument` if the attribute isn't an array.
open func arrayAttribute<T>(_ attribute: Attribute) throws -> [T]? {
return try arrayAttribute(attribute.rawValue)
}
open func arrayAttribute<T>(_ attribute: String) throws -> [T]? {
guard let value: Any = try self.attribute(attribute) else {
return nil
}
guard let array = value as? [AnyObject] else {
// For consistency with the other array attribute APIs, throw if it's not an array.
throw AXError.illegalArgument
}
return array.map({ unpackAXValue($0) as! T })
}
/// Returns a subset of values from an array attribute.
///
/// - parameter attribute: The name of the array attribute.
/// - parameter startAtIndex: The index of the array to start taking values from.
/// - parameter maxValues: The maximum number of values you want.
///
/// - returns: An array of up to `maxValues` values starting at `startAtIndex`.
/// - The array is empty if `startAtIndex` is out of range.
/// - `nil` if the attribute doesn't exist or has no value.
///
/// - throws: `Error.IllegalArgument` if the attribute isn't an array.
open func valuesForAttribute<T: AnyObject>
(_ attribute: Attribute, startAtIndex index: Int, maxValues: Int) throws -> [T]? {
return try valuesForAttribute(attribute.rawValue, startAtIndex: index, maxValues: maxValues)
}
open func valuesForAttribute<T: AnyObject>
(_ attribute: String, startAtIndex index: Int, maxValues: Int) throws -> [T]? {
var values: CFArray?
let error = AXUIElementCopyAttributeValues(
element, attribute as CFString, index, maxValues, &values
)
if error == .noValue || error == .attributeUnsupported {
return nil
}
guard error == .success else {
throw error
}
let array = values! as [AnyObject]
return array.map({ unpackAXValue($0) as! T })
}
/// Returns the number of values an array attribute has.
/// - returns: The number of values, or `nil` if `attribute` isn't an array (or doesn't exist).
open func valueCountForAttribute(_ attribute: Attribute) throws -> Int? {
return try valueCountForAttribute(attribute.rawValue)
}
open func valueCountForAttribute(_ attribute: String) throws -> Int? {
var count: Int = 0
let error = AXUIElementGetAttributeValueCount(element, attribute as CFString, &count)
if error == .attributeUnsupported || error == .illegalArgument {
return nil
}
guard error == .success else {
throw error
}
return count
}
// MARK: Parameterized attributes
/// Returns a list of all parameterized attributes of the element.
///
/// Parameterized attributes are attributes that require parameters to retrieve. For example,
/// the cell contents of a spreadsheet might require the row and column of the cell you want.
open func parameterizedAttributes() throws -> [Attribute] {
return try parameterizedAttributesAsStrings().compactMap({ Attribute(rawValue: $0) })
}
open func parameterizedAttributesAsStrings() throws -> [String] {
var names: CFArray?
let error = AXUIElementCopyParameterizedAttributeNames(element, &names)
if error == .noValue || error == .attributeUnsupported {
return []
}
guard error == .success else {
throw error
}
// We must first convert the CFArray to a native array, then downcast to an array of
// strings.
return names! as [AnyObject] as! [String]
}
/// Returns the value of the parameterized attribute `attribute` with parameter `param`.
///
/// The expected type of `param` depends on the attribute. See the
/// [NSAccessibility Informal Protocol Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Protocols/NSAccessibility_Protocol/)
/// for more info.
open func parameterizedAttribute<T, U>(_ attribute: Attribute, param: U) throws -> T? {
return try parameterizedAttribute(attribute.rawValue, param: param)
}
open func parameterizedAttribute<T, U>(_ attribute: String, param: U) throws -> T? {
var value: AnyObject?
let error = AXUIElementCopyParameterizedAttributeValue(
element, attribute as CFString, param as AnyObject, &value
)
if error == .noValue || error == .attributeUnsupported {
return nil
}
guard error == .success else {
throw error
}
return (unpackAXValue(value!) as! T)
}
// MARK: Attribute helpers
// Checks if the value is an AXValue and if so, unwraps it.
// If the value is an AXUIElement, wraps it in UIElement.
fileprivate func unpackAXValue(_ value: AnyObject) -> Any {
switch CFGetTypeID(value) {
case AXUIElementGetTypeID():
return UIElement(value as! AXUIElement)
case AXValueGetTypeID():
let type = AXValueGetType(value as! AXValue)
switch type {
case .axError:
var result: AXError = .success
let success = AXValueGetValue(value as! AXValue, type, &result)
assert(success)
return result
case .cfRange:
var result: CFRange = CFRange()
let success = AXValueGetValue(value as! AXValue, type, &result)
assert(success)
return result
case .cgPoint:
var result: CGPoint = CGPoint.zero
let success = AXValueGetValue(value as! AXValue, type, &result)
assert(success)
return result
case .cgRect:
var result: CGRect = CGRect.zero
let success = AXValueGetValue(value as! AXValue, type, &result)
assert(success)
return result
case .cgSize:
var result: CGSize = CGSize.zero
let success = AXValueGetValue(value as! AXValue, type, &result)
assert(success)
return result
case .illegal:
return value
@unknown default:
return value
}
default:
return value
}
}
// Checks if the value is one supported by AXValue and if so, wraps it.
// If the value is a UIElement, unwraps it to an AXUIElement.
fileprivate func packAXValue(_ value: Any) -> AnyObject {
switch value {
case let val as UIElement:
return val.element
case var val as CFRange:
return AXValueCreate(AXValueType(rawValue: kAXValueCFRangeType)!, &val)!
case var val as CGPoint:
return AXValueCreate(AXValueType(rawValue: kAXValueCGPointType)!, &val)!
case var val as CGRect:
return AXValueCreate(AXValueType(rawValue: kAXValueCGRectType)!, &val)!
case var val as CGSize:
return AXValueCreate(AXValueType(rawValue: kAXValueCGSizeType)!, &val)!
default:
return value as AnyObject // must be an object to pass to AX
}
}
// MARK: - Actions
/// Returns a list of actions that can be performed on the element.
open func actions() throws -> [Action] {
return try actionsAsStrings().compactMap({ Action(rawValue: $0) })
}
open func actionsAsStrings() throws -> [String] {
var names: CFArray?
let error = AXUIElementCopyActionNames(element, &names)
if error == .noValue || error == .attributeUnsupported {
return []
}
guard error == .success else {
throw error
}
// We must first convert the CFArray to a native array, then downcast to an array of strings.
return names! as [AnyObject] as! [String]
}
/// Returns the human-readable description of `action`.
open func actionDescription(_ action: Action) throws -> String? {
return try actionDescription(action.rawValue)
}
open func actionDescription(_ action: String) throws -> String? {
var description: CFString?
let error = AXUIElementCopyActionDescription(element, action as CFString, &description)
if error == .noValue || error == .actionUnsupported {
return nil
}
guard error == .success else {
throw error
}
return description! as String
}
/// Performs the action `action` on the element, returning on success.
///
/// - note: If the action times out, it might mean that the application is taking a long time to
/// actually perform the action. It doesn't necessarily mean that the action wasn't
/// performed.
/// - throws: `Error.ActionUnsupported` if the action is not supported.
open func performAction(_ action: Action) throws {
try performAction(action.rawValue)
}
open func performAction(_ action: String) throws {
let error = AXUIElementPerformAction(element, action as CFString)
guard error == .success else {
throw error
}
}
// MARK: -
/// Returns the process ID of the application that the element is a part of.
///
/// Throws only if the element is invalid (`Errors.InvalidUIElement`).
open func pid() throws -> pid_t {
var pid: pid_t = -1
let error = AXUIElementGetPid(element, &pid)
guard error == .success else {
throw error
}
return pid
}
/// The timeout in seconds for all messages sent to this element. Use this to control how long a
/// method call can delay execution. The default is `0`, which means to use the global timeout.
///
/// - note: Only applies to this instance of UIElement, not other instances that happen to equal
/// it.
/// - seeAlso: `UIElement.globalMessagingTimeout(_:)`
open var messagingTimeout: Float = 0 {
didSet {
messagingTimeout = max(messagingTimeout, 0)
let error = AXUIElementSetMessagingTimeout(element, messagingTimeout)
// InvalidUIElement errors are only relevant when actually passing messages, so we can
// ignore them here.
guard error == .success || error == .invalidUIElement else {
fatalError("Unexpected error setting messaging timeout: \(error)")
}
}
}
// Gets the element at the specified coordinates.
// This can only be called on applications and the system-wide element, so it is internal here.
func elementAtPosition(_ x: Float, _ y: Float) throws -> UIElement? {
var result: AXUIElement?
let error = AXUIElementCopyElementAtPosition(element, x, y, &result)
if error == .noValue {
return nil
}
guard error == .success else {
throw error
}
return UIElement(result!)
}
// TODO: convenience functions for attributes
// TODO: get any attribute as a UIElement or [UIElement] (or a subclass)
// TODO: promoters
}
// MARK: - CustomStringConvertible
extension UIElement: CustomStringConvertible {
public var description: String {
var roleString: String
var description: String?
let pid = try? self.pid()
do {
let role = try self.role()
roleString = role?.rawValue ?? "UIElementNoRole"
switch role {
case .some(.application):
description = pid
.flatMap { NSRunningApplication(processIdentifier: $0) }
.flatMap { $0.bundleIdentifier } ?? ""
case .some(.window):
description = (try? attribute(.title) ?? "") ?? ""
default:
break
}
} catch AXError.invalidUIElement {
roleString = "InvalidUIElement"
} catch {
roleString = "UnknownUIElement"
}
let pidString = (pid == nil) ? "??" : String(pid!)
return "<\(roleString) \""
+ "\(description ?? String(describing: element))"
+ "\" (pid=\(pidString))>"
}
public var inspect: String {
guard let attributeNames = try? attributes() else {
return "InvalidUIElement"
}
guard let attributes = try? getMultipleAttributes(attributeNames) else {
return "InvalidUIElement"
}
return "\(attributes)"
}
}
// MARK: - Equatable
extension UIElement: Equatable {}
public func ==(lhs: UIElement, rhs: UIElement) -> Bool {
return CFEqual(lhs.element, rhs.element)
}
// MARK: - Convenience getters
extension UIElement {
/// Returns the role (type) of the element, if it reports one.
///
/// Almost all elements report a role, but this could return nil for elements that aren't
/// finished initializing.
///
/// - seeAlso: [Roles](https://developer.apple.com/library/mac/documentation/AppKit/Reference/NSAccessibility_Protocol_Reference/index.html#//apple_ref/doc/constant_group/Roles)
public func role() throws -> Role? {
// should this be non-optional?
if let str: String = try self.attribute(.role) {
return Role(rawValue: str)
} else {
return nil
}
}
/// - seeAlso: [Subroles](https://developer.apple.com/library/mac/documentation/AppKit/Reference/NSAccessibility_Protocol_Reference/index.html#//apple_ref/doc/constant_group/Subroles)
public func subrole() throws -> Subrole? {
if let str: String = try self.attribute(.subrole) {
return Subrole(rawValue: str)
} else {
return nil
}
}
}
| gpl-3.0 | 5344c6d726f0f53499f6452dfbcf633d | 37.086053 | 187 | 0.624075 | 4.857143 | false | false | false | false |
joshpc/AutoWebkit | Tests/AutoWebkitTests/ScriptActionTests.swift | 1 | 12915 | //
// ScriptActionTests.swift
// AutoWebkit
//
// Created by Joshua Tessier on 2017-06-28.
// Copyright © 2017 Joshua Tessier. All rights reserved.
//
import XCTest
import WebKit
@testable import AutoWebkit
class MockWebview: WKWebView {
var attemptedUrl: String?
var attemptedJavascript: String?
var attemptedBody: String?
var attemptedBaseURL: URL?
override func load(_ request: URLRequest) -> WKNavigation? {
attemptedUrl = request.url?.absoluteString
return nil
}
override func loadHTMLString(_ string: String, baseURL: URL?) -> WKNavigation? {
attemptedBody = string
attemptedBaseURL = baseURL
return nil
}
override func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Void)? = nil) {
attemptedJavascript = javaScriptString
completionHandler?(nil, nil)
}
}
class ScriptActionTests: XCTestCase {
var webView: MockWebview!
var completedExpectation: XCTestExpectation!
var context: ScriptContext!
override func setUp() {
super.setUp()
context = ScriptContext()
webView = MockWebview()
completedExpectation = XCTestExpectation()
}
// MARK: LoadActions
func testLoadAction() {
let action = LoadAction.load(url: URL(string: "http://www.banana.com/")!)
action.performAction(with: webView, context: context) { (error) in
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("http://www.banana.com/", webView.attemptedUrl)
}
func testLoadHtmlString() {
let html = "<html><body>banana</body></html>"
let url = URL(string: "http://www.banana.com/")!
let action = LoadAction.loadHtml(html: html, baseURL: url)
action.performAction(with: webView, context: context) { (error) in
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual(webView.attemptedBody, html)
XCTAssertEqual(webView.attemptedBaseURL, url)
}
// MARK: DomActions
func testSetAttributeAction() {
let action = DomAction.setAttribute(name: "banana", value: "dinosaur", selector: "[id=\"red\"]")
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("{ var element = document.querySelector(\"[id=\"red\"]\");element.setAttribute(\'banana\', \'dinosaur\'); }", webView.attemptedJavascript)
}
func testSetAttributeWithContextAction() {
let action = DomAction.setAttributeWithContext(name: "banana", contextKey: "dinosaur", selector: "[id=\"red\"]")
context.environment["dinosaur"] = "coconut"
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("{ var element = document.querySelector(\"[id=\"red\"]\");element.setAttribute(\'banana\', \'coconut\'); }", webView.attemptedJavascript)
}
func testRemoveAttributeAction() {
let action = DomAction.setAttribute(name: "banana", value: nil, selector: "[id=\"red\"]")
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("{ var element = document.querySelector(\"[id=\"red\"]\");element.removeAttribute(\'banana\'); }", webView.attemptedJavascript)
}
func testRemoveAttributeWithContextAction() {
let action = DomAction.setAttributeWithContext(name: "banana", contextKey: "not present", selector: "[id=\"red\"]")
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("{ var element = document.querySelector(\"[id=\"red\"]\");element.removeAttribute(\'banana\'); }", webView.attemptedJavascript)
}
func testSubmitAction() {
var action = DomAction.submit(selector: "form[name=\"banana\"]", shouldBlock: true)
context.hasLoaded = true
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
XCTAssertFalse(context.hasLoaded)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("{ var element = document.querySelector(\"form[name=\"banana\"]\");element.submit(); }", webView.attemptedJavascript)
context.hasLoaded = true
action = DomAction.submit(selector: "form[name=\"banana\"]", shouldBlock: false)
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertTrue(context.hasLoaded)
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("{ var element = document.querySelector(\"form[name=\"banana\"]\");element.submit(); }", webView.attemptedJavascript)
}
func testGetHtmlAction() {
let action = DomAction.getHtml { html, context, error, completion in
completion(context, error)
}
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("document.documentElement.outerHTML.toString();", webView.attemptedJavascript)
}
func testGetIFrameHtmlAction() {
let action = DomAction.getIFrameHtml(iFrameSelector: "iframe[id='banana']") { html, context, error, completion in
completion(context, error)
}
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("var element = document.querySelector(\"iframe[id='banana']\");element.contentDocument.documentElement.outerHTML.toString();", webView.attemptedJavascript)
}
func testGetHtmlElementAction() {
let action = DomAction.getHtmlByElement(selector: "form[name=\"banana\"]") { html, context, error, completion in
completion(context, error)
}
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("{ var element = document.querySelector(\"form[name=\"banana\"]\");if (element != null) { element.innerHTML.toString(); } }", webView.attemptedJavascript)
}
// MARK: JavascriptActions
func testEvaluateJavascriptAction() {
let action = JavascriptAction.evaluateJavascript(script: "alert('banana');") { html, context, error, completion in
completion(context, error)
}
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
XCTAssertEqual("alert('banana');", webView.attemptedJavascript)
}
// MARK: WaitActions
func testWaitAction() {
let action = WaitAction.wait(duration: DispatchTimeInterval.seconds(2))
let startTime = Date()
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 3.0))
let duration = abs(startTime.timeIntervalSinceNow)
XCTAssertTrue(duration <= 2.15 && duration >= 1.85)
}
func testWaitForLoaded() {
let action = WaitAction.waitUntilLoaded { context, completion in
completion(context, nil)
}
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
}
// MARK: BranchActions
func testIfPresentSuccess() {
let success: [Scriptable] = [ DebugAction.printMessage(message: "hello"), DebugAction.printMessage(message: "goodbye"), ]
let failure: [Scriptable] = [ WaitAction.wait(duration: DispatchTimeInterval.seconds(1)) ]
let action = Branch.ifIsPresent(key: "banana", success: success, failure: failure)
var context = self.context!
context.environment["banana"] = "dinosaur"
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
//We can't do equality checks on Scriptable values so the count differentiation is sufficient in this test
XCTAssertEqual(2, nextSteps?.count ?? 0)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
}
func testIfPresentFail() {
let success: [Scriptable] = [ DebugAction.printMessage(message: "hello"), DebugAction.printMessage(message: "goodbye"), ]
let failure: [Scriptable] = [ WaitAction.wait(duration: DispatchTimeInterval.seconds(1)) ]
let action = Branch.ifIsPresent(key: "banana", success: success, failure: failure)
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
//We can't do equality checks on Scriptable values so the count differentiation is sufficient in this test
XCTAssertEqual(1, nextSteps?.count ?? 0)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
}
func testIfEqualSuccess() {
let success: [Scriptable] = [ DebugAction.printMessage(message: "hello"), DebugAction.printMessage(message: "goodbye"), ]
let failure: [Scriptable] = [ WaitAction.wait(duration: DispatchTimeInterval.seconds(1)) ]
let action = Branch.ifEquals(key: "banana", value: "12345", success: success, failure: failure)
var context = self.context!
context.environment["banana"] = "12345"
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
//We can't do equality checks on Scriptable values so the count differentiation is sufficient in this test
XCTAssertEqual(2, nextSteps?.count ?? 0)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
}
func testIfEqualNotPresent() {
let success: [Scriptable] = [ DebugAction.printMessage(message: "hello"), DebugAction.printMessage(message: "goodbye"), ]
let failure: [Scriptable] = [ WaitAction.wait(duration: DispatchTimeInterval.seconds(1)) ]
let action = Branch.ifEquals(key: "banana", value: "12345", success: success, failure: failure)
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
//We can't do equality checks on Scriptable values so the count differentiation is sufficient in this test
XCTAssertEqual(1, nextSteps?.count ?? 0)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
}
func testIfEqualFailure() {
let success: [Scriptable] = [ DebugAction.printMessage(message: "hello"), DebugAction.printMessage(message: "goodbye"), ]
let failure: [Scriptable] = [ WaitAction.wait(duration: DispatchTimeInterval.seconds(1)) ]
let action = Branch.ifEquals(key: "banana", value: "12345", success: success, failure: failure)
var context = self.context!
context.environment["banana"] = "NOT RIGHT"
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
//We can't do equality checks on Scriptable values so the count differentiation is sufficient in this test
XCTAssertEqual(1, nextSteps?.count ?? 0)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
}
// MARK: DebugActions
func testPrintDebugMessage() {
let action = DebugAction.printMessage(message: "Test")
//We're only testing to ensure that it calls the completion handler
action.performAction(with: webView, context: context) { (context, error, nextSteps) in
XCTAssertNil(nextSteps)
self.completedExpectation.fulfill()
}
XCTAssertEqual(.completed, XCTWaiter.wait(for: [completedExpectation], timeout: 1.0))
}
}
| mit | bf07090a9466d1a50421513004833048 | 36.870968 | 172 | 0.729596 | 3.87575 | false | true | false | false |
IngmarStein/swift | stdlib/public/core/LifetimeManager.swift | 3 | 4666 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Evaluate `f()` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluate `f(x)` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
extension String {
/// Invokes the given closure on the contents of the string, represented as a
/// pointer to a null-terminated sequence of UTF-8 code units.
///
/// The `withCString(_:)` method ensures that the sequence's lifetime extends
/// through the execution of `f`.
///
/// - Parameter f: A closure that takes a pointer to the string's UTF-8 code
/// unit sequence as its sole argument. If the closure has a return value,
/// it is used as the return value of the `withCString(_:)` method.
/// - Returns: The return value of the `f` closure, if any.
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.utf8CString.withUnsafeBufferPointer {
try body($0.baseAddress!)
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Invokes `body` with an `UnsafeMutablePointer` to `arg` and returns the
/// result. Useful for calling Objective-C APIs that take "in/out"
/// parameters (and default-constructible "out" parameters) by pointer.
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Invokes `body` with an `UnsafePointer` to `arg` and returns the
/// result. Useful for calling Objective-C APIs that take "in/out"
/// parameters (and default-constructible "out" parameters) by pointer.
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
@available(*, unavailable, renamed: "withUnsafeMutablePointer(to:_:)")
public func withUnsafeMutablePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, renamed: "withUnsafePointer(to:_:)")
public func withUnsafePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
| apache-2.0 | 7b90b27c4c59055d51415f6a7be11e25 | 31.402778 | 88 | 0.672953 | 4.001715 | false | false | false | false |
seaburg/IGIdenticon | Identicon/CGImageExtension.swift | 1 | 828 | //
// CGImageExtension.swift
// Example
//
// Created by Evgeniy Yurtaev on 20/11/2016.
// Copyright © 2016 Evgeniy Yurtaev. All rights reserved.
//
import CoreGraphics
extension CGImage {
func scale(toWidth width: Int, height: Int) -> CGImage? {
if (self.width == width && self.height == height) {
return self
}
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: 0,
space: colorSpace ?? CGColorSpaceCreateDeviceRGB(),
bitmapInfo: bitmapInfo.rawValue
) else {
return nil
}
context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height))
return context.makeImage()
}
}
| mit | 4bdf1630ab2adb6a96faf4415d15fe89 | 24.84375 | 80 | 0.570738 | 4.446237 | false | false | false | false |
nixzhu/Baby | Sources/BabyBrain/Value+Code.swift | 1 | 24273 |
/*
* @nixzhu ([email protected])
*/
extension Value {
private func initializerCode(indentation: Indentation, meta: Meta) -> String {
let indent = indentation.value
let indent1 = indentation.deeper.value
var lines: [String] = []
switch self {
case let .object(_, dictionary, keys):
let arguments = keys.map({
let propertyType = dictionary[$0]!.propertyType(key: $0, meta: meta)
return "\($0.propertyName(meta: meta)): \(propertyType.propertyType)"
}).joined(separator: ", ")
lines.append("\(indent)\(meta.publicCode)init(\(arguments)) {")
for key in keys {
let propertyName = key.propertyName(meta: meta)
lines.append("\(indent1)self.\(propertyName.removedQuotationMark()) = \(propertyName)")
}
default:
break
}
lines.append("\(indent)}")
return lines.filter({ !$0.isEmpty }).joined(separator: "\n")
}
private func optionalInitialCodeInArray(indentation: Indentation, meta: Meta, name: String) -> String {
let indent = indentation.value
var lines: [String] = []
let selfType = self.type(key: name, meta: meta)
switch self {
case .empty:
lines.append("\(indent)let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [Any]")
case .null(let optionalValue):
if let value = optionalValue {
if case .object = value {
let propertyName = name.propertyName(meta: meta)
let jsonArray = "\(propertyName)JSONArray"
lines.append("\(indent)let \(jsonArray) = json[\"\(name)\"] as? [\(meta.jsonDictionaryName)?]")
lines.append("\(indent)let \(propertyName) = \(jsonArray).flatMap({ $0.flatMap({ \(name.type(meta: meta, needSingularForm: true))(json: $0) }) })")
} else {
lines.append("\(indent)let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(selfType)]")
}
} else {
lines.append("\(indent)let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(selfType)]")
}
case .bool:
lines.append("\(indent)let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(selfType)]")
case .number, .string:
let propertyType = self.propertyType(key: name, meta: meta)
switch propertyType {
case .normal:
lines.append("\(indent)let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(propertyType.name)]")
case .enum:
lines.append("\(indent)let \(name.propertyName(meta: meta))RawValues = json[\"\(name)\"] as? [\(selfType)]")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(name.propertyName(meta: meta))RawValues.flatMap({ \(propertyType.name.removedQuotationMark())(rawValue: $0) }).flatMap({ $0 })")
}
lines.append("\(indent)let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(selfType)]")
case .object:
let jsonArray = "\(name.propertyName(meta: meta))JSONArray"
lines.append("\(indent)let \(jsonArray) = json[\"\(name)\"] as? [\(meta.jsonDictionaryName)]")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(jsonArray).flatMap({ \(name.type(meta: meta, needSingularForm: true))(json: $0) }).flatMap({ $0 })")
case .array:
lines.append("* Unsupported array in array!")
case .url:
let urlStrings = "\(name.propertyName(meta: meta))Strings"
lines.append("\(indent)let \(urlStrings) = json[\"\(name)\"] as? [String]")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(urlStrings).flatMap({ URL(string: $0)! })")
case .date(let type):
switch type {
case .iso8601:
let dateStrings = "\(name.propertyName(meta: meta))Strings"
lines.append("\(indent)let \(dateStrings) = json[\"\(name)\"] as? [String]")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(dateStrings).flatMap({ DateFormatter.iso8601.date(from: $0) })")
case .dateOnly:
let dateStrings = "\(name.propertyName(meta: meta))Strings"
lines.append("\(indent)let \(dateStrings) = json[\"\(name)\"] as? [String]")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(dateStrings).flatMap({ DateFormatter.dateOnly.date(from: $0) })")
case .secondsSince1970:
let dateTimeIntervals = "\(name.propertyName(meta: meta))TimeIntervals"
lines.append("\(indent)let \(dateTimeIntervals) = json[\"\(name)\"] as? [TimeInterval]")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(dateTimeIntervals).flatMap({ Date(timeIntervalSince1970: $0) })")
}
}
return lines.filter({ !$0.isEmpty }).joined(separator: "\n")
}
private func optionalInitialCode(indentation: Indentation, meta: Meta, key: String) -> String {
let indent = indentation.value
var lines: [String] = []
let selfType = self.type(key: key, meta: meta)
switch self {
case .empty:
lines.append("\(indent)let \(key.propertyName(meta: meta)) = json[\"\(key)\"]")
case .null:
lines.append("\(indent)let \(key.propertyName(meta: meta)) = json[\"\(key)\"]")
case .bool:
lines.append("\(indent)let \(key.propertyName(meta: meta)) = json[\"\(key)\"] as? \(selfType)")
case .number, .string:
let propertyType = self.propertyType(key: key, meta: meta)
switch propertyType {
case .normal:
lines.append("\(indent)let \(key.propertyName(meta: meta)) = json[\"\(key)\"] as? \(propertyType.name)")
case .enum:
lines.append("\(indent)let \(key.propertyName(meta: meta))RawValue = json[\"\(key)\"] as? \(selfType)")
lines.append("\(indent)let \(key.propertyName(meta: meta)) = \(key.propertyName(meta: meta))RawValue.flatMap{( \(propertyType.name.removedQuotationMark())(rawValue: $0) )}")
}
case let .object(name, _, _):
let jsonDictionary = "\(name.propertyName(meta: meta))JSONDictionary"
lines.append("\(indent)let \(jsonDictionary) = json[\"\(name)\"] as? \(meta.jsonDictionaryName)")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(jsonDictionary).flatMap({ \(name.type(meta: meta))(json: $0) })")
case let .array(name, values):
if let value = values.first {
lines.append(value.optionalInitialCodeInArray(indentation: indentation, meta: meta, name: name))
} else {
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [Any] else { return nil }")
}
case .url:
let urlString = "\(key.propertyName(meta: meta))String"
lines.append("\(indent)let \(urlString) = json[\"\(key)\"] as? String")
lines.append("\(indent)let \(key.propertyName(meta: meta)) = \(urlString).flatMap({ URL(string: $0) })")
case .date(let type):
switch type {
case .iso8601:
let dateString = "\(key.propertyName(meta: meta))String"
lines.append("\(indent)let \(dateString) = json[\"\(key)\"] as? String")
lines.append("\(indent)let \(key.propertyName(meta: meta)) = \(dateString).flatMap({ DateFormatter.iso8601.date(from: $0) })")
case .dateOnly:
let dateString = "\(key.propertyName(meta: meta))String"
lines.append("\(indent)let \(dateString) = json[\"\(key)\"] as? String")
lines.append("\(indent)let \(key.propertyName(meta: meta)) = \(dateString).flatMap({ DateFormatter.dateOnly.date(from: $0) })")
case .secondsSince1970:
let dateTimeInterval = "\(key.propertyName(meta: meta))TimeInterval"
lines.append("\(indent)let \(dateTimeInterval) = json[\"\(key)\"] as? TimeInterval")
lines.append("\(indent)let \(key.propertyName(meta: meta)) = \(dateTimeInterval).flatMap({ Date(timeIntervalSince1970: $0) })")
}
}
return lines.filter({ !$0.isEmpty }).joined(separator: "\n")
}
private func initialCodeInArray(indentation: Indentation, meta: Meta, name: String) -> String {
let indent = indentation.value
var lines: [String] = []
let selfType = self.type(key: name, meta: meta)
switch self {
case let .null(optionalValue):
if let value = optionalValue {
if case .object = value {
let propertyName = name.propertyName(meta: meta)
let jsonArray = "\(propertyName)JSONArray"
lines.append("\(indent)guard let \(jsonArray) = json[\"\(name)\"] as? [\(meta.jsonDictionaryName)?] else { return nil }")
lines.append("\(indent)let \(propertyName) = \(jsonArray).map({ $0.flatMap({ \(name.type(meta: meta, needSingularForm: true))(json: $0) }) })")
} else {
let propertyType = value.propertyType(key: name, meta: meta)
switch propertyType {
case .normal:
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(propertyType.name)] else { return nil }")
case .enum:
lines.append("\(indent)guard let \(name.propertyName(meta: meta))RawValue = json[\"\(name)\"] as? [\(selfType)])] else { return nil }")
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = \(propertyType.name.removedQuotationMark())(rawValue: \(name.propertyName(meta: meta))RawValue) else { return nil }")
}
}
} else {
let propertyType = self.propertyType(key: name, meta: meta)
switch propertyType {
case .normal:
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(propertyType.name)] else { return nil }")
case .enum:
lines.append("\(indent)guard let \(name.propertyName(meta: meta))RawValue = json[\"\(name)\"] as? [\(selfType)])] else { return nil }")
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = \(propertyType.name.removedQuotationMark())(rawValue: \(name.propertyName(meta: meta))RawValue) else { return nil }")
}
}
case .empty, .bool:
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(selfType)] else { return nil }")
case .number, .string:
let propertyType = self.propertyType(key: name, meta: meta, inArray: true)
switch propertyType {
case .normal:
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [\(propertyType.name)] else { return nil }")
case .enum:
lines.append("\(indent)guard let \(name.propertyName(meta: meta))RawValues = json[\"\(name)\"] as? [\(selfType)] else { return nil }")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(name.propertyName(meta: meta))RawValues.map({ \(propertyType.name.removedQuotationMark())(rawValue: $0) }).flatMap({ $0 })")
}
case .object:
let jsonArray = "\(name.propertyName(meta: meta))JSONArray"
lines.append("\(indent)guard let \(jsonArray) = json[\"\(name)\"] as? [\(meta.jsonDictionaryName)] else { return nil }")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(jsonArray).map({ \(name.type(meta: meta, needSingularForm: true))(json: $0) }).flatMap({ $0 })")
case .array:
lines.append("* Unsupported array in array!")
case .url:
let urlStrings = "\(name.propertyName(meta: meta))Strings"
lines.append("\(indent)guard let \(urlStrings) = json[\"\(name)\"] as? [String] else { return nil }")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(urlStrings).map({ URL(string: $0) }).flatMap({ $0 })")
case .date(let type):
switch type {
case .iso8601:
let dateStrings = "\(name.propertyName(meta: meta))Strings"
lines.append("\(indent)guard let \(dateStrings) = json[\"\(name)\"] as? [String] else { return nil }")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(dateStrings).flatMap({ DateFormatter.iso8601.date(from: $0) })")
case .dateOnly:
let dateStrings = "\(name.propertyName(meta: meta))Strings"
lines.append("\(indent)guard let \(dateStrings) = json[\"\(name)\"] as? [String] else { return nil }")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(dateStrings).flatMap({ DateFormatter.dateOnly.date(from: $0) })")
case .secondsSince1970:
let dateTimeIntervals = "\(name.propertyName(meta: meta))TimeIntervals"
lines.append("\(indent)guard let \(dateTimeIntervals) = json[\"\(name)\"] as? [TimeInterval] else { return nil }")
lines.append("\(indent)let \(name.propertyName(meta: meta)) = \(dateTimeIntervals).map({ Date(timeIntervalSince1970: $0) })")
}
}
return lines.filter({ !$0.isEmpty }).joined(separator: "\n")
}
private func initialCode(indentation: Indentation, meta: Meta, key: String) -> String {
let indent = indentation.value
var lines: [String] = []
let selfType = self.type(key: key, meta: meta)
switch self {
case .empty:
lines.append("\(indent)guard let \(key.propertyName(meta: meta)) = json[\"\(key)\"] else { return nil }")
case let .null(optionalValue):
if let value = optionalValue {
lines.append(value.optionalInitialCode(indentation: indentation, meta: meta, key: key))
} else {
lines.append("\(indent)let \(key.propertyName(meta: meta)) = json[\"\(key)\"]")
}
case .bool:
lines.append("\(indent)guard let \(key.propertyName(meta: meta)) = json[\"\(key)\"] as? \(selfType) else { return nil }")
case .number, .string:
let propertyType = self.propertyType(key: key, meta: meta)
switch propertyType {
case .normal:
lines.append("\(indent)guard let \(key.propertyName(meta: meta)) = json[\"\(key)\"] as? \(propertyType.name) else { return nil }")
case .enum:
lines.append("\(indent)guard let \(key.propertyName(meta: meta))RawValue = json[\"\(key)\"] as? \(selfType) else { return nil }")
lines.append("\(indent)guard let \(key.propertyName(meta: meta)) = \(propertyType.name.removedQuotationMark())(rawValue: \(key.propertyName(meta: meta))RawValue) else { return nil }")
}
case let .object(name, _, _):
let jsonDictionary = "\(name.propertyName(meta: meta))JSONDictionary"
lines.append("\(indent)guard let \(jsonDictionary) = json[\"\(name)\"] as? \(meta.jsonDictionaryName) else { return nil }")
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = \(name.type(meta: meta))(json: \(jsonDictionary)) else { return nil }")
case let .array(name, values):
if let value = values.first {
lines.append(value.initialCodeInArray(indentation: indentation, meta: meta, name: name))
} else {
lines.append("\(indent)guard let \(name.propertyName(meta: meta)) = json[\"\(name)\"] as? [Any] else { return nil }")
}
case .url:
let urlString = "\(key.propertyName(meta: meta))String"
lines.append("\(indent)guard let \(urlString) = json[\"\(key)\"] as? String else { return nil }")
lines.append("\(indent)guard let \(key.propertyName(meta: meta)) = URL(string: \(urlString)) else { return nil }")
case .date(let type):
switch type {
case .iso8601:
let dateString = "\(key.propertyName(meta: meta))String"
lines.append("\(indent)guard let \(dateString) = json[\"\(key)\"] as? String else { return nil }")
lines.append("\(indent)guard let \(key.propertyName(meta: meta)) = DateFormatter.iso8601.date(from: \(dateString)) else { return nil }")
case .dateOnly:
let dateString = "\(key.propertyName(meta: meta))String"
lines.append("\(indent)guard let \(dateString) = json[\"\(key)\"] as? String else { return nil }")
lines.append("\(indent)guard let \(key.propertyName(meta: meta)) = DateFormatter.dateOnly.date(from: \(dateString)) else { return nil }")
case .secondsSince1970:
let dateTimeInterval = "\(key.propertyName(meta: meta))TimeInterval"
lines.append("\(indent)guard let \(dateTimeInterval) = json[\"\(key)\"] as? TimeInterval else { return nil }")
lines.append("\(indent)let \(key.propertyName(meta: meta)) = Date(timeIntervalSince1970: \(dateTimeInterval))")
}
}
return lines.filter({ !$0.isEmpty }).joined(separator: "\n")
}
private func failableInitializerCode(indentation: Indentation, meta: Meta) -> String {
let indent = indentation.value
let indent1 = indentation.deeper.value
var lines: [String] = []
switch self {
case let .object(_, dictionary, keys):
let declareInit: String
if meta.modelType == "class" {
declareInit = "convenience init"
} else {
declareInit = "init"
}
lines.append("\(indent)\(meta.publicCode)\(declareInit)?(json: \(meta.jsonDictionaryName)) {")
for key in keys {
let value = dictionary[key]!
lines.append(value.initialCode(indentation: indentation.deeper, meta: meta, key: key))
}
let arguments = keys.map({ "\($0.propertyName(meta: meta).removedQuotationMark()): \($0.propertyName(meta: meta))" }).joined(separator: ", ")
lines.append("\(indent1)self.init(\(arguments))")
default:
break
}
lines.append("\(indent)}")
return lines.filter({ !$0.isEmpty }).joined(separator: "\n")
}
public func swiftCode(indentation: Indentation = .default, meta: Meta = .default) -> String {
let indent = indentation.value
let indent1 = indentation.deeper.value
let indent2 = indentation.deeper.deeper.value
switch self {
case let .null(optionalValue):
return optionalValue?.swiftCode(indentation: indentation, meta: meta) ?? ""
case let .object(name, dictionary, keys):
var lines: [String] = []
if meta.codable {
lines.append("\(indent)\(meta.publicCode)\(meta.modelType) \(name.type(meta: meta)): Codable {")
} else {
lines.append("\(indent)\(meta.publicCode)\(meta.modelType) \(name.type(meta: meta)) {")
}
for key in keys {
let value = dictionary[key]!
lines.append(value.swiftCode(indentation: indentation.deeper, meta: meta))
let propertyType = value.propertyType(key: key, meta: meta)
if case .enum(_, _, let rawType, let rawValues) = propertyType {
if meta.codable {
lines.append("\(indent1)\(meta.publicCode)enum \(propertyType.name): \(propertyType.enumRawType), Codable {")
} else {
lines.append("\(indent1)\(meta.publicCode)enum \(propertyType.name): \(propertyType.enumRawType) {")
}
func appendCase(name: String, rawValue: String) {
if name.removedQuotationMark() == rawValue {
lines.append("\(indent2)case \(name)")
} else {
switch rawType {
case .string:
lines.append("\(indent2)case \(name) = \"\(rawValue)\"")
case .int, .double:
lines.append("\(indent2)case \(name) = \(rawValue)")
}
}
}
if let enumCases = meta.enumCases(key: key) {
for enumCase in enumCases {
let caseName = enumCase.name.propertyName(meta: .default)
let caseRawValue = enumCase.rawValue ?? enumCase.name
appendCase(name: caseName, rawValue: caseRawValue)
}
} else {
if !rawValues.isEmpty {
let allRawValues = rawValues.components(separatedBy: Meta.enumRawValueSeparator)
var validCaseRawValues: [String] = []
for rawValue in allRawValues {
if !validCaseRawValues.contains(rawValue) {
validCaseRawValues.append(rawValue)
}
}
for rawValue in validCaseRawValues {
let caseName = rawValue.propertyName(meta: meta)
let caseRawValue = rawValue
appendCase(name: caseName, rawValue: caseRawValue)
}
}
}
lines.append("\(indent1)}")
lines.append("\(indent1)\(meta.publicCode)\(meta.declareKeyword) \(key.propertyName(meta: meta)): \(propertyType.propertyType)")
} else {
lines.append("\(indent1)\(meta.publicCode)\(meta.declareKeyword) \(key.propertyName(meta: meta)): \(value.type(key: key, meta: meta))")
}
}
if meta.codable {
func needCodingKeys(with dictionary: [String: Any]) -> Bool {
for key in keys {
let propertyName = key.propertyName(meta: meta).removedQuotationMark()
if propertyName != key {
return true
}
}
return false
}
if needCodingKeys(with: dictionary) {
lines.append("\(indent1)private enum CodingKeys: String, CodingKey {")
for key in keys {
let propertyName = key.propertyName(meta: meta)
if propertyName == key {
lines.append("\(indent2)case \(propertyName)")
} else {
lines.append("\(indent2)case \(propertyName) = \"\(key)\"")
}
}
lines.append("\(indent1)}")
}
} else {
lines.append(self.initializerCode(indentation: indentation.deeper, meta: meta))
lines.append(self.failableInitializerCode(indentation: indentation.deeper, meta: meta))
}
lines.append("\(indent)}")
return lines.filter({ !$0.isEmpty }).joined(separator: "\n")
case let .array(_, values):
return values.first?.swiftCode(indentation: indentation, meta: meta) ?? ""
default:
return ""
}
}
}
| mit | 66f3f2bd0a28868bfbc7b923d7e30446 | 60.295455 | 209 | 0.541548 | 4.669681 | false | true | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Onboarding/Main/OnboardingFinishViewController.swift | 1 | 2439 | //
// OnboardingFinishViewController.swift
// HTWDD
//
// Created by Mustafa Karademir on 07.08.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
import Lottie
import SwiftKeychainWrapper
class OnboardingFinishViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var lblFinishHeader: UILabel!
@IBOutlet weak var lblFinishDescription: UILabel!
@IBOutlet weak var finishAnimationView: AnimationView!
@IBOutlet weak var btnFinish: UIButton!
// MARK: - Properties
private lazy var finishAnimation: Animation? = {
return Animation.named("FinishGrey")
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in
guard let self = self else { return }
self.lblFinishHeader.emitConfetti(duration: Double.random(in: 1.8...4.2))
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.finishAnimationView.play { [weak self] finish in
guard let self = self else { return }
self.btnFinish.setState(with: finish ? .active : .inactive)
}
}
}
// MARK: - User Interaction
@IBAction func onFinishTap(_ sender: UIButton) {
UserDefaults.standard.needsOnboarding = false
dismiss(animated: true, completion: nil)
}
}
// MARK: - Setup
extension OnboardingFinishViewController {
private func setup() {
finishAnimationView.apply {
$0.animation = finishAnimation
$0.contentMode = .scaleAspectFit
$0.loopMode = .playOnce
}
lblFinishHeader.apply {
$0.text = R.string.localizable.onboadingFinishHeader()
$0.textColor = UIColor.htw.Label.primary
}
lblFinishDescription.apply {
$0.text = R.string.localizable.onboadingFinishDescription()
$0.textColor = UIColor.htw.Label.primary
}
btnFinish.apply {
$0.setTitle(R.string.localizable.letsgo(), for: .normal)
$0.setState(with: .inactive)
$0.makeDropShadow()
}
}
}
| gpl-2.0 | 8f7d82afcd51893e9b96ad3569b78bf0 | 29.860759 | 86 | 0.604184 | 4.481618 | false | false | false | false |
SaeidBsn/SwiftyGuideOverlay | Source/GDOverlay.swift | 1 | 18603 | //
// GDOverlay.swift
// SwiftyGuideOverlay
//
// Created by Saeid Basirnia on 8/16/16.
// Copyright © 2016 Saeidbsn. All rights reserved.
//
import UIKit
public protocol SkipOverlayDelegate: class{
func onSkipSignal()
}
class GDOverlay: UIView {
//MARK: - Attributes
fileprivate var _backColor: UIColor = UIColor.black.withAlphaComponent(0.8)
public var backColor: UIColor{
get{
return _backColor
}
set{
_backColor = newValue
}
}
fileprivate var _boxBackColor: UIColor = UIColor.white.withAlphaComponent(0.05)
public var boxBackColor: UIColor{
get{
return _boxBackColor
}
set{
_boxBackColor = newValue
}
}
fileprivate var _boxBorderColor: UIColor = UIColor.white
public var boxBorderColor: UIColor{
get{
return _boxBorderColor
}
set{
_boxBorderColor = newValue
}
}
fileprivate var _showBorder: Bool = true
public var showBorder: Bool{
get{
return _showBorder
}
set{
_showBorder = newValue
}
}
fileprivate var _lineType: LineType = .dash_bubble
public var lineType: LineType{
get{
return _lineType
}
set{
_lineType = newValue
}
}
fileprivate var _labelFont: UIFont = UIFont.boldSystemFont(ofSize: 14)
public var labelFont: UIFont{
get{
return _labelFont
}
set{
_labelFont = newValue
}
}
fileprivate var _labelColor: UIColor = UIColor.white
public var labelColor: UIColor{
get{
return _labelColor
}
set{
_labelColor = newValue
}
}
fileprivate var _arrowColor: UIColor = UIColor.white
public var arrowColor: UIColor{
get{
return _arrowColor
}
set{
_arrowColor = newValue
}
}
fileprivate var _headColor: UIColor = UIColor.white
public var headColor: UIColor{
get{
return _headColor
}
set{
_headColor = newValue
}
}
fileprivate var _arrowWidth: CGFloat = 2.0
public var arrowWidth: CGFloat{
get{
return _arrowWidth
}
set{
_arrowWidth = newValue
}
}
fileprivate var _headRadius: CGFloat = 4.0
public var headRadius: CGFloat{
get{
return _headRadius
}
set{
_headRadius = newValue
}
}
fileprivate var _highlightView: Bool = false
public var highlightView: Bool{
get{
return _highlightView
}
set{
_highlightView = newValue
}
}
//MARK: - Self Init
weak var delegate: SkipOverlayDelegate? = nil
fileprivate var helpView: UIView!
init(){
super.init(frame: CGRect.zero)
self.frame = self.topView.frame
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func calculateCenter() -> CGPoint {
let targetRect = helpView.convert(helpView.bounds , to: topView)
return targetRect.center
}
private func initViews(_ circle: Bool){
let targetCenter: CGPoint = calculateCenter()
self.createBackgroundView()
self.createContainerView()
self.topView.addSubview(self)
setupContainerViewConstraints(to: targetCenter)
layoutIfNeeded()
if _highlightView{
self.unmaskView(targetCenter, isCircle: circle)
}
self.createTargetView(center: targetCenter)
}
public func drawOverlay(to barButtonItem: UIBarButtonItem, desc: String){
if let barView = barButtonItem.value(forKey: "view") as? UIView {
let barFrame = barView.frame
let windowRect = barView.convert(barFrame, to: topView)
let v = UIView()
v.frame = windowRect
self.addSubview(v)
helpView = v
}
descLabel.text = desc
initViews(true)
}
public func drawOverlay(to tabbarView: UITabBar, item: Int, desc: String){
var targetRect: CGRect? = nil
var barView: UIView? = nil
var frames = tabbarView.subviews.flatMap { (view: UIView) -> CGRect? in
if let view = view as? UIControl {
barView = view
return view.frame
}
return nil
}
frames.sort { $0.origin.x < $1.origin.x }
if frames.count > item {
targetRect = frames[item]
}else{
targetRect = frames.last ?? CGRect.zero
}
guard let rect = targetRect, let barview = barView else { return }
let windowRect = barview.convert(rect, to: topView)
let v = UIView()
v.frame = windowRect
self.addSubview(v)
helpView = v
descLabel.text = desc
initViews(false)
}
public func drawOverlay(to tableView: UITableView, section: Int, row: Int, desc: String){
let indexPath: IndexPath = IndexPath(row: row, section: section)
let tableRect = tableView.rectForRow(at: indexPath)
let windowRect = tableView.convert(tableRect, to: topView)
let v = UIView()
v.frame = windowRect
self.addSubview(v)
helpView = v
descLabel.text = desc
initViews(false)
}
public func drawOverlay(to view: UIView, desc: String, isCircle: Bool = true){
let windowRect = view.convert(view.bounds , to: topView)
let v = UIView()
v.frame = windowRect
self.addSubview(v)
helpView = v
descLabel.text = desc
initViews(isCircle)
}
//MARK: - Background View
fileprivate var backgroundView: UIView!
private func createBackgroundView(){
backgroundView = UIView()
backgroundView.frame = self.frame
backgroundView.isUserInteractionEnabled = true
backgroundView.backgroundColor = UIColor.clear
backgroundView.backgroundColor = _backColor
self.addSubview(backgroundView)
self.setupGestures()
}
private func setupGestures(){
let tapGest = UITapGestureRecognizer(target: self, action: #selector(gotoNext(_:)))
tapGest.numberOfTapsRequired = 1
tapGest.numberOfTouchesRequired = 1
self.backgroundView.addGestureRecognizer(tapGest)
}
@objc private func gotoNext(_ sender: UIGestureRecognizer){
self.removeFromSuperview()
self.backgroundView.removeFromSuperview()
self.delegate?.onSkipSignal()
}
//MARK: - Description Label
fileprivate var descLabel: UILabel = {
let lbl = UILabel()
lbl.numberOfLines = 3
lbl.lineBreakMode = .byWordWrapping
lbl.sizeToFit()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.textAlignment = .center
return lbl
}()
private lazy var getLabelHeight: CGFloat = {
let lblHeight = self.descLabel.frame.height
return lblHeight
}()
//MARK: - Container View
fileprivate var contView: UIView!
private func createContainerView(){
self.descLabel.font = _labelFont
self.descLabel.textColor = _labelColor
contView = UIView()
contView.frame = CGRect(x: 0, y: 0, width: topView.frame.width - 60, height: 50)
contView.backgroundColor = _boxBackColor
if _showBorder{
contView.layer.borderColor = _boxBorderColor.cgColor
contView.layer.borderWidth = 2
contView.layer.cornerRadius = 5
}
contView.translatesAutoresizingMaskIntoConstraints = false
contView.addSubview(descLabel)
backgroundView.addSubview(contView)
setupLabelConstraints()
}
//MARK: - Tools
private func unmaskView(_ targetPoint: CGPoint, isCircle: Bool){
let maskLayer = CAShapeLayer()
let path = CGMutablePath()
let radius: CGFloat = isCircle ? (max(helpView.frame.width + 20, helpView.frame.height + 10)) / 2 : 0
let clipPath: CGPath = UIBezierPath(roundedRect: CGRect(x: helpView.frame.origin.x - 20, y: helpView.frame.origin.y - 10, width: helpView.frame.width + 40, height: helpView.frame.height + 20), cornerRadius: radius).cgPath
path.addPath(clipPath)
path.addRect(CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path
maskLayer.fillRule = kCAFillRuleEvenOdd
backgroundView.layer.mask = maskLayer
backgroundView.clipsToBounds = false
}
}
// MARK: - setup constraints
extension GDOverlay{
fileprivate func setupLabelConstraints(){
descLabel.leftAnchor.constraint(equalTo: contView.leftAnchor, constant: 10.0).isActive = true
descLabel.rightAnchor.constraint(equalTo: contView.rightAnchor, constant: -10.0).isActive = true
descLabel.topAnchor.constraint(equalTo: contView.topAnchor, constant: 10.0).isActive = true
descLabel.bottomAnchor.constraint(equalTo: contView.bottomAnchor, constant: -10.0).isActive = true
descLabel.widthAnchor.constraint(equalToConstant: contView.frame.width - 10).isActive = true
}
fileprivate func setupContainerViewConstraints(to point: CGPoint){
let section = setSection(point)
let consts = setSectionPoint(section)
topView.addConstraints(consts)
}
}
//MARK: - Create and calculate points
extension GDOverlay{
private func calcCenterPoint(_ start: CGPoint, end: CGPoint) -> CGPoint{
let x = (start.x + end.x) / 2
let y = (start.y + end.y) / 2
return CGPoint(x: x, y: y)
}
fileprivate func createTargetView(center: CGPoint){
let section = setSection(center)
var startPoint: CGPoint!
var endPoint: CGPoint!
var controlPoint: CGPoint!
let dir = LineDirection.randomDir()
let offsetTop: CGFloat = highlightView ? 20.0 : 0.0
let offsetBottom: CGFloat = highlightView ? -20.0 : 0.0
switch section{
case 0, 1:
if dir == .left{
startPoint = CGPoint(x: contView.frame.midX - 50, y: contView.frame.minY - 10)
endPoint = CGPoint(x: helpView.frame.midX, y: helpView.frame.maxY + offsetTop)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x - 50, y: cp.y)
}else{
startPoint = CGPoint(x: contView.frame.midX, y: contView.frame.minY - 20)
endPoint = CGPoint(x: helpView.frame.midX + 25, y: helpView.frame.maxY + offsetTop)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x + 50, y: cp.y)
}
case 2:
if dir == .left{
startPoint = CGPoint(x: contView.frame.midX + contView.frame.midX / 4, y: contView.frame.minY - 10)
endPoint = CGPoint(x: helpView.frame.minX - 25, y: helpView.frame.maxY + offsetTop)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x - 50, y: cp.y)
}else{
startPoint = CGPoint(x: contView.frame.midX + contView.frame.midX / 4, y: contView.frame.minY - 10)
endPoint = CGPoint(x: helpView.frame.midX + 5, y: helpView.frame.maxY + offsetTop)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x + 50, y: cp.y)
}
case 3:
if dir == .left{
startPoint = CGPoint(x: contView.frame.midX - contView.frame.midX / 4, y: contView.frame.maxY + 10)
endPoint = CGPoint(x: helpView.frame.midX, y: helpView.frame.minY + offsetBottom)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x - 50, y: cp.y)
}else{
startPoint = CGPoint(x: contView.frame.midX - contView.frame.midX / 4, y: contView.frame.maxY + 10)
endPoint = CGPoint(x: helpView.frame.maxX, y: helpView.frame.minY + offsetBottom)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x + 50, y: cp.y)
}
case 4:
if dir == .left{
startPoint = CGPoint(x: contView.frame.midX + contView.frame.midX / 4, y: contView.frame.maxY + 20)
endPoint = CGPoint(x: helpView.frame.midX + 5, y: helpView.frame.minY + offsetBottom)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x + 50, y: cp.y)
}else{
startPoint = CGPoint(x: contView.frame.midX, y: contView.frame.maxY + 10)
endPoint = CGPoint(x: helpView.frame.minX - 5, y: helpView.frame.minY + offsetBottom)
let cp = calcCenterPoint(startPoint, end: endPoint)
controlPoint = CGPoint(x: cp.x - 50, y: cp.y)
}
default:
break
}
let lineShape: CAShapeLayer!
var bubbleShape: CAShapeLayer?
switch _lineType{
case .dash_bubble:
lineShape = drawLine(startPoint: startPoint, endPoint: endPoint, controlPoint: controlPoint)
lineShape.lineDashPattern = [3, 6]
bubbleShape = drawHead(endPoint)
case .line_arrow:
lineShape = drawArrow(startPoint: startPoint, endPoint: endPoint, controlPoint: controlPoint)
lineShape.lineDashPattern = nil
case .line_bubble:
lineShape = drawLine(startPoint: startPoint, endPoint: endPoint, controlPoint: controlPoint)
lineShape.lineDashPattern = nil
bubbleShape = drawHead(endPoint)
}
self.backgroundView.layer.addSublayer(lineShape)
if let bs = bubbleShape{
self.backgroundView.layer.addSublayer(bs)
}
animateArrow(lineShape)
}
fileprivate func setSection(_ targetPoint: CGPoint) -> Int{
let centerPoint: CGPoint = topView.center
if targetPoint == centerPoint{
return 0
}else if targetPoint.x < centerPoint.x && targetPoint.y < centerPoint.y{
return 1
}else if targetPoint.x < centerPoint.x && targetPoint.y > centerPoint.y{
return 3
}else if targetPoint.x > centerPoint.x && targetPoint.y < centerPoint.y{
return 2
}else if targetPoint.x > centerPoint.x && targetPoint.y > centerPoint.y{
return 4
}else{
return 0
}
}
fileprivate func setSectionPoint(_ section: Int) -> [NSLayoutConstraint]{
let dynamicSpace = CGFloat(arc4random_uniform(20) + 100)
switch section {
case 0, 1, 2:
let x = contView.centerXAnchor.constraint(equalTo: topView.centerXAnchor, constant: 0.0)
x.isActive = true
let y = contView.topAnchor.constraint(equalTo: helpView.bottomAnchor, constant: dynamicSpace)
y.isActive = true
return [x, y]
case 3, 4:
let x = contView.centerXAnchor.constraint(equalTo: topView.centerXAnchor, constant: 0.0)
x.isActive = true
let y = contView.bottomAnchor.constraint(equalTo: helpView.topAnchor, constant: -dynamicSpace)
y.isActive = true
return [x, y]
default:
return []
}
}
}
//MARK: - Drawing lines
extension GDOverlay{
fileprivate func drawArrow(startPoint: CGPoint, endPoint: CGPoint, controlPoint: CGPoint) -> CAShapeLayer{
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = nil
shapeLayer.strokeColor = _arrowColor.cgColor
shapeLayer.lineWidth = _arrowWidth
shapeLayer.lineJoin = kCALineCapRound
shapeLayer.lineCap = kCALineCapRound
let path = UIBezierPath()
path.addArrowForm(point: endPoint, controlPoint: controlPoint, width: 5, height: 10)
path.addQuadCurve(to: startPoint, controlPoint: controlPoint)
shapeLayer.path = path.cgPath
return shapeLayer
}
fileprivate func drawLine(startPoint: CGPoint, endPoint: CGPoint, controlPoint: CGPoint) -> CAShapeLayer{
let bez = UIBezierPath()
bez.move(to: CGPoint(x: startPoint.x, y: startPoint.y))
bez.addQuadCurve(to: CGPoint(x: endPoint.x, y: endPoint.y), controlPoint: controlPoint)
let shape = CAShapeLayer()
shape.path = bez.cgPath
shape.strokeColor = _arrowColor.cgColor
shape.fillColor = nil
shape.lineWidth = _arrowWidth
shape.lineCap = kCALineCapRound
shape.lineJoin = kCALineJoinMiter
shape.strokeStart = 0.0
shape.strokeEnd = 0.0
return shape
}
fileprivate func drawHead(_ endPoint: CGPoint) -> CAShapeLayer{
let circlePath: UIBezierPath = UIBezierPath(arcCenter: CGPoint(x: endPoint.x, y: endPoint.y), radius: _headRadius, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
circleShape.fillColor = _headColor.cgColor
return circleShape
}
fileprivate func animateArrow(_ shape1: CAShapeLayer){
let arrowAnim = CABasicAnimation(keyPath: "strokeEnd")
arrowAnim.fromValue = 0.0
arrowAnim.toValue = 1.0
arrowAnim.duration = 0.5
arrowAnim.autoreverses = false
arrowAnim.fillMode = kCAFillModeForwards
arrowAnim.isRemovedOnCompletion = false
shape1.add(arrowAnim, forKey: nil)
}
}
| mit | 8dca22cd92b968ff7f6a1bd9c4a3a7b2 | 33.069597 | 229 | 0.587786 | 4.645854 | false | false | false | false |
nestorgt/LeetCode-Algorithms-Swift | LeetCode-Algorithms/LeetCode-Algorithms/002_AddTwoNumbers.swift | 1 | 2503 | //
// 002_AddTwoNumbers.swift
// LeetCode-Algorithms
//
// Created by nestorgt on 10/03/16.
// Copyright © 2016 nestorgt. All rights reserved.
//
/* #2 Add Two Numbers - Medium - https://leetcode.com/problems/add-two-numbers/
- QUESTION
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
- SOLUTION
t = O(n), s = O(1)
Loop through both list nodes, make the sum and save carriage that will be applied to next sum.
Consider list nodes of diferent sizes.
*/
import Foundation
// Definition for singly-linked list.
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
public init(val: Int, next: ListNode?) {
self.val = val
self.next = next
}
}
typealias SumCarriage = (sum: Int, carriage: Int)
struct _002_AddTwoNumbers {
/** t = O(n), s = O(1)
loop through both list nodes, make the sum and save carriage that will be applied to next sum
*/
func addTwoNumbers(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var varl1 = l1
var varl2 = l2
guard varl1 != nil || varl2 != nil else {
return nil
}
let sumCarriage: SumCarriage = sumList(n1: varl1!.val, n2: varl2!.val)
var listNode: ListNode? = ListNode(sumCarriage.sum)
var prevCarriage: Int = sumCarriage.carriage
let result = listNode
while varl1?.next != nil || varl2?.next != nil {
varl1 = varl1?.next != nil ? varl1!.next : ListNode(0)
varl2 = varl2?.next != nil ? varl2!.next : ListNode(0)
let sumCarriage: SumCarriage = sumList(n1: varl1!.val, n2: varl2!.val, prevCarriage: prevCarriage)
listNode!.next = ListNode(sumCarriage.sum)
prevCarriage = sumCarriage.carriage
listNode = listNode!.next
}
if prevCarriage > 0 {
listNode?.next = ListNode(prevCarriage)
}
return result
}
func sumList(n1 n1: Int, n2: Int, prevCarriage: Int = 0) -> SumCarriage {
let tempSum = n1+n2+prevCarriage
let sum = tempSum >= 10 ? (tempSum)%10 : tempSum
let carriage = tempSum >= 10 ? (tempSum)/10 : 0
return (sum, carriage)
}
} | mit | 0e530a2f1ad301299491d236c8ebf41d | 30.2875 | 208 | 0.608313 | 3.574286 | false | false | false | false |
hoanganh6491/ScrollPager | ScrollPager/ViewController.swift | 1 | 1548 | //
// ViewController.swift
// ScrollPager
//
// Created by Aryan Ghassemi on 2/22/15.
// Copyright (c) 2015 Aryan Ghassemi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, ScrollPagerDelegate {
@IBOutlet var scrollPager: ScrollPager!
@IBOutlet var secondScrollPager: ScrollPager!
override func viewDidLoad() {
super.viewDidLoad()
let firstView = UILabel()
firstView.backgroundColor = UIColor.whiteColor()
firstView.text = "first View"
firstView.textAlignment = .Center
let secondView = UILabel()
secondView.backgroundColor = UIColor.whiteColor()
secondView.text = "second view"
secondView.textAlignment = .Center
let thirdView = UILabel()
thirdView.backgroundColor = UIColor.whiteColor()
thirdView.text = "third view"
thirdView.textAlignment = .Center
let fourthView = UILabel()
fourthView.backgroundColor = UIColor.whiteColor()
fourthView.text = "fourth view"
fourthView.textAlignment = .Center
scrollPager.delegate = self
scrollPager.addSegmentsWithTitlesAndViews([
("Home", firstView),
("Public Feed", secondView),
("Profile", thirdView),
("One More", fourthView)
])
secondScrollPager.addSegmentsWithImages([
UIImage(named: "envelope")!,
UIImage(named: "home")!,
UIImage(named: "like")!,
UIImage(named: "message")!,
UIImage(named: "notes")!
])
}
// MARK: - ScrollPagerDelegate -
func scrollPager(scrollPager: ScrollPager, changedIndex: Int) {
println("scrollPager index changed: \(changedIndex)")
}
}
| mit | e8f6239cfb71aa13a6cde233aeb22706 | 23.571429 | 64 | 0.71124 | 3.73012 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-security | Source/mca/internal/BMSSecurityConstants.swift | 1 | 8435 | /*
* Copyright 2015 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import BMSCore
import BMSAnalyticsAPI
internal class BMSSecurityConstants {
internal static let SECURE_PATTERN_START = "/*-secure-\n"
internal static let SECURE_PATTERN_END = "*/"
internal static let base64EncodingTable:[Character] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"
]
internal static let base64EncodingTableUrlSafe:[Character] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "_"
]
internal static let base64DecodingTable: [Int8] = [
-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
-2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
]
internal static var deviceInfo = Utils.getDeviceDictionary()
internal static let nameAndVer = Utils.getApplicationDetails()
internal static var authorizationProcessManagerLoggerName = Logger.bmsLoggerPrefix + "AuthorizationProcessManager"
internal static var authorizationRequestManagerLoggerName = Logger.bmsLoggerPrefix + "AuthorizationRequestManager"
internal static var authorizationEndPoint = "authorization"
internal static var tokenEndPoint = "token"
internal static var clientsInstanceEndPoint = "clients/instance"
internal static var client_id_String = "client_id"
internal static var authorization_code_String = "authorization_code"
internal static var JSON_RSA_VALUE = "RSA"
internal static var JSON_RS256_VALUE = "RS256"
internal static var JSON_ALG_KEY = "alg"
internal static var JSON_MOD_KEY = "mod"
internal static var JSON_EXP_KEY = "exp"
internal static var JSON_JPK_KEY = "jpk"
internal static var X_WL_SESSION_HEADER_NAME = "X-WL-Session"
internal static var X_WL_AUTHENTICATE_HEADER_NAME = "X-WL-Authenticate"
internal static var JSON_RESPONSE_TYPE_KEY = "response_type"
internal static var JSON_CSR_KEY = "CSR"
internal static var JSON_IMF_USER_KEY = "imf.user"
internal static var JSON_REDIRECT_URI_KEY = "redirect_uri"
internal static var JSON_CODE_KEY = "code"
internal static var JSON_GRANT_TYPE_KEY = "grant_type"
internal static let MFP_SECURITY_PACKAGE = Logger.bmsLoggerPrefix + "security"
internal static let BEARER = "Bearer"
internal static let AUTHORIZATION_HEADER = "Authorization"
internal static let WWW_AUTHENTICATE_HEADER = "WWW-Authenticate"
internal static let AUTH_REALM = "\"imfAuthentication\""
internal static let HTTP_LOCALHOST = "http://localhost"
/**
* Parts of the path to authorization endpoint.
*/
internal static let AUTH_SERVER_NAME = "imf-authserver"
internal static let AUTH_PATH = "authorization/v1/apps/"
/**
* The name of "result" parameter returned from authorization endpoint.
*/
internal static let WL_RESULT = "wl_result";
/**
* Name of location header.
*/
internal static let LOCATION_HEADER_NAME = "Location"
/**
* Name of the standard "www-authenticate" header.
*/
internal static let AUTHENTICATE_HEADER_NAME = "WWW-Authenticate"
/**
* Name of "www-authenticate" header value.
*/
internal static let AUTHENTICATE_HEADER_VALUE = "WL-Composite-Challenge"
/**
* Names of JSON values returned from the server.
*/
internal static let AUTH_FAILURE_VALUE_NAME = "WL-Authentication-Failure"
internal static let AUTH_SUCCESS_VALUE_NAME = "WL-Authentication-Success"
internal static let CHALLENGES_VALUE_NAME = "challenges"
//JSON keys
internal static let JSON_CERTIFICATE_KEY = "certificate"
internal static let JSON_CLIENT_ID_KEY = "clientId"
internal static let JSON_DEVICE_ID_KEY = "deviceId"
internal static let JSON_OS_KEY = "deviceOs"
internal static let JSON_ENVIRONMENT_KEY = "environment"
internal static let JSON_MODEL_KEY = "deviceModel"
internal static let JSON_APPLICATION_ID_KEY = "applicationId"
internal static let JSON_APPLICATION_VERSION_KEY = "applicationVersion"
internal static let JSON_IOS_ENVIRONMENT_VALUE = "iOSnative"
internal static let JSON_ACCESS_TOKEN_KEY = "access_token"
internal static let JSON_ID_TOKEN_KEY = "id_token"
//label names
internal static let KEY_CHAIN_PREFIX = "com.ibm.mobilefirstplatform.clientsdk.swift.bmssecurity"
internal static let OAUTH_CERT_LABEL = "\(KEY_CHAIN_PREFIX).certificate"
internal static let _PUBLIC_KEY_LABEL = "\(KEY_CHAIN_PREFIX).publickey"
internal static let CLIENT_ID_KEY_LABEL = "\(KEY_CHAIN_PREFIX).clientid"
internal static let _PRIVATE_KEY_LABEL = "\(KEY_CHAIN_PREFIX).privatekey"
internal static let OAUTH_ACCESS_TOKEN_LABEL = "\(KEY_CHAIN_PREFIX).accesstoken"
internal static let OAUTH_ID_TOKEN_LABEL = "\(KEY_CHAIN_PREFIX).idtoken"
internal static let PERSISTENCE_POLICY_LABEL = "persistencePolicy"
internal static let APP_IDENTITY_LABEL = "appIdentity"
internal static let DEVICE_IDENTITY_LABEL = "deviceIdentity"
internal static let USER_IDENTITY_LABEL = "userIdentity"
//labels
internal static let BMSSecurityErrorDomain = "com.ibm.mobilefirstplatform.clientsdk.swift.bmssecurity"
internal static let privateKeyIdentifier = "\(_PRIVATE_KEY_LABEL):\(nameAndVer.name):\(nameAndVer.version)"
internal static let publicKeyIdentifier = "\(_PUBLIC_KEY_LABEL):\(nameAndVer.name):\(nameAndVer.version)"
internal static let idTokenLabel = "\(OAUTH_ID_TOKEN_LABEL):\(nameAndVer.name):\(nameAndVer.version)"
internal static let accessTokenLabel = "\(OAUTH_ACCESS_TOKEN_LABEL):\(nameAndVer.name):\(nameAndVer.version)"
internal static let clientIdLabel = "\(CLIENT_ID_KEY_LABEL):\(nameAndVer.name):\(nameAndVer.version)"
internal static let certificateIdentifier = "\(OAUTH_CERT_LABEL):\(nameAndVer.name):\(nameAndVer.version)"
internal static let AuthorizationKeyChainTagsDictionary = [privateKeyIdentifier : kSecClassKey, publicKeyIdentifier : kSecClassKey, idTokenLabel : kSecClassGenericPassword, accessTokenLabel : kSecClassGenericPassword, certificateIdentifier : kSecClassCertificate]
}
| apache-2.0 | c0ea6f48568acfc3ae00222cf85ecdac | 48.733728 | 267 | 0.60928 | 3.160963 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Data/RoomList/Common/MXRoomListDataFilterable.swift | 1 | 6596 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Protocol to be used in room list data managers to filter rooms
internal protocol MXRoomListDataFilterable {
/// Filter options to use
var filterOptions: MXRoomListDataFilterOptions { get }
/// Filter rooms in-memory
/// - Parameter rooms: rooms to filter
/// - Returns filtered rooms
func filterRooms(_ rooms: [MXRoomSummaryProtocol]) -> [MXRoomSummaryProtocol]
/// Predicate to be used when filtering rooms
/// - Parameter filterOptions: filter options to create predicate
/// - Returns predicate
func filterPredicate(for filterOptions: MXRoomListDataFilterOptions) -> NSPredicate?
}
// MARK: - Default Implementation
extension MXRoomListDataFilterable {
/// Just to be used for in-memory data
func filterRooms(_ rooms: [MXRoomSummaryProtocol]) -> [MXRoomSummaryProtocol] {
guard let predicate = filterPredicate(for: filterOptions) else {
return rooms
}
return (rooms as NSArray).filtered(using: predicate) as! [MXRoomSummaryProtocol]
}
func filterPredicate(for filterOptions: MXRoomListDataFilterOptions) -> NSPredicate? {
var predicates: [NSPredicate] = []
if !filterOptions.onlySuggested {
if filterOptions.hideUnknownMembershipRooms {
let memberPredicate = NSPredicate(format: "%K != %d",
#keyPath(MXRoomSummaryProtocol.membership),
MXMembership.unknown.rawValue)
predicates.append(memberPredicate)
}
if !filterOptions.dataTypes.isEmpty {
let predicate: NSPredicate
if filterOptions.strictMatches {
predicate = NSPredicate(format: "(%K & %d) == %d",
#keyPath(MXRoomSummaryProtocol.dataTypes),
filterOptions.dataTypes.rawValue,
filterOptions.dataTypes.rawValue)
} else {
predicate = NSPredicate(format: "(%K & %d) != 0",
#keyPath(MXRoomSummaryProtocol.dataTypes),
filterOptions.dataTypes.rawValue)
}
predicates.append(predicate)
}
if !filterOptions.notDataTypes.isEmpty {
let predicate = NSPredicate(format: "(%K & %d) == 0",
#keyPath(MXRoomSummaryProtocol.dataTypes),
filterOptions.notDataTypes.rawValue)
predicates.append(predicate)
}
if let space = filterOptions.space {
let predicate = NSPredicate(format: "%@ IN %K",
space.spaceId,
#keyPath(MXRoomSummaryProtocol.parentSpaceIds))
predicates.append(predicate)
} else {
// home space
// In case of home space we show a room if one of the following conditions is true:
// - Show All Rooms is enabled
// - It's a direct room
// - The room is a favourite
// - The room is orphaned
let predicate1 = NSPredicate(value: filterOptions.showAllRoomsInHomeSpace)
let directDataTypes: MXRoomSummaryDataTypes = .direct
let predicate2 = NSPredicate(format: "(%K & %d) != 0",
#keyPath(MXRoomSummaryProtocol.dataTypes),
directDataTypes.rawValue)
let favoritedDataTypes: MXRoomSummaryDataTypes = .favorited
let predicate3 = NSPredicate(format: "(%K & %d) != 0",
#keyPath(MXRoomSummaryProtocol.dataTypes),
favoritedDataTypes.rawValue)
let predicate4_1 = NSPredicate(format: "%K == NULL",
#keyPath(MXRoomSummaryProtocol.parentSpaceIds))
let predicate4_2 = NSPredicate(format: "%K.@count == 0",
#keyPath(MXRoomSummaryProtocol.parentSpaceIds))
let predicate4 = NSCompoundPredicate(type: .or,
subpredicates: [predicate4_1, predicate4_2])
let predicate = NSCompoundPredicate(type: .or,
subpredicates: [predicate1, predicate2, predicate3, predicate4])
predicates.append(predicate)
}
}
if let query = filterOptions.query, !query.isEmpty {
let predicate1 = NSPredicate(format: "%K CONTAINS[cd] %@",
#keyPath(MXRoomSummaryProtocol.displayname),
query)
let predicate2 = NSPredicate(format: "%K CONTAINS[cd] %@",
#keyPath(MXRoomSummaryProtocol.spaceChildInfo.displayName),
query)
let predicate = NSCompoundPredicate(type: .or,
subpredicates: [predicate1, predicate2])
predicates.append(predicate)
}
guard !predicates.isEmpty else {
return nil
}
if predicates.count == 1 {
return predicates.first
}
return NSCompoundPredicate(type: .and,
subpredicates: predicates)
}
}
| apache-2.0 | 87bd57c13ac8a570e14f9ce61c0b067f | 44.178082 | 116 | 0.519861 | 5.894549 | false | false | false | false |
Ossey/WeiBo | XYWeiBo/XYWeiBo/Classes/Compose(发布)/PicturePiker/XYPicPikerCollectionViewCell.swift | 1 | 1794 | //
// XYPicPikerCollectionViewCell.swift
// XYWeiBo
//
// Created by mofeini on 16/10/2.
// Copyright © 2016年 sey. All rights reserved.
//
import UIKit
class XYPicPikerCollectionViewCell: UICollectionViewCell {
// MARK:- 控件属性
@IBOutlet weak var addPicButton: UIButton!
@IBOutlet weak var picView: UIImageView!
@IBOutlet weak var removePicButton: UIButton!
var image : UIImage? {
didSet{
if (image != nil) {
picView.image = image
addPicButton.isUserInteractionEnabled = false
removePicButton.isHidden = false
} else {
picView.image = nil
addPicButton.isUserInteractionEnabled = true
removePicButton.isHidden = true
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
// MARK:- 事件监听
extension XYPicPikerCollectionViewCell {
// 点击加号按钮时,跳转到相册
@IBAction func addPicButtonClick(_ sender: AnyObject) {
// 由于当前cell非控制器,且父控件也非控制器,这里无法弹出控制器,使用通知的方式
// 发布通知
NotificationCenter.default.post(name: XYClickAddPictureButtonNotification, object: nil)
}
// 点击删除图片按钮的点击事件
@IBAction func removePicButtonClick(_ sender: AnyObject) {
// 发布点击了删除按照片按钮的通知:并将删除的这张图片作为参数传递出去,方便外界知道要删除哪张图片
NotificationCenter.default.post(name: XYClickRemovePictureButtonNotification, object: picView.image)
}
}
| apache-2.0 | 9bbe5a05ba3e6b0e775fb3cae3df3b53 | 24.016129 | 108 | 0.612508 | 4.381356 | false | false | false | false |
thedanpan/Perspective | Perspective/Perspective/RecordVC.swift | 2 | 4317 | //
// RecordVC.swift
// Perspective
//
// Created by Apprentice on 2/15/15.
// Copyright (c) 2015 Dev Bootcamp. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
import MobileCoreServices
class RecordVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
let captureSession = AVCaptureSession()
let date = NSDate()
var previewLayer : AVCaptureVideoPreviewLayer?
var captureDevice : AVCaptureDevice?
var currentUser = PFUser.currentUser()
var newPerspective : Bool!
var perspectiveId : String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
captureSession.sessionPreset = AVCaptureSessionPreset1280x720
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
println("captureVideoPressed and camera available.")
var imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera;
imagePicker.mediaTypes = [kUTTypeMovie!]
imagePicker.allowsEditing = true
imagePicker.showsCameraControls = true
self.presentViewController(imagePicker, animated: false, completion: nil)
}
else {
println("Camera not available.")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
self.navigationController?.popToRootViewControllerAnimated(true)
println("Video cancel button tapped, pop to root VC.")
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary!) {
let timestamp = date.timeIntervalSince1970
let tempImage = info[UIImagePickerControllerMediaURL] as NSURL!
let pathString = tempImage.relativePath
let fileUrl = info[UIImagePickerControllerMediaURL] as NSURL!
var uploadRequest:AWSS3TransferManagerUploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.bucket = "theperspectiveapp"
uploadRequest.key = "\(timestamp).mp4"
uploadRequest.contentType = "video/mp4"
uploadRequest.body = fileUrl
uploadRequest.uploadProgress = { (bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) -> Void in
dispatch_sync(dispatch_get_main_queue(), {() -> Void in
println(totalBytesSent)
})
}
AWSS3TransferManager.defaultS3TransferManager().upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
if (task.error != nil) {
//failed
println("failed")
println(task.error.code)
println(task.error.localizedDescription)
} else {
//completed
println("completed")
// self.createVideoParseObj(uploadRequest.key)
}
return nil
}
// println("view stack= \(self.view)")
if newPerspective == true {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("PerspectiveFieldsVC") as PerspectiveFieldsVC
vc.url = "https://s3.amazonaws.com/theperspectiveapp/\(uploadRequest.key)"
self.dismissViewControllerAnimated(true, completion: nil)
self.navigationController?.pushViewController(vc, animated: true)
println("Leaving RecordVC, pushing PerspectiveFieldsVC")
} else {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("WhosNextVC") as WhosNextVC
vc.url = "https://s3.amazonaws.com/theperspectiveapp/\(uploadRequest.key)"
vc.perspectiveId = perspectiveId
self.dismissViewControllerAnimated(true, completion: nil)
self.navigationController?.pushViewController(vc, animated: true)
println("Leaving RecordVC, pushing WhosNextVC")
}
}
}
| mit | f6a6b9c20b2a3eb6f7045f3c5bd3f309 | 38.972222 | 128 | 0.671763 | 5.577519 | false | false | false | false |
gregomni/swift | test/expr/unary/keypath/keypath.swift | 3 | 44910 | // RUN: %target-swift-frontend -typecheck -parse-as-library %s -verify
struct Sub: Hashable {
static func ==(_: Sub, _: Sub) -> Bool { return true }
func hash(into hasher: inout Hasher) {}
}
struct OptSub: Hashable {
static func ==(_: OptSub, _: OptSub) -> Bool { return true }
func hash(into hasher: inout Hasher) {}
}
struct NonHashableSub {}
struct Prop {
subscript(sub: Sub) -> A { get { return A() } set { } }
subscript(optSub: OptSub) -> A? { get { return A() } set { } }
subscript(nonHashableSub: NonHashableSub) -> A { get { return A() } set { } }
subscript(a: Sub, b: Sub) -> A { get { return A() } set { } }
subscript(a: Sub, b: NonHashableSub) -> A { get { return A() } set { } }
var nonMutatingProperty: B {
get { fatalError() }
nonmutating set { fatalError() }
}
}
struct A: Hashable {
init() { fatalError() }
var property: Prop
var optProperty: Prop?
let optLetProperty: Prop?
subscript(sub: Sub) -> A { get { return self } set { } }
static func ==(_: A, _: A) -> Bool { fatalError() }
func hash(into hasher: inout Hasher) { fatalError() }
}
struct B {}
struct C<T> { // expected-note 4 {{'T' declared as parameter to type 'C'}}
var value: T
subscript() -> T { get { return value } }
subscript(sub: Sub) -> T { get { return value } set { } }
subscript<U: Hashable>(sub: U) -> U { get { return sub } set { } }
subscript<X>(noHashableConstraint sub: X) -> X { get { return sub } set { } }
}
struct Unavailable {
@available(*, unavailable)
var unavailableProperty: Int
// expected-note@-1 {{'unavailableProperty' has been explicitly marked unavailable here}}
@available(*, unavailable)
subscript(x: Sub) -> Int { get { } set { } }
// expected-note@-1 {{'subscript(_:)' has been explicitly marked unavailable here}}
}
struct Deprecated {
@available(*, deprecated)
var deprecatedProperty: Int
@available(*, deprecated)
subscript(x: Sub) -> Int { get { } set { } }
}
@available(*, deprecated)
func getDeprecatedSub() -> Sub {
return Sub()
}
extension Array where Element == A {
var property: Prop { fatalError() }
}
protocol P { var member: String { get } }
extension B : P { var member : String { return "Member Value" } }
struct Exactly<T> {}
func expect<T>(_ x: inout T, toHaveType _: Exactly<T>.Type) {}
func testKeyPath(sub: Sub, optSub: OptSub,
nonHashableSub: NonHashableSub, x: Int) {
var a = \A.property
expect(&a, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self)
var b = \A.[sub]
expect(&b, toHaveType: Exactly<WritableKeyPath<A, A>>.self)
var c = \A.[sub].property
expect(&c, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self)
var d = \A.optProperty?
expect(&d, toHaveType: Exactly<KeyPath<A, Prop?>>.self)
var e = \A.optProperty?[sub]
expect(&e, toHaveType: Exactly<KeyPath<A, A?>>.self)
var f = \A.optProperty!
expect(&f, toHaveType: Exactly<WritableKeyPath<A, Prop>>.self)
var g = \A.property[optSub]?.optProperty![sub]
expect(&g, toHaveType: Exactly<KeyPath<A, A?>>.self)
var h = \[A].property
expect(&h, toHaveType: Exactly<KeyPath<[A], Prop>>.self)
var i = \[A].property.nonMutatingProperty
expect(&i, toHaveType: Exactly<ReferenceWritableKeyPath<[A], B>>.self)
var j = \[A].[x]
expect(&j, toHaveType: Exactly<WritableKeyPath<[A], A>>.self)
var k = \[A: B].[A()]
expect(&k, toHaveType: Exactly<WritableKeyPath<[A: B], B?>>.self)
var l = \C<A>.value
expect(&l, toHaveType: Exactly<WritableKeyPath<C<A>, A>>.self)
// expected-error@+1{{generic parameter 'T' could not be inferred}}
_ = \C.value
// expected-error@+1{{}}
_ = \(() -> ()).noMember
let _: (A) -> Prop = \.property
let _: PartialKeyPath<A> = \.property
let _: KeyPath<A, Prop> = \.property
let _: WritableKeyPath<A, Prop> = \.property
let _: ReferenceWritableKeyPath<A, Prop> = \.property
//expected-error@-1 {{cannot convert value of type 'WritableKeyPath<A, Prop>' to specified type 'ReferenceWritableKeyPath<A, Prop>'}}
let _: (A) -> A = \.[sub]
let _: PartialKeyPath<A> = \.[sub]
let _: KeyPath<A, A> = \.[sub]
let _: WritableKeyPath<A, A> = \.[sub]
let _: ReferenceWritableKeyPath<A, A> = \.[sub]
//expected-error@-1 {{cannot convert value of type 'WritableKeyPath<A, A>' to specified type 'ReferenceWritableKeyPath<A, A>'}}
let _: (A) -> Prop? = \.optProperty?
let _: PartialKeyPath<A> = \.optProperty?
let _: KeyPath<A, Prop?> = \.optProperty?
// expected-error@+1{{cannot convert}}
let _: WritableKeyPath<A, Prop?> = \.optProperty?
// expected-error@+1{{cannot convert}}
let _: ReferenceWritableKeyPath<A, Prop?> = \.optProperty?
let _: (A) -> A? = \.optProperty?[sub]
let _: PartialKeyPath<A> = \.optProperty?[sub]
let _: KeyPath<A, A?> = \.optProperty?[sub]
// expected-error@+1{{cannot convert}}
let _: WritableKeyPath<A, A?> = \.optProperty?[sub]
// expected-error@+1{{cannot convert}}
let _: ReferenceWritableKeyPath<A, A?> = \.optProperty?[sub]
let _: KeyPath<A, Prop> = \.optProperty!
let _: KeyPath<A, Prop> = \.optLetProperty!
let _: KeyPath<A, Prop?> = \.property[optSub]?.optProperty!
let _: KeyPath<A, A?> = \.property[optSub]?.optProperty![sub]
let _: (C<A>) -> A = \.value
let _: PartialKeyPath<C<A>> = \.value
let _: KeyPath<C<A>, A> = \.value
let _: WritableKeyPath<C<A>, A> = \.value
let _: ReferenceWritableKeyPath<C<A>, A> = \.value
// expected-error@-1 {{cannot convert value of type 'WritableKeyPath<C<A>, A>' to specified type 'ReferenceWritableKeyPath<C<A>, A>'}}
let _: (C<A>) -> A = \C.value
let _: PartialKeyPath<C<A>> = \C.value
let _: KeyPath<C<A>, A> = \C.value
let _: WritableKeyPath<C<A>, A> = \C.value
// expected-error@+1{{cannot convert}}
let _: ReferenceWritableKeyPath<C<A>, A> = \C.value
let _: (Prop) -> B = \.nonMutatingProperty
let _: PartialKeyPath<Prop> = \.nonMutatingProperty
let _: KeyPath<Prop, B> = \.nonMutatingProperty
let _: WritableKeyPath<Prop, B> = \.nonMutatingProperty
let _: ReferenceWritableKeyPath<Prop, B> = \.nonMutatingProperty
var m = [\A.property, \A.[sub], \A.optProperty!]
expect(&m, toHaveType: Exactly<[PartialKeyPath<A>]>.self)
// \.optProperty returns an optional of Prop and `\.[sub]` returns `A`, all this unifies into `[PartialKeyPath<A>]`
var n = [\A.property, \.optProperty, \.[sub], \.optProperty!]
expect(&n, toHaveType: Exactly<[PartialKeyPath<A>]>.self)
let _: [PartialKeyPath<A>] = [\.property, \.optProperty, \.[sub], \.optProperty!]
var o = [\A.property, \C<A>.value]
expect(&o, toHaveType: Exactly<[AnyKeyPath]>.self)
let _: AnyKeyPath = \A.property
let _: AnyKeyPath = \C<A>.value
let _: AnyKeyPath = \.property // expected-error {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{24-24=<#Root#>}}
let _: AnyKeyPath = \C.value // expected-error{{generic parameter 'T' could not be inferred}}
let _: AnyKeyPath = \.value // expected-error {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{24-24=<#Root#>}}
let _ = \Prop.[nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}}
let _ = \Prop.[sub, sub]
let _ = \Prop.[sub, nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}}
let _ = \C<Int>.[]
let _ = \C<Int>.[sub]
let _ = \C<Int>.[noHashableConstraint: sub]
let _ = \C<Int>.[noHashableConstraint: nonHashableSub] // expected-error{{subscript index of type 'NonHashableSub' in a key path must be Hashable}}
let _ = \Unavailable.unavailableProperty // expected-error {{'unavailableProperty' is unavailable}}
let _ = \Unavailable.[sub] // expected-error {{'subscript(_:)' is unavailable}}
let _ = \Deprecated.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated}}
let _ = \Deprecated.[sub] // expected-warning {{'subscript(_:)' is deprecated}}
let _ = \A.[getDeprecatedSub()] // expected-warning {{'getDeprecatedSub()' is deprecated}}
}
func testKeyPathInGenericContext<H: Hashable, X>(hashable: H, anything: X) {
let _ = \C<Int>.[hashable]
let _ = \C<Int>.[noHashableConstraint: hashable]
let _ = \C<Int>.[noHashableConstraint: anything] // expected-error{{subscript index of type 'X' in a key path must be Hashable}}
}
func testDisembodiedStringInterpolation(x: Int) {
\(x) // expected-error{{string interpolation can only appear inside a string literal}}
\(x, radix: 16) // expected-error{{string interpolation can only appear inside a string literal}}
}
func testNoComponents() {
let _: KeyPath<A, A> = \A // expected-error{{must have at least one component}}
let _: KeyPath<C, A> = \C // expected-error{{must have at least one component}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
let _: KeyPath<A, C> = \A // expected-error{{must have at least one component}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
_ = \A // expected-error {{key path must have at least one component}}
}
struct TupleStruct {
var unlabeled: (Int, String)
var labeled: (foo: Int, bar: String)
}
typealias UnlabeledGenericTuple<T, U> = (T, U)
typealias LabeledGenericTuple<T, U> = (a: T, b: U)
func tupleComponent<T, U>(_: T, _: U) {
let _ = \(Int, String).0
let _ = \(Int, String).1
let _ = \TupleStruct.unlabeled.0
let _ = \TupleStruct.unlabeled.1
let _ = \(foo: Int, bar: String).0
let _ = \(foo: Int, bar: String).1
let _ = \(foo: Int, bar: String).foo
let _ = \(foo: Int, bar: String).bar
let _ = \TupleStruct.labeled.0
let _ = \TupleStruct.labeled.1
let _ = \TupleStruct.labeled.foo
let _ = \TupleStruct.labeled.bar
let _ = \(T, U).0
let _ = \(T, U).1
let _ = \UnlabeledGenericTuple<T, U>.0
let _ = \UnlabeledGenericTuple<T, U>.1
let _ = \(a: T, b: U).0
let _ = \(a: T, b: U).1
let _ = \(a: T, b: U).a
let _ = \(a: T, b: U).b
let _ = \LabeledGenericTuple<T, U>.0
let _ = \LabeledGenericTuple<T, U>.1
let _ = \LabeledGenericTuple<T, U>.a
let _ = \LabeledGenericTuple<T, U>.b
}
func tuple_el_0<T, U>() -> KeyPath<(T, U), T> {
return \.0
}
func tuple_el_1<T, U>() -> KeyPath<(T, U), U> {
return \.1
}
func tupleGeneric<T, U>(_ v: (T, U)) {
_ = (1, "hello")[keyPath: tuple_el_0()]
_ = (1, "hello")[keyPath: tuple_el_1()]
_ = v[keyPath: tuple_el_0()]
_ = v[keyPath: tuple_el_1()]
_ = ("tuple", "too", "big")[keyPath: tuple_el_1()]
// expected-note@-12 {{}}
// expected-error@-2 {{generic parameter 'T' could not be inferred}}
// expected-error@-3 {{generic parameter 'U' could not be inferred}}
}
struct Z { }
func testKeyPathSubscript(readonly: Z, writable: inout Z,
kp: KeyPath<Z, Int>,
wkp: WritableKeyPath<Z, Int>,
rkp: ReferenceWritableKeyPath<Z, Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}}
writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}}
readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}}
writable[keyPath: wkp] = sink
readonly[keyPath: rkp] = sink
writable[keyPath: rkp] = sink
let pkp: PartialKeyPath = rkp
var anySink1 = readonly[keyPath: pkp]
expect(&anySink1, toHaveType: Exactly<Any>.self)
var anySink2 = writable[keyPath: pkp]
expect(&anySink2, toHaveType: Exactly<Any>.self)
readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: 'pkp' is a read-only key path}}
writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: 'pkp' is a read-only key path}}
let akp: AnyKeyPath = pkp
var anyqSink1 = readonly[keyPath: akp]
expect(&anyqSink1, toHaveType: Exactly<Any?>.self)
var anyqSink2 = writable[keyPath: akp]
expect(&anyqSink2, toHaveType: Exactly<Any?>.self)
readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}}
writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign through subscript: 'writable' is immutable}}
}
struct ZwithSubscript {
subscript(keyPath kp: KeyPath<ZwithSubscript, Int>) -> Int { return 0 }
subscript(keyPath kp: WritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 }
subscript(keyPath kp: ReferenceWritableKeyPath<ZwithSubscript, Int>) -> Int { return 0 }
subscript(keyPath kp: PartialKeyPath<ZwithSubscript>) -> Any { return 0 }
}
struct NotZ {}
func testKeyPathSubscript(readonly: ZwithSubscript, writable: inout ZwithSubscript,
wrongType: inout NotZ,
kp: KeyPath<ZwithSubscript, Int>,
wkp: WritableKeyPath<ZwithSubscript, Int>,
rkp: ReferenceWritableKeyPath<ZwithSubscript, Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}}
writable[keyPath: kp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}}
readonly[keyPath: wkp] = sink // expected-error {{cannot assign through subscript: subscript is get-only}}
// FIXME: silently falls back to keypath application, which seems inconsistent
writable[keyPath: wkp] = sink
// FIXME: silently falls back to keypath application, which seems inconsistent
readonly[keyPath: rkp] = sink
// FIXME: silently falls back to keypath application, which seems inconsistent
writable[keyPath: rkp] = sink
let pkp: PartialKeyPath = rkp
var anySink1 = readonly[keyPath: pkp]
expect(&anySink1, toHaveType: Exactly<Any>.self)
var anySink2 = writable[keyPath: pkp]
expect(&anySink2, toHaveType: Exactly<Any>.self)
readonly[keyPath: pkp] = anySink1 // expected-error{{cannot assign through subscript: subscript is get-only}}
writable[keyPath: pkp] = anySink2 // expected-error{{cannot assign through subscript: subscript is get-only}}
let akp: AnyKeyPath = pkp
var anyqSink1 = readonly[keyPath: akp]
expect(&anyqSink1, toHaveType: Exactly<Any?>.self)
var anyqSink2 = writable[keyPath: akp]
expect(&anyqSink2, toHaveType: Exactly<Any?>.self)
// FIXME: silently falls back to keypath application, which seems inconsistent
readonly[keyPath: akp] = anyqSink1 // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}}
// FIXME: silently falls back to keypath application, which seems inconsistent
writable[keyPath: akp] = anyqSink2 // expected-error{{cannot assign through subscript: 'writable' is immutable}}
_ = wrongType[keyPath: kp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: wkp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: rkp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: pkp] // expected-error{{cannot be applied}}
_ = wrongType[keyPath: akp]
}
func testKeyPathSubscriptMetatype(readonly: Z.Type, writable: inout Z.Type,
kp: KeyPath<Z.Type, Int>,
wkp: WritableKeyPath<Z.Type, Int>,
rkp: ReferenceWritableKeyPath<Z.Type, Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}}
writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}}
readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}}
writable[keyPath: wkp] = sink
readonly[keyPath: rkp] = sink
writable[keyPath: rkp] = sink
}
func testKeyPathSubscriptTuple(readonly: (Z,Z), writable: inout (Z,Z),
kp: KeyPath<(Z,Z), Int>,
wkp: WritableKeyPath<(Z,Z), Int>,
rkp: ReferenceWritableKeyPath<(Z,Z), Int>) {
var sink: Int
sink = readonly[keyPath: kp]
sink = writable[keyPath: kp]
sink = readonly[keyPath: wkp]
sink = writable[keyPath: wkp]
sink = readonly[keyPath: rkp]
sink = writable[keyPath: rkp]
readonly[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}}
writable[keyPath: kp] = sink // expected-error{{cannot assign through subscript: 'kp' is a read-only key path}}
readonly[keyPath: wkp] = sink // expected-error{{cannot assign through subscript: 'readonly' is a 'let' constant}}
writable[keyPath: wkp] = sink
readonly[keyPath: rkp] = sink
writable[keyPath: rkp] = sink
}
func testKeyPathSubscriptLValue(base: Z, kp: inout KeyPath<Z, Z>) {
_ = base[keyPath: kp]
}
func testKeyPathSubscriptExistentialBase(concreteBase: inout B,
existentialBase: inout P,
kp: KeyPath<P, String>,
wkp: WritableKeyPath<P, String>,
rkp: ReferenceWritableKeyPath<P, String>,
pkp: PartialKeyPath<P>,
s: String) {
_ = concreteBase[keyPath: kp]
_ = concreteBase[keyPath: wkp]
_ = concreteBase[keyPath: rkp]
_ = concreteBase[keyPath: pkp]
concreteBase[keyPath: kp] = s // expected-error {{cannot assign through subscript: 'kp' is a read-only key path}}
concreteBase[keyPath: wkp] = s // expected-error {{key path with root type 'any P' cannot be applied to a base of type 'B'}}
concreteBase[keyPath: rkp] = s
concreteBase[keyPath: pkp] = s // expected-error {{cannot assign through subscript: 'pkp' is a read-only key path}}
_ = existentialBase[keyPath: kp]
_ = existentialBase[keyPath: wkp]
_ = existentialBase[keyPath: rkp]
_ = existentialBase[keyPath: pkp]
existentialBase[keyPath: kp] = s // expected-error {{cannot assign through subscript: 'kp' is a read-only key path}}
existentialBase[keyPath: wkp] = s
existentialBase[keyPath: rkp] = s
existentialBase[keyPath: pkp] = s // expected-error {{cannot assign through subscript: 'pkp' is a read-only key path}}
}
struct AA {
subscript(x: Int) -> Int { return x }
subscript(labeled x: Int) -> Int { return x }
var c: CC? = CC()
}
class CC {
var i = 0
}
func testKeyPathOptional() {
_ = \AA.c?.i
_ = \AA.c!.i
// SR-6198
let path: KeyPath<CC,Int>! = \CC.i
let cc = CC()
_ = cc[keyPath: path]
}
func testLiteralInAnyContext() {
let _: AnyKeyPath = \A.property
let _: AnyObject = \A.property
let _: Any = \A.property
let _: Any? = \A.property
}
func testMoreGeneralContext<T, U>(_: KeyPath<T, U>, with: T.Type) {}
func testLiteralInMoreGeneralContext() {
testMoreGeneralContext(\.property, with: A.self)
}
func testLabeledSubscript() {
let _: KeyPath<AA, Int> = \AA.[labeled: 0]
let _: KeyPath<AA, Int> = \.[labeled: 0]
let k = \AA.[labeled: 0]
// TODO: These ought to work without errors.
let _ = \AA.[keyPath: k]
// expected-error@-1 {{cannot convert value of type 'KeyPath<AA, Int>' to expected argument type 'Int'}}
let _ = \AA.[keyPath: \AA.[labeled: 0]] // expected-error {{extraneous argument label 'keyPath:' in call}}
// expected-error@-1 {{cannot convert value of type 'KeyPath<AA, Int>' to expected argument type 'Int'}}
}
func testInvalidKeyPathComponents() {
let _ = \.{return 0} // expected-error* {{}}
}
class X {
class var a: Int { return 1 }
static var b = 2
}
func testStaticKeyPathComponent() {
_ = \X.a // expected-error{{cannot refer to static member}}
_ = \X.Type.a // expected-error{{cannot refer to static member}}
_ = \X.b // expected-error{{cannot refer to static member}}
_ = \X.Type.b // expected-error{{cannot refer to static member}}
}
class Bass: Hashable {
static func ==(_: Bass, _: Bass) -> Bool { return false }
func hash(into hasher: inout Hasher) {}
}
class Treble: Bass { }
struct BassSubscript {
subscript(_: Bass) -> Int { fatalError() }
subscript(_: @autoclosure () -> String) -> Int { fatalError() }
}
func testImplicitConversionInSubscriptIndex() {
_ = \BassSubscript.[Treble()]
_ = \BassSubscript.["hello"] // expected-error{{must be Hashable}}
}
// Crash in diagnostics + SR-11438
struct UnambiguousSubscript {
subscript(sub: Sub) -> Int { get { } set { } }
subscript(y y: Sub) -> Int { get { } set { } }
}
func useUnambiguousSubscript(_ sub: Sub) {
let _: PartialKeyPath<UnambiguousSubscript> = \.[sub]
}
struct BothUnavailableSubscript {
@available(*, unavailable)
subscript(sub: Sub) -> Int { get { } set { } } // expected-note {{'subscript(_:)' has been explicitly marked unavailable here}}
@available(*, unavailable)
subscript(y y: Sub) -> Int { get { } set { } }
}
func useBothUnavailableSubscript(_ sub: Sub) {
let _: PartialKeyPath<BothUnavailableSubscript> = \.[sub]
// expected-error@-1 {{'subscript(_:)' is unavailable}}
}
// SR-6106
func sr6106() {
class B {}
class A {
var b: B? = nil
}
class C {
var a: A?
func myFunc() {
let _ = \C.a?.b
}
}
}
// SR-6744
func sr6744() {
struct ABC {
let value: Int
func value(adding i: Int) -> Int { return value + i }
}
let abc = ABC(value: 0)
func get<T>(for kp: KeyPath<ABC, T>) -> T {
return abc[keyPath: kp]
}
_ = get(for: \.value)
}
func sr7380() {
_ = ""[keyPath: \.count]
_ = ""[keyPath: \String.count]
let arr1 = [1]
_ = arr1[keyPath: \.[0]]
_ = arr1[keyPath: \[Int].[0]]
let dic1 = [1:"s"]
_ = dic1[keyPath: \.[1]]
_ = dic1[keyPath: \[Int: String].[1]]
var arr2 = [1]
arr2[keyPath: \.[0]] = 2
arr2[keyPath: \[Int].[0]] = 2
var dic2 = [1:"s"]
dic2[keyPath: \.[1]] = ""
dic2[keyPath: \[Int: String].[1]] = ""
_ = [""][keyPath: \.[0]]
_ = [""][keyPath: \[String].[0]]
_ = ["": ""][keyPath: \.["foo"]]
_ = ["": ""][keyPath: \[String: String].["foo"]]
class A {
var a: String = ""
}
_ = A()[keyPath: \.a]
_ = A()[keyPath: \A.a]
A()[keyPath: \.a] = ""
A()[keyPath: \A.a] = ""
}
struct VisibilityTesting {
private(set) var x: Int
fileprivate(set) var y: Int
let z: Int
// Key path exprs should not get special dispensation to write to lets
// in init contexts
init() {
var xRef = \VisibilityTesting.x
var yRef = \VisibilityTesting.y
var zRef = \VisibilityTesting.z
expect(&xRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&yRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
// Allow WritableKeyPath for Swift 3/4 only.
expect(&zRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
}
func inPrivateContext() {
var xRef = \VisibilityTesting.x
var yRef = \VisibilityTesting.y
var zRef = \VisibilityTesting.z
expect(&xRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&yRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&zRef,
toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self)
}
}
struct VisibilityTesting2 {
func inFilePrivateContext() {
var xRef = \VisibilityTesting.x
var yRef = \VisibilityTesting.y
var zRef = \VisibilityTesting.z
// Allow WritableKeyPath for Swift 3/4 only.
expect(&xRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&yRef,
toHaveType: Exactly<WritableKeyPath<VisibilityTesting, Int>>.self)
expect(&zRef,
toHaveType: Exactly<KeyPath<VisibilityTesting, Int>>.self)
}
}
protocol PP {}
class Base : PP { var i: Int = 0 }
class Derived : Base {}
func testSubtypeKeypathClass(_ keyPath: ReferenceWritableKeyPath<Base, Int>) {
testSubtypeKeypathClass(\Derived.i)
}
func testSubtypeKeypathProtocol(_ keyPath: ReferenceWritableKeyPath<PP, Int>) {
testSubtypeKeypathProtocol(\Base.i)
// expected-error@-1 {{cannot convert value of type 'ReferenceWritableKeyPath<Base, Int>' to expected argument type 'ReferenceWritableKeyPath<any PP, Int>'}}
// expected-note@-2 {{arguments to generic parameter 'Root' ('Base' and 'any PP') are expected to be equal}}
}
// rdar://problem/32057712
struct Container {
let base: Base? = Base()
}
var rdar32057712 = \Container.base?.i
var identity1 = \Container.self
var identity2: WritableKeyPath = \Container.self
var identity3: WritableKeyPath<Container, Container> = \Container.self
var identity4: WritableKeyPath<Container, Container> = \.self
var identity5: KeyPath = \Container.self
var identity6: KeyPath<Container, Container> = \Container.self
var identity7: KeyPath<Container, Container> = \.self
var identity8: PartialKeyPath = \Container.self
var identity9: PartialKeyPath<Container> = \Container.self
var identity10: PartialKeyPath<Container> = \.self
var identity11: AnyKeyPath = \Container.self
var identity12: (Container) -> Container = \Container.self
var identity13: (Container) -> Container = \.self
var interleavedIdentityComponents = \Container.self.base.self?.self.i.self
protocol P_With_Static_Members {
static var x: Int { get }
static var arr: [Int] { get }
}
func test_keypath_with_static_members(_ p: P_With_Static_Members) {
let _ = p[keyPath: \.x]
// expected-error@-1 {{key path cannot refer to static member 'x'}}
let _: KeyPath<P_With_Static_Members, Int> = \.x
// expected-error@-1 {{key path cannot refer to static member 'x'}}
let _ = \P_With_Static_Members.arr.count
// expected-error@-1 {{key path cannot refer to static member 'arr'}}
let _ = p[keyPath: \.arr.count]
// expected-error@-1 {{key path cannot refer to static member 'arr'}}
struct S {
static var foo: String = "Hello"
var bar: Bar
}
struct Bar {
static var baz: Int = 42
}
func foo(_ s: S) {
let _ = \S.Type.foo
// expected-error@-1 {{key path cannot refer to static member 'foo'}}
let _ = s[keyPath: \.foo]
// expected-error@-1 {{key path cannot refer to static member 'foo'}}
let _: KeyPath<S, String> = \.foo
// expected-error@-1 {{key path cannot refer to static member 'foo'}}
let _ = \S.foo
// expected-error@-1 {{key path cannot refer to static member 'foo'}}
let _ = \S.bar.baz
// expected-error@-1 {{key path cannot refer to static member 'baz'}}
let _ = s[keyPath: \.bar.baz]
// expected-error@-1 {{key path cannot refer to static member 'baz'}}
}
}
func test_keypath_with_mutating_getter() {
struct S {
var foo: Int {
mutating get { return 42 }
}
subscript(_: Int) -> [Int] {
mutating get { return [] }
}
}
_ = \S.foo
// expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}}
let _: KeyPath<S, Int> = \.foo
// expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}}
_ = \S.[0]
// expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}}
_ = \S.[0].count
// expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}}
func test_via_subscript(_ s: S) {
_ = s[keyPath: \.foo]
// expected-error@-1 {{key path cannot refer to 'foo', which has a mutating getter}}
_ = s[keyPath: \.[0].count]
// expected-error@-1 {{key path cannot refer to 'subscript(_:)', which has a mutating getter}}
}
}
func test_keypath_with_method_refs() {
struct S {
func foo() -> Int { return 42 }
static func bar() -> Int { return 0 }
}
let _: KeyPath<S, Int> = \.foo // expected-error {{key path cannot refer to instance method 'foo()'}}
// expected-error@-1 {{key path value type '() -> Int' cannot be converted to contextual type 'Int'}}
let _: KeyPath<S, Int> = \.bar // expected-error {{key path cannot refer to static member 'bar()'}}
let _ = \S.Type.bar // expected-error {{key path cannot refer to static method 'bar()'}}
struct A {
func foo() -> B { return B() }
static func faz() -> B { return B() }
}
struct B {
var bar: Int = 42
}
let _: KeyPath<A, Int> = \.foo.bar // expected-error {{key path cannot refer to instance method 'foo()'}}
let _: KeyPath<A, Int> = \.faz.bar // expected-error {{key path cannot refer to static member 'faz()'}}
let _ = \A.foo.bar // expected-error {{key path cannot refer to instance method 'foo()'}}
let _ = \A.Type.faz.bar // expected-error {{key path cannot refer to static method 'faz()'}}
}
// SR-12519: Compiler crash on invalid method reference in key path.
protocol Zonk {
func wargle()
}
typealias Blatz = (gloop: String, zoop: Zonk?)
func sr12519(fleep: [Blatz]) {
fleep.compactMap(\.zoop?.wargle) // expected-error {{key path cannot refer to instance method 'wargle()'}}
}
// SR-10467 - Argument type 'KeyPath<String, Int>' does not conform to expected type 'Any'
func test_keypath_in_any_context() {
func foo(_: Any) {}
foo(\String.count) // Ok
}
protocol PWithTypeAlias {
typealias Key = WritableKeyPath<Self, Int?>
static var fooKey: Key? { get }
static var barKey: Key! { get }
static var fazKey: Key?? { get }
static var bazKey: Key?! { get }
}
func test_keypath_inference_with_optionals() {
final class S : PWithTypeAlias {
static var fooKey: Key? { return \.foo }
static var barKey: Key! { return \.foo }
static var fazKey: Key?? { return \.foo }
static var bazKey: Key?! { return \.foo }
var foo: Int? = nil
}
}
func sr11562() {
struct S1 {
subscript(x x: Int) -> Int { x }
}
_ = \S1.[5] // expected-error {{missing argument label 'x:' in call}} {{12-12=x: }}
struct S2 {
subscript(x x: Int) -> Int { x } // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(x:)')}}
subscript(y y: Int) -> Int { y } // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(y:)')}}
}
_ = \S2.[5] // expected-error {{no exact matches in call to subscript}}
struct S3 {
subscript(x x: Int, y y: Int) -> Int { x }
}
_ = \S3.[y: 5, x: 5] // expected-error {{argument 'x' must precede argument 'y'}}
struct S4 {
subscript(x: (Int, Int)) -> Int { x.0 }
}
_ = \S4.[1, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{12-12=(}} {{16-16=)}}
// expected-error@-1 {{subscript index of type '(Int, Int)' in a key path must be Hashable}}
}
// SR-12290: Ban keypaths with contextual root and without a leading dot
struct SR_12290 {
let property: [Int] = []
let kp1: KeyPath<SR_12290, Int> = \property.count // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{38-38=.}}
let kp2: KeyPath<SR_12290, Int> = \.property.count // Ok
let kp3: KeyPath<SR_12290, Int> = \SR_12290.property.count // Ok
func foo1(_: KeyPath<SR_12290, Int> = \property.count) {} // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{42-42=.}}
func foo2(_: KeyPath<SR_12290, Int> = \.property.count) {} // Ok
func foo3(_: KeyPath<SR_12290, Int> = \SR_12290.property.count) {} // Ok
func foo4<T>(_: KeyPath<SR_12290, T>) {}
func useFoo4() {
foo4(\property.count) // expected-error {{a Swift key path with contextual root must begin with a leading dot}}{{11-11=.}}
foo4(\.property.count) // Ok
foo4(\SR_12290.property.count) // Ok
}
}
func testKeyPathHole() {
_ = \.x // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{8-8=<#Root#>}}
_ = \.x.y // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{8-8=<#Root#>}}
let _ : AnyKeyPath = \.x
// expected-error@-1 {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{25-25=<#Root#>}}
let _ : AnyKeyPath = \.x.y
// expected-error@-1 {{'AnyKeyPath' does not provide enough context for root type to be inferred; consider explicitly specifying a root type}} {{25-25=<#Root#>}}
func f(_ i: Int) {}
f(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{6-6=<#Root#>}}
f(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}} {{6-6=<#Root#>}}
func provideValueButNotRoot<T>(_ fn: (T) -> String) {}
provideValueButNotRoot(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}}
provideValueButNotRoot(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}}
provideValueButNotRoot(\String.foo) // expected-error {{value of type 'String' has no member 'foo'}}
func provideKPValueButNotRoot<T>(_ kp: KeyPath<T, String>) {} // expected-note {{in call to function 'provideKPValueButNotRoot'}}
provideKPValueButNotRoot(\.x) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}}
provideKPValueButNotRoot(\.x.y) // expected-error {{cannot infer key path type from context; consider explicitly specifying a root type}}
provideKPValueButNotRoot(\String.foo)
// expected-error@-1 {{value of type 'String' has no member 'foo'}}
// expected-error@-2 {{generic parameter 'T' could not be inferred}}
}
func testMissingMember() {
let _: KeyPath<String, String> = \.foo // expected-error {{value of type 'String' has no member 'foo'}}
let _: KeyPath<String, String> = \.foo.bar // expected-error {{value of type 'String' has no member 'foo'}}
let _: PartialKeyPath<String> = \.foo // expected-error {{value of type 'String' has no member 'foo'}}
let _: PartialKeyPath<String> = \.foo.bar // expected-error {{value of type 'String' has no member 'foo'}}
_ = \String.x.y // expected-error {{value of type 'String' has no member 'x'}}
}
// SR-5688
struct SR5688_A {
var b: SR5688_B?
}
struct SR5688_AA {
var b: SR5688_B
}
struct SR5688_B {
var m: Int
var c: SR5688_C?
}
struct SR5688_C {
var d: Int
}
struct SR5688_S {
subscript(_ x: Int) -> String? { "" }
}
struct SR5688_O {
struct Nested {
var foo = ""
}
}
func SR5688_KP(_ kp: KeyPath<String?, Int>) {}
func testMemberAccessOnOptionalKeyPathComponent() {
_ = \SR5688_A.b.m
// expected-error@-1 {{value of optional type 'SR5688_B?' must be unwrapped to refer to member 'm' of wrapped base type 'SR5688_B'}}
// expected-note@-2 {{chain the optional using '?' to access member 'm' only for non-'nil' base values}} {{18-18=?}}
// expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{18-18=!}}
_ = \SR5688_A.b.c.d
// expected-error@-1 {{value of optional type 'SR5688_B?' must be unwrapped to refer to member 'c' of wrapped base type 'SR5688_B'}}
// expected-note@-2 {{chain the optional using '?' to access member 'c' only for non-'nil' base values}} {{18-18=?}}
// expected-error@-3 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}}
// expected-note@-4 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{20-20=?}}
// expected-note@-5 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{20-20=!}}
_ = \SR5688_A.b?.c.d
// expected-error@-1 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}}
// expected-note@-2 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{21-21=?}}
_ = \SR5688_AA.b.c.d
// expected-error@-1 {{value of optional type 'SR5688_C?' must be unwrapped to refer to member 'd' of wrapped base type 'SR5688_C'}}
// expected-note@-2 {{chain the optional using '?' to access member 'd' only for non-'nil' base values}} {{21-21=?}}
// expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{21-21=!}}
\String?.count
// expected-error@-1 {{value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'}}
// expected-note@-2 {{use unwrapped type 'String' as key path root}} {{4-11=String}}
\Optional<String>.count
// expected-error@-1 {{value of optional type 'Optional<String>' must be unwrapped to refer to member 'count' of wrapped base type 'String'}}
// expected-note@-2 {{use unwrapped type 'String' as key path root}} {{4-20=String}}
\SR5688_S.[5].count
// expected-error@-1 {{value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'}}
// expected-note@-2 {{chain the optional using '?' to access member 'count' only for non-'nil' base values}}{{16-16=?}}
// expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{16-16=!}}
\SR5688_O.Nested?.foo.count
// expected-error@-1 {{value of optional type 'SR5688_O.Nested?' must be unwrapped to refer to member 'foo' of wrapped base type 'SR5688_O.Nested'}}
// expected-note@-2 {{use unwrapped type 'SR5688_O.Nested' as key path root}}{{4-20=SR5688_O.Nested}}
\(Int, Int)?.0
// expected-error@-1 {{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}}
// expected-note@-2 {{use unwrapped type '(Int, Int)' as key path root}}{{4-15=(Int, Int)}}
SR5688_KP(\.count) // expected-error {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'count' of unwrapped type 'String'}}
// expected-note@-1 {{chain the optional using '?.' to access unwrapped type member 'count'}} {{15-15=?.}}
// expected-note@-2 {{unwrap the optional using '!.' to access unwrapped type member 'count'}} {{15-15=!.}}
let _ : KeyPath<String?, Int> = \.count // expected-error {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'count' of unwrapped type 'String'}}
// expected-note@-1 {{chain the optional using '?.' to access unwrapped type member 'count'}} {{37-37=?.}}
// expected-note@-2 {{unwrap the optional using '!.' to access unwrapped type member 'count'}} {{37-37=!.}}
let _ : KeyPath<String?, Int> = \.utf8.count
// expected-error@-1 {{key path root inferred as optional type 'String?' must be unwrapped to refer to member 'utf8' of unwrapped type 'String'}}
// expected-note@-2 {{chain the optional using '?.' to access unwrapped type member 'utf8'}} {{37-37=?.}}
// expected-note@-3 {{unwrap the optional using '!.' to access unwrapped type member 'utf8'}} {{37-37=!.}}
}
func testSyntaxErrors() {
_ = \. ; // expected-error{{expected member name following '.'}}
_ = \.a ;
_ = \[a ;
_ = \[a];
_ = \? ;
_ = \! ;
_ = \. ; // expected-error{{expected member name following '.'}}
_ = \.a ;
_ = \[a ;
_ = \[a,;
_ = \[a:;
_ = \[a];
_ = \.a?;
_ = \.a!;
_ = \A ;
_ = \A, ;
_ = \A< ;
_ = \A. ; // expected-error{{expected member name following '.'}}
_ = \A.a ;
_ = \A[a ;
_ = \A[a];
_ = \A? ;
_ = \A! ;
_ = \A. ; // expected-error{{expected member name following '.'}}
_ = \A.a ;
_ = \A[a ;
_ = \A[a,;
_ = \A[a:;
_ = \A[a];
_ = \A.a?;
_ = \A.a!;
}
// SR-14644
func sr14644() {
_ = \Int.byteSwapped.signum() // expected-error {{invalid component of Swift key path}}
_ = \Int.byteSwapped.init() // expected-error {{invalid component of Swift key path}}
_ = \Int // expected-error {{key path must have at least one component}}
_ = \Int? // expected-error {{key path must have at least one component}}
_ = \Int. // expected-error {{invalid component of Swift key path}}
// expected-error@-1 {{expected member name following '.'}}
}
// SR-13364 - keypath missing optional crashes compiler: "Inactive constraints left over?"
func sr13364() {
let _: KeyPath<String?, Int?> = \.utf8.count // expected-error {{no exact matches in reference to property 'count'}}
// expected-note@-1 {{found candidate with type 'Int'}}
}
// rdar://74711236 - crash due to incorrect member access in key path
func rdar74711236() {
struct S {
var arr: [V] = []
}
struct V : Equatable {
}
enum Type {
case store
}
struct Context {
func supported() -> [Type] {
return []
}
}
func test(context: Context?) {
var s = S()
s.arr = {
if let type = context?.store { // expected-error {{value of type 'Context' has no member 'store'}}
// `isSupported` should be an invalid declaration to trigger a crash in `map(\.option)`
let isSupported = context!.supported().contains(type)
return (isSupported ? [type] : []).map(\.option)
}
return []
}()
}
}
extension String {
var filterOut : (Self) throws -> Bool {
{ $0.contains("a") }
}
}
func test_kp_as_function_mismatch() {
let a : [String] = [ "asd", "bcd", "def" ]
let _ : (String) -> Bool = \.filterOut // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}}
_ = a.filter(\.filterOut) // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}}
let _ : (String) -> Bool = \String.filterOut // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}}
_ = a.filter(\String.filterOut) // expected-error{{key path value type '(String) throws -> Bool' cannot be converted to contextual type 'Bool'}}
}
func test_partial_keypath_inference() {
// rdar://problem/34144827
struct S { var i: Int = 0 }
enum E { case A(pkp: PartialKeyPath<S>) }
_ = E.A(pkp: \.i) // Ok
// rdar://problem/36472188
class ThePath {
var isWinding:Bool?
}
func walk<T>(aPath: T, forKey: PartialKeyPath<T>) {}
func walkThePath(aPath: ThePath, forKey: PartialKeyPath<ThePath>) {}
func test(path: ThePath) {
walkThePath(aPath: path, forKey: \.isWinding) // Ok
walk(aPath: path, forKey: \.isWinding) // Ok
}
}
// SR-14499
struct SR14499_A { }
struct SR14499_B { }
func sr14499() {
func reproduceA() -> [(SR14499_A, SR14499_B)] {
[
(true, .init(), SR14499_B.init()) // expected-error {{cannot infer contextual base in reference to member 'init'}}
]
.filter(\.0) // expected-error {{value of type 'Any' has no member '0'}}
// expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
.prefix(3)
.map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}}
// expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
}
func reproduceB() -> [(SR14499_A, SR14499_B)] {
[
(true, SR14499_A.init(), .init()) // expected-error {{cannot infer contextual base in reference to member 'init'}}
]
.filter(\.0) // expected-error {{value of type 'Any' has no member '0'}}
// expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
.prefix(3)
.map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}}
// expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
}
func reproduceC() -> [(SR14499_A, SR14499_B)] {
[
(true, .init(), .init()) // expected-error 2 {{cannot infer contextual base in reference to member 'init'}}
]
.filter(\.0) // expected-error {{value of type 'Any' has no member '0'}}
// expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
.prefix(3)
.map { ($0.1, $0.2) } // expected-error {{value of type 'Any' has no member '1'}} expected-error{{value of type 'Any' has no member '2'}}
// expected-note@-1 2 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}
}
}
| apache-2.0 | 7042501a057eda7be5b55fad5a02824d | 37.123939 | 191 | 0.642463 | 3.643518 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/InputBar/ConversationInputBarViewController+FilesPopover.swift | 1 | 7024 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import MobileCoreServices
import WireSyncEngine
extension ConversationInputBarViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
uploadFiles(at: urls)
}
}
extension ConversationInputBarViewController {
func configPopover(docController: UIDocumentPickerViewController,
sourceView: UIView,
delegate: UIPopoverPresentationControllerDelegate,
pointToView: UIView) {
guard let popover = docController.popoverPresentationController else { return }
popover.delegate = delegate
popover.config(from: self, pointToView: pointToView, sourceView: sourceView)
popover.permittedArrowDirections = .down
}
func createDocUploadActionSheet(sender: IconButton? = nil) -> UIAlertController {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// Alert actions for debugging
#if targetEnvironment(simulator)
let plistHandler: ((UIAlertAction) -> Void) = { _ in
ZMUserSession.shared()?.enqueue({
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
guard let basePath = paths.first,
let sourceLocation = Bundle.main.url(forResource: "CountryCodes", withExtension: "plist") else { return }
let destLocation = URL(fileURLWithPath: basePath).appendingPathComponent(sourceLocation.lastPathComponent)
try? FileManager.default.copyItem(at: sourceLocation, to: destLocation)
self.uploadFile(at: destLocation)
})
}
controller.addAction(UIAlertAction(title: "CountryCodes.plist",
style: .default,
handler: plistHandler))
let size = UInt(ZMUserSession.shared()?.maxUploadFileSize ?? 0) + 1
let humanReadableSize = size / 1024 / 1024
controller.addAction(uploadTestAlertAction(size: size, title: "Big file (size = \(humanReadableSize) MB)", fileName: "BigFile.bin"))
controller.addAction(uploadTestAlertAction(size: 20971520, title: "20 MB file", fileName: "20MBFile.bin"))
controller.addAction(uploadTestAlertAction(size: 41943040, title: "40 MB file", fileName: "40MBFile.bin"))
if ZMUser.selfUser()?.hasTeam == true {
controller.addAction(uploadTestAlertAction(size: 83886080, title: "80 MB file", fileName: "80MBFile.bin"))
controller.addAction(uploadTestAlertAction(size: 125829120, title: "120 MB file", fileName: "120MBFile.bin"))
}
#endif
let uploadVideoHandler: ((UIAlertAction) -> Void) = { _ in
self.presentImagePicker(with: .photoLibrary,
mediaTypes: [kUTTypeMovie as String], allowsEditing: true,
pointToView: self.videoButton.imageView)
}
controller.addAction(UIAlertAction(icon: .movie,
title: "content.file.upload_video".localized,
tintColor: view.tintColor,
handler: uploadVideoHandler))
let takeVideoHandler: ((UIAlertAction) -> Void) = { _ in
self.recordVideo()
}
controller.addAction(UIAlertAction(icon: .cameraShutter,
title: "content.file.take_video".localized,
tintColor: view.tintColor,
handler: takeVideoHandler))
let browseHandler: ((UIAlertAction) -> Void) = { _ in
let documentPickerViewController = UIDocumentPickerViewController(documentTypes: [kUTTypeItem as String], in: .import)
documentPickerViewController.modalPresentationStyle = self.isIPadRegular() ? .popover : .fullScreen
if self.isIPadRegular(),
let sourceView = self.parent?.view,
let pointToView = sender?.imageView {
self.configPopover(docController: documentPickerViewController, sourceView: sourceView, delegate: self, pointToView: pointToView)
}
documentPickerViewController.delegate = self
documentPickerViewController.allowsMultipleSelection = true
self.parent?.present(documentPickerViewController, animated: true)
}
controller.addAction(UIAlertAction(icon: .ellipsis,
title: "content.file.browse".localized, tintColor: view.tintColor,
handler: browseHandler))
controller.addAction(.cancel())
controller.configPopover(pointToView: sender ?? view)
return controller
}
@objc
func docUploadPressed(_ sender: IconButton) {
mode = ConversationInputBarViewControllerMode.textInput
inputBar.textView.resignFirstResponder()
let controller = createDocUploadActionSheet(sender: sender)
present(controller, animated: true)
}
@objc
func videoButtonPressed(_ sender: IconButton) {
recordVideo()
}
private func recordVideo() {
guard !CameraAccess.displayAlertIfOngoingCall(at: .recordVideo, from: self) else { return }
presentImagePicker(with: .camera, mediaTypes: [kUTTypeMovie as String], allowsEditing: false, pointToView: videoButton.imageView)
}
#if targetEnvironment(simulator)
private func uploadTestAlertAction(size: UInt, title: String, fileName: String) -> UIAlertAction {
return UIAlertAction(title: title, style: .default, handler: {_ in
ZMUserSession.shared()?.enqueue({
let randomData = Data.secureRandomData(length: UInt(size))
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(fileName)
try? randomData.write(to: fileURL)
self.uploadFile(at: fileURL)
}
})
})
}
#endif
}
| gpl-3.0 | 048d56e01c1740a5e580b1ec261b8940 | 42.627329 | 145 | 0.632118 | 5.341445 | false | false | false | false |
sachin004/firefox-ios | Sync/KeyBundle.swift | 11 | 10542 | /* 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 FxA
import Account
private let KeyLength = 32
public class KeyBundle: Hashable {
let encKey: NSData
let hmacKey: NSData
public class func fromKB(kB: NSData) -> KeyBundle {
let salt = NSData()
let contextInfo = FxAClient10.KW("oldsync")
let len: UInt = 64 // KeyLength + KeyLength, without type nonsense.
let derived = kB.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: len)
return KeyBundle(encKey: derived.subdataWithRange(NSRange(location: 0, length: KeyLength)),
hmacKey: derived.subdataWithRange(NSRange(location: KeyLength, length: KeyLength)))
}
public class func random() -> KeyBundle {
// Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which
// on iOS is populated by the OS from kernel-level sources of entropy.
// That should mean that we don't need to seed or initialize anything before calling
// this. That is probably not true on (some versions of) OS X.
return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32))
}
public class var invalid: KeyBundle {
return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")
}
public init(encKeyB64: String, hmacKeyB64: String) {
self.encKey = Bytes.decodeBase64(encKeyB64)
self.hmacKey = Bytes.decodeBase64(hmacKeyB64)
}
public init(encKey: NSData, hmacKey: NSData) {
self.encKey = encKey
self.hmacKey = hmacKey
}
private func _hmac(ciphertext: NSData) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) {
let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CCHmac(hmacAlgorithm, hmacKey.bytes, hmacKey.length, ciphertext.bytes, ciphertext.length, result)
return (result, digestLen)
}
public func hmac(ciphertext: NSData) -> NSData {
let (result, digestLen) = _hmac(ciphertext)
let data = NSMutableData(bytes: result, length: digestLen)
result.destroy()
return data
}
/**
* Returns a hex string for the HMAC.
*/
public func hmacString(ciphertext: NSData) -> String {
let (result, digestLen) = _hmac(ciphertext)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(hash)
}
public func encrypt(cleartext: NSData, iv: NSData?=nil) -> (ciphertext: NSData, iv: NSData)? {
let iv = iv ?? Bytes.generateRandomBytes(16)
let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt))
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = NSData(bytes: b, length: Int(copied))
b.destroy()
return (d, iv)
}
b.destroy()
return nil
}
// You *must* verify HMAC before calling this.
public func decrypt(ciphertext: NSData, iv: NSData) -> String? {
let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt))
if success == CCCryptorStatus(kCCSuccess) {
// Hooray!
let d = NSData(bytesNoCopy: b, length: Int(copied))
let s = NSString(data: d, encoding: NSUTF8StringEncoding)
b.destroy()
return s as String?
}
b.destroy()
return nil
}
private func crypt(input: NSData, iv: NSData, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutablePointer<Void>, count: Int) {
let resultSize = input.length + kCCBlockSizeAES128
let result = UnsafeMutablePointer<Void>.alloc(resultSize)
var copied: Int = 0
let success: CCCryptorStatus =
CCCrypt(op,
CCHmacAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
encKey.bytes,
kCCKeySizeAES256,
iv.bytes,
input.bytes,
input.length,
result,
resultSize,
&copied
);
return (success, result, copied)
}
public func verify(hmac hmac: NSData, ciphertextB64: NSData) -> Bool {
let expectedHMAC = hmac
let computedHMAC = self.hmac(ciphertextB64)
return expectedHMAC.isEqualToData(computedHMAC)
}
/**
* Swift can't do functional factories. I would like to have one of the following
* approaches be viable:
*
* 1. Derive the constructor from the consumer of the factory.
* 2. Accept a type as input.
*
* Neither of these are viable, so we instead pass an explicit constructor closure.
*
* Most of these approaches produce either odd compiler errors, or -- worse --
* compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159).
*
* For this reason, be careful trying to simplify or improve this code.
*/
public func factory<T: CleartextPayloadJSON>(f: JSON -> T) -> String -> T? {
return { (payload: String) -> T? in
let potential = EncryptedJSON(json: payload, keyBundle: self)
if !(potential.isValid()) {
return nil
}
let cleartext = potential.cleartext
if (cleartext == nil) {
return nil
}
return f(cleartext!)
}
}
// TODO: how much do we want to move this into EncryptedJSON?
public func serializer<T: CleartextPayloadJSON>(f: T -> JSON) -> Record<T> -> JSON? {
return { (record: Record<T>) -> JSON? in
let json = f(record.payload)
if let data = json.toString(false).utf8EncodedData,
// We pass a null IV, which means "generate me a new one".
// We then include the generated IV in the resulting record.
let (ciphertext, iv) = self.encrypt(data, iv: nil) {
// So we have the encrypted payload. Now let's build the envelope around it.
let ciphertext = ciphertext.base64EncodedString
// The HMAC is computed over the base64 string. As bytes. Yes, I know.
if let encodedCiphertextBytes = ciphertext.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false) {
let hmac = self.hmacString(encodedCiphertextBytes)
let iv = iv.base64EncodedString
// The payload is stringified JSON. Yes, I know.
let payload = JSON([
"ciphertext": ciphertext,
"IV": iv,
"hmac": hmac,
]).toString(false)
return JSON([
"id": record.id,
"sortindex": record.sortindex,
"ttl": record.ttl ?? JSON.null,
"payload": payload,
])
}
}
return nil
}
}
public func asPair() -> [String] {
return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString]
}
public var hashValue: Int {
return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue
}
}
public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool {
return lhs.encKey.isEqualToData(rhs.encKey) &&
lhs.hmacKey.isEqualToData(rhs.hmacKey)
}
public class Keys: Equatable {
let valid: Bool
let defaultBundle: KeyBundle
var collectionKeys: [String: KeyBundle] = [String: KeyBundle]()
public init(defaultBundle: KeyBundle) {
self.defaultBundle = defaultBundle
self.valid = true
}
public init(payload: KeysPayload?) {
if let payload = payload where payload.isValid() {
if let keys = payload.defaultKeys {
self.defaultBundle = keys
self.collectionKeys = payload.collectionKeys
self.valid = true
return
}
}
self.defaultBundle = KeyBundle.invalid
self.valid = false
}
public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) {
let f: (JSON) -> KeysPayload = { KeysPayload($0) }
let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f))
self.init(payload: keysRecord?.payload)
}
public class func random() -> Keys {
return Keys(defaultBundle: KeyBundle.random())
}
public func forCollection(collection: String) -> KeyBundle {
if let bundle = collectionKeys[collection] {
return bundle
}
return defaultBundle
}
public func encrypter<T: CleartextPayloadJSON>(collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> {
return RecordEncrypter(bundle: forCollection(collection), encoder: encoder)
}
public func asPayload() -> KeysPayload {
let json: JSON = JSON([
"id": "keys",
"collection": "crypto",
"default": self.defaultBundle.asPair(),
"collections": mapValues(self.collectionKeys, f: { $0.asPair() })
])
return KeysPayload(json)
}
}
/**
* Yup, these are basically typed tuples.
*/
public struct RecordEncoder<T: CleartextPayloadJSON> {
let decode: JSON -> T
let encode: T -> JSON
}
public struct RecordEncrypter<T: CleartextPayloadJSON> {
let serializer: Record<T> -> JSON?
let factory: String -> T?
init(bundle: KeyBundle, encoder: RecordEncoder<T>) {
self.serializer = bundle.serializer(encoder.encode)
self.factory = bundle.factory(encoder.decode)
}
init(serializer: Record<T> -> JSON?, factory: String -> T?) {
self.serializer = serializer
self.factory = factory
}
}
public func ==(lhs: Keys, rhs: Keys) -> Bool {
return lhs.valid == rhs.valid &&
lhs.defaultBundle == rhs.defaultBundle &&
lhs.collectionKeys == rhs.collectionKeys
}
| mpl-2.0 | eb951821ea8cb06edc282972efe5744e | 34.375839 | 145 | 0.60055 | 4.687417 | false | false | false | false |
toggl/superday | teferi/UI/Modules/Main/Views/AddGoalAlert.swift | 1 | 1841 | import Foundation
import UIKit
import SnapKit
class AddGoalAlert: Alert
{
let tapClosure: () -> ()
init(inViewController viewController: UIViewController?, tapClosure: @escaping () -> ())
{
self.tapClosure = tapClosure
super.init(inViewController: viewController)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
override func buildContentView() -> UIView
{
let btn = UIButton()
btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
btn.setTitle("Set a goal", for: .normal)
btn.backgroundColor = UIColor.familyGreen
btn.layer.cornerRadius = 14
btn.isUserInteractionEnabled = false
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor.almostBlack
label.text = "What do you want to achieve today?"
let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
container.addSubview(label)
container.addSubview(btn)
label.snp.makeConstraints { make in
make.leading.top.bottom.equalToSuperview().inset(14)
make.trailing.equalTo(btn.snp.leading).offset(-27)
}
btn.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.trailing.equalToSuperview().inset(15)
make.height.equalTo(28)
make.width.equalTo(92)
}
let tap = UITapGestureRecognizer(target: self, action: #selector(AddGoalAlert.tap))
container.addGestureRecognizer(tap)
return container
}
@objc private func tap()
{
hide()
tapClosure()
}
}
| bsd-3-clause | 31e8e544122cff6102f44474c2fcbe22 | 28.222222 | 92 | 0.597501 | 4.76943 | false | false | false | false |
pman215/ONH305 | Sources/ONH305SvrLib/ServerUtil.swift | 1 | 2982 | import Foundation
import PerfectLib
import PerfectLogger
struct ServerUtil {
let name = "0.0.0.0"
let port: UInt16 = 8080
let root = "./v2"
let templates = "./v2/templates"
let dataPath = "./v2/data"
let httpLogFile = "./v2/log/ONH305SvrHTTP.log"
let logFile = "./v2/log/ONH305Svr.log"
let templateExtension = ".mustache"
let dataExtension = ".json"
func root(path: String) -> String {
guard let url = URL(string: path) else {
return ""
}
var pathComponents = url.pathComponents
if !pathComponents.isEmpty { pathComponents.removeFirst() }
pathComponents.popLast()
pathComponents.insert("", at: 0)
return pathComponents.joined(separator: "/")
}
func templatePath(path: String) -> String {
guard let url = URL(string: path) else {
return ""
}
let templateFolder = folder(url: url, name: "templates")
let templateName = url.lastPathComponent + templateExtension
return templateFolder + "/" + templateName
}
func data(path: String) -> [String : Any] {
guard let url = URL(string: path) else {
return [String : Any]()
}
let templateFolder = folder(url: url, name: "data")
let dataFilenames = filenames(in: templateFolder)
let dataFiles = dataFilenames.map {
File("\(templateFolder)/\($0)")
}
let dataContent: [String] = dataFiles.map {
do {
let content = try $0.readString()
return content
} catch {
LogFile.error("Unable to read content of file \($0.path)")
return ""
}
}
var values = [String : Any]()
dataContent.forEach {
do {
guard let decodedValues = try $0.jsonDecode() as? [String : Any] else {
return
}
decodedValues.forEach {
values[$0.key] = $0.value
}
} catch {
LogFile.error("Unable to decode file as JSON: \($0)")
return
}
}
return values
}
}
private extension ServerUtil {
func folder(url: URL, name: String) -> String {
var pathComponents = url.pathComponents
let lastPathComponent = url.lastPathComponent
if !pathComponents.isEmpty { pathComponents.removeFirst() }
pathComponents.popLast()
pathComponents.append(name)
pathComponents.append(lastPathComponent)
pathComponents.insert(".", at: 0)
return pathComponents.joined(separator: "/")
}
func filenames(in folder: String) -> [String] {
guard File(folder).isDir else {
LogFile.warning("Path \(folder) is not a folder")
return [String]()
}
let dir = Dir(folder)
var files = [String]()
do {
try dir.forEachEntry { (entry) in
files.append(entry)
}
} catch {
LogFile.error("Unable to retrieve folder \(folder) files")
}
LogFile.debug("Folder \(folder) contains files \(files)")
return files
}
func filenames(in folder: String, ext: String, prefix: String) -> [String] {
let allFiles = filenames(in: folder)
let allFilesPrefix = allFiles.filter {
$0.hasPrefix(prefix) && $0.hasSuffix(ext)
}
return allFilesPrefix
}
}
| apache-2.0 | 940a369f7bd1f5ac36e58cb1fc2c141d | 24.271186 | 81 | 0.649229 | 3.491803 | false | false | false | false |
HTWDD/htwcampus | HTWDD/Components/Grades/Models/Grade.swift | 1 | 2363 | //
// Grade.swift
// HTWDD
//
// Created by Benjamin Herzog on 04/01/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import RxSwift
import Marshal
struct Grade: Codable, Identifiable {
enum Status: String, Codable {
case signedUp = "AN"
case passed = "BE"
case failed = "NB"
case ultimatelyFailed = "EN"
var localizedDescription: String {
switch self {
case .signedUp: return Loca.Grades.status.signedUp
case .passed: return Loca.Grades.status.passed
case .failed: return Loca.Grades.status.failed
case .ultimatelyFailed: return Loca.Grades.status.ultimatelyFailed
}
}
}
let nr: Int
let state: Status
let credits: Double
let text: String
let semester: Semester
let numberOfTry: Int
let date: Date?
let mark: Double?
let note: String?
let form: String?
static func get(network: Network, course: Course) -> Observable<[Grade]> {
let parameters = [
"POVersion": "\(course.POVersion)",
"AbschlNr": course.abschlNr,
"StgNr": course.stgNr
]
return network.getArrayM(url: Grade.url, params: parameters)
}
}
extension Grade: Unmarshaling {
static let url = "https://wwwqis.htw-dresden.de/appservice/v2/getgrades"
init(object: MarshaledObject) throws {
self.nr = try object <| "nr"
self.state = try object <| "state"
self.credits = try object <| "credits"
self.text = try object <| "text"
self.semester = try object <| "semester"
self.numberOfTry = try object <| "tries"
let dateRaw: String? = try object <| "examDate"
self.date = try dateRaw.map {
try Date.from(string: $0, format: "yyyy-MM-dd'T'HH:mmZ")
}
let markRaw: Double? = try object <| "grade"
self.mark = markRaw.map { $0 / 100 }
self.note = try? object <| "note"
self.form = try? object <| "form"
}
}
extension Grade: Equatable {
static func ==(lhs: Grade, rhs: Grade) -> Bool {
return lhs.nr == rhs.nr
&& lhs.mark == rhs.mark
&& lhs.credits == rhs.credits
&& lhs.semester == rhs.semester
&& lhs.state == rhs.state
}
}
| mit | fd0c5d55b65fcc00ee2c1a9b4e3d51e5 | 25.539326 | 78 | 0.57536 | 3.910596 | false | false | false | false |
BrandonMA/SwifterUI | SwifterUI/SwifterUI/UILibrary/Views/SFCollectionViewCell.swift | 1 | 1614 | //
// SFCollectionViewCell.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 10/02/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
open class SFCollectionViewCell: UICollectionViewCell, SFViewColorStyle, SFLayoutView {
// MARK: - Class Properties
open class var identifier: String {
return "SFCollectionViewCell"
}
// MARK: - Instance Properties
open var customConstraints: Constraints = []
open var automaticallyAdjustsColorStyle: Bool = true
open var useAlternativeColors: Bool = false
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
prepareSubviews()
setConstraints()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Instance Methods
open func prepareSubviews() {
if automaticallyAdjustsColorStyle {
updateColors()
}
}
open func setConstraints() {
}
open func updateColors() {
backgroundColor = useAlternativeColors ? colorStyle.alternativeColor : colorStyle.mainColor
updateSubviewsColors()
}
public func updateSubviewsColors() {
for view in self.contentView.subviews {
if let subview = view as? SFViewColorStyle {
if subview.automaticallyAdjustsColorStyle == true {
subview.updateColors()
}
}
}
}
}
| mit | 7c7e58466a479b3cb112198c64b2e73d | 23.439394 | 99 | 0.608184 | 5.600694 | false | false | false | false |
RemyDCF/tpg-offline | tpg offline/Settings/CreditsTableViewController.swift | 1 | 6548 | //
// CreditsTableViewController.swift
// tpg offline
//
// Created by Rémy Da Costa Faro on 21/10/2017.
// Copyright © 2018 Rémy Da Costa Faro. All rights reserved.
//
import UIKit
import SafariServices
import Crashlytics
class CreditsTableViewController: UITableViewController {
var credits: [[Credit]] = []
var titles: [String] = [
Text.atCoreOfProject,
Text.specialThanks,
Text.dataProviders,
Text.externalProject
]
override func viewDidLoad() {
super.viewDidLoad()
App.log("Show credits")
App.logEvent("Show credits")
credits.append([
Credit(title: Text.remy, subTitle: Text.designAndDevelopement) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.asmartcode)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
},
Credit(title: Text.cedric, subTitle: Text.testing) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.dacostafaro)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
}])
credits.append([
Credit(title: Text.snotpg, subTitle: Text.linesHistory) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.snotpg)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
}])
credits.append([
Credit(title: Text.tpgOpenData,
subTitle: Text.tpgOpenDataDescription) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.openData)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
},
Credit(title: Text.sbb, subTitle: Text.sbbDescription) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.gtfs)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
},
Credit(title: Text.transportApi, subTitle: Text.routes) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.transportApi)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
}
])
credits.append([
Credit(title: "Alamofire",
subTitle: Text.alamofireDescription) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.alamofire)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
},
Credit(title: "Fabric",
subTitle: Text.fabricDescription) { (_) in
let vc = SFSafariViewController(url: URL(string: URL.fabric)!,
entersReaderIfAvailable: false)
if App.darkMode, #available(iOS 10.0, *) {
vc.preferredBarTintColor = .black
}
vc.delegate = self
self.present(vc, animated: true)
}])
if App.darkMode {
self.tableView.backgroundColor = .black
self.tableView.separatorColor = App.separatorColor
}
ColorModeManager.shared.addColorModeDelegate(self)
}
deinit {
ColorModeManager.shared.removeColorModeDelegate(self)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return credits.count
}
override func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return credits[section].count
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
let credit = credits[indexPath.section][indexPath.row]
credit.action(credit)
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier: "creditCell", for: indexPath)
cell.backgroundColor = App.cellBackgroundColor
cell.textLabel?.textColor = App.textColor
cell.detailTextLabel?.textColor = App.textColor
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.numberOfLines = 0
cell.textLabel?.text = credits[indexPath.section][indexPath.row].title
cell.detailTextLabel?.text =
credits[indexPath.section][indexPath.row].subTitle
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let headerCell = tableView.dequeueReusableCell(withIdentifier: "headerCell")
headerCell?.backgroundColor = App.darkMode ? .black : #colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1)
headerCell?.textLabel?.text = titles[section]
headerCell?.textLabel?.textColor = App.darkMode ?
#colorLiteral(red: 1, green: 0.3411764706, blue: 0.1333333333, alpha: 1) : headerCell?.backgroundColor?.contrast
return headerCell
}
override func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
}
extension CreditsTableViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
dismiss(animated: true)
}
}
struct Credit {
var title: String = ""
var subTitle: String = ""
var action: ((Credit) -> Void)!
}
| mit | 68ffd48892c7f69e814f2804cb9ac4d4 | 33.447368 | 130 | 0.607487 | 4.8125 | false | false | false | false |
BlueBiteLLC/escaconfig-ios | Pod/Classes/Scanner.swift | 1 | 4125 | //
// Scanner.swift
// Pods
//
// Created by Tanner Nelson on 9/14/15.
//
//
import CoreBluetooth
class Scanner: NSObject {
//MARK: Singleton
static let shared = Scanner()
//MARK: Properties
var nearbyBeacons: [Beacon] {
get {
if Device.isSimulator {
return []
} else {
var beacons = [Beacon]()
for (_, beacon) in self.discoveredBeacons {
beacons.append(beacon)
}
return beacons.sorted { beacon1, beacon2 in
return beacon1.rssi > beacon2.rssi
}
}
}
}
var bluetoothManager: CBCentralManager?
var discoveredBeacons: [UUID: Beacon] = [:]
var beaconConnectionCallbacks: [UUID: (_ error: NSError?)->()] = [:]
//MARK: Start
func startScanningNearby(_ delegate: ScannerNearbyDelegate) {
self.nearbyBeaconsDelegate = delegate
if self.bluetoothManager == nil {
self.bluetoothManager = CBCentralManager(delegate: self, queue: nil)
}
}
func stopScanningNearby() {
self.bluetoothManager = nil
}
//MARK: Delegate
var nearbyBeaconsDelegate: ScannerNearbyDelegate?
func notifyNearbyBeaconsDidChange() {
self.nearbyBeaconsDelegate?.escaConfigNearbyBeaconsDidChange()
}
}
extension Scanner: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
log("Bluetooth is \(central.stateString)")
if central.state == .poweredOn {
log("Scanning started")
central.scanForPeripherals(withServices: [escaUuid.service], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
} else {
log("Unable to start scanning")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
let identifier = peripheral.identifier
if let beacon = self.discoveredBeacons[identifier] {
beacon.parseAdvertisementData(advertisementData, rssi: RSSI.intValue)
} else {
if let beacon = Beacon.beaconWithAdvertisementData(advertisementData, peripheral: peripheral, rssi: RSSI.intValue, identifier: identifier) {
beacon.connectionDelegate = self
self.discoveredBeacons[identifier] = beacon
}
}
self.notifyNearbyBeaconsDidChange()
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
if let callback = self.beaconConnectionCallbacks[peripheral.identifier] {
callback(nil)
}
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
if let beacon = self.discoveredBeacons[peripheral.identifier] {
log("\(beacon) did disconnect")
beacon.didDisconnect()
}
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
log("Failed to connect to peripheral")
if let callback = self.beaconConnectionCallbacks[peripheral.identifier] {
callback(error as NSError?)
}
}
}
extension Scanner: BeaconConnectionDelegate {
func connectToBeacon(_ beacon: Beacon, completion: @escaping (_ error: NSError?)->()) {
if let central = self.bluetoothManager {
self.beaconConnectionCallbacks[beacon.peripheral.identifier] = completion
central.connect(beacon.peripheral, options: nil)
}
}
func disconnectFromBeacon(_ beacon: Beacon) {
if let central = self.bluetoothManager {
central.cancelPeripheralConnection(beacon.peripheral)
}
}
}
//MARK: Protocol
public protocol ScannerNearbyDelegate {
func escaConfigNearbyBeaconsDidChange()
}
| mit | 24b9d53f39fbb99d04373c4571181705 | 30.015038 | 152 | 0.615758 | 5.371094 | false | false | false | false |
ztyjr888/WeChat | WeChat/Plugins/Loading/WebView/WeChatWebViewProgressView.swift | 1 | 2902 | //
// WeChatWebViewLoading.swift
// WeChat
//
// Created by Smile on 16/3/2.
// Copyright © 2016年 [email protected]. All rights reserved.
//
import UIKit
//WebView进度条
class WeChatWebViewProgressView: UIView {
var progressBarView:UIView!
var barAnimationDuration:NSTimeInterval = 0.27
var fadeAnimationDuration:NSTimeInterval = 0.27
var fadeOutDelay:NSTimeInterval = 0.1
//var progressBarColor:UIColor = UIColor(red: 22/255, green: 126/255, blue: 251/255, alpha: 1)// iOS7 Safari bar color
var progressBarColor:UIColor = UIColor(red: 51/255, green: 153/255, blue: 102/255, alpha: 1)
override init(frame: CGRect) {
super.init(frame: frame)
configureViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configureViews(){
self.userInteractionEnabled = false
self.autoresizingMask = .FlexibleWidth
self.progressBarView = UIView(frame: self.bounds)
self.progressBarView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth,UIViewAutoresizing.FlexibleHeight]
let tintColor = progressBarColor
//tintColor = (UIApplication.sharedApplication().delegate?.window!!.tintColor)!
self.progressBarView.backgroundColor = tintColor
self.addSubview(progressBarView)
}
func setProgress(progress:CGFloat){
setProgress(progress,animated: false)
}
func setProgress(progress:CGFloat,animated:Bool){
let isGrowing:Bool = (progress > 0)
UIView.animateWithDuration(
(isGrowing && animated) ? self.barAnimationDuration : 0,
delay: 0,
options: .CurveEaseInOut,
animations: { () -> Void in
var frame = self.progressBarView.frame
frame.size.width = progress * self.bounds.size.width
self.progressBarView.frame = frame
}) { (Bool) -> Void in
}
if progress >= 1 {
UIView.animateWithDuration(
animated ? self.fadeAnimationDuration : 0,
delay: self.fadeOutDelay,
options: .CurveEaseInOut,
animations: { () -> Void in
self.progressBarView.alpha = 0
}, completion: { (Bool) -> Void in
var frame = self.progressBarView.frame
frame.size.width = 0
self.progressBarView.frame = frame
})
} else {
UIView.animateWithDuration(
animated ? self.fadeAnimationDuration : 0,
delay: 0,
options: .CurveEaseInOut,
animations: { () -> Void in
self.progressBarView.alpha = 1
}, completion: nil)
}
}
}
| apache-2.0 | a82cf051e3d7170c7d22e4ece72238b8 | 32.639535 | 122 | 0.58244 | 4.945299 | false | false | false | false |
dterana/Pokedex-API | Sources/App/Models/Pokemon_Type.swift | 1 | 1792 | import Vapor
import Fluent
final class Pokemon_Type: Model {
// MARK: - Properties
var id: Node?
var exists: Bool = false
var pokemon_id: Node
var type_id: Node
// MARK: - Init
//Attention - Postgresql field name are only full lowcase
init(pokemon_id: Node, type_id: Node) {
self.id = nil
self.pokemon_id = pokemon_id
self.type_id = type_id
}
// MARK: - NodeConvertible
//Attention - Postgresql field name are only full lowcase
init(node: Node, in context: Context) throws {
id = try node.extract("id")
pokemon_id = try node.extract("pokemon_id")
type_id = try node.extract("type_id")
}
//Attention - Postgresql field name are only full lowcase
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"pokemon_id": pokemon_id,
"type_id": type_id
])
}
// MARK: - Preparation
//Attention - Postgresql field name are only full lowcase
static func prepare(_ database: Database) throws {
try database.create("pokemons_types") { users in
users.id()
users.int("pokemon_id")
users.int("type_id")
}
var sql = "ALTER TABLE pokemons_types ADD CONSTRAINT pokemonfk FOREIGN KEY (pokemon_id) REFERENCES pokemons(id) MATCH FULL;"
try database.driver.raw(sql)
sql = "ALTER TABLE pokemons_types ADD CONSTRAINT typefk FOREIGN KEY (type_id) REFERENCES types(id) MATCH FULL;"
try database.driver.raw(sql)
}
static func revert(_ database: Database) throws {
try database.delete("pokemons_types")
}
}
| mit | 1881c8fb81cdd03648b22ea450fda1b7 | 26.569231 | 132 | 0.574777 | 4.256532 | false | false | false | false |
HelloCore/RXSwiftTutorialProject | Projects/03-Simple/RXSwiftPlayground.playground/Pages/06-Combine-Operator.xcplaygroundpage/Contents.swift | 1 | 2055 | //: [Previous](@previous)
import Foundation
import RxSwift
let subject1 = BehaviorSubject<Int>(value: 0)
let subject2 = BehaviorSubject<Int>(value: 100)
/*:
## `Merge`
เป็น Operator ที่ใช้รวมค่าใน Stream
เมื่อมีค่ามาใน Stream ใด Stream หนึ่ง ค่านั้นจะถูกส่งมาที่ Observable ที่ได้จาก Operator นี้ด้วย
*/
print("---------------------[Example of Merge]-----------------\n")
let mergedStream = Observable.merge([
subject1.asObserver(),
subject2.asObserver()
])
let mergeSubscribe = mergedStream.subscribe(onNext: { (value) in
print("mergeSubscribe onNext: [\(value)]")
})
subject1.onNext(1)
subject1.onNext(2)
subject2.onNext(50)
subject2.onNext(60)
subject1.onNext(3)
mergeSubscribe.dispose()
print("\n------------------------------------------------------")
/*:
-----------------------------------------------
## `CombineLastest`
เป็น Operator ที่ใช้รวมค่าสุดท้ายของ Stream
เมื่อมีค่ามาใน Stream ใด Stream หนึ่ง ค่านั้นจะถูกส่งมาใน Observable ใหม่ พร้อมกับค่าจาก Stream อื่นด้วย
*/
// clear ค่าเก่า
subject1.onNext(0)
subject2.onNext(100)
print("--------------[Example of Combine Latest]-------------\n")
let combineStream = Observable.combineLatest(
subject1.asObservable(),
subject2.asObservable()
) { (sub1, sub2) -> (subject1: Int, subject2: Int) in
return (subject1: sub1, subject2: sub2)
}
let combineSubscribe = combineStream.subscribe( onNext: { (value) in
print("value subject1:\(value.subject1) subject2:\(value.subject2)")
})
subject2.onNext(99)
subject2.onNext(98)
subject1.onNext(1)
subject2.onNext(97)
subject2.onNext(96)
subject1.onNext(2)
combineSubscribe.dispose()
print("\n------------------------------------------------------")
//: [Next](@next)
| mit | 1d19e8045a529f48e43641dc0c65187d | 20.074074 | 104 | 0.620387 | 2.883446 | false | false | false | false |
jacks205/JPulseHUD | Example/JPulseHUD/ViewController.swift | 1 | 5389 | //
// ViewController.swift
// JPulseHUD
//
// Created by Mark Jackson on 07/24/2016.
// Copyright (c) 2016 Mark Jackson. All rights reserved.
//
import UIKit
import JPulseHUD
class ViewController: UIViewController {
let addHUDSimpleBtn: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Add HUD Simple", forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
btn.setTitleColor(UIColor.grayColor(), forState: .Highlighted)
return btn
}()
let addHUDInstanceBtn: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Add HUD Instance", forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
btn.setTitleColor(UIColor.grayColor(), forState: .Highlighted)
return btn
}()
let timingFncEaseInBtn: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Timing Function Ease In", forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
btn.setTitleColor(UIColor.grayColor(), forState: .Highlighted)
return btn
}()
let timingFncEaseInOutBtn: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("Timing Function Ease In Ease Out", forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
btn.setTitleColor(UIColor.grayColor(), forState: .Highlighted)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(addHUDSimpleBtn)
view.addSubview(addHUDInstanceBtn)
view.addSubview(timingFncEaseInBtn)
view.addSubview(timingFncEaseInOutBtn)
addHUDSimpleBtn.addTarget(self, action: #selector(addHUDStaticClick), forControlEvents: .TouchUpInside)
addHUDInstanceBtn.addTarget(self, action: #selector(addHUDInstanceClick), forControlEvents: .TouchUpInside)
timingFncEaseInBtn.addTarget(self, action: #selector(timingFncEaseInClick), forControlEvents: .TouchUpInside)
timingFncEaseInOutBtn.addTarget(self, action: #selector(timingFncEaseInOutClick), forControlEvents: .TouchUpInside)
setConstraints()
view.backgroundColor = UIColor.blackColor()
}
func addHUDStaticClick(sender: AnyObject) {
JPulseHUD.addHUDToView(view)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(20 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
JPulseHUD.removeHUDFromView(self.view, animated: true)
}
}
}
func addHUDInstanceClick(sender: AnyObject) {
let hud = JPulseHUD(frame: view.frame)
hud.pulseDurationOffset = -0.1
hud.pulseFillColor = UIColor.redColor()
hud.timingFunction = CAMediaTimingFunction(controlPoints: 0, 1, 1, 0.5)
hud.showInView(view)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(8 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
hud.hide(true)
}
}
func timingFncEaseInClick(sender: AnyObject) {
let hud = JPulseHUD(frame: view.frame)
hud.hideAnimationDuration = 5
hud.pulseDurationOffset = 2
hud.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
hud.showInView(view)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(8 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
hud.hide(true)
}
}
func timingFncEaseInOutClick(sender: AnyObject) {
let hud = JPulseHUD(frame: view.frame)
hud.pulseFillColor = UIColor(red: 0.4, green: 0.2, blue: 0.6, alpha: 1)
hud.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
hud.showInView(view)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(8 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
hud.hide(true)
}
}
private func setConstraints() {
addHUDSimpleBtn.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor, constant: 36).active = true
addHUDSimpleBtn.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
addHUDInstanceBtn.topAnchor.constraintEqualToAnchor(addHUDSimpleBtn.bottomAnchor, constant: 16).active = true
addHUDInstanceBtn.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
timingFncEaseInBtn.topAnchor.constraintEqualToAnchor(addHUDInstanceBtn.bottomAnchor, constant: 16).active = true
timingFncEaseInBtn.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
timingFncEaseInOutBtn.topAnchor.constraintEqualToAnchor(timingFncEaseInBtn.bottomAnchor, constant: 16).active = true
timingFncEaseInOutBtn.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
}
}
| mit | 473751612a4ba8cd89d267a14d0bec54 | 43.172131 | 124 | 0.688625 | 4.536195 | false | false | false | false |
shinobicontrols/iOS8-LevellingUp | LevellingUp/PopoverViewController.swift | 1 | 1479 | //
// Copyright 2015 Scott Logic
//
// 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 UIKit
class PopoverViewController: UIViewController, UIPopoverPresentationControllerDelegate {
@IBAction func handlePopoverPressed(sender: UIView) {
let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("PopoverContentVC") as! UIViewController
popoverVC.modalPresentationStyle = .Popover
presentViewController(popoverVC, animated: true, completion: nil)
if let popoverController = popoverVC.popoverPresentationController {
popoverController.sourceView = sender
popoverController.sourceRect = sender.bounds
popoverController.permittedArrowDirections = .Any
popoverController.delegate = self
}
}
// MARK:- UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .FullScreen
}
}
| apache-2.0 | 2d63c7a7026c223db0d3ed7a4f5a80f8 | 35.975 | 125 | 0.770115 | 5.581132 | false | false | false | false |
ideastouch/MGO | mgoclient/MainSceneViewController.swift | 1 | 4036 | //
// MainSceneViewController.swift
// mgoclient
//
// Created by Gustavo Halperin on 9/25/14.
// Copyright (c) 2014 mgo. All rights reserved.
//
import Foundation
import UIKit
class MainSceneViewController: UIViewController {
@IBOutlet private var _mainSceneCollectionViewModel: MainSceneCollectionViewModel!
@IBOutlet private weak var _collectionView: UICollectionView!
@IBOutlet private weak var _collectionViewFlowLayout: UICollectionViewFlowLayout!
override func viewDidLoad() {
super.viewDidLoad()
_mainSceneCollectionViewModel._numberOfCells = 6
_mainSceneCollectionViewModel._completion = self.performSegueWithIconId
NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged:", name:UIDeviceOrientationDidChangeNotification , object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil)
}
override func viewDidLayoutSubviews() {
var collectionViewFrame:CGRect = _collectionView.frame
var minSize:CGFloat = min(collectionViewFrame.size.width, collectionViewFrame.size.height) / 2.0
var maxSize:CGFloat = max(collectionViewFrame.size.width, collectionViewFrame.size.height) / 3.0
var cellSideSize:CGFloat = min(minSize, maxSize) * 0.9
if ( collectionViewFrame.size.width > collectionViewFrame.size.height) {
_collectionViewFlowLayout.minimumInteritemSpacing = (collectionViewFrame.size.width - cellSideSize * 3.0 ) / 2.0
_collectionViewFlowLayout.minimumLineSpacing = collectionViewFrame.size.height - cellSideSize * 2.0
}
else {
_collectionViewFlowLayout.minimumInteritemSpacing = collectionViewFrame.size.width - cellSideSize * 2.0
_collectionViewFlowLayout.minimumLineSpacing = (collectionViewFrame.size.height - cellSideSize * 3.0 ) / 2.0
}
_collectionViewFlowLayout.itemSize = CGSizeMake(cellSideSize, cellSideSize)
_collectionView.reloadData()
}
func orientationChanged(notification:NSNotification) {
var collectionViewFrame:CGRect = _collectionView.frame
var minSize:CGFloat = min(collectionViewFrame.size.width, collectionViewFrame.size.height) / 2.0
var maxSize:CGFloat = max(collectionViewFrame.size.width, collectionViewFrame.size.height) / 3.0
var cellSideSize:CGFloat = min(minSize, maxSize) * 0.9
if ( collectionViewFrame.size.width > collectionViewFrame.size.height) {
_collectionViewFlowLayout.minimumInteritemSpacing = (collectionViewFrame.size.width - cellSideSize * 3.0 ) / 2.0
_collectionViewFlowLayout.minimumLineSpacing = collectionViewFrame.size.height - cellSideSize * 2.0
}
else {
_collectionViewFlowLayout.minimumInteritemSpacing = collectionViewFrame.size.width - cellSideSize * 2.0
_collectionViewFlowLayout.minimumLineSpacing = (collectionViewFrame.size.height - cellSideSize * 3.0 ) / 2.0
}
_collectionViewFlowLayout.minimumInteritemSpacing *= 0.95
_collectionViewFlowLayout.minimumLineSpacing *= 0.95
_collectionViewFlowLayout.itemSize = CGSizeMake(cellSideSize, cellSideSize)
_collectionView.reloadData()
}
@IBAction func logOutAction(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion:nil)
}
func performSegueWithIconId(properties:NSDictionary) {
self.performSegueWithIdentifier("VideoInfoSegueId", sender: properties)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "VideoInfoSegueId" {
let infoViewController:InfoViewController = segue.destinationViewController as InfoViewController
infoViewController._properties = sender as NSDictionary
}
}
}
| gpl-2.0 | ea87d0e3ecb9482983c6a4a2651800c4 | 42.869565 | 156 | 0.709613 | 5.359894 | false | false | false | false |
cemolcay/ALKit | ALKit/ALKit.swift | 1 | 6398 | //
// ALKit.swift
// AutolayoutPlayground
//
// Created by Cem Olcay on 22/10/15.
// Copyright © 2015 prototapp. All rights reserved.
//
// https://www.github.com/cemolcay/ALKit
//
import UIKit
public extension UIEdgeInsets {
/// Equal insets for all edges.
public init(inset: CGFloat) {
self.init()
top = inset
bottom = inset
left = inset
right = inset
}
}
public extension UIView{
/// Auto layout wrapper function to pin a view's edge to another view's edge.
///
/// - Parameters:
/// - edge: View's edge is going to be pinned.
/// - toEdge: Pinning edge of other view.
/// - ofView: The view to be pinned.
/// - withInset: Space between pinning edges.
public func pin(
edge: NSLayoutConstraint.Attribute,
toEdge: NSLayoutConstraint.Attribute,
ofView: UIView?,
withInset: CGFloat = 0) {
guard let view = superview else {
return assertionFailure("view must be added as subview in view hierarchy")
}
view.addConstraint(NSLayoutConstraint(
item: self,
attribute: edge,
relatedBy: .equal,
toItem: ofView,
attribute: toEdge,
multiplier: 1,
constant: withInset))
}
// MARK: Pin Super
/// Pins right edge of view to other view's right edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinRight(to view: UIView, inset: CGFloat = 0) {
pin(edge: .right, toEdge: .right, ofView: view, withInset: -inset)
}
/// Pins left edge of view to other view's left edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinLeft(to view: UIView, inset: CGFloat = 0) {
pin(edge: .left, toEdge: .left, ofView: view, withInset: inset)
}
/// Pins top edge of view to other view's top edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinTop(to view: UIView, inset: CGFloat = 0) {
pin(edge: .top, toEdge: .top, ofView: view, withInset: inset)
}
/// Pins bottom edge of view to other view's bottom edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinBottom(to view: UIView, inset: CGFloat = 0) {
pin(edge: .bottom, toEdge: .bottom, ofView: view, withInset: -inset)
}
// MARK: Pin To Another View In Super
/// Pins left edge of view to other view's right edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinToRight(of view: UIView, offset: CGFloat = 0) {
pin(edge: .left, toEdge: .right, ofView: view, withInset: offset)
}
/// Pins right edge of view to other view's left edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinToLeft(of view: UIView, offset: CGFloat = 0) {
pin(edge: .right, toEdge: .left, ofView: view, withInset: -offset)
}
/// Pins bottom edge of view to other view's top edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinToTop(of view: UIView, offset: CGFloat = 0) {
pin(edge: .bottom, toEdge: .top, ofView: view, withInset: -offset)
}
/// Pins top edge of view to other view's bottom edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
public func pinToBottom(of view: UIView, offset: CGFloat = 0) {
pin(edge: .top, toEdge: .bottom, ofView: view, withInset: offset)
}
// MARK: Fill In Super
/// Pins all edges of the view to other view's edges with insets.
///
/// - Parameters:
/// - view: The view is going to be pinned.
/// - insets: Spaces between edges.
public func fill(to view: UIView, insets: UIEdgeInsets = .zero) {
pinLeft(to: view, inset: insets.left)
pinRight(to: view, inset: insets.right)
pinTop(to: view, inset: insets.top)
pinBottom(to: view, inset: insets.bottom)
}
/// Pins left and right edges of the view to other view's left and right edges with equal insets.
///
/// - Parameters:
/// - view: The view is going to be pinned.
/// - insets: Equal insets between left and right edges.
public func fillHorizontal(to view: UIView, insets: CGFloat = 0) {
pinRight(to: view, inset: insets)
pinLeft(to: view, inset: insets)
}
/// Pins top and bottom edges of the view to other view's top and bottom edges with equal insets.
///
/// - Parameters:
/// - view: The view is going to be pinned.
/// - insets: Equal insets between top and bottom edges.
public func fillVertical(to view: UIView, insets: CGFloat = 0) {
pinTop(to: view, inset: insets)
pinBottom(to: view, inset: insets)
}
// MARK: Size
/// Pins width and height of the view to constant width and height values.
///
/// - Parameters:
/// - width: Width constant.
/// - height: Height constant.
public func pinSize(width: CGFloat, height: CGFloat) {
pinWidth(width: width)
pinHeight(height: height)
}
/// Pins width of the view to constant width value.
///
/// - Parameter width: Width constant.
public func pinWidth(width: CGFloat) {
pin(edge: .width, toEdge: .notAnAttribute, ofView: nil, withInset: width)
}
/// Pins height of the view to constant width value.
///
/// - Parameter height: Height constant.
public func pinHeight(height: CGFloat) {
pin(edge: .height, toEdge: .notAnAttribute, ofView: nil, withInset: height)
}
// MARK: Center
/// Pins center of the view to other view's center.
///
/// - Parameter view: The view is going to be pinned.
public func pinCenter(to view: UIView) {
pinCenterX(to: view)
pinCenterY(to: view)
}
/// Pins horizontally center the view to other view's center.
///
/// - Parameter view: The view is going to be pinned.
public func pinCenterX(to view: UIView) {
pin(edge: .centerX, toEdge: .centerX, ofView: view)
}
/// Pins vertically center of the view to other view's center.
///
/// - Parameter view: The view is going to be pinned.
public func pinCenterY(to view: UIView) {
pin(edge: .centerY, toEdge: .centerY, ofView: view)
}
}
| mit | 70f058868fb7c8512916fa691156fce7 | 29.317536 | 99 | 0.634047 | 3.785207 | false | false | false | false |
withcopper/CopperKit | CopperKit/C29ImageCache.swift | 1 | 2526 | //
// CopperImageCache.swift
// Copper
// This class is our basic Cobject Database
//
// Created by Doug Williams on 11/17/15.
// Copyright (c) 2014 Doug Williams. All rights reserved.
//
import UIKit
public class C29ImageCache: NSObject, NSCoding {
// Constant used to find this document in the filesystem; assumed unique
public static var CacheFile = "C29ImageCache"
static var FileType = FileSystemType.Caches
// Local store for our images, url => UIImage
private var cache:[String:UIImage] = [String:UIImage]()
public var session: C29SessionDataSource?
// MARK: - NSCoding
// The following two methods allow serialization, etc...
convenience required public init?(coder decoder: NSCoder) {
self.init()
self.cache = decoder.decodeObjectForKey("cache") as! [String: UIImage]
}
public func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(cache, forKey: "cache")
}
public func getImage(url: String, cacheOnDownload: Bool = true, callback: (image: UIImage?)->()) {
if let image = cache[url] {
callback(image: image)
return
}
UIImage.c29_imageFromUrl(url, callback: { returnedImage in
if returnedImage != nil && cacheOnDownload {
self.update(returnedImage, forUrl: url)
}
callback(image: returnedImage)
})
}
public func update(image: UIImage?, forUrl: String) {
if image == nil {
remove(forUrl)
} else {
cache.updateValue(image!, forKey: forUrl)
}
save()
}
public func remove(url: String) {
cache.removeValueForKey(url)
save()
}
public func removeAll() {
cache.removeAll()
save()
}
public var status: String {
return "\(C29ImageCache.CacheFile) status: total images \(cache.count)"
}
public func load() -> Bool {
if let session = session {
return load(session.appGroupIdentifier)
}
return false
}
public func deleteFile() {
if let session = session {
deleteFile(session.appGroupIdentifier)
}
}
public func save() {
if let session = session {
save(session.appGroupIdentifier)
}
}
}
extension C29ImageCache:FileSaveable {
}
extension C29ImageCache:FileLoadable {
public func set(cache: C29ImageCache) {
self.cache = cache.cache
}
} | mit | cc26e74d47521bc98214f3dea4b9907c | 25.051546 | 102 | 0.60095 | 4.455026 | false | false | false | false |
typelift/Basis | Basis/Stream.swift | 2 | 9626 | //
// Stream.swift
// Basis
//
// Created by Robert Widmann on 12/22/14.
// Copyright (c) 2014 TypeLift. All rights reserved.
// Released under the MIT license.
//
/// A lazy infinite sequence of values.
public struct Stream<T> {
let step : () -> (head : T, tail : Stream<T>)
init(_ step : () -> (head : T, tail : Stream<T>)) {
self.step = step
}
public subscript(n : UInt) -> T {
return index(self)(n)
}
}
/// Looks up the nth element of a Stream.
public func index<T>(s : Stream<T>) -> UInt -> T {
return { n in
if n == 0 {
return s.step().head
}
return index(s.step().tail)(n - 1)
}
}
/// Returns the first element of a Stream.
public func head<T>(s : Stream<T>) -> T {
return s.step().head
}
/// Returns the remaining elements of a Stream.
public func tail<T>(s : Stream<T>) -> Stream<T> {
return s.step().tail
}
/// Returns a Stream of all initial segments of a Stream.
public func inits<T>(s : Stream<T>) -> Stream<[T]> {
return Stream { ([], map({ s.step().head <| $0 })(inits(s.step().tail))) }
}
/// Returns a Stream of all final segments of a Stream.
public func tails<T>(s : Stream<T>) -> Stream<Stream<T>> {
return Stream { (s, tails(s.step().tail)) }
}
/// Repeats a value into a constant stream of that same value.
public func repeat<T>(x : T) -> Stream<T> {
return Stream { (x, repeat(x)) }
}
/// Returns a Stream of an infinite number of iteratations of applications of a function to a value.
public func iterate<T>(f : T -> T) -> T -> Stream<T> {
return { x in Stream { (x, iterate(f)(f(x))) } }
}
/// Cycles a non-empty list into an infinite Stream of repeating values.
///
/// This function is partial with respect to the empty list.
public func cycle<T>(xs : [T]) -> Stream<T> {
switch match(xs) {
case .Nil:
return error("Cannot cycle an empty list.")
case .Cons(let x, let xs):
return Stream { (x, cycle(xs + [x])) }
}
}
/// Maps a function over a Stream and returns a new Stream of those values.
public func map<A, B>(f : A -> B) -> Stream<A> -> Stream<B> {
return { s in Stream { (f(s.step().head), map(f)(s.step().tail)) } }
}
/// Uses function to construct a Stream.
///
/// Unlike unfold for lists, unfolds to construct a Stream have no base case.
public func unfold<A, B>(f : A -> (B, A)) -> A -> Stream<B> {
return { z in
let (x, d) = f(z)
return Stream { (x, unfold(f)(d)) }
}
}
/// Returns a Stream of alternating elements from each Stream.
public func interleave<T>(s1 : Stream<T>) -> Stream<T> -> Stream<T> {
return { s2 in Stream { (s1.step().head, interleave(s2)(s1)) } }
}
/// Creates a Stream alternating an element in between the values of another Stream.
public func intersperse<T>(x : T) -> Stream<T> -> Stream<T> {
return { s in Stream { (s.step().head, Stream { (x, intersperse(x)(s.step().tail)) } ) } }
}
/// Returns a Stream of successive reduced values.
public func scanl<A, B>(f : A -> B -> A) -> A -> Stream<B> -> Stream<A> {
return { z in { s in Stream { (z, scanl(f)(f(z)(s.step().head))(s.step().tail)) } } }
}
/// Returns a Stream of successive reduced values.
public func scanl1<A>(f : A -> A -> A) -> Stream<A> -> Stream<A> {
return { s in scanl(f)(s.step().head)(s.step().tail) }
}
/// Transposes the "Rows and Columns" of an infinite Stream.
public func transpose<T>(ss : Stream<Stream<T>>) -> Stream<Stream<T>> {
let xs = ss.step().head
let yss = ss.step().tail
return Stream { (Stream { (xs.step().head, map(head)(yss)) }, transpose(Stream { (xs.step().tail, map(tail)(yss)) } )) }
}
/// Returns the first n elements of a Stream.
public func take<T>(n : UInt) -> Stream<T> -> [T] {
return { s in
if n == 0 {
return []
}
return s.step().head <| take(n - 1)(s.step().tail)
}
}
/// Returns a Stream with the first n elements removed.
public func drop<T>(n : UInt) -> Stream<T> -> Stream<T> {
return { s in
if n == 0 {
return s
}
return drop(n - 1)(tail(s.step().tail))
}
}
/// Returns a pair of the first n elements and the remaining eleemnts in a Stream.
public func splitAt<T>(n : UInt) -> Stream<T> -> ([T], Stream<T>) {
return { xs in
if n == 0 {
return ([], xs)
}
let (p, r) = splitAt(n - 1)(tail(xs))
return (head(xs) <| p, r)
}
}
/// Returns the longest prefix of values in a Stream for which a predicate holds.
public func takeWhile<T>(p : T -> Bool) -> Stream<T> -> [T] {
return { s in
if p(s.step().head) {
return s.step().head <| takeWhile(p)(s.step().tail)
}
return []
}
}
/// Returns the longest suffix remaining after a predicate holds.
public func dropWhile<T>(p : T -> Bool) -> Stream<T> -> Stream<T> {
return { s in
if p(s.step().head) {
return dropWhile(p)(s.step().tail)
}
return s
}
}
/// Removes elements from the Stream that do not satisfy a given predicate.
///
/// If there are no elements that satisfy this predicate this function will diverge.
public func filter<T>(p : T -> Bool) -> Stream<T> -> Stream<T> {
return { s in
if p(s.step().head) {
return Stream { (s.step().head, filter(p)(s.step().tail)) }
}
return filter(p)(s.step().tail)
}
}
/// Zips two Streams into a Stream of pairs.
public func zip<A, B>(s1 : Stream<A>) -> Stream<B> -> Stream<(A, B)> {
return { s2 in Stream { ((s1.step().head, s2.step().head), zip(s1.step().tail)(s2.step().tail)) } }
}
/// Zips two Streams into a third Stream using a combining function.
public func zipWith<A, B, C>(f : A -> B -> C) -> Stream<A> -> Stream<B> -> Stream<C> {
return { s1 in { s2 in Stream { (f(s1.step().head)(s2.step().head), zipWith(f)(s1.step().tail)(s2.step().tail)) } } }
}
/// Unzips a Stream of pairs into a pair of Streams.
public func unzip<A, B>(sp : Stream<(A, B)>) -> (Stream<A>, Stream<B>) {
return (map(fst)(sp), map(snd)(sp))
}
extension Stream : Functor {
typealias A = T
typealias B = Swift.Any
typealias FB = Stream<B>
public static func fmap<B>(f : A -> B) -> Stream<A> -> Stream<B> {
return map(f)
}
}
public func <%> <A, B>(f : A -> B, b : Stream<A>) -> Stream<B> {
return Stream.fmap(f)(b)
}
public func <% <A, B>(a : A, _ : Stream<B>) -> Stream<A> {
return repeat(a)
}
extension Stream : Applicative {
typealias FAB = Stream<A -> B>
public static func pure(x : A) -> Stream<A> {
return repeat(x)
}
public static func ap<B>(f : Stream<A -> B>) -> Stream<A> -> Stream<B> {
return { o in f >*< o }
}
}
public func <*> <A, B>(f : Stream<A -> B> , o : Stream<A>) -> Stream<B> {
return f >*< o
}
public func *> <A, B>(a : Stream<A>, b : Stream<B>) -> Stream<B> {
return a *< b
}
public func <* <A, B>(a : Stream<A>, b : Stream<B>) -> Stream<A> {
return a >* b
}
extension Stream : ApplicativeOps {
typealias C = Any
typealias FC = Stream<C>
typealias D = Any
typealias FD = Stream<D>
public static func liftA<B>(f : A -> B) -> Stream<A> -> Stream<B> {
return { a in Stream<A -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(f : A -> B -> C) -> Stream<A> -> Stream<B> -> Stream<C> {
return { a in { b in f <%> a <*> b } }
}
public static func liftA3<B, C, D>(f : A -> B -> C -> D) -> Stream<A> -> Stream<B> -> Stream<C> -> Stream<D> {
return { a in { b in { c in f <%> a <*> b <*> c } } }
}
}
extension Stream : Monad {
public func bind<B>(f : A -> Stream<B>) -> Stream<B> {
return unfold({ ss in
let bs = ss.step().head
let bss = ss.step().tail
return (head(bs), map(tail)(bss))
})(map(f)(self))
}
}
public func >>- <A, B>(x : Stream<A>, f : A -> Stream<B>) -> Stream<B> {
return x.bind(f)
}
public func >> <A, B>(_ : Stream<A>, bs : Stream<B>) -> Stream<B> {
return bs
}
extension Stream : MonadOps {
typealias MLA = Stream<[A]>
typealias MLB = Stream<[B]>
typealias MU = Stream<()>
public static func mapM<B>(f : A -> Stream<B>) -> [A] -> Stream<[B]> {
return { xs in Stream<B>.sequence(map(f)(xs)) }
}
public static func mapM_<B>(f : A -> Stream<B>) -> [A] -> Stream<()> {
return { xs in Stream<B>.sequence_(map(f)(xs)) }
}
public static func forM<B>(xs : [A]) -> (A -> Stream<B>) -> Stream<[B]> {
return flip(Stream.mapM)(xs)
}
public static func forM_<B>(xs : [A]) -> (A -> Stream<B>) -> Stream<()> {
return flip(Stream.mapM_)(xs)
}
public static func sequence(ls : [Stream<A>]) -> Stream<[A]> {
return foldr({ m, m2 in m >>- { x in m2 >>- { xs in Stream<[A]>.pure(cons(x)(xs)) } } })(Stream<[A]>.pure([]))(ls)
}
public static func sequence_(ls : [Stream<A>]) -> Stream<()> {
return foldr(>>)(Stream<()>.pure(()))(ls)
}
}
public func -<< <A, B>(f : A -> Stream<B>, xs : Stream<A>) -> Stream<B> {
return xs.bind(f)
}
public func >-> <A, B, C>(f : A -> Stream<B>, g : B -> Stream<C>) -> A -> Stream<C> {
return { x in f(x) >>- g }
}
public func <-< <A, B, C>(g : B -> Stream<C>, f : A -> Stream<B>) -> A -> Stream<C> {
return { x in f(x) >>- g }
}
extension Stream : Copointed {
public func extract() -> A {
return head(self)
}
}
extension Stream : Comonad {
typealias FFA = Stream<Stream<A>>
public static func duplicate(b : Stream<A>) -> Stream<Stream<A>> {
return tails(b)
}
public static func extend<B>(f : Stream<A> -> B) -> Stream<A> -> Stream<B> {
return { b in
return Stream<B> { (f(b), Stream.extend(f)(tail(b))) }
}
}
}
extension Stream : ComonadApply {}
public func >*< <A, B>(fab : Stream<A -> B> , xs : Stream<A>) -> Stream<B> {
let f = fab.step().head
let fs = fab.step().tail
let x = xs.step().head
let xss = xs.step().tail
return Stream { (f(x), (fs >*< xss)) }
}
public func *< <A, B>(_ : Stream<A>, b : Stream<B>) -> Stream<B> {
return b
}
public func >* <A, B>(a : Stream<A>, _ : Stream<B>) -> Stream<A> {
return a
}
| mit | f998e7baee90cdb2df52526e8a4a9aca | 26.115493 | 121 | 0.583939 | 2.733106 | false | false | false | false |
luanlzsn/pos | pos/Carthage/Checkouts/IQKeyboardManager/IQKeyboardManagerSwift/IQKeyboardManager.swift | 6 | 110011 | //
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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 CoreGraphics
import UIKit
///---------------------
/// MARK: IQToolbar tags
///---------------------
/**
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
open class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
/**
Default tag for toolbar with Done button -1002.
*/
fileprivate static let kIQDoneButtonToolbarTag = -1002
/**
Default tag for toolbar with Previous/Next buttons -1005.
*/
fileprivate static let kIQPreviousNextButtonToolbarTag = -1005
///---------------------------
/// MARK: UIKeyboard handling
///---------------------------
/**
Registered classes list with library.
*/
fileprivate var registeredClasses = [UIView.Type]()
/**
Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
*/
open var enable = false {
didSet {
//If not enable, enable it.
if enable == true &&
oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if _kbShowNotification != nil {
keyboardWillShow(_kbShowNotification)
}
showLog("enabled")
} else if enable == false &&
oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
showLog("disabled")
}
}
}
fileprivate func privateIsEnabled()-> Bool {
var isEnabled = enable
if let textFieldViewController = _textFieldView?.viewController() {
if isEnabled == false {
//If viewController is kind of enable viewController class, then assuming it's enabled.
for enabledClass in enabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: enabledClass) {
isEnabled = true
break
}
}
}
if isEnabled == true {
//If viewController is kind of disabled viewController class, then assuming it's disabled.
for disabledClass in disabledDistanceHandlingClasses {
if textFieldViewController.isKind(of: disabledClass) {
isEnabled = false
break
}
}
}
}
return isEnabled
}
/**
To set keyboard distance from textField. can't be less than zero. Default is 10.0.
*/
open var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/**
Boolean to know if keyboard is showing.
*/
open var keyboardShowing: Bool {
get {
return _privateIsKeyboardShowing
}
}
/**
moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value.
*/
open var movedDistance: CGFloat {
get {
return _privateMovedDistance
}
}
/**
Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES.
*/
open var preventShowingBottomBlankSpace = true
/**
Returns the default singleton instance.
*/
open class func sharedManager() -> IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
///-------------------------
/// MARK: IQToolbar handling
///-------------------------
/**
Automatic add the IQToolbar functionality. Default is YES.
*/
open var enableAutoToolbar = true {
didSet {
privateIsEnableAutoToolbar() ?addToolbarIfRequired():removeToolbarIfRequired()
let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
showLog("enableAutoToolbar: \(enableToolbar)")
}
}
fileprivate func privateIsEnableAutoToolbar() -> Bool {
var enableToolbar = enableAutoToolbar
if let textFieldViewController = _textFieldView?.viewController() {
if enableToolbar == false {
//If found any toolbar enabled classes then return.
for enabledClass in enabledToolbarClasses {
if textFieldViewController.isKind(of: enabledClass) {
enableToolbar = true
break
}
}
}
if enableToolbar == true {
//If found any toolbar disabled classes then return.
for disabledClass in disabledToolbarClasses {
if textFieldViewController.isKind(of: disabledClass) {
enableToolbar = false
break
}
}
}
}
return enableToolbar
}
/**
/**
IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view.
IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's.
IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate.
Default is IQAutoToolbarBySubviews.
*/
AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
*/
open var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews
/**
If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
*/
open var shouldToolbarUsesTextFieldTintColor = false
/**
This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
*/
open var toolbarTintColor : UIColor?
/**
If YES, then hide previous/next button. Default is NO.
*/
@available(*,deprecated, message: "Please use `previousNextDisplayMode` for better handling of previous/next button display. This property will be removed in future releases in favor of `previousNextDisplayMode`.")
open var shouldHidePreviousNext = false {
didSet {
previousNextDisplayMode = shouldHidePreviousNext ? .alwaysHide : .Default
}
}
/**
IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide.
IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case.
IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled.
*/
open var previousNextDisplayMode = IQPreviousNextDisplayMode.Default
/**
Toolbar done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
*/
open var toolbarDoneBarButtonItemImage : UIImage?
/**
Toolbar done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
*/
open var toolbarDoneBarButtonItemText : String?
/**
If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
*/
open var shouldShowTextFieldPlaceholder = true
/**
Placeholder Font. Default is nil.
*/
open var placeholderFont: UIFont?
///--------------------------
/// MARK: UITextView handling
///--------------------------
/** used to adjust contentInset of UITextView. */
fileprivate var startingTextViewContentInsets = UIEdgeInsets.zero
/** used to adjust scrollIndicatorInsets of UITextView. */
fileprivate var startingTextViewScrollIndicatorInsets = UIEdgeInsets.zero
/** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/
fileprivate var isTextViewContentInsetChanged = false
///---------------------------------------
/// MARK: UIKeyboard appearance overriding
///---------------------------------------
/**
Override the keyboardAppearance for all textField/textView. Default is NO.
*/
open var overrideKeyboardAppearance = false
/**
If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
*/
open var keyboardAppearance = UIKeyboardAppearance.default
///-----------------------------------------------------------
/// MARK: UITextField/UITextView Next/Previous/Resign handling
///-----------------------------------------------------------
/**
Resigns Keyboard on touching outside of UITextField/View. Default is NO.
*/
open var shouldResignOnTouchOutside = false {
didSet {
_tapGesture.isEnabled = privateShouldResignOnTouchOutside()
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
showLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
fileprivate func privateShouldResignOnTouchOutside() -> Bool {
var shouldResign = shouldResignOnTouchOutside
if let textFieldViewController = _textFieldView?.viewController() {
if shouldResign == false {
//If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled.
for enabledClass in enabledTouchResignedClasses {
if textFieldViewController.isKind(of: enabledClass) {
shouldResign = true
break
}
}
}
if shouldResign == true {
//If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable.
for disabledClass in disabledTouchResignedClasses {
if textFieldViewController.isKind(of: disabledClass) {
shouldResign = false
break
}
}
}
}
return shouldResign
}
/**
Resigns currently first responder field.
*/
@discardableResult open func resignFirstResponder()-> Bool {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to resign first responder: \(String(describing: _textFieldView?._IQDescription()))")
}
return isResignFirstResponder
}
return false
}
/**
Returns YES if can navigate to previous responder textField/textView, otherwise NO.
*/
open var canGoPrevious: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index > 0 {
return true
}
}
}
}
return false
}
/**
Returns YES if can navigate to next responder textField/textView, otherwise NO.
*/
open var canGoNext: Bool {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index < textFields.count-1 {
return true
}
}
}
}
return false
}
/**
Navigate to previous responder textField/textView.
*/
@discardableResult open func goPrevious()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/**
Navigate to next responder textField/textView.
*/
@discardableResult open func goNext()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.index(of: textFieldRetain) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
showLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/** previousAction. */
internal func previousAction (_ barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoPrevious == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goPrevious()
if isAcceptAsFirstResponder &&
textFieldRetain.previousInvocation.target != nil &&
textFieldRetain.previousInvocation.action != nil {
UIApplication.shared.sendAction(textFieldRetain.previousInvocation.action!, to: textFieldRetain.previousInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** nextAction. */
internal func nextAction (_ barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if canGoNext == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goNext()
if isAcceptAsFirstResponder &&
textFieldRetain.nextInvocation.target != nil &&
textFieldRetain.nextInvocation.action != nil {
UIApplication.shared.sendAction(textFieldRetain.nextInvocation.action!, to: textFieldRetain.nextInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
}
/** doneAction. Resigning current textField. */
internal func doneAction (_ barButton : IQBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.current.playInputClick()
}
if let textFieldRetain = _textFieldView {
//Resign textFieldView.
let isResignedFirstResponder = resignFirstResponder()
if isResignedFirstResponder &&
textFieldRetain.doneInvocation.target != nil &&
textFieldRetain.doneInvocation.action != nil{
UIApplication.shared.sendAction(textFieldRetain.doneInvocation.action!, to: textFieldRetain.doneInvocation.target, from: textFieldRetain, for: UIEvent())
}
}
}
/** Resigning on tap gesture. (Enhancement ID: #14)*/
internal func tapRecognized(_ gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.ended {
//Resigning currently responder textField.
_ = resignFirstResponder()
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
for ignoreClass in touchResignedGestureIgnoreClasses {
if touch.view?.isKind(of: ignoreClass) == true {
return false
}
}
return true
}
///-----------------------
/// MARK: UISound handling
///-----------------------
/**
If YES, then it plays inputClick sound on next/previous/done click.
*/
open var shouldPlayInputClicks = true
///---------------------------
/// MARK: UIAnimation handling
///---------------------------
/**
If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
*/
open var layoutIfNeededOnUpdate = false
///-----------------------------------------------
/// @name InteractivePopGestureRecognizer handling
///-----------------------------------------------
/**
If YES, then always consider UINavigationController.view begin point as {0,0}, this is a workaround to fix a bug #464 because there are no notification mechanism exist when UINavigationController.view.frame gets changed internally.
*/
open var shouldFixInteractivePopGestureRecognizer = true
///------------------------------------
/// MARK: Class Level disabling methods
///------------------------------------
/**
Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController.
*/
open var disabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored.
*/
open var enabledDistanceHandlingClasses = [UIViewController.Type]()
/**
Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController.
*/
open var disabledToolbarClasses = [UIViewController.Type]()
/**
Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore.
*/
open var enabledToolbarClasses = [UIViewController.Type]()
/**
Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView.
*/
open var toolbarPreviousNextAllowedClasses = [UIView.Type]()
/**
Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController.
*/
open var disabledTouchResignedClasses = [UIViewController.Type]()
/**
Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored.
*/
open var enabledTouchResignedClasses = [UIViewController.Type]()
/**
if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar]
*/
open var touchResignedGestureIgnoreClasses = [UIView.Type]()
///-------------------------------------------
/// MARK: Third Party Library support
/// Add TextField/TextView Notifications customised NSNotifications. For example while using YYTextView https://github.com/ibireme/YYText
///-------------------------------------------
/**
Add customised Notification for third party customised TextField/TextView. Please be aware that the NSNotification object must be idential to UITextField/UITextView NSNotification objects and customised TextField/TextView support must be idential to UITextField/UITextView.
@param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification
@param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification
*/
open func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) {
registeredClasses.append(aClass)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil)
}
/**************************************************************************************/
///------------------------
/// MARK: Private variables
///------------------------
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
fileprivate weak var _textFieldView: UIView?
/** To save rootViewController.view.frame. */
fileprivate var _topViewBeginRect = CGRect.zero
/** To save rootViewController */
fileprivate weak var _rootViewController: UIViewController?
/** To save topBottomLayoutConstraint original constant */
fileprivate var _layoutGuideConstraintInitialConstant: CGFloat = 0
/** To save topBottomLayoutConstraint original constraint reference */
fileprivate weak var _layoutGuideConstraint: NSLayoutConstraint?
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
fileprivate weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
fileprivate var _startingContentOffset = CGPoint.zero
/** LastScrollView's initial scrollIndicatorInsets. */
fileprivate var _startingScrollIndicatorInsets = UIEdgeInsets.zero
/** LastScrollView's initial contentInsets. */
fileprivate var _startingContentInsets = UIEdgeInsets.zero
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
fileprivate var _kbShowNotification: Notification?
/** To save keyboard size. */
fileprivate var _kbSize = CGSize.zero
/** To save Status Bar size. */
fileprivate var _statusBarFrame = CGRect.zero
/** To save keyboard animation duration. */
fileprivate var _animationDuration = 0.25
/** To mimic the keyboard animation */
fileprivate var _animationCurve = UIViewAnimationOptions.curveEaseOut
/*******************************************/
/** TapGesture to resign keyboard on view's touch. */
fileprivate var _tapGesture: UITapGestureRecognizer!
/*******************************************/
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
fileprivate var _privateIsKeyboardShowing = false
fileprivate var _privateMovedDistance : CGFloat = 0.0
/** To use with keyboardDistanceFromTextField. */
fileprivate var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/**************************************************************************************/
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
/* Singleton Object Initialization. */
override init() {
super.init()
// Registering for keyboard notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
// Registering for UITextField notification.
registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue)
// Registering for UITextView notification.
registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue)
// Registering for orientation changes notification
NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared)
// Registering for status bar frame change notification
NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarFrame(_:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared)
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
_tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:)))
_tapGesture.cancelsTouchesInView = false
_tapGesture.delegate = self
_tapGesture.isEnabled = shouldResignOnTouchOutside
//Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard apperance delay (Bug ID: #550)
let textField = UITextField()
textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:)))
textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)))
disabledDistanceHandlingClasses.append(UITableViewController.self)
disabledDistanceHandlingClasses.append(UIAlertController.self)
disabledToolbarClasses.append(UIAlertController.self)
disabledTouchResignedClasses.append(UIAlertController.self)
toolbarPreviousNextAllowedClasses.append(UITableView.self)
toolbarPreviousNextAllowedClasses.append(UICollectionView.self)
toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self)
touchResignedGestureIgnoreClasses.append(UIControl.self)
touchResignedGestureIgnoreClasses.append(UINavigationBar.self)
//Special Controllers
struct InternalClass {
static var UIAlertControllerTextFieldViewController: UIViewController.Type? = NSClassFromString("_UIAlertControllerTextFieldViewController") as? UIViewController.Type //UIAlertView
}
if let aClass = InternalClass.UIAlertControllerTextFieldViewController {
disabledDistanceHandlingClasses.append(aClass.self)
disabledToolbarClasses.append(aClass.self)
disabledTouchResignedClasses.append(aClass.self)
}
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
/** It doesn't work from Swift 1.2 */
// override public class func load() {
// super.load()
//
// //Enabling IQKeyboardManager.
// IQKeyboardManager.sharedManager().enable = true
// }
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NotificationCenter.default.removeObserver(self)
}
/** Getting keyWindow. */
fileprivate func keyWindow() -> UIWindow? {
if let keyWindow = _textFieldView?.window {
return keyWindow
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static var keyWindow : UIWindow?
}
/* (Bug ID: #23, #25, #73) */
let originalKeyWindow = UIApplication.shared.keyWindow
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if originalKeyWindow != nil &&
(Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
///-----------------------
/// MARK: Helper Functions
///-----------------------
/* Helper function to manipulate RootViewController's frame with animation. */
fileprivate func setRootViewFrame(_ frame: CGRect) {
// Getting topMost ViewController.
var controller = _textFieldView?.topMostController()
if controller == nil {
controller = keyWindow()?.topMostController()
}
if let unwrappedController = controller {
var newFrame = frame
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
newFrame.size = unwrappedController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
// Setting it's new frame
unwrappedController.view.frame = newFrame
self.showLog("Set \(String(describing: controller?._IQDescription())) frame to : \(newFrame)")
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
unwrappedController.view.setNeedsLayout()
unwrappedController.view.layoutIfNeeded()
}
}) { (animated:Bool) -> Void in}
} else { // If can't get rootViewController then printing warning to user.
showLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager")
}
}
/* Adjusting RootViewController's frame according to interface orientation. */
fileprivate func adjustFrame() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _textFieldView == nil {
return
}
let textFieldView = _textFieldView!
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting KeyWindow object.
let optionalWindow = keyWindow()
// Getting RootViewController. (Bug ID: #1, #4)
var optionalRootController = _textFieldView?.topMostController()
if optionalRootController == nil {
optionalRootController = keyWindow()?.topMostController()
}
// Converting Rectangle according to window bounds.
let optionalTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: optionalWindow)
if optionalRootController == nil ||
optionalWindow == nil ||
optionalTextFieldViewRect == nil {
return
}
let rootController = optionalRootController!
let window = optionalWindow!
let textFieldViewRect = optionalTextFieldViewRect!
// Getting RootViewRect.
var rootViewRect = rootController.view.frame
//Getting statusBarFrame
//Maintain keyboardDistanceFromTextField
var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField
if textFieldView.isSearchBarTextField() {
if let searchBar = textFieldView.superviewOfClassType(UISearchBar.self) {
specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField
}
}
let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField
var kbSize = _kbSize
kbSize.height += newKeyboardDistanceFromTextField
let statusBarFrame = UIApplication.shared.statusBarFrame
// (Bug ID: #250)
var layoutGuidePosition = IQLayoutGuidePosition.none
if let viewController = textFieldView.viewController() {
if let constraint = _layoutGuideConstraint {
var layoutGuide : UILayoutSupport?
if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
} else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
}
if let itemLayoutGuide : UILayoutSupport = layoutGuide {
if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint
{
layoutGuidePosition = .top
}
else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint
{
layoutGuidePosition = .bottom
}
}
}
}
let topLayoutGuide : CGFloat = statusBarFrame.height
var move : CGFloat = 0.0
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Checking if there is bottomLayoutGuide attached (Bug ID: #250)
if layoutGuidePosition == .bottom {
// Calculating move position.
move = textFieldViewRect.maxY-(window.frame.height-kbSize.height)
} else {
// Calculating move position. Common for both normal and special cases.
move = min(textFieldViewRect.minY-(topLayoutGuide+5), textFieldViewRect.maxY-(window.frame.height-kbSize.height))
}
showLog("Need to move: \(move)")
var superScrollView : UIScrollView? = nil
var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView
//Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285)
while let view = superView {
if (view.isScrollEnabled) {
superScrollView = view
break
}
else {
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_lastScrollView = superScrollView
_startingContentInsets = superScrollView!.contentInset
_startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets
_startingContentOffset = superScrollView!.contentOffset
showLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
_startingContentOffset = unwrappedSuperScrollView.contentOffset
showLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 {
var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
var nextScrollView : UIScrollView? = nil
while let view = tempScrollView {
if (view.isScrollEnabled) {
nextScrollView = view
break
} else {
tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
if textFieldView is UITextView == true &&
nextScrollView == nil &&
shouldOffsetY >= 0 {
var maintainTopLayout : CGFloat = 0
if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame {
maintainTopLayout = navigationBarFrame.maxY
}
maintainTopLayout += 10.0 //For good UI
// Converting Rectangle according to window bounds.
if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) {
//Calculating expected fix distance which needs to be managed from navigation bar
let expectedFixDistance = currentTextFieldViewRect.minY - maintainTopLayout
//Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
//Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
move = 0
}
else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
}
else
{
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.showLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset")
self.showLog("Remaining Move: \(move)")
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY)
}) { (animated:Bool) -> Void in }
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = nextScrollView
} else {
break
}
}
//Updating contentInset
if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) {
let bottom : CGFloat = kbSize.height-newKeyboardDistanceFromTextField-(window.frame.height-lastScrollViewRect.maxY)
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
showLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)")
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = movedInsets
var newInset = lastScrollView.scrollIndicatorInsets
newInset.bottom = movedInsets.bottom
lastScrollView.scrollIndicatorInsets = newInset
}) { (animated:Bool) -> Void in }
showLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)")
}
}
//Going ahead. No else if.
if layoutGuidePosition == .top {
if let constraint = _layoutGuideConstraint {
let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else if layoutGuidePosition == .bottom {
if let constraint = _layoutGuideConstraint {
let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move)
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
}
} else {
//Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen)
//_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
if let textView = textFieldView as? UITextView {
let textViewHeight = min(textView.frame.height, (window.frame.height-kbSize.height-(topLayoutGuide)))
if (textView.frame.size.height-textView.contentInset.bottom>textViewHeight)
{
UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
//_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92)
if (self.isTextViewContentInsetChanged == false)
{
self.startingTextViewContentInsets = textView.contentInset
self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets
}
var newContentInset = textView.contentInset
newContentInset.bottom = textView.frame.size.height-textViewHeight
textView.contentInset = newContentInset
textView.scrollIndicatorInsets = newContentInset
self.isTextViewContentInsetChanged = true
self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)")
}, completion: { (finished) -> Void in })
}
}
// Special case for iPad modalPresentationStyle.
if rootController.modalPresentationStyle == UIModalPresentationStyle.formSheet ||
rootController.modalPresentationStyle == UIModalPresentationStyle.pageSheet {
showLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)")
// +Positive or zero.
if move >= 0 {
// We should only manipulate y.
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
let minimumY: CGFloat = (window.frame.height-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField)
rootViewRect.origin.y = max(rootViewRect.minY, minimumY)
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
// Calculating disturbed distance. Pull Request #3
let disturbDistance = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
// We should only manipulate y.
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
} else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
// +Positive or zero.
if move >= 0 {
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField))
}
showLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
} else { // -Negative
let disturbDistance : CGFloat = rootViewRect.minY-_topViewBeginRect.minY
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
rootViewRect.origin.y -= max(move, disturbDistance)
showLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
_privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y)
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///---------------------
/// MARK: Public Methods
///---------------------
/* Refreshes textField/textView position if any external changes is explicitly made by user. */
open func reloadLayoutIfNeeded() -> Void {
if privateIsEnabled() == true {
if _textFieldView != nil &&
_privateIsKeyboardShowing == true &&
_topViewBeginRect.equalTo(CGRect.zero) == false &&
_textFieldView?.isAlertViewTextField() == false {
adjustFrame()
}
}
}
///-------------------------------
/// MARK: UIKeyboard Notifications
///-------------------------------
/* UIKeyboardWillShowNotification. */
internal func keyboardWillShow(_ notification : Notification?) -> Void {
_kbShowNotification = notification
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = true
let oldKBSize = _kbSize
if let info = (notification as NSNotification?)?.userInfo {
// Getting keyboard animation.
if let curve = (info[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue {
_animationCurve = UIViewAnimationOptions(rawValue: curve)
} else {
_animationCurve = UIViewAnimationOptions.curveEaseOut
}
// Getting keyboard animation duration
if let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
} else {
_animationDuration = 0.25
}
// Getting UIKeyboardSize.
if let kbFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let screenSize = UIScreen.main.bounds
//Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
let intersectRect = kbFrame.intersection(screenSize)
if intersectRect.isNull {
_kbSize = CGSize(width: screenSize.size.width, height: 0)
} else {
_kbSize = intersectRect.size
}
showLog("UIKeyboard Size : \(_kbSize)")
}
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// (Bug ID: #5)
if _textFieldView != nil && _topViewBeginRect.equalTo(CGRect.zero) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if _kbSize.equalTo(oldKBSize) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardDidShowNotification. */
internal func keyboardDidShow(_ notification : Notification?) -> Void {
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
if _textFieldView != nil &&
(topMostController?.modalPresentationStyle == UIModalPresentationStyle.formSheet || topMostController?.modalPresentationStyle == UIModalPresentationStyle.pageSheet) &&
_textFieldView?.isAlertViewTextField() == false {
//In case of form sheet or page sheet, we'll add adjustFrame call in main queue to perform it when UI thread will do all framing updation so adjustFrame will be executed after all internal operations.
OperationQueue.main.addOperation {
self.adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
internal func keyboardWillHide(_ notification : Notification?) -> Void {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
// Boolean to know keyboard is showing/hiding
_privateIsKeyboardShowing = false
let info : [AnyHashable: Any]? = (notification as NSNotification?)?.userInfo
// Getting keyboard animation duration
if let duration = (info?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
//If not enabled then do nothing.
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.contentOffset = self._startingContentOffset
}
self.showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)")
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView : UIScrollView? = lastScrollView
while let scrollView = superScrollView {
let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
let minimumY = contentSize.height - scrollView.frame.height
if minimumY < scrollView.contentOffset.y {
scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
self.showLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)")
}
superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
}) { (finished) -> Void in }
}
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if _topViewBeginRect.equalTo(CGRect.zero) == false {
if let rootViewController = _rootViewController {
//frame size needs to be adjusted on iOS8 due to orientation API changes.
_topViewBeginRect.size = rootViewController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
if let constraint = self._layoutGuideConstraint {
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
else {
self.showLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)")
// Setting it's new frame
rootViewController.view.frame = self._topViewBeginRect
self._privateMovedDistance = 0
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
}
}) { (finished) -> Void in }
_rootViewController = nil
}
} else if let constraint = self._layoutGuideConstraint {
if let rootViewController = _rootViewController {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}) { (finished) -> Void in }
}
}
//Reset all values
_lastScrollView = nil
_kbSize = CGSize.zero
_layoutGuideConstraint = nil
_layoutGuideConstraintInitialConstant = 0
_startingContentInsets = UIEdgeInsets.zero
_startingScrollIndicatorInsets = UIEdgeInsets.zero
_startingContentOffset = CGPoint.zero
// topViewBeginRect = CGRectZero //Commented due to #82
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
internal func keyboardDidHide(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
_topViewBeginRect = CGRect.zero
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///-------------------------------------------
/// MARK: UITextField/UITextView Notifications
///-------------------------------------------
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
internal func textFieldViewDidBeginEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if let textFieldView = _textFieldView as? UITextField {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
} else if let textFieldView = _textFieldView as? UITextView {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if privateIsEnableAutoToolbar() == true {
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if _textFieldView is UITextView == true &&
_textFieldView?.inputAccessoryView == nil {
UIView.animate(withDuration: 0.00001, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (finished) -> Void in
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
self._textFieldView?.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
} else {
removeToolbarIfRequired()
}
_tapGesture.isEnabled = privateShouldResignOnTouchOutside()
_textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14)
if privateIsEnabled() == true {
if _topViewBeginRect.equalTo(CGRect.zero) == true { // (Bug ID: #5)
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint {
_layoutGuideConstraint = constraint
_layoutGuideConstraintInitialConstant = constraint.constant
}
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let rootViewController = _rootViewController {
_topViewBeginRect = rootViewController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
rootViewController is UINavigationController &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
rootViewController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-rootViewController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)")
}
}
//If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
internal func textFieldViewDidEndEditing(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//Removing gesture recognizer (Enhancement ID: #14)
_textFieldView?.window?.removeGestureRecognizer(_tapGesture)
// We check if there's a change in original frame or not.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
//Setting object to nil
_textFieldView = nil
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------------------------------
/// MARK: UIStatusBar Notification methods
///------------------------------------------
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
internal func willChangeStatusBarOrientation(_ notification:Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
//If textViewContentInsetChanged is saved then restore it.
if let textView = _textFieldView as? UITextView {
if isTextViewContentInsetChanged == true {
UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.isTextViewContentInsetChanged = false
self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)")
//Setting textField to it's initial contentInset
textView.contentInset = self.startingTextViewContentInsets
textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets
}, completion: { (finished) -> Void in })
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** UIApplicationDidChangeStatusBarFrameNotification. Need to refresh view position and update _topViewBeginRect. (Bug ID: #446)*/
internal func didChangeStatusBarFrame(_ notification : Notification?) -> Void {
let oldStatusBarFrame = _statusBarFrame;
// Getting keyboard animation duration
if let newFrame = ((notification as NSNotification?)?.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSNumber)?.cgRectValue {
_statusBarFrame = newFrame
}
if privateIsEnabled() == false {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
if _rootViewController != nil &&
!_topViewBeginRect.equalTo(_rootViewController!.view.frame) == true {
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
if shouldFixInteractivePopGestureRecognizer == true &&
unwrappedRootController is UINavigationController &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet &&
unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet {
if let window = keyWindow() {
_topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height)
} else {
_topViewBeginRect.origin = CGPoint.zero
}
}
showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRect.zero
}
}
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _privateIsKeyboardShowing == true &&
_textFieldView != nil &&
_statusBarFrame.size.equalTo(oldStatusBarFrame.size) == false &&
_textFieldView?.isAlertViewTextField() == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
///------------------
/// MARK: AutoToolbar
///------------------
/** Get all UITextField/UITextView siblings of textFieldView. */
fileprivate func responderViews()-> [UIView]? {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView.
for disabledClass in toolbarPreviousNextAllowedClasses {
superConsideredView = _textFieldView?.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
//If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
if superConsideredView != nil {
return superConsideredView?.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.bySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
fileprivate func addToolbarIfRequired() {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
// If only one object is found, then adding only Done button.
if (siblings.count == 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysHide {
if let textField = _textFieldView {
var needReload = false;
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
//Supporting Custom Done button image (Enhancement ID: #366)
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
needReload = true
}
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
}
else if let toolbar = textField.inputAccessoryView as? IQToolbar {
if toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
if toolbar.doneTitle != doneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
} else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) ||
(toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
}
}
}
}
if textField.inputAccessoryView is IQToolbar &&
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
//Setting toolbar tintColor // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true &&
textField.shouldHidePlaceholderText == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.title == nil ||
toolbar.title != textField.drawingPlaceholderText {
toolbar.title = textField.drawingPlaceholderText
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
} else {
toolbar.title = nil
}
}
if needReload {
textField.reloadInputViews()
}
}
} else if (siblings.count > 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysShow {
// If more than 1 textField is found. then adding previous/next/done buttons on it.
for textField in siblings {
var needReload = false;
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) {
if textField.inputAccessoryView == nil ||
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
needReload = true
}
//Supporting Custom Done button image (Enhancement ID: #366)
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: doneBarButtonItemImage, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: doneBarButtonItemText, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
}
else if let toolbar = textField.inputAccessoryView as? IQToolbar {
if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: toolbarDoneBarButtonItemImage!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
if toolbar.doneTitle != doneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: toolbarDoneBarButtonItemText!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
} else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) ||
(toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
needReload = true
}
}
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
}
if textField.inputAccessoryView is IQToolbar &&
textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
toolbar.tintColor = UIColor.white
default:
toolbar.barStyle = UIBarStyle.default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.black
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true &&
textField.shouldHidePlaceholderText == false {
//Updating placeholder font to toolbar. //(Bug ID: #148, #272)
if toolbar.title == nil ||
toolbar.title != textField.drawingPlaceholderText {
toolbar.title = textField.drawingPlaceholderText
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
}
else {
toolbar.title = nil
}
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings[0] == textField {
if (siblings.count == 1) {
textField.setEnablePrevious(false, isNextEnabled: false)
} else {
textField.setEnablePrevious(false, isNextEnabled: true)
}
} else if siblings.last == textField { // If lastTextField then next should not be enaled.
textField.setEnablePrevious(true, isNextEnabled: false)
} else {
textField.setEnablePrevious(true, isNextEnabled: true)
}
}
if needReload {
textField.reloadInputViews()
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** Remove any toolbar if it is IQToolbar. */
fileprivate func removeToolbarIfRequired() { // (Bug ID: #18)
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******")
// Getting all the sibling textFields.
if let siblings = responderViews() {
showLog("Found \(siblings.count) responder sibling(s)")
for view in siblings {
if let toolbar = view.inputAccessoryView as? IQToolbar {
//setInputAccessoryView: check (Bug ID: #307)
if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) &&
(toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
if let textField = view as? UITextField {
textField.inputAccessoryView = nil
} else if let textView = view as? UITextView {
textView.inputAccessoryView = nil
}
}
}
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******")
}
/** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */
open func reloadInputViews() {
//If enabled then adding toolbar.
if privateIsEnableAutoToolbar() == true {
self.addToolbarIfRequired()
} else {
self.removeToolbarIfRequired()
}
}
open var enableDebugging = false
fileprivate func showLog(_ logString: String) {
if enableDebugging {
print("IQKeyboardManager: " + logString)
}
}
}
| mit | c13b56fae2f2ace6d5f5c0dab4da5dc7 | 47.698982 | 370 | 0.561898 | 7.174786 | false | false | false | false |
talentsparkio/UIViewAnimateWithDuration | UIViewAnimateWithDuration/AlphaExampleViewController.swift | 1 | 1292 | //
// AlphaExampleViewController.swift
// UIViewAnimateWithDuration
//
// Created by Nick Chen on 8/29/15.
// Copyright © 2015 Nick Chen. All rights reserved.
//
import UIKit
class AlphaExampleViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var fadeInButton: UIButton!
@IBOutlet weak var fadeOutButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
fadeInButton.enabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func fadeIn(sender: UIButton) {
UIView.animateWithDuration(1.0, animations: {
self.textField.alpha = 100
}, completion: { finished in
if(finished) {
self.fadeInButton.enabled = false
self.fadeOutButton.enabled = true
}
})
}
@IBAction func fadeOut(sender: UIButton) {
UIView.animateWithDuration(1.0, animations: {
self.textField.alpha = 0
}, completion: { finished in
if(finished) {
self.fadeOutButton.enabled = false
self.fadeInButton.enabled = true
}
})
}
}
| bsd-3-clause | a2e8a78a1e4b9499e0136b12fbf70718 | 26.468085 | 54 | 0.587916 | 5.003876 | false | false | false | false |
mapsme/omim | iphone/Maps/UI/Welcome/TermsOfUse/TermsOfUseViewController.swift | 5 | 2666 | import SafariServices
protocol ITermsOfUseView: class {
var presenter: ITermsOfUsePresenter? { get set }
func setTitle(_ title: String)
func setText(_ text: String)
func setTitleImage(_ titleImage: UIImage?)
func setPrivacyPolicyTitle( _ htmlString: String)
func setTermsOfUseTitle( _ htmlString: String)
}
class TermsOfUseViewController: MWMViewController {
var presenter: ITermsOfUsePresenter?
@IBOutlet private var image: UIImageView!
@IBOutlet private var alertTitle: UILabel!
@IBOutlet private var alertText: UILabel!
@IBOutlet private weak var privacyPolicyTextView: UITextView! {
didSet {
privacyPolicyTextView.delegate = self
}
}
@IBOutlet private weak var termsOfUseTextView: UITextView! {
didSet {
termsOfUseTextView.delegate = self
}
}
@IBOutlet private weak var privacyPolicyCheck: Checkmark!
@IBOutlet private weak var termsOfUseCheck: Checkmark!
override func viewDidLoad() {
super.viewDidLoad()
presenter?.configure()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
presenter?.onAppear()
}
@IBAction func onCheck(_ sender: Checkmark) {
if (privacyPolicyCheck.isChecked && termsOfUseCheck.isChecked) {
presenter?.onNext()
}
}
@IBAction func onPrivacyTap(_ sender: UITapGestureRecognizer) {
privacyPolicyCheck.isChecked = !privacyPolicyCheck.isChecked
onCheck(privacyPolicyCheck)
}
@IBAction func onTermsTap(_ sender: UITapGestureRecognizer) {
termsOfUseCheck.isChecked = !termsOfUseCheck.isChecked
onCheck(termsOfUseCheck)
}
}
extension TermsOfUseViewController: ITermsOfUseView {
func setTitle(_ title: String) {
alertTitle.text = title
}
func setText(_ text: String) {
alertText.text = text
}
func setTitleImage(_ titleImage: UIImage?) {
image.image = titleImage
}
func setPrivacyPolicyTitle(_ htmlString: String) {
setHtmlTitle(textView: privacyPolicyTextView, htmlString: htmlString)
}
func setTermsOfUseTitle(_ htmlString: String) {
setHtmlTitle(textView: termsOfUseTextView, htmlString: htmlString)
}
private func setHtmlTitle(textView: UITextView, htmlString: String) {
textView.attributedText = NSAttributedString.string(withHtml: htmlString,
defaultAttributes: [:])
}
}
extension TermsOfUseViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let safari = SFSafariViewController(url: URL)
present(safari, animated: true, completion: nil)
return false;
}
}
| apache-2.0 | 491a7f325f45722a6ffa45427040ea9b | 27.063158 | 106 | 0.721305 | 4.557265 | false | false | false | false |
gxfeng/iOS- | HeadScrollCell.swift | 1 | 898 | //
// HeadScrollCell.swift
// ProjectSwift
//
// Created by ZJQ on 2016/12/23.
// Copyright © 2016年 ZJQ. All rights reserved.
//
import UIKit
class HeadScrollCell: UICollectionViewCell {
var img = UIImageView()
var title = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
img = UIImageView.init(frame: CGRect.init(x: 5, y: 5, width: 30, height: 30))
img.layer.cornerRadius = 15
img.layer.masksToBounds = true
self.contentView.addSubview(img)
title = UILabel.init(frame: .init(x: 0, y: 35, width: 40, height: 15))
title.textAlignment = .center
title.font = UIFont.systemFont(ofSize: 8)
self.contentView.addSubview(title)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | f3152a99c521f96b6d5b226b7764aa81 | 23.861111 | 85 | 0.604469 | 3.908297 | false | false | false | false |
honishi/Hakumai | Hakumai/Controllers/CustomView/LiveThumbnailImageView.swift | 1 | 1792 | //
// LiveThumbnailImageView.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 2021/12/10.
// Copyright © 2021 Hiroyuki Onishi. All rights reserved.
//
import Cocoa
import SnapKit
private let defaultAspectRatio: CGFloat = 1
@IBDesignable
class LiveThumbnailImageView: NSImageView {
@IBInspectable
var height: Float = 0 { didSet { updateHeight(CGFloat(height)) } }
override var image: NSImage? { didSet { setImage(image) } }
private var heightConstraint: Constraint?
private var aspectRatioConstraint: Constraint?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func awakeFromNib() {
configure()
}
}
private extension LiveThumbnailImageView {
func configure() {
updateHeight(CGFloat(height))
updateAspectRatio(defaultAspectRatio)
}
func updateHeight(_ height: CGFloat) {
heightConstraint?.deactivate()
snp.makeConstraints { make in
heightConstraint = make
.height
.equalTo(height)
.constraint
}
}
func updateAspectRatio(_ ratio: CGFloat) {
aspectRatioConstraint?.deactivate()
snp.makeConstraints { make in
aspectRatioConstraint = make
.height
.equalTo(snp.width)
.multipliedBy(ratio)
.constraint
}
}
func setImage(_ image: NSImage?) {
super.image = image
let aspectRatio: CGFloat = {
guard let image = image else { return defaultAspectRatio }
return image.size.height / image.size.width
}()
updateAspectRatio(aspectRatio)
}
}
| mit | 205c97e7274f6bbb64d6069dbfdf20a0 | 23.875 | 70 | 0.612507 | 5.016807 | false | false | false | false |
ptankTwilio/video-quickstart-swift | VideoQuickStart/ViewController.swift | 1 | 13878 | //
// ViewController.swift
// VideoQuickStart
//
// Copyright © 2016-2017 Twilio, Inc. All rights reserved.
//
import UIKit
import TwilioVideo
class ViewController: UIViewController {
// MARK: View Controller Members
// Configure access token manually for testing, if desired! Create one manually in the console
// at https://www.twilio.com/user/account/video/dev-tools/testing-tools
var accessToken = "TWILIO_ACCESS_TOKEN"
// Configure remote URL to fetch token from
var tokenUrl = "http://localhost:8000/token.php"
// Video SDK components
var room: TVIRoom?
var camera: TVICameraCapturer?
var localVideoTrack: TVILocalVideoTrack?
var localAudioTrack: TVILocalAudioTrack?
var participant: TVIParticipant?
var remoteView: TVIVideoView?
// MARK: UI Element Outlets and handles
// `TVIVideoView` created from a storyboard
@IBOutlet weak var previewView: TVIVideoView!
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var roomTextField: UITextField!
@IBOutlet weak var roomLine: UIView!
@IBOutlet weak var roomLabel: UILabel!
@IBOutlet weak var micButton: UIButton!
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if PlatformUtils.isSimulator {
self.previewView.removeFromSuperview()
} else {
// Preview our local camera track in the local video preview view.
self.startPreview()
}
// Disconnect and mic button will be displayed when the Client is connected to a Room.
self.disconnectButton.isHidden = true
self.micButton.isHidden = true
self.roomTextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
}
func setupRemoteVideoView() {
// Creating `TVIVideoView` programmatically
self.remoteView = TVIVideoView.init(frame: CGRect.zero, delegate:self)
self.view.insertSubview(self.remoteView!, at: 0)
// `TVIVideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit
// scaleAspectFit is the default mode when you create `TVIVideoView` programmatically.
self.remoteView!.contentMode = .scaleAspectFit;
let centerX = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerX)
let centerY = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerY)
let width = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.width,
multiplier: 1,
constant: 0);
self.view.addConstraint(width)
let height = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.height,
multiplier: 1,
constant: 0);
self.view.addConstraint(height)
}
// MARK: IBActions
@IBAction func connect(sender: AnyObject) {
// Configure access token either from server or manually.
// If the default wasn't changed, try fetching from server.
if (accessToken == "TWILIO_ACCESS_TOKEN") {
do {
accessToken = try TokenUtils.fetchToken(url: tokenUrl)
} catch {
let message = "Failed to fetch access token"
logMessage(messageText: message)
return
}
}
// Prepare local media which we will share with Room Participants.
self.prepareLocalMedia()
// Preparing the connect options with the access token that we fetched (or hardcoded).
let connectOptions = TVIConnectOptions.init(token: accessToken) { (builder) in
// Use the local media that we prepared earlier.
builder.audioTracks = self.localAudioTrack != nil ? [self.localAudioTrack!] : [TVILocalAudioTrack]()
builder.videoTracks = self.localVideoTrack != nil ? [self.localVideoTrack!] : [TVILocalVideoTrack]()
// The name of the Room where the Client will attempt to connect to. Please note that if you pass an empty
// Room `name`, the Client will create one for you. You can get the name or sid from any connected Room.
builder.roomName = self.roomTextField.text
}
// Connect to the Room using the options we provided.
room = TwilioVideo.connect(with: connectOptions, delegate: self)
logMessage(messageText: "Attempting to connect to room \(String(describing: self.roomTextField.text))")
self.showRoomUI(inRoom: true)
self.dismissKeyboard()
}
@IBAction func disconnect(sender: AnyObject) {
self.room!.disconnect()
logMessage(messageText: "Attempting to disconnect from room \(room!.name)")
}
@IBAction func toggleMic(sender: AnyObject) {
if (self.localAudioTrack != nil) {
self.localAudioTrack?.isEnabled = !(self.localAudioTrack?.isEnabled)!
// Update the button title
if (self.localAudioTrack?.isEnabled == true) {
self.micButton.setTitle("Mute", for: .normal)
} else {
self.micButton.setTitle("Unmute", for: .normal)
}
}
}
// MARK: Private
func startPreview() {
if PlatformUtils.isSimulator {
return
}
// Preview our local camera track in the local video preview view.
camera = TVICameraCapturer(source: .frontCamera, delegate: self)
localVideoTrack = TVILocalVideoTrack.init(capturer: camera!)
if (localVideoTrack == nil) {
logMessage(messageText: "Failed to create video track")
} else {
// Add renderer to video track for local preview
localVideoTrack!.addRenderer(self.previewView)
logMessage(messageText: "Video track created")
// We will flip camera on tap.
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.flipCamera))
self.previewView.addGestureRecognizer(tap)
}
}
func flipCamera() {
if (self.camera?.source == .frontCamera) {
self.camera?.selectSource(.backCameraWide)
} else {
self.camera?.selectSource(.frontCamera)
}
}
func prepareLocalMedia() {
// We will share local audio and video when we connect to the Room.
// Create an audio track.
if (localAudioTrack == nil) {
localAudioTrack = TVILocalAudioTrack.init()
if (localAudioTrack == nil) {
logMessage(messageText: "Failed to create audio track")
}
}
// Create a video track which captures from the camera.
if (localVideoTrack == nil) {
self.startPreview()
}
}
// Update our UI based upon if we are in a Room or not
func showRoomUI(inRoom: Bool) {
self.connectButton.isHidden = inRoom
self.roomTextField.isHidden = inRoom
self.roomLine.isHidden = inRoom
self.roomLabel.isHidden = inRoom
self.micButton.isHidden = !inRoom
self.disconnectButton.isHidden = !inRoom
UIApplication.shared.isIdleTimerDisabled = inRoom
}
func dismissKeyboard() {
if (self.roomTextField.isFirstResponder) {
self.roomTextField.resignFirstResponder()
}
}
func cleanupRemoteParticipant() {
if ((self.participant) != nil) {
if ((self.participant?.videoTracks.count)! > 0) {
self.participant?.videoTracks[0].removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
self.participant = nil
}
func logMessage(messageText: String) {
messageLabel.text = messageText
}
}
// MARK: UITextFieldDelegate
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.connect(sender: textField)
return true
}
}
// MARK: TVIRoomDelegate
extension ViewController : TVIRoomDelegate {
func didConnect(to room: TVIRoom) {
// At the moment, this example only supports rendering one Participant at a time.
logMessage(messageText: "Connected to room \(room.name) as \(String(describing: room.localParticipant?.identity))")
if (room.participants.count > 0) {
self.participant = room.participants[0]
self.participant?.delegate = self
}
}
func room(_ room: TVIRoom, didDisconnectWithError error: Error?) {
logMessage(messageText: "Disconncted from room \(room.name), error = \(String(describing: error))")
self.cleanupRemoteParticipant()
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, didFailToConnectWithError error: Error) {
logMessage(messageText: "Failed to connect to room with error")
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, participantDidConnect participant: TVIParticipant) {
if (self.participant == nil) {
self.participant = participant
self.participant?.delegate = self
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) connected")
}
func room(_ room: TVIRoom, participantDidDisconnect participant: TVIParticipant) {
if (self.participant == participant) {
cleanupRemoteParticipant()
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected")
}
}
// MARK: TVIParticipantDelegate
extension ViewController : TVIParticipantDelegate {
func participant(_ participant: TVIParticipant, addedVideoTrack videoTrack: TVIVideoTrack) {
logMessage(messageText: "Participant \(participant.identity) added video track")
if (self.participant == participant) {
setupRemoteVideoView()
videoTrack.addRenderer(self.remoteView!)
}
}
func participant(_ participant: TVIParticipant, removedVideoTrack videoTrack: TVIVideoTrack) {
logMessage(messageText: "Participant \(participant.identity) removed video track")
if (self.participant == participant) {
videoTrack.removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
func participant(_ participant: TVIParticipant, addedAudioTrack audioTrack: TVIAudioTrack) {
logMessage(messageText: "Participant \(participant.identity) added audio track")
}
func participant(_ participant: TVIParticipant, removedAudioTrack audioTrack: TVIAudioTrack) {
logMessage(messageText: "Participant \(participant.identity) removed audio track")
}
func participant(_ participant: TVIParticipant, enabledTrack track: TVITrack) {
var type = ""
if (track is TVIVideoTrack) {
type = "video"
} else {
type = "audio"
}
logMessage(messageText: "Participant \(participant.identity) enabled \(type) track")
}
func participant(_ participant: TVIParticipant, disabledTrack track: TVITrack) {
var type = ""
if (track is TVIVideoTrack) {
type = "video"
} else {
type = "audio"
}
logMessage(messageText: "Participant \(participant.identity) disabled \(type) track")
}
}
// MARK: TVIVideoViewDelegate
extension ViewController : TVIVideoViewDelegate {
func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) {
self.view.setNeedsLayout()
}
}
// MARK: TVICameraCapturerDelegate
extension ViewController : TVICameraCapturerDelegate {
func cameraCapturer(_ capturer: TVICameraCapturer, didStartWith source: TVICameraCaptureSource) {
self.previewView.shouldMirror = (source == .frontCamera)
}
}
| mit | 5ed43153747c26fa4bf02383483dc2ca | 37.019178 | 123 | 0.601499 | 5.491492 | false | false | false | false |
gajjartejas/SMDImagePicker | SMDImagePicker/SMDImagePickerOptions.swift | 1 | 3546 | //
// SMDImagePickerOptions.swift
// SMDImagePicker
//
// Created by Tejas on 6/25/17.
// Copyright © 2017 Gajjar Tejas. All rights reserved.
//
import UIKit
import AVFoundation
import AssetsLibrary
import MobileCoreServices
import Photos
extension SMDImagePicker {
public struct IPadOptions {
public var sourceView : UIView?
public init(sourceView :UIView? = nil) {
self.sourceView = sourceView
}
}
public struct PhotoCaptureOptions {
public var allowsEditing: Bool = false
public var cameraDevice: UIImagePickerControllerCameraDevice = .front
public var mediaTypes: [String] = [kUTTypeImage as String]
public var flashMode: UIImagePickerControllerCameraFlashMode = .auto
public init(allowsEditing: Bool = true,
cameraDevice: UIImagePickerControllerCameraDevice = .front,
mediaTypes: [String] = [kUTTypeImage as String],
flashMode: UIImagePickerControllerCameraFlashMode = .auto) {
self.allowsEditing = allowsEditing
self.cameraDevice = cameraDevice
self.mediaTypes = mediaTypes
self.flashMode = flashMode
}
}
public struct VideoRecorderOptions {
var allowsEditing: Bool = false
var cameraDevice: UIImagePickerControllerCameraDevice = .front
var maximumDuration: TimeInterval = 60*10// default value is 10 minutes.
var quality: UIImagePickerControllerQualityType = .typeMedium
var flashMode: UIImagePickerControllerCameraFlashMode = .auto
public init(allowsEditing: Bool = true,
cameraDevice: UIImagePickerControllerCameraDevice = .front,
maximumDuration: TimeInterval = 60*10,
quality: UIImagePickerControllerQualityType = .typeMedium,
flashMode: UIImagePickerControllerCameraFlashMode = .auto) {
self.allowsEditing = allowsEditing
self.cameraDevice = cameraDevice
self.maximumDuration = maximumDuration
self.quality = quality
self.flashMode = flashMode
}
}
public struct PhotoGallaryOptions {
var allowsEditing: Bool = false
var mediaTypes: [String] = [kUTTypeImage as String]
public init(allowsEditing: Bool = true,
mediaTypes: [String] = [kUTTypeImage as String]
) {
self.allowsEditing = allowsEditing
self.mediaTypes = mediaTypes
}
}
public struct VideoGallaryOptions {
var allowsEditing: Bool = false
var mediaTypes: [String] = [kUTTypeMovie as String, kUTTypeVideo as String, kUTTypeMPEG4 as String]
var maximumDuration: TimeInterval = 60*10// default value is 10 minutes.
var quality: UIImagePickerControllerQualityType = .typeMedium
public init(allowsEditing: Bool = false,
mediaTypes: [String] = [kUTTypeMovie as String, kUTTypeVideo as String, kUTTypeMPEG4 as String],
maximumDuration: TimeInterval = 60*10,
quality: UIImagePickerControllerQualityType = .typeMedium
) {
self.allowsEditing = allowsEditing
self.mediaTypes = mediaTypes
self.maximumDuration = maximumDuration
self.quality = quality
}
}
}
| gpl-3.0 | 37f16b9743f3c16e28fb0959f155d4c9 | 35.173469 | 116 | 0.619182 | 5.764228 | false | false | false | false |
srn214/Floral | Floral/Pods/Hue/Source/iOS+tvOS/UIColor+Hue.swift | 1 | 7637 | import UIKit
// MARK: - Color Builders
public extension UIColor {
/// Constructing color from hex string
///
/// - Parameter hex: A hex string, can either contain # or not
convenience init(hex string: String) {
var hex = string.hasPrefix("#")
? String(string.dropFirst())
: string
guard hex.count == 3 || hex.count == 6
else {
self.init(white: 1.0, alpha: 0.0)
return
}
if hex.count == 3 {
for (index, char) in hex.enumerated() {
hex.insert(char, at: hex.index(hex.startIndex, offsetBy: index * 2))
}
}
guard let intCode = Int(hex, radix: 16) else {
self.init(white: 1.0, alpha: 0.0)
return
}
self.init(
red: CGFloat((intCode >> 16) & 0xFF) / 255.0,
green: CGFloat((intCode >> 8) & 0xFF) / 255.0,
blue: CGFloat((intCode) & 0xFF) / 255.0, alpha: 1.0)
}
/// Adjust color based on saturation
///
/// - Parameter minSaturation: The minimun saturation value
/// - Returns: The adjusted color
func color(minSaturation: CGFloat) -> UIColor {
var (hue, saturation, brightness, alpha): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return saturation < minSaturation
? UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha)
: self
}
/// Convenient method to change alpha value
///
/// - Parameter value: The alpha value
/// - Returns: The alpha adjusted color
func alpha(_ value: CGFloat) -> UIColor {
return withAlphaComponent(value)
}
}
// MARK: - Helpers
public extension UIColor {
func hex(hashPrefix: Bool = true) -> String {
var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getRed(&r, green: &g, blue: &b, alpha: &a)
let prefix = hashPrefix ? "#" : ""
return String(format: "\(prefix)%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
}
internal func rgbComponents() -> [CGFloat] {
var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 0.0, 0.0)
getRed(&r, green: &g, blue: &b, alpha: &a)
return [r, g, b]
}
var isDark: Bool {
let RGB = rgbComponents()
return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5
}
var isBlackOrWhite: Bool {
let RGB = rgbComponents()
return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09)
}
var isBlack: Bool {
let RGB = rgbComponents()
return (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09)
}
var isWhite: Bool {
let RGB = rgbComponents()
return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91)
}
func isDistinct(from color: UIColor) -> Bool {
let bg = rgbComponents()
let fg = color.rgbComponents()
let threshold: CGFloat = 0.25
var result = false
if abs(bg[0] - fg[0]) > threshold || abs(bg[1] - fg[1]) > threshold || abs(bg[2] - fg[2]) > threshold {
if abs(bg[0] - bg[1]) < 0.03 && abs(bg[0] - bg[2]) < 0.03 {
if abs(fg[0] - fg[1]) < 0.03 && abs(fg[0] - fg[2]) < 0.03 {
result = false
}
}
result = true
}
return result
}
func isContrasting(with color: UIColor) -> Bool {
let bg = rgbComponents()
let fg = color.rgbComponents()
let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2]
let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2]
let contrast = bgLum > fgLum
? (bgLum + 0.05) / (fgLum + 0.05)
: (fgLum + 0.05) / (bgLum + 0.05)
return 1.6 < contrast
}
}
// MARK: - Gradient
public extension Array where Element : UIColor {
func gradient(_ transform: ((_ gradient: inout CAGradientLayer) -> CAGradientLayer)? = nil) -> CAGradientLayer {
var gradient = CAGradientLayer()
gradient.colors = self.map { $0.cgColor }
if let transform = transform {
gradient = transform(&gradient)
}
return gradient
}
}
// MARK: - Components
public extension UIColor {
var redComponent: CGFloat {
var red: CGFloat = 0
getRed(&red, green: nil , blue: nil, alpha: nil)
return red
}
var greenComponent: CGFloat {
var green: CGFloat = 0
getRed(nil, green: &green , blue: nil, alpha: nil)
return green
}
var blueComponent: CGFloat {
var blue: CGFloat = 0
getRed(nil, green: nil , blue: &blue, alpha: nil)
return blue
}
var alphaComponent: CGFloat {
var alpha: CGFloat = 0
getRed(nil, green: nil , blue: nil, alpha: &alpha)
return alpha
}
var hueComponent: CGFloat {
var hue: CGFloat = 0
getHue(&hue, saturation: nil, brightness: nil, alpha: nil)
return hue
}
var saturationComponent: CGFloat {
var saturation: CGFloat = 0
getHue(nil, saturation: &saturation, brightness: nil, alpha: nil)
return saturation
}
var brightnessComponent: CGFloat {
var brightness: CGFloat = 0
getHue(nil, saturation: nil, brightness: &brightness, alpha: nil)
return brightness
}
}
// MARK: - Blending
public extension UIColor {
/**adds hue, saturation, and brightness to the HSB components of this color (self)*/
func add(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) -> UIColor {
var (oldHue, oldSat, oldBright, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
getHue(&oldHue, saturation: &oldSat, brightness: &oldBright, alpha: &oldAlpha)
// make sure new values doesn't overflow
var newHue = oldHue + hue
while newHue < 0.0 { newHue += 1.0 }
while newHue > 1.0 { newHue -= 1.0 }
let newBright: CGFloat = max(min(oldBright + brightness, 1.0), 0)
let newSat: CGFloat = max(min(oldSat + saturation, 1.0), 0)
let newAlpha: CGFloat = max(min(oldAlpha + alpha, 1.0), 0)
return UIColor(hue: newHue, saturation: newSat, brightness: newBright, alpha: newAlpha)
}
/**adds red, green, and blue to the RGB components of this color (self)*/
func add(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
var (oldRed, oldGreen, oldBlue, oldAlpha) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
getRed(&oldRed, green: &oldGreen, blue: &oldBlue, alpha: &oldAlpha)
// make sure new values doesn't overflow
let newRed: CGFloat = max(min(oldRed + red, 1.0), 0)
let newGreen: CGFloat = max(min(oldGreen + green, 1.0), 0)
let newBlue: CGFloat = max(min(oldBlue + blue, 1.0), 0)
let newAlpha: CGFloat = max(min(oldAlpha + alpha, 1.0), 0)
return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha)
}
func add(hsb color: UIColor) -> UIColor {
var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return self.add(hue: h, saturation: s, brightness: b, alpha: 0)
}
func add(rgb color: UIColor) -> UIColor {
return self.add(red: color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: 0)
}
func add(hsba color: UIColor) -> UIColor {
var (h,s,b,a) : (CGFloat, CGFloat, CGFloat, CGFloat) = (0,0,0,0)
color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return self.add(hue: h, saturation: s, brightness: b, alpha: a)
}
/**adds the rgb components of two colors*/
func add(rgba color: UIColor) -> UIColor {
return self.add(red: color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: color.alphaComponent)
}
}
| mit | c0326c2da187be9192fb32b0550587ff | 29.919028 | 129 | 0.604819 | 3.32622 | false | false | false | false |
tidwall/Safe | Source/sync.swift | 1 | 6886 | /*
* Sync (sync.swift) - Please be Safe
*
* Copyright (C) 2015 ONcast, LLC. All Rights Reserved.
* Created by Josh Baker ([email protected])
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* Portions of the documentation of this code are reproduced from
* work created and shared by Google and used according to terms
* described in the Creative Commons 3.0 Attribution License.
*
* http://golang.org/pkg/sync/
*/
#if os(Linux)
import Glibc
#endif
import Foundation
/// The WaitResult enum is used as a return value by Mutex.wait()
public enum WaitResult {
/// The wait resulted in a signal
case signaled
/// The wait resulted in a timeout
case timedOut
}
/// A Mutex is a mutual exclusion lock.
open class Mutex {
fileprivate var mutex = pthread_mutex_t()
/// Returns a new Mutex.
public init(){
pthread_mutex_init(&mutex, nil)
}
deinit{
pthread_mutex_destroy(&mutex)
}
/// Locks the mutex. If the lock is already in use, the calling operation blocks until the mutex is available.
open func lock(){
pthread_mutex_lock(&mutex)
}
/**
Unlocks the mutex. It's an undefined error if mutex is not locked on entry to unlock.
A locked Mutex is not associated with a particular operation.
It is allowed for one operation to lock a Mutex and then arrange for another operation to unlock it.
*/
open func unlock(){
pthread_mutex_unlock(&mutex)
}
/// Locks the mutex before calling the function. Unlocks after closure is completed
/// - Parameter: closure Closure function
open func lock(_ closure : ()->()) {
lock()
closure()
unlock()
}
}
/**
`Cond` implements a condition variable, a rendezvous point for an operation waiting for or announcing the occurrence of an event.
Each `Cond` has an associated `Mutex`, which must be held when changing the condition and when calling the `wait` method.
*/
open class Cond {
fileprivate var cond = pthread_cond_t()
open let mutex : Mutex
/// Returns a new Cond.
/// - Parameter mutex: A Mutex object.
public init(_ mutex : Mutex){
self.mutex = mutex
pthread_cond_init(&cond, nil)
}
deinit {
pthread_cond_destroy(&cond)
}
/// Wakes all operations waiting on `Cond`.
open func broadcast() {
pthread_cond_broadcast(&cond)
}
/// Wakes one operations waiting on `Cond`.
open func signal() {
pthread_cond_signal(&cond)
}
/**
Atomically unlocks `.mutex` and suspends execution of the calling operation.
After later resuming execution, `waita locks `.mutex' before returning.
Unlike in other systems, `wait` cannot return unless awoken by `broadcast` or `signal', or the `timeout` param has been reached.
Because `.mutex` is not locked when 'wait first resumes, the caller typically cannot assume that the condition is true when `wait` returns.
Instead, the caller should `wait` in a loop:
```
cond.mutex.lock()
while !condition() {
cond.mutex.wait()
}
... make use of condition ...
cond.mutex.unlock()
```
*/
/// - Parameter timeout: The length of time to wait. Default is forever.
/// - Returns: WaitResult
open func wait(_ timeout : TimeInterval = -1) -> WaitResult {
if timeout < 0 {
pthread_cond_wait(&cond, &mutex.mutex)
return .signaled
}
let timeInMs = Int(timeout * 1000)
var tv = timeval()
var ts = timespec()
gettimeofday(&tv, nil)
ts.tv_sec = time(nil) + timeInMs / 1000
let intermediate = 1000 * 1000 * (timeInMs % 1000)
// I suspect this could have problems on a 32-bit system.
ts.tv_nsec = Int(Int(tv.tv_usec * 1000) + intermediate)
ts.tv_sec += ts.tv_nsec / 1000000000
ts.tv_nsec %= 1000000000
if (pthread_cond_timedwait(&cond, &mutex.mutex, &ts) == 0) {
return .signaled
}
return .timedOut
}
}
/// Once is an object that will perform exactly one action.
open class Once {
fileprivate var mutex = Mutex()
fileprivate var oncer = false
/// Returns a new Once.
public init() {}
/**
Calls the `action` if and only if `doit` is being called for the first time for this instance of `Once`. In other words, given
```
var once Once
```
If `doit` is called multiple times, only the first call will invoke `action`, even if `action` has a different value in each invocation.
A new instance of `Once` is required for each function to execute.
This method is intended for initialization that must be run exactly once.
*/
/// - Parameter action: An action function.
open func doit(_ action: ()->()) {
mutex.lock()
defer { mutex.unlock() }
if oncer{
return
}
oncer = true
action()
}
}
/**
A WaitGroup waits for a collection of operations to finish.
The main operation calls 'add' to set the number of operation to wait for.
Then each of the operations runs and calls 'done' when finished.
At the same time, 'wait' can be used to block until all operations have finished.
*/
open class WaitGroup {
fileprivate var cond = Cond(Mutex())
fileprivate var count = 0
/// Returns a new WaitGroup.
public init() {}
/**
Adds delta, which may be negative, to the WaitGroup counter.
If the counter becomes Zero, all operations blocked on 'wait' are released.
If the counter goes negative, 'add' fires a system exception.
Note that calls with a positive delta that occur when the counter is Zero must happen before a 'wait'.
Calls with a negative delta, or calls with a positive delta that start when the counter is greater than zero, may happen at any time.
Typically this means the calls to 'add' should execute before the statement creating the operation or other event to be waited for.
*/
open func add(_ delta: Int) {
cond.mutex.lock()
defer { cond.mutex.unlock() }
count += delta
if count < 0 {
#if os(Linux)
assertionFailure("negative WaitGroup counter")
#else
NSException.raise(NSExceptionName(rawValue: "Exception"), format: "negative WaitGroup counter", arguments: getVaList([]))
#endif
}
cond.broadcast()
}
/// Decrements the WaitGroup counter.
open func done() {
add(-1)
}
/// Blocks until the WaitGroup counter is Zero.
open func wait() {
cond.mutex.lock()
defer { cond.mutex.unlock() }
while count > 0 {
cond.wait()
}
cond.mutex.unlock()
}
}
| mit | 6eb1320a4f43ea4dc8077ac8db604993 | 32.2657 | 143 | 0.632297 | 4.258503 | false | false | false | false |
qiulang/PeerKit | example/Pods/SwiftyBeaver/sources/SwiftyBeaver.swift | 2 | 6927 | //
// SwiftyBeaver.swift
// SwiftyBeaver
//
// Created by Sebastian Kreutzberger (Twitter @skreutzb) on 28.11.15.
// Copyright © 2015 Sebastian Kreutzberger
// Some rights reserved: http://opensource.org/licenses/MIT
//
import Foundation
public class SwiftyBeaver {
/// version string of framework
public static let version = "1.1.1" // UPDATE ON RELEASE!
/// build number of framework
public static let build = 1110 // version 0.7.1 -> 710, UPDATE ON RELEASE!
public enum Level: Int {
case verbose = 0
case debug = 1
case info = 2
case warning = 3
case error = 4
}
// a set of active destinations
public private(set) static var destinations = Set<BaseDestination>()
// MARK: Destination Handling
/// returns boolean about success
@discardableResult
public class func addDestination(_ destination: BaseDestination) -> Bool {
if destinations.contains(destination) {
return false
}
destinations.insert(destination)
return true
}
/// returns boolean about success
@discardableResult
public class func removeDestination(_ destination: BaseDestination) -> Bool {
if destinations.contains(destination) == false {
return false
}
destinations.remove(destination)
return true
}
/// if you need to start fresh
public class func removeAllDestinations() {
destinations.removeAll()
}
/// returns the amount of destinations
public class func countDestinations() -> Int {
return destinations.count
}
/// returns the current thread name
class func threadName() -> String {
#if os(Linux)
// on 9/30/2016 not yet implemented in server-side Swift:
// > import Foundation
// > Thread.isMainThread
return ""
#else
if Thread.isMainThread {
return ""
} else {
let threadName = Thread.current.name
if let threadName = threadName, !threadName.isEmpty {
return threadName
} else {
return String(format: "%p", Thread.current)
}
}
#endif
}
// MARK: Levels
/// log something generally unimportant (lowest priority)
public class func verbose(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line) {
custom(level: .verbose, message: message, file: file, function: function, line: line)
}
/// log something which help during debugging (low priority)
public class func debug(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line) {
custom(level: .debug, message: message, file: file, function: function, line: line)
}
/// log something which you are really interested but which is not an issue or error (normal priority)
public class func info(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line) {
custom(level: .info, message: message, file: file, function: function, line: line)
}
/// log something which may cause big trouble soon (high priority)
public class func warning(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line) {
custom(level: .warning, message: message, file: file, function: function, line: line)
}
/// log something which will keep you awake at night (highest priority)
public class func error(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line) {
custom(level: .error, message: message, file: file, function: function, line: line)
}
/// custom logging to manually adjust values, should just be used by other frameworks
public class func custom(level: SwiftyBeaver.Level, message: @autoclosure () -> Any,
file: String = #file, function: String = #function, line: Int = #line) {
dispatch_send(level: level, message: message, thread: threadName(),
file: file, function: function, line: line)
}
/// internal helper which dispatches send to dedicated queue if minLevel is ok
class func dispatch_send(level: SwiftyBeaver.Level, message: @autoclosure () -> Any,
thread: String, file: String, function: String, line: Int) {
var resolvedMessage: String?
for dest in destinations {
guard let queue = dest.queue else {
continue
}
resolvedMessage = resolvedMessage == nil && dest.hasMessageFilters() ? "\(message())" : nil
if dest.shouldLevelBeLogged(level, path: file, function: function, message: resolvedMessage) {
// try to convert msg object to String and put it on queue
let msgStr = resolvedMessage == nil ? "\(message())" : resolvedMessage!
let f = stripParams(function: function)
if dest.asynchronously {
queue.async() {
let _ = dest.send(level, msg: msgStr, thread: thread, file: file, function: f, line: line)
}
} else {
queue.sync() {
let _ = dest.send(level, msg: msgStr, thread: thread, file: file, function: f, line: line)
}
}
}
}
}
/**
DEPRECATED & NEEDS COMPLETE REWRITE DUE TO SWIFT 3 AND GENERAL INCORRECT LOGIC
Flush all destinations to make sure all logging messages have been written out
Returns after all messages flushed or timeout seconds
- returns: true if all messages flushed, false if timeout or error occurred
*/
public class func flush(secondTimeout: Int64) -> Bool {
/*
guard let grp = dispatch_group_create() else { return false }
for dest in destinations {
if let queue = dest.queue {
dispatch_group_enter(grp)
queue.asynchronously(execute: {
dest.flush()
grp.leave()
})
}
}
let waitUntil = DispatchTime.now(dispatch_time_t(DISPATCH_TIME_NOW), secondTimeout * 1000000000)
return dispatch_group_wait(grp, waitUntil) == 0
*/
return true
}
/// removes the parameters from a function because it looks weird with a single param
class func stripParams(function: String) -> String {
var f = function
if let indexOfBrace = f.characters.index(of: "(") {
f = f.substring(to: indexOfBrace)
}
f = f + "()"
return f
}
}
| mit | a8623c94d69e082e486722b0bb08ed26 | 36.037433 | 114 | 0.590817 | 4.667116 | false | false | false | false |
a1b2c3d4e5x/IRR | Base/Double+Decimal.swift | 1 | 625 | //
// Double+Format.swift
// FinancialFunction
//
// Created by GuoHao on 2017/3/3.
// Copyright © 2017年 cgh. All rights reserved.
//
import Foundation
extension Double {
public enum Decimal: String {
case ´1´ = "1"
case ´2´ = "2"
case ´3´ = "3"
case ´4´ = "4"
case ´5´ = "5"
case ´6´ = "6"
case ´7´ = "7"
case ´8´ = "8"
case ´9´ = "9"
}
/**
Ex: 0.131419.decimal(.´2´) = 0.13
*/
public func decimal(_ f: Decimal) -> String {
return String(format:"%.\(f.rawValue)f", self)
}
}
| apache-2.0 | 722f8f5daf2007b77755cd6a42d261eb | 18.419355 | 54 | 0.468439 | 2.866667 | false | false | false | false |
pratikgujarati/iOS-Projects | SpriteKitSwiftLabelTutorial/SpriteKitSwiftLabelTutorial/GameScene.swift | 4 | 1575 | //
// GameScene.swift
// SpriteKitSwiftLabelTutorial
//
// Created by Arthur Knopper on 11/11/14.
// Copyright (c) 2014 Arthur Knopper. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var deltaPoint = CGPointZero
var myLabel:SKLabelNode!
override func didMoveToView(view: SKView) {
var bgImage = SKSpriteNode(imageNamed: "wallpaper.png")
bgImage.position = CGPointMake(self.size.width/2, self.size.height/2)
self.addChild(bgImage)
myLabel = SKLabelNode(fontNamed: "Arial")
myLabel.text = "Drag this label"
myLabel.fontSize = 20
myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
self.addChild(myLabel)
}
override func touchesMoved(touches: NSSet, withEvent: UIEvent) {
var currentPoint:CGPoint! = touches.anyObject()?.locationInNode(self)
var previousPoint:CGPoint! = touches.anyObject()?.previousLocationInNode(self)
deltaPoint = CGPointMake(currentPoint.x - previousPoint.x, currentPoint.y - previousPoint.y)
}
override func touchesEnded(touches: NSSet, withEvent: UIEvent) {
deltaPoint = CGPointZero
}
override func touchesCancelled(touches: NSSet!, withEvent: UIEvent!) {
deltaPoint = CGPointZero
}
override func update(currentTime: CFTimeInterval) {
var newPoint = CGPointMake(self.myLabel.position.x + self.deltaPoint.x, self.myLabel.position.y + self.deltaPoint.y)
myLabel.position = newPoint
deltaPoint = CGPointZero
}
}
| mit | 58bf495e9fe7618832de04bb7b464c96 | 30.5 | 122 | 0.690794 | 4.5 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer | GeekSpeak Show Timer/BreakCount-2/SettingsViewController+TimerNotifications.swift | 2 | 1986 | import UIKit
extension SettingsViewController {
func registerForTimerNotifications() {
let notifyCenter = NotificationCenter.default
notifyCenter.addObserver( self,
selector: #selector(SettingsViewController.updateElapsedTimeLabels),
name: NSNotification.Name(rawValue: Timer.Constants.TimeChange),
object: timer)
notifyCenter.addObserver( self,
selector: #selector(SettingsViewController.updateElapsedTimeLabels),
name: NSNotification.Name(rawValue: Timer.Constants.DurationChanged),
object: timer)
}
func unregisterForTimerNotifications() {
let notifyCenter = NotificationCenter.default
// TODO: When I explicitly remove each observer it throws an execption. why?
// notifyCenter.removeObserver( self,
// forKeyPath: Timer.Constants.TimeChange)
// notifyCenter.removeObserver( self,
// forKeyPath: Timer.Constants.DurationChanged)
notifyCenter.removeObserver(self)
}
// MARK: Actions
@objc func updateElapsedTimeLabels() {
if let timer = timer {
let timing = timer.timing
var segment1 = timing.asShortString(timing.timeElapsed.section1)
var segment2 = timing.asShortString(timing.timeElapsed.section2)
var postshow = timing.asShortString(timing.timeElapsed.postShow)
switch timing.phase {
case .PreShow,
.Break1:
break
case .Section1:
segment1 = timing.asShortString(timer.secondsElapsed)
case .Section2:
segment2 = timing.asShortString(timer.secondsElapsed)
case .PostShow:
postshow = timing.asShortString(timer.secondsElapsed)
}
segment1Label.text = segment1
segment2Label.text = segment2
postShowLabel.text = postshow
generateBlurredBackground()
}
}
}
| mit | b1df37574cd9a415232e0f48a8dfb77a | 30.52381 | 93 | 0.643505 | 5.118557 | false | false | false | false |
proversity-org/edx-app-ios | Source/DiscussionBlockViewController.swift | 1 | 1865 | //
// DiscussionBlockViewController.swift
// edX
//
// Created by Saeed Bashir on 5/27/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
class DiscussionBlockViewController: UIViewController,CourseBlockViewController {
typealias Environment = NetworkManagerProvider & OEXRouterProvider & OEXAnalyticsProvider & OEXStylesProvider
let courseID: String
let blockID : CourseBlockID?
private let topicID: String?
private let environment : Environment
private let postsController:PostsViewController
init(blockID: CourseBlockID?, courseID : String, topicID: String?, environment : Environment) {
self.blockID = blockID
self.courseID = courseID
self.topicID = topicID
self.environment = environment
self.postsController = PostsViewController(environment: self.environment, courseID: self.courseID, topicID: self.topicID)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = OEXStyles.shared().standardBackgroundColor()
addChild(postsController)
postsController.didMove(toParent: self)
view.addSubview(postsController.view)
}
override func updateViewConstraints() {
super.updateViewConstraints()
postsController.view.snp.remakeConstraints { make in
make.top.equalTo(safeTop)
make.leading.equalTo(safeLeading)
make.trailing.equalTo(safeTrailing)
let barHeight = navigationController?.toolbar.frame.size.height ?? 0.0
make.bottom.equalTo(safeBottom).offset(-barHeight)
}
}
}
| apache-2.0 | 905eb2dcb36345e5ccaf3c1e6b1f138c | 31.701754 | 129 | 0.67221 | 5.221289 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Post/AbstractPostListViewController.swift | 1 | 44099 | import Foundation
import Gridicons
import CocoaLumberjack
import WordPressShared
import wpxmlrpc
import WordPressFlux
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class AbstractPostListViewController: UIViewController,
WPContentSyncHelperDelegate,
UISearchControllerDelegate,
UISearchResultsUpdating,
WPTableViewHandlerDelegate,
// This protocol is not in an extension so that subclasses can override noConnectionMessage()
NetworkAwareUI {
fileprivate static let postsControllerRefreshInterval = TimeInterval(300)
fileprivate static let HTTPErrorCodeForbidden = Int(403)
fileprivate static let postsFetchRequestBatchSize = Int(10)
fileprivate static let pagesNumberOfLoadedElement = Int(100)
fileprivate static let postsLoadMoreThreshold = Int(4)
fileprivate static let preferredFiltersPopoverContentSize = CGSize(width: 320.0, height: 220.0)
fileprivate static let defaultHeightForFooterView = CGFloat(44.0)
fileprivate let abstractPostWindowlessCellIdenfitier = "AbstractPostWindowlessCellIdenfitier"
private var fetchBatchSize: Int {
return postTypeToSync() == .page ? 0 : type(of: self).postsFetchRequestBatchSize
}
private var fetchLimit: Int {
return postTypeToSync() == .page ? 0 : Int(numberOfPostsPerSync())
}
private var numberOfLoadedElement: NSNumber {
return postTypeToSync() == .page ? NSNumber(value: type(of: self).pagesNumberOfLoadedElement) : NSNumber(value: numberOfPostsPerSync())
}
private(set) var ghostableTableView = UITableView()
var ghostingEnabled = false
@objc var blog: Blog!
/// This closure will be executed whenever the noResultsView must be visually refreshed. It's up
/// to the subclass to define this property.
///
@objc var refreshNoResultsViewController: ((NoResultsViewController) -> ())!
@objc var tableViewController: UITableViewController!
@objc var reloadTableViewBeforeAppearing = false
@objc var tableView: UITableView {
get {
return self.tableViewController.tableView
}
}
@objc var refreshControl: UIRefreshControl? {
get {
return self.tableViewController.refreshControl
}
}
@objc lazy var tableViewHandler: WPTableViewHandler = {
let tableViewHandler = WPTableViewHandler(tableView: self.tableView)
tableViewHandler.cacheRowHeights = false
tableViewHandler.delegate = self
tableViewHandler.updateRowAnimation = .none
return tableViewHandler
}()
@objc lazy var estimatedHeightsCache: NSCache = { () -> NSCache<AnyObject, AnyObject> in
let estimatedHeightsCache = NSCache<AnyObject, AnyObject>()
return estimatedHeightsCache
}()
@objc lazy var syncHelper: WPContentSyncHelper = {
let syncHelper = WPContentSyncHelper()
syncHelper.delegate = self
return syncHelper
}()
@objc lazy var searchHelper: WPContentSearchHelper = {
let searchHelper = WPContentSearchHelper()
return searchHelper
}()
@objc lazy var noResultsViewController: NoResultsViewController = {
let noResultsViewController = NoResultsViewController.controller()
noResultsViewController.delegate = self
return noResultsViewController
}()
@objc lazy var filterSettings: PostListFilterSettings = {
return PostListFilterSettings(blog: self.blog, postType: self.postTypeToSync())
}()
@objc var postListFooterView: PostListFooterView!
@IBOutlet var filterTabBar: FilterTabBar!
@objc var searchController: UISearchController!
@objc var recentlyTrashedPostObjectIDs = [NSManagedObjectID]() // IDs of trashed posts. Cleared on refresh or when filter changes.
fileprivate var searchesSyncing = 0
private var emptyResults: Bool {
return tableViewHandler.resultsController.fetchedObjects?.count == 0
}
private var atLeastSyncedOnce = false
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
refreshControl?.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
configureFilterBar()
configureTableView()
configureFooterView()
configureWindowlessCell()
configureNavbar()
configureSearchController()
configureSearchHelper()
configureAuthorFilter()
configureSearchBackingView()
configureGhostableTableView()
WPStyleGuide.configureColors(view: view, tableView: tableView)
tableView.reloadData()
observeNetworkStatus()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startGhost()
if reloadTableViewBeforeAppearing {
reloadTableViewBeforeAppearing = false
tableView.reloadData()
}
filterTabBar.layoutIfNeeded()
updateSelectedFilter()
refreshResults()
}
fileprivate var searchBarHeight: CGFloat {
return searchController.searchBar.bounds.height + view.safeAreaInsets.top
}
fileprivate func localKeyboardFrameFromNotification(_ notification: Foundation.Notification) -> CGRect {
let key = UIResponder.keyboardFrameEndUserInfoKey
guard let keyboardFrame = (notification.userInfo?[key] as? NSValue)?.cgRectValue else {
return .zero
}
// Convert the frame from window coordinates
return view.convert(keyboardFrame, from: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
automaticallySyncIfAppropriate()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if searchController?.isActive == true {
searchController?.isActive = false
}
dismissAllNetworkErrorNotices()
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
// MARK: - Configuration
func heightForFooterView() -> CGFloat {
return type(of: self).defaultHeightForFooterView
}
func configureNavbar() {
// IMPORTANT: this code makes sure that the back button in WPPostViewController doesn't show
// this VC's title.
//
let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
}
func configureFilterBar() {
WPStyleGuide.configureFilterTabBar(filterTabBar)
filterTabBar.items = filterSettings.availablePostListFilters()
filterTabBar.addTarget(self, action: #selector(selectedFilterDidChange(_:)), for: .valueChanged)
}
func configureTableView() {
assert(false, "You should implement this method in the subclass")
}
func configureFooterView() {
let mainBundle = Bundle.main
guard let footerView = mainBundle.loadNibNamed("PostListFooterView", owner: nil, options: nil)![0] as? PostListFooterView else {
preconditionFailure("Could not load the footer view from the nib file.")
}
postListFooterView = footerView
postListFooterView.showSpinner(false)
var frame = postListFooterView.frame
frame.size.height = heightForFooterView()
postListFooterView.frame = frame
tableView.tableFooterView = postListFooterView
}
@objc func configureWindowlessCell() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: abstractPostWindowlessCellIdenfitier)
}
private func refreshResults() {
guard isViewLoaded == true else {
return
}
let _ = DispatchDelayedAction(delay: .milliseconds(500)) { [weak self] in
self?.refreshControl?.endRefreshing()
}
hideNoResultsView()
if emptyResults {
stopGhostIfConnectionIsNotAvailable()
showNoResultsView()
}
updateBackgroundColor()
}
// Update controller's background color to avoid a white line below
// the search bar - due to a margin between searchBar and the tableView
private func updateBackgroundColor() {
if searchController.isActive && emptyResults {
view.backgroundColor = noResultsViewController.view.backgroundColor
} else {
view.backgroundColor = tableView.backgroundColor
}
}
func configureAuthorFilter() {
fatalError("You should implement this method in the subclass")
}
/// Subclasses should override this method (and call super) to insert the
/// search controller's search bar into the view hierarchy
@objc func configureSearchController() {
// Required for insets to work out correctly when the search bar becomes active
extendedLayoutIncludesOpaqueBars = true
definesPresentationContext = true
searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = false
searchController.delegate = self
searchController.searchResultsUpdater = self
WPStyleGuide.configureSearchBar(searchController.searchBar)
searchController.searchBar.autocorrectionType = .default
}
fileprivate func configureInitialScrollInsets() {
tableView.layoutIfNeeded()
tableView.contentInset = .zero
tableView.scrollIndicatorInsets = .zero
tableView.contentOffset = .zero
}
fileprivate func configureSearchBackingView() {
// This mask view is required to cover the area between the top of the search
// bar and the top of the screen on an iPhone X and on iOS 10.
let topAnchor = view.safeAreaLayoutGuide.topAnchor
let backingView = UIView()
view.addSubview(backingView)
backingView.backgroundColor = searchController.searchBar.barTintColor
backingView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
backingView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
backingView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
backingView.topAnchor.constraint(equalTo: view.topAnchor),
backingView.bottomAnchor.constraint(equalTo: topAnchor)
])
}
func configureGhostableTableView() {
view.addSubview(ghostableTableView)
ghostableTableView.isHidden = true
ghostableTableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
ghostableTableView.widthAnchor.constraint(equalTo: tableView.widthAnchor),
ghostableTableView.heightAnchor.constraint(equalTo: tableView.heightAnchor),
ghostableTableView.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
ghostableTableView.topAnchor.constraint(equalTo: searchController.searchBar.bottomAnchor)
])
ghostableTableView.backgroundColor = .white
ghostableTableView.isScrollEnabled = false
}
@objc func configureSearchHelper() {
searchHelper.resetConfiguration()
searchHelper.configureImmediateSearch({ [weak self] in
self?.updateForLocalPostsMatchingSearchText()
})
searchHelper.configureDeferredSearch({ [weak self] in
self?.syncPostsMatchingSearchText()
})
}
@objc func propertiesForAnalytics() -> [String: AnyObject] {
var properties = [String: AnyObject]()
properties["type"] = postTypeToSync().rawValue as AnyObject?
properties["filter"] = filterSettings.currentPostListFilter().title as AnyObject?
if let dotComID = blog.dotComID {
properties[WPAppAnalyticsKeyBlogID] = dotComID
}
return properties
}
// MARK: - GUI: No results view logic
func hideNoResultsView() {
postListFooterView.isHidden = false
noResultsViewController.removeFromView()
}
func showNoResultsView() {
guard refreshNoResultsViewController != nil, atLeastSyncedOnce else {
return
}
postListFooterView.isHidden = true
refreshNoResultsViewController(noResultsViewController)
// Only add no results view if it isn't already in the table view
if noResultsViewController.view.isDescendant(of: tableView) == false {
tableViewController.addChild(noResultsViewController)
tableView.addSubview(withFadeAnimation: noResultsViewController.view)
noResultsViewController.view.frame = tableView.frame
// Adjust the NRV to accommodate for the search bar.
if let tableHeaderView = tableView.tableHeaderView {
noResultsViewController.view.frame.origin.y = tableHeaderView.frame.origin.y
}
noResultsViewController.didMove(toParent: tableViewController)
}
tableView.sendSubviewToBack(noResultsViewController.view)
}
// MARK: - TableView Helpers
@objc func dequeCellForWindowlessLoadingIfNeeded(_ tableView: UITableView) -> UITableViewCell? {
// As also seen in ReaderStreamViewController:
// We want to avoid dequeuing card cells when we're not present in a window, on the iPad.
// Doing so can create a situation where cells are not updated with the correct NSTraitCollection.
// The result is the cells do not show the correct layouts relative to superview margins.
// HACK: kurzee, 2016-07-12
// Use a generic cell in this situation and reload the table view once its back in a window.
if tableView.window == nil {
reloadTableViewBeforeAppearing = true
return tableView.dequeueReusableCell(withIdentifier: abstractPostWindowlessCellIdenfitier)
}
return nil
}
// MARK: - TableViewHandler Delegate Methods
@objc func entityName() -> String {
fatalError("You should implement this method in the subclass")
}
func managedObjectContext() -> NSManagedObjectContext {
return ContextManager.sharedInstance().mainContext
}
func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName())
fetchRequest.predicate = predicateForFetchRequest()
fetchRequest.sortDescriptors = sortDescriptorsForFetchRequest()
fetchRequest.fetchBatchSize = fetchBatchSize
fetchRequest.fetchLimit = fetchLimit
return fetchRequest
}
@objc func sortDescriptorsForFetchRequest() -> [NSSortDescriptor] {
return filterSettings.currentPostListFilter().sortDescriptors
}
@objc func updateAndPerformFetchRequest() {
assert(Thread.isMainThread, "AbstractPostListViewController Error: NSFetchedResultsController accessed in BG")
var predicate = predicateForFetchRequest()
let sortDescriptors = sortDescriptorsForFetchRequest()
let fetchRequest = tableViewHandler.resultsController.fetchRequest
// Set the predicate based on filtering by the oldestPostDate and not searching.
let filter = filterSettings.currentPostListFilter()
if let oldestPostDate = filter.oldestPostDate, !isSearching() {
// Filter posts by any posts newer than the filter's oldestPostDate.
// Also include any posts that don't have a date set, such as local posts created without a connection.
let datePredicate = NSPredicate(format: "(date_created_gmt = NULL) OR (date_created_gmt >= %@)", oldestPostDate as CVarArg)
predicate = NSCompoundPredicate.init(andPredicateWithSubpredicates: [predicate, datePredicate])
}
// Set up the fetchLimit based on filtering or searching
if filter.oldestPostDate != nil || isSearching() == true {
// If filtering by the oldestPostDate or searching, the fetchLimit should be disabled.
fetchRequest.fetchLimit = 0
} else {
// If not filtering by the oldestPostDate or searching, set the fetchLimit to the default number of posts.
fetchRequest.fetchLimit = fetchLimit
}
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sortDescriptors
do {
try tableViewHandler.resultsController.performFetch()
} catch {
DDLogError("Error fetching posts after updating the fetch request predicate: \(error)")
}
}
@objc func updateAndPerformFetchRequestRefreshingResults() {
updateAndPerformFetchRequest()
tableView.reloadData()
refreshResults()
}
@objc func resetTableViewContentOffset(_ animated: Bool = false) {
// Reset the tableView contentOffset to the top before we make any dataSource changes.
var tableOffset = tableView.contentOffset
tableOffset.y = -tableView.contentInset.top
tableView.setContentOffset(tableOffset, animated: animated)
}
@objc func predicateForFetchRequest() -> NSPredicate {
fatalError("You should implement this method in the subclass")
}
// MARK: - Table View Handling
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
// When using UITableViewAutomaticDimension for auto-sizing cells, UITableView
// likes to reload rows in a strange way.
// It uses the estimated height as a starting value for reloading animations.
// So this estimated value needs to be as accurate as possible to avoid any "jumping" in
// the cell heights during reload animations.
// Note: There may (and should) be a way to get around this, but there is currently no obvious solution.
// Brent C. August 2/2016
if let height = estimatedHeightsCache.object(forKey: indexPath as AnyObject) as? CGFloat {
// Return the previously known height as it was cached via willDisplayCell.
return height
}
// Otherwise return whatever we have set to the tableView explicitly, and ideally a pretty close value.
return tableView.estimatedRowHeight
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
assert(false, "You should implement this method in the subclass")
}
func tableViewDidChangeContent(_ tableView: UITableView) {
refreshResults()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Cache the cell's layout height as the currently known height, for estimation.
// See estimatedHeightForRowAtIndexPath
estimatedHeightsCache.setObject(cell.frame.height as AnyObject, forKey: indexPath as AnyObject)
guard isViewOnScreen() && !isSearching() else {
return
}
// Are we approaching the end of the table?
if indexPath.section + 1 == tableView.numberOfSections
&& indexPath.row + type(of: self).postsLoadMoreThreshold >= tableView.numberOfRows(inSection: indexPath.section)
&& postTypeToSync() == .post {
// Only 3 rows till the end of table
if filterSettings.currentPostListFilter().hasMore {
syncHelper.syncMoreContent()
}
}
}
func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) {
assert(false, "You should implement this method in the subclass")
}
// MARK: - Actions
@IBAction func refresh(_ sender: AnyObject) {
syncItemsWithUserInteraction(true)
WPAnalytics.track(.postListPullToRefresh, withProperties: propertiesForAnalytics())
}
// MARK: - Synching
@objc func automaticallySyncIfAppropriate() {
// Only automatically refresh if the view is loaded and visible on the screen
if !isViewLoaded || view.window == nil {
DDLogVerbose("View is not visible and will not check for auto refresh.")
return
}
// Do not start auto-sync if connection is down
let appDelegate = WordPressAppDelegate.shared
if appDelegate?.connectionAvailable == false {
refreshResults()
dismissAllNetworkErrorNotices()
handleConnectionError()
return
}
if let lastSynced = lastSyncDate(), abs(lastSynced.timeIntervalSinceNow) <= type(of: self).postsControllerRefreshInterval {
refreshResults()
} else {
// Update in the background
syncItemsWithUserInteraction(false)
}
}
@objc func syncItemsWithUserInteraction(_ userInteraction: Bool) {
syncHelper.syncContentWithUserInteraction(userInteraction)
refreshResults()
}
@objc func updateFilter(_ filter: PostListFilter, withSyncedPosts posts: [AbstractPost], syncOptions options: PostServiceSyncOptions) {
guard posts.count > 0 else {
assertionFailure("This method should not be called with no posts.")
return
}
// Reset the filter to only show the latest sync point, based on the oldest post date in the posts just synced.
// Note: Getting oldest date manually as the API may return results out of order if there are
// differing time offsets in the created dates.
let oldestPost = posts.min {$0.date_created_gmt < $1.date_created_gmt}
filter.oldestPostDate = oldestPost?.date_created_gmt
filter.hasMore = posts.count >= options.number.intValue
updateAndPerformFetchRequestRefreshingResults()
}
@objc func numberOfPostsPerSync() -> UInt {
return PostServiceDefaultNumberToSync
}
// MARK: - WPContentSyncHelperDelegate
@objc internal func postTypeToSync() -> PostServiceType {
// Subclasses should override.
return .any
}
@objc func lastSyncDate() -> Date? {
return blog.lastPostsSync
}
func syncHelper(_ syncHelper: WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((_ hasMore: Bool) -> ())?, failure: ((_ error: NSError) -> ())?) {
if recentlyTrashedPostObjectIDs.count > 0 {
refreshAndReload()
}
let postType = postTypeToSync()
let filter = filterSettings.currentPostListFilter()
let author = filterSettings.shouldShowOnlyMyPosts() ? blogUserID() : nil
let postService = PostService(managedObjectContext: managedObjectContext())
let options = PostServiceSyncOptions()
options.statuses = filter.statuses.strings
options.authorID = author
options.number = numberOfLoadedElement
options.purgesLocalSync = true
postService.syncPosts(
ofType: postType,
with: options,
for: blog,
success: {[weak self] posts in
guard let strongSelf = self,
let posts = posts else {
return
}
if posts.count > 0 {
strongSelf.updateFilter(filter, withSyncedPosts: posts, syncOptions: options)
SearchManager.shared.indexItems(posts)
}
success?(filter.hasMore)
if strongSelf.isSearching() {
// If we're currently searching, go ahead and request a sync with the searchText since
// an action was triggered to syncContent.
strongSelf.syncPostsMatchingSearchText()
}
}, failure: {[weak self] (error: Error?) -> () in
guard let strongSelf = self,
let error = error else {
return
}
failure?(error as NSError)
if userInteraction == true {
strongSelf.handleSyncFailure(error as NSError)
}
})
}
let loadMoreCounter = LoadMoreCounter()
func syncHelper(_ syncHelper: WPContentSyncHelper, syncMoreWithSuccess success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) {
// See https://github.com/wordpress-mobile/WordPress-iOS/issues/6819
loadMoreCounter.increment(properties: propertiesForAnalytics())
postListFooterView.showSpinner(true)
let postType = postTypeToSync()
let filter = filterSettings.currentPostListFilter()
let author = filterSettings.shouldShowOnlyMyPosts() ? blogUserID() : nil
let postService = PostService(managedObjectContext: managedObjectContext())
let options = PostServiceSyncOptions()
options.statuses = filter.statuses.strings
options.authorID = author
options.number = numberOfLoadedElement
options.offset = tableViewHandler.resultsController.fetchedObjects?.count as NSNumber?
postService.syncPosts(
ofType: postType,
with: options,
for: blog,
success: {[weak self] posts in
guard let strongSelf = self,
let posts = posts else {
return
}
if posts.count > 0 {
strongSelf.updateFilter(filter, withSyncedPosts: posts, syncOptions: options)
SearchManager.shared.indexItems(posts)
}
success?(filter.hasMore)
}, failure: { (error) -> () in
guard let error = error else {
return
}
failure?(error as NSError)
})
}
func syncContentStart(_ syncHelper: WPContentSyncHelper) {
startGhost()
atLeastSyncedOnce = true
}
func syncContentEnded(_ syncHelper: WPContentSyncHelper) {
refreshControl?.endRefreshing()
postListFooterView.showSpinner(false)
noResultsViewController.removeFromView()
stopGhost()
if emptyResults {
// This is a special case. Core data can be a bit slow about notifying
// NSFetchedResultsController delegates about changes to the fetched results.
// To compensate, call configureNoResultsView after a short delay.
// It will be redisplayed if necessary.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(100 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC), execute: { [weak self] in
self?.refreshResults()
})
}
}
@objc func handleSyncFailure(_ error: NSError) {
if error.domain == WPXMLRPCFaultErrorDomain
&& error.code == type(of: self).HTTPErrorCodeForbidden {
promptForPassword()
return
}
stopGhost()
dismissAllNetworkErrorNotices()
// If there is no internet connection, we'll show the specific error message defined in
// `noConnectionMessage()` (overridden by subclasses). For everything else, we let
// `WPError.showNetworkingNotice` determine the user-friendly error message.
if !connectionAvailable() {
handleConnectionError()
} else {
let title = NSLocalizedString("Unable to Sync", comment: "Title of error prompt shown when a sync the user initiated fails.")
WPError.showNetworkingNotice(title: title, error: error)
}
}
@objc func promptForPassword() {
let message = NSLocalizedString("The username or password stored in the app may be out of date. Please re-enter your password in the settings and try again.", comment: "Error message informing a user about an invalid password.")
// bad login/pass combination
let editSiteViewController = SiteSettingsViewController(blog: blog)
let navController = UINavigationController(rootViewController: editSiteViewController!)
navController.navigationBar.isTranslucent = false
navController.modalTransitionStyle = .crossDissolve
navController.modalPresentationStyle = .formSheet
WPError.showAlert(withTitle: NSLocalizedString("Unable to Connect", comment: "An error message."), message: message, withSupportButton: true) { _ in
self.present(navController, animated: true)
}
}
// MARK: - Ghost cells
final func startGhost() {
guard ghostingEnabled, emptyResults else {
return
}
if isViewOnScreen() {
ghostableTableView.startGhostAnimation()
}
ghostableTableView.isHidden = false
noResultsViewController.view.isHidden = true
}
final func stopGhost() {
ghostableTableView.isHidden = true
ghostableTableView.stopGhostAnimation()
noResultsViewController.view.isHidden = false
}
private func stopGhostIfConnectionIsNotAvailable() {
guard WordPressAppDelegate.shared?.connectionAvailable == false else {
return
}
atLeastSyncedOnce = true
stopGhost()
}
// MARK: - Searching
@objc func isSearching() -> Bool {
return searchController.isActive && currentSearchTerm()?.count > 0
}
@objc func currentSearchTerm() -> String? {
return searchController.searchBar.text
}
@objc func updateForLocalPostsMatchingSearchText() {
updateAndPerformFetchRequest()
tableView.reloadData()
let filter = filterSettings.currentPostListFilter()
if filter.hasMore && emptyResults {
// If the filter detects there are more posts, but there are none that match the current search
// hide the no results view while the upcoming syncPostsMatchingSearchText() may in fact load results.
hideNoResultsView()
postListFooterView.isHidden = true
} else {
refreshResults()
}
}
@objc func isSyncingPostsWithSearch() -> Bool {
return searchesSyncing > 0
}
@objc func postsSyncWithSearchDidBegin() {
searchesSyncing += 1
postListFooterView.showSpinner(true)
postListFooterView.isHidden = false
}
@objc func postsSyncWithSearchEnded() {
searchesSyncing -= 1
assert(searchesSyncing >= 0, "Expected Int searchesSyncing to be 0 or greater while searching.")
if !isSyncingPostsWithSearch() {
postListFooterView.showSpinner(false)
refreshResults()
}
}
@objc func syncPostsMatchingSearchText() {
guard let searchText = searchController.searchBar.text, !searchText.isEmpty() else {
return
}
let filter = filterSettings.currentPostListFilter()
guard filter.hasMore else {
return
}
postsSyncWithSearchDidBegin()
let author = filterSettings.shouldShowOnlyMyPosts() ? blogUserID() : nil
let postService = PostService(managedObjectContext: managedObjectContext())
let options = PostServiceSyncOptions()
options.statuses = filter.statuses.strings
options.authorID = author
options.number = 20
options.purgesLocalSync = false
options.search = searchText
postService.syncPosts(
ofType: postTypeToSync(),
with: options,
for: blog,
success: { [weak self] posts in
self?.postsSyncWithSearchEnded()
}, failure: { [weak self] (error) in
self?.postsSyncWithSearchEnded()
}
)
}
// MARK: - Actions
@objc func publishPost(_ apost: AbstractPost, completion: (() -> Void)? = nil) {
let title = NSLocalizedString("Are you sure you want to publish?", comment: "Title of the message shown when the user taps Publish in the post list.")
let cancelTitle = NSLocalizedString("Cancel", comment: "Button shown when the author is asked for publishing confirmation.")
let publishTitle = NSLocalizedString("Publish", comment: "Button shown when the author is asked for publishing confirmation.")
let style: UIAlertController.Style = UIDevice.isPad() ? .alert : .actionSheet
let alertController = UIAlertController(title: title, message: nil, preferredStyle: style)
alertController.addCancelActionWithTitle(cancelTitle)
alertController.addDefaultActionWithTitle(publishTitle) { [unowned self] _ in
WPAnalytics.track(.postListPublishAction, withProperties: self.propertiesForAnalytics())
PostCoordinator.shared.publish(apost)
completion?()
}
present(alertController, animated: true)
}
@objc func moveToDraft(_ apost: AbstractPost) {
WPAnalytics.track(.postListDraftAction, withProperties: propertiesForAnalytics())
PostCoordinator.shared.moveToDraft(apost)
}
@objc func viewPost(_ apost: AbstractPost) {
WPAnalytics.track(.postListViewAction, withProperties: propertiesForAnalytics())
let post = apost.hasRevision() ? apost.revision! : apost
let controller = PreviewWebKitViewController(post: post, source: "posts_pages_view_post")
controller.trackOpenEvent()
// NOTE: We'll set the title to match the title of the View action button.
// If the button title changes we should also update the title here.
controller.navigationItem.title = NSLocalizedString("View", comment: "Verb. The screen title shown when viewing a post inside the app.")
let navWrapper = LightNavigationController(rootViewController: controller)
if navigationController?.traitCollection.userInterfaceIdiom == .pad {
navWrapper.modalPresentationStyle = .fullScreen
}
navigationController?.present(navWrapper, animated: true)
}
@objc func deletePost(_ apost: AbstractPost) {
WPAnalytics.track(.postListTrashAction, withProperties: propertiesForAnalytics())
let postObjectID = apost.objectID
recentlyTrashedPostObjectIDs.append(postObjectID)
// Remove the trashed post from spotlight
SearchManager.shared.deleteSearchableItem(apost)
// Update the fetch request *before* making the service call.
updateAndPerformFetchRequest()
let indexPath = tableViewHandler.resultsController.indexPath(forObject: apost)
if let indexPath = indexPath {
tableView.reloadRows(at: [indexPath], with: .fade)
}
let postService = PostService(managedObjectContext: ContextManager.sharedInstance().mainContext)
let trashed = (apost.status == .trash)
postService.trashPost(apost, success: {
// If we permanently deleted the post
if trashed {
PostCoordinator.shared.cancelAnyPendingSaveOf(post: apost)
MediaCoordinator.shared.cancelUploadOfAllMedia(for: apost)
}
}, failure: { [weak self] (error) in
guard let strongSelf = self else {
return
}
if let error = error as NSError?, error.code == type(of: strongSelf).HTTPErrorCodeForbidden {
strongSelf.promptForPassword()
} else {
WPError.showXMLRPCErrorAlert(error)
}
if let index = strongSelf.recentlyTrashedPostObjectIDs.firstIndex(of: postObjectID) {
strongSelf.recentlyTrashedPostObjectIDs.remove(at: index)
// We don't really know what happened here, why did the request fail?
// Maybe we could not delete the post or maybe the post was already deleted
// It is safer to re fetch the results than to reload that specific row
DispatchQueue.main.async {
strongSelf.updateAndPerformFetchRequestRefreshingResults()
}
}
})
}
@objc func restorePost(_ apost: AbstractPost, completion: (() -> Void)? = nil) {
WPAnalytics.track(.postListRestoreAction, withProperties: propertiesForAnalytics())
// if the post was recently deleted, update the status helper and reload the cell to display a spinner
let postObjectID = apost.objectID
if let index = recentlyTrashedPostObjectIDs.firstIndex(of: postObjectID) {
recentlyTrashedPostObjectIDs.remove(at: index)
}
if filterSettings.currentPostListFilter().filterType != .draft {
// Needed or else the post will remain in the published list.
updateAndPerformFetchRequest()
tableView.reloadData()
}
let postService = PostService(managedObjectContext: ContextManager.sharedInstance().mainContext)
postService.restore(apost, success: { [weak self] in
guard let strongSelf = self else {
return
}
var apost: AbstractPost
// Make sure the post still exists.
do {
apost = try strongSelf.managedObjectContext().existingObject(with: postObjectID) as! AbstractPost
} catch {
DDLogError("\(error)")
return
}
DispatchQueue.main.async {
completion?()
}
if let postStatus = apost.status {
// If the post was restored, see if it appears in the current filter.
// If not, prompt the user to let it know under which filter it appears.
let filter = strongSelf.filterSettings.filterThatDisplaysPostsWithStatus(postStatus)
if filter.filterType == strongSelf.filterSettings.currentPostListFilter().filterType {
return
}
strongSelf.promptThatPostRestoredToFilter(filter)
// Reindex the restored post in spotlight
SearchManager.shared.indexItem(apost)
}
}) { [weak self] (error) in
guard let strongSelf = self else {
return
}
if let error = error as NSError?, error.code == type(of: strongSelf).HTTPErrorCodeForbidden {
strongSelf.promptForPassword()
} else {
WPError.showXMLRPCErrorAlert(error)
}
strongSelf.recentlyTrashedPostObjectIDs.append(postObjectID)
}
}
@objc func copyPostLink(_ apost: AbstractPost) {
let pasteboard = UIPasteboard.general
guard let link = apost.permaLink else { return }
pasteboard.string = link as String
let noticeTitle = NSLocalizedString("Link Copied to Clipboard", comment: "Link copied to clipboard notice title")
let notice = Notice(title: noticeTitle, feedbackType: .success)
ActionDispatcher.dispatch(NoticeAction.dismiss) // Dismiss any old notices
ActionDispatcher.dispatch(NoticeAction.post(notice))
}
@objc func promptThatPostRestoredToFilter(_ filter: PostListFilter) {
assert(false, "You should implement this method in the subclass")
}
private func dismissAllNetworkErrorNotices() {
dismissNoNetworkAlert()
WPError.dismissNetworkingNotice()
}
// MARK: - Post Actions
@objc func createPost() {
assert(false, "You should implement this method in the subclass")
}
// MARK: - Data Sources
/// Retrieves the userID for the user of the current blog.
///
/// - Returns: the userID for the user of the current WPCom blog. If the blog is not hosted at
/// WordPress.com, `nil` is returned instead.
///
@objc func blogUserID() -> NSNumber? {
return blog.userID
}
// MARK: - Filtering
@objc func refreshAndReload() {
recentlyTrashedPostObjectIDs.removeAll()
updateSelectedFilter()
resetTableViewContentOffset()
updateAndPerformFetchRequestRefreshingResults()
}
func updateFilterWithPostStatus(_ status: BasePost.Status) {
filterSettings.setFilterWithPostStatus(status)
refreshAndReload()
WPAnalytics.track(.postListStatusFilterChanged, withProperties: propertiesForAnalytics())
}
func updateFilter(index: Int) {
filterSettings.setCurrentFilterIndex(index)
refreshAndReload()
}
func updateSelectedFilter() {
if filterTabBar.selectedIndex != filterSettings.currentFilterIndex() {
filterTabBar.setSelectedIndex(filterSettings.currentFilterIndex(), animated: false)
}
}
@objc func selectedFilterDidChange(_ filterBar: FilterTabBar) {
filterSettings.setCurrentFilterIndex(filterBar.selectedIndex)
refreshAndReload()
startGhost()
syncItemsWithUserInteraction(false)
configureInitialScrollInsets()
WPAnalytics.track(.postListStatusFilterChanged, withProperties: propertiesForAnalytics())
}
// MARK: - Search Controller Delegate Methods
func willPresentSearchController(_ searchController: UISearchController) {
WPAnalytics.track(.postListSearchOpened, withProperties: propertiesForAnalytics())
}
func willDismissSearchController(_ searchController: UISearchController) {
searchController.searchBar.text = nil
searchHelper.searchCanceled()
configureInitialScrollInsets()
}
func updateSearchResults(for searchController: UISearchController) {
resetTableViewContentOffset()
searchHelper.searchUpdated(searchController.searchBar.text)
}
// MARK: - NetworkAwareUI
func contentIsEmpty() -> Bool {
return tableViewHandler.resultsController.isEmpty()
}
func noConnectionMessage() -> String {
return ReachabilityUtils.noConnectionMessage()
}
// MARK: - Others
override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
// We override this method to dismiss any Notice that is currently being shown. If we
// don't do this, the present Notice will be shown on top of the ViewController we are
// presenting.
dismissAllNetworkErrorNotices()
super.present(viewControllerToPresent, animated: flag, completion: completion)
}
// MARK: - Accessibility
override func accessibilityPerformEscape() -> Bool {
guard searchController.isActive else {
return super.accessibilityPerformEscape()
}
searchController.isActive = false
return true
}
}
extension AbstractPostListViewController: NetworkStatusDelegate {
func networkStatusDidChange(active: Bool) {
automaticallySyncIfAppropriate()
}
}
extension AbstractPostListViewController: EditorAnalyticsProperties { }
// MARK: - NoResultsViewControllerDelegate
extension AbstractPostListViewController: NoResultsViewControllerDelegate {
func actionButtonPressed() {
WPAnalytics.track(.postListNoResultsButtonPressed, withProperties: propertiesForAnalytics())
createPost()
}
}
| gpl-2.0 | 3b2dc6dbeebc1e641b7a035d0119d688 | 35.566335 | 236 | 0.664278 | 5.510997 | false | false | false | false |
oisinlavery/HackingWithSwift | project4-oisin/project4-oisin/WebViewController.swift | 1 | 2952 | //
// ViewController.swift
// project4-oisin
//
// Created by Oisín Lavery on 10/1/15.
// Copyright © 2015 Oisín Lavery. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var progressView: UIProgressView!
var website: String? {
didSet {
self.loadWebsite()
}
}
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
override func viewDidDisappear(animated: Bool) {
webView.removeObserver(self, forKeyPath: "estimatedProgress")
}
override func viewDidLoad() {
super.viewDidLoad()
loadWebsite()
webView.allowsBackForwardNavigationGestures = true
// navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Open", style: .Plain, target: self, action: "openTapped")
let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let refresh = UIBarButtonItem(barButtonSystemItem: .Refresh, target: webView, action: "reload")
progressView = UIProgressView(progressViewStyle: .Default)
progressView.sizeToFit()
let progressButton = UIBarButtonItem(customView: progressView)
toolbarItems = [progressButton, spacer, refresh]
navigationController?.toolbarHidden = false
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "estimatedProgress" {
progressView.progress = Float(webView.estimatedProgress)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
title = webView.title
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.URL
if let host = url!.host {
if host.rangeOfString(website!) != nil {
decisionHandler(.Allow)
return
}
}
decisionHandler(.Cancel)
}
func loadWebsite() {
if let website = self.website {
let url = NSURL(string: "https://" + website)
if let webView = self.webView {
webView.loadRequest(NSURLRequest(URL: url!))
}
}
}
// func openTapped(){
// let ac = UIAlertController(title: "Open page…", message: nil, preferredStyle: .ActionSheet)
//
// ac.addAction(UIAlertAction(title: website, style: .Default, handler: openPage))
// ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
// presentViewController(ac, animated: true, completion: nil)
// }
// func openPage(action: UIAlertAction!) {
// let url = NSURL(string: "https://" + action.title!)!
// webView.loadRequest(NSURLRequest(URL: url))
// }
}
| unlicense | ce24a549622243a50101d3b29060cc98 | 27.066667 | 159 | 0.699355 | 4.583204 | false | false | false | false |
AlexZd/ApplicationSupport | ApplicationSupport/Extensions/String+Extension.swift | 1 | 2053 | //
// String+Extension.swift
// Pods
//
// Created by Alex Zdorovets on 6/7/16.
//
//
// extension String: AnyType, DatabaseRepresentable {
// //MARK: - AnyType
// public var rawType: String { return "String" }
// //MARK: - DatabaseRepresentable
// public var dbValue: AnyType { return "'\(self)'" }
// }
public extension String {
var untrim: String {
var untrimmed = ""
if !self.hasPrefix(" ") {
untrimmed = " " + self
}
if !self.hasSuffix(" ") {
untrimmed = self + " "
}
return untrimmed
}
public func wrap(char: String) -> String {
return char + self + char
}
public var embrace: String {
return "(" + self + ")"
}
}
public extension String {
var camelString: String {
return self.characters.split("_").map({ return String($0).capitalizedString }).joinWithSeparator("").lowercaseFirst
}
var sneakyString: String {
let regex = try? NSRegularExpression(pattern: "([a-z])([A-Z])", options: NSRegularExpressionOptions.AllowCommentsAndWhitespace)
let value = regex?.stringByReplacingMatchesInString(self, options: .ReportCompletion, range: NSRange(location: 0, length: self.characters.count), withTemplate: "$1_$2")
if let result = value where result.isEmpty == false {
return result.lowercaseString
}
return self
}
var first: String { return String(characters.prefix(1)) }
var last: String { return String(characters.suffix(1)) }
var uppercaseFirst: String { return first.uppercaseString + String(characters.dropFirst()) }
var lowercaseFirst: String { return first.lowercaseString + String(characters.dropFirst()) }
}
public extension String {
var quoted: String {
var result = ""
if self.hasPrefix("'") == false {
result += "'"
}
result += self
if self.hasSuffix("'") == false {
result += "'"
}
return result
}
} | mit | 8f58259d57a951a9dae80cf1bc4fc78d | 27.929577 | 176 | 0.588407 | 4.368085 | false | false | false | false |
hyperconnect/SQLite.swift | Sources/SQLite/Typed/CoreFunctions.swift | 7 | 28588 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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
private enum Function: String {
case abs
case round
case random
case randomblob
case zeroblob
case length
case lower
case upper
case ltrim
case rtrim
case trim
case replace
case substr
case like = "LIKE"
case `in` = "IN"
case glob = "GLOB"
case match = "MATCH"
case regexp = "REGEXP"
case collate = "COLLATE"
case ifnull
func infix<T>(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression<T> {
return self.rawValue.infix(lhs, rhs, wrap: wrap)
}
func wrap<T>(_ expression: Expressible) -> Expression<T> {
return self.rawValue.wrap(expression)
}
func wrap<T>(_ expressions: [Expressible]) -> Expression<T> {
return self.rawValue.wrap(", ".join(expressions))
}
}
extension ExpressionType where UnderlyingType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return Function.abs.wrap(self)
}
}
extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int?>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return Function.abs.wrap(self)
}
}
extension ExpressionType where UnderlyingType == Double {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return Function.round.wrap([self])
}
return Function.round.wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType == Double? {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return Function.round.wrap(self)
}
return Function.round.wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype == Int64 {
/// Builds an expression representing the `random` function.
///
/// Expression<Int>.random()
/// // random()
///
/// - Returns: An expression calling the `random` function.
public static func random() -> Expression<UnderlyingType> {
return Function.random.wrap([])
}
}
extension ExpressionType where UnderlyingType == Data {
/// Builds an expression representing the `randomblob` function.
///
/// Expression<Int>.random(16)
/// // randomblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `randomblob` function.
public static func random(_ length: Int) -> Expression<UnderlyingType> {
return Function.randomblob.wrap([])
}
/// Builds an expression representing the `zeroblob` function.
///
/// Expression<Int>.allZeros(16)
/// // zeroblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `zeroblob` function.
public static func allZeros(_ length: Int) -> Expression<UnderlyingType> {
return Function.zeroblob.wrap([])
}
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return Function.length.wrap(self)
}
}
extension ExpressionType where UnderlyingType == Data? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData?>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return Function.length.wrap(self)
}
}
extension ExpressionType where UnderlyingType == String {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return Function.length.wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return Function.lower.wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return Function.upper.wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
let like: Expression<Bool> = Function.like.infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool> {
return Function.glob.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
return Function.match.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool> {
return Function.regexp.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
return Function.collate.infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.ltrim.wrap(self)
}
return Function.ltrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.rtrim.wrap(self)
}
return Function.rtrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.trim.wrap([self])
}
return Function.trim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return Function.replace.wrap([self, pattern, replacement])
}
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return Function.substr.wrap([self, location])
}
return Function.substr.wrap([self, location, length])
}
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension ExpressionType where UnderlyingType == String? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String?>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return Function.length.wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String?>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return Function.lower.wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String?>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return Function.upper.wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String?>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
let like: Expression<Bool> = Function.like.infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String?>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool?> {
return Function.glob.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String?>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
return Function.match.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool?> {
return Function.regexp.infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String?>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
return Function.collate.infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String?>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.ltrim.wrap(self)
}
return Function.ltrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String?>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.rtrim.wrap(self)
}
return Function.rtrim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String?>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return Function.trim.wrap(self)
}
return Function.trim.wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String?>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return Function.replace.wrap([self, pattern, replacement])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title.substr(-100)
/// // substr("title", -100)
/// title.substr(0, length: 100)
/// // substr("title", 0, 100)
///
/// - Parameters:
///
/// - location: The substring’s start index.
///
/// - length: An optional substring length.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return Function.substr.wrap([self, location])
}
return Function.substr.wrap([self, location, length])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title[0..<100]
/// // substr("title", 0, 100)
///
/// - Parameter range: The character index range of the substring.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension Collection where Iterator.Element : Value {
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element>) -> Expression<Bool> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return Function.in.infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String?>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element?>) -> Expression<Bool?> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return Function.in.infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
}
extension String {
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = "[email protected]"
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // '[email protected]' LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return Function.like.infix(self, pattern)
}
let like: Expression<Bool> = Function.like.infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let name = Expression<String?>("name")
/// name ?? "An Anonymous Coward"
/// // ifnull("name", 'An Anonymous Coward')
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback value for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: V) -> Expression<V> {
return Function.ifnull.wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V>) -> Expression<V> {
return Function.ifnull.wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String?>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V?>) -> Expression<V> {
return Function.ifnull.wrap([optional, defaultValue])
}
| mit | b10a47e7ba549620c8414d18625a7ba4 | 34.910804 | 110 | 0.597271 | 4.292687 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Stereo Panning.xcplaygroundpage/Contents.swift | 1 | 979 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Stereo Panning
//: Panning is a basic operation that is essential to mixing and direction
//: perception and it couldn't be easier with AKPanner.
import AudioKitPlaygrounds
import AudioKit
//: Set up the audio player
let file = try AKAudioFile(readFileName: "drumloop.wav")
let player = try AKAudioPlayer(file: file)
player.looping = true
//: Route the audio player through the panner
var panner = AKPanner(player)
//: Adjust the pan to smoothly cycle left and right over time
var time = 0.0
let timeStep = 0.05
let timer = AKPeriodicFunction(every: timeStep) {
panner.pan = sin(time)
time += timeStep
}
AudioKit.output = panner
AudioKit.start(withPeriodicFunctions: timer)
player.play()
timer.start()
timer.sporth
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | 0219acc5090e4ee58043896e64bae6b5 | 25.459459 | 74 | 0.730337 | 3.680451 | false | false | false | false |
anishathalye/skipchat | Models/Message.swift | 1 | 896 | //
// SkipChat.swift
// SkipChat
//
// Created by Katie Siegel on 1/18/15.
// Copyright (c) 2015 SkipChat. All rights reserved.
//
import Foundation
import CoreData
class Message: NSManagedObject {
@NSManaged var outgoing: NSNumber
@NSManaged var peer: String
@NSManaged var text: String
@NSManaged var publicKey: String
@NSManaged var contactDate: NSDate
class func createInManagedObjectContext(moc: NSManagedObjectContext, peer: String, publicKey: String, text: String, outgoing: Bool, contactDate: NSDate) -> Message {
let newItem = NSEntityDescription.insertNewObjectForEntityForName("Message", inManagedObjectContext: moc) as Message
newItem.peer = peer
newItem.publicKey = publicKey
newItem.text = text
newItem.outgoing = outgoing
newItem.contactDate = contactDate
return newItem
}
}
| mit | 4775cf09122c5635c7031841be09f7ba | 27.903226 | 169 | 0.698661 | 4.715789 | false | false | false | false |
edwardaux/DateTimeKit | DateTimeKit/Duration.swift | 1 | 4959 | //
// Duration.swift
// DateTimeKit
//
// Created by Craig Edwards
// Copyright (c) 2015 Craig Edwards. All rights reserved.
//
import Foundation
/**
A duration is a period of time that can unequivocably be measured in seconds (or fractions thereof).
For example, 2 hours can easily be expressed as a `Duration`. However, 2 months *cannot* as there is
no common definition of the length of a month (ie. it could be 28, 29, 30 or 31 days). If you want to
represent these more general temporal concepts, you can use a `Period` object instead.
Note, a duration (like `NSDate` before it) conveniently pretends that leap seconds don't exist.
*/
// MARK: - Duration
public struct Duration {
public static let HoursPerDay = 24
public static let DaysPerWeek = 7
public static let MinutesPerHour = 60
public static let MinutesPerDay = MinutesPerHour * HoursPerDay
public static let SecondsPerMinute = 60
public static let SecondsPerHour = SecondsPerMinute * MinutesPerHour
public static let SecondsPerDay = SecondsPerHour * HoursPerDay
public static let MillisPerDay = SecondsPerDay * 1_000
public static let MicrosPerDay = SecondsPerDay * 1_000_000
public static let NanosPerSecond = 1_000_000_000
public static let NanosPerMinute = NanosPerSecond * SecondsPerMinute
public static let NanosPerHour = NanosPerMinute * MinutesPerHour
public static let NanosPerDay = NanosPerHour * HoursPerDay
/** The length of this duation in seconds. */
public let seconds: Double
/**
Constructs a `Duration` of a specified length
- parameter seconds: The length of the duration. Can be negative or positive.
*/
public init(_ seconds: Double) {
self.seconds = seconds
}
/**
Constructs a `Duration` of a specified length
- parameter seconds: The length of the duration. Can be negative or positive.
*/
public init(_ seconds: Int) {
self.init(Double(seconds))
}
/**
Constructs a `Duration` that represents the difference between two instants.
- parameter startInstant: The starting instant
- parameter endInstant: The ending instant
*/
public init(_ startInstant: Instant, _ endInstant: Instant) {
self.init(endInstant.minus(startInstant).seconds)
}
/**
Adds another duration to this duration and returns a new object representing the new duration.
If a negative duration is passed, the new duration will be shorter than the current one.
Also available by the `+` operator.
- parameter duration: The duration to be added
- returns: A new duration that includes the passed duration
*/
public func plus(duration: Duration) -> Duration {
return Duration(self.seconds + duration.seconds)
}
/**
Subtracts another duration from this duration and returns a new object representing the new duration.
If a negative duration is passed, the new duration will be longer than the current one.
Also available by the `+` operator.
- parameter duration: The duration to be subtracted
- returns: A new duration that includes the passed duration
*/
public func minus(duration: Duration) -> Duration {
return Duration(self.seconds - duration.seconds)
}
}
// MARK: - Printable protocol
extension Duration : CustomStringConvertible {
public var description: String {
return "\(self.seconds) seconds"
}
}
// MARK: - DebugPrintable protocol
extension Duration : CustomDebugStringConvertible {
public var debugDescription: String {
return self.description
}
}
// MARK: - Comparable protocol
extension Duration : Comparable {}
public func ==(lhs: Duration, rhs: Duration) -> Bool {
return lhs.seconds == rhs.seconds
}
public func <(lhs: Duration, rhs: Duration) -> Bool {
return lhs.seconds < rhs.seconds
}
// MARK: - Operators
public func + (lhs: Duration, rhs: Duration) -> Duration {
return lhs.plus(rhs)
}
public func - (lhs: Duration, rhs: Duration) -> Duration {
return lhs.minus(rhs)
}
// MARK: - Int and Double extensions
public extension Int {
var milliseconds: Duration {
return Duration(Double(self) / 1000.0)
}
var seconds: Duration {
return Duration(self)
}
var minutes: Duration {
return Duration(self * Duration.SecondsPerMinute)
}
var hours: Duration {
return Duration(self * Duration.SecondsPerHour)
}
var days: Duration {
return Duration(self * Duration.SecondsPerDay)
}
var weeks: Duration {
return Duration(self * Duration.SecondsPerDay * Duration.DaysPerWeek)
}
}
public extension Double {
var milliseconds: Duration {
return Duration(self / 1000.0)
}
var seconds: Duration {
return Duration(self)
}
var minutes: Duration {
return Duration(self * Double(Duration.SecondsPerMinute))
}
var hours: Duration {
return Duration(self * Double(Duration.SecondsPerHour))
}
var days: Duration {
return Duration(self * Double(Duration.SecondsPerDay))
}
var weeks: Duration {
return Duration(self * Double(Duration.SecondsPerDay * Duration.DaysPerWeek))
}
}
| mit | c4661afd97e353c0243604516f6d6dc0 | 26.703911 | 102 | 0.728978 | 3.829344 | false | false | false | false |
wackosix/WSNetEaseNews | NetEaseNews/Classes/External/PhotoBrowser/Frameworks/NVActivityIndicatorView/NVActivityIndicatorView.swift | 1 | 6547 | //
// NVActivityIndicatorView.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/21/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
public enum NVActivityIndicatorType {
case Blank
case BallPulse
case BallGridPulse
case BallClipRotate
case SquareSpin
case BallClipRotatePulse
case BallClipRotateMultiple
case BallPulseRise
case BallRotate
case CubeTransition
case BallZigZag
case BallZigZagDeflect
case BallTrianglePath
case BallScale
case LineScale
case LineScaleParty
case BallScaleMultiple
case BallPulseSync
case BallBeat
case LineScalePulseOut
case LineScalePulseOutRapid
case BallScaleRipple
case BallScaleRippleMultiple
case BallSpinFadeLoader
case LineSpinFadeLoader
case TriangleSkewSpin
case Pacman
case BallGridBeat
case SemiCircleSpin
case BallRotateChase
private func animation() -> NVActivityIndicatorAnimationDelegate {
switch self {
case .Blank:
return NVActivityIndicatorAnimationBlank()
case .BallPulse:
return NVActivityIndicatorAnimationBallPulse()
case .BallGridPulse:
return NVActivityIndicatorAnimationBallGridPulse()
case .BallClipRotate:
return NVActivityIndicatorAnimationBallClipRotate()
case .SquareSpin:
return NVActivityIndicatorAnimationSquareSpin()
case .BallClipRotatePulse:
return NVActivityIndicatorAnimationBallClipRotatePulse()
case .BallClipRotateMultiple:
return NVActivityIndicatorAnimationBallClipRotateMultiple()
case .BallPulseRise:
return NVActivityIndicatorAnimationBallPulseRise()
case .BallRotate:
return NVActivityIndicatorAnimationBallRotate()
case .CubeTransition:
return NVActivityIndicatorAnimationCubeTransition()
case .BallZigZag:
return NVActivityIndicatorAnimationBallZigZag()
case .BallZigZagDeflect:
return NVActivityIndicatorAnimationBallZigZagDeflect()
case .BallTrianglePath:
return NVActivityIndicatorAnimationBallTrianglePath()
case .BallScale:
return NVActivityIndicatorAnimationBallScale()
case .LineScale:
return NVActivityIndicatorAnimationLineScale()
case .LineScaleParty:
return NVActivityIndicatorAnimationLineScaleParty()
case .BallScaleMultiple:
return NVActivityIndicatorAnimationBallScaleMultiple()
case .BallPulseSync:
return NVActivityIndicatorAnimationBallPulseSync()
case .BallBeat:
return NVActivityIndicatorAnimationBallBeat()
case .LineScalePulseOut:
return NVActivityIndicatorAnimationLineScalePulseOut()
case .LineScalePulseOutRapid:
return NVActivityIndicatorAnimationLineScalePulseOutRapid()
case .BallScaleRipple:
return NVActivityIndicatorAnimationBallScaleRipple()
case .BallScaleRippleMultiple:
return NVActivityIndicatorAnimationBallScaleRippleMultiple()
case .BallSpinFadeLoader:
return NVActivityIndicatorAnimationBallSpinFadeLoader()
case .LineSpinFadeLoader:
return NVActivityIndicatorAnimationLineSpinFadeLoader()
case .TriangleSkewSpin:
return NVActivityIndicatorAnimationTriangleSkewSpin()
case .Pacman:
return NVActivityIndicatorAnimationPacman()
case .BallGridBeat:
return NVActivityIndicatorAnimationBallGridBeat()
case .SemiCircleSpin:
return NVActivityIndicatorAnimationSemiCircleSpin()
case .BallRotateChase:
return NVActivityIndicatorAnimationBallRotateChase()
}
}
}
public class NVActivityIndicatorView: UIView {
private static let DEFAULT_TYPE: NVActivityIndicatorType = .Pacman
private static let DEFAULT_COLOR = UIColor.whiteColor()
private static let DEFAULT_SIZE: CGSize = CGSize(width: 40, height: 40)
public var type: NVActivityIndicatorType
public var color: UIColor
public var nvSize: CGSize
public var animating: Bool = false
public var hidesWhenStopped: Bool = true
/**
Create a activity indicator view with default type, color and size
This is used by storyboard to initiate the view
- Default type is pacman\n
- Default color is white\n
- Default size is 40
- parameter decoder:
- returns: The activity indicator view
*/
required public init?(coder aDecoder: NSCoder) {
self.type = NVActivityIndicatorView.DEFAULT_TYPE
self.color = NVActivityIndicatorView.DEFAULT_COLOR
self.nvSize = NVActivityIndicatorView.DEFAULT_SIZE
super.init(coder: aDecoder);
super.backgroundColor = UIColor.clearColor()
}
/**
Create a activity indicator view with specified type, color, size and size
- parameter frame: view's frame
- parameter type: animation type, value of NVActivityIndicatorType enum. Default type is pacman.
- parameter color: color of activity indicator view. Default color is white.
- parameter size: actual size of animation in view. Default size is 40
- returns: The activity indicator view
*/
public init(frame: CGRect, type: NVActivityIndicatorType = DEFAULT_TYPE, color: UIColor = DEFAULT_COLOR, size: CGSize = DEFAULT_SIZE) {
self.type = type
self.color = color
self.nvSize = size
super.init(frame: frame)
}
/**
Start animation
*/
public func startAnimation() {
if hidesWhenStopped && hidden {
hidden = false
}
if (self.layer.sublayers == nil) {
setUpAnimation()
}
self.layer.speed = 1
self.animating = true
}
/**
Stop animation
*/
public func stopAnimation() {
self.layer.speed = 0
self.animating = false
if hidesWhenStopped && !hidden {
hidden = true
}
}
// MARK: Privates
private func setUpAnimation() {
let animation: protocol<NVActivityIndicatorAnimationDelegate> = self.type.animation()
self.layer.sublayers = nil
animation.setUpAnimationInLayer(self.layer, size: self.nvSize, color: self.color)
}
}
| mit | b46b8d5423b4a4b1ffe00c41b24e0864 | 33.277487 | 139 | 0.674966 | 5.946412 | false | false | false | false |
djflsdl08/BasicIOS | FoodTracker/FoodTracker/Meal.swift | 1 | 1926 | //
// Meal.swift
// FoodTracker
//
// Created by 김예진 on 2017. 10. 18..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
import os.log
class Meal : NSObject, NSCoding {
//MARK : Properties
var name : String
var photo : UIImage?
var rating : Int
struct PropertyKey {
static let name = "name"
static let photo = "photo"
static let rating = "rating"
}
//MARK : Archiving Paths
static let DocumentsDirectory = FileManager().urls(
for:.documentDirectory,
in : .userDomainMask
).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("meals")
//MARK : Initialization
init?(name : String, photo : UIImage?, rating : Int) {
/*
if name.isEmpty || rating < 0 {
return nil
}*/
guard !name.isEmpty else { // The name must not be empty
return nil
}
guard (rating >= 0) && (rating <= 5) else {
return nil
}
self.name = name
self.photo = photo
self.rating = rating
}
//MARK : NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey : PropertyKey.name)
aCoder.encode(photo, forKey : PropertyKey.photo)
aCoder.encode(rating, forKey : PropertyKey.rating)
}
required convenience init?(coder aDecoder : NSCoder) {
guard let name = aDecoder.decodeObject(forKey : PropertyKey.name) as? String else {
os_log("Unable to decode the name for a Meal object", log : OSLog.default, type : .debug)
return nil
}
let photo = aDecoder.decodeObject(forKey:PropertyKey.photo) as? UIImage
let rating = aDecoder.decodeInteger(forKey:PropertyKey.rating)
self.init(name : name, photo : photo, rating : rating)
}
}
| mit | 1164abc25e7c64339cd6c66928886462 | 27.191176 | 101 | 0.581116 | 4.5 | false | false | false | false |
tomasharkema/R.swift | Sources/RswiftCore/Generators/StringsStructGenerator.swift | 1 | 12829 | //
// StringsStructGenerator.swift
// R.swift
//
// Created by Nolan Warner on 2016/02/23.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
struct StringsStructGenerator: ExternalOnlyStructGenerator {
private let localizableStrings: [LocalizableStrings]
private let developmentLanguage: String
init(localizableStrings: [LocalizableStrings], developmentLanguage: String) {
self.localizableStrings = localizableStrings
self.developmentLanguage = developmentLanguage
}
func generatedStruct(at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> Struct {
let structName: SwiftIdentifier = "string"
let qualifiedName = prefix + structName
let localized = localizableStrings.grouped(by: { $0.filename })
let groupedLocalized = localized.grouped(bySwiftIdentifier: { $0.0 })
groupedLocalized.printWarningsForDuplicatesAndEmpties(source: "strings file", result: "file")
let structs = groupedLocalized.uniques.compactMap { arg -> Struct? in
let (key, value) = arg
return stringStructFromLocalizableStrings(filename: key, strings: value, at: externalAccessLevel, prefix: qualifiedName)
}
return Struct(
availables: [],
comments: ["This `\(qualifiedName)` struct is generated, and contains static references to \(groupedLocalized.uniques.count) localization tables."],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: structName),
implements: [],
typealiasses: [],
properties: [],
functions: [],
structs: structs,
classes: [],
os: []
)
}
private func stringStructFromLocalizableStrings(filename: String, strings: [LocalizableStrings], at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> Struct? {
let structName = SwiftIdentifier(name: filename)
let qualifiedName = prefix + structName
let params = computeParams(filename: filename, strings: strings)
return Struct(
availables: [],
comments: ["This `\(qualifiedName)` struct is generated, and contains static references to \(params.count) localization keys."],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: structName),
implements: [],
typealiasses: [],
properties: params.map { stringLet(values: $0, at: externalAccessLevel) },
functions: params.map { stringFunction(values: $0, at: externalAccessLevel) },
structs: [],
classes: [],
os: []
)
}
// Ahem, this code is a bit of a mess. It might need cleaning up... ;-)
// Maybe when we pick up this issue: https://github.com/mac-cain13/R.swift/issues/136
private func computeParams(filename: String, strings: [LocalizableStrings]) -> [StringValues] {
var allParams: [String: [(Locale, String, [StringParam])]] = [:]
let primaryLanguage: String
let primaryKeys: Set<String>?
let bases = strings.filter { $0.locale.isBase }
let developments = strings.filter { $0.locale.language == developmentLanguage }
if !bases.isEmpty {
primaryKeys = Set(bases.flatMap { $0.dictionary.keys })
primaryLanguage = "Base"
} else if !developments.isEmpty {
primaryKeys = Set(developments.flatMap { $0.dictionary.keys })
primaryLanguage = developmentLanguage
} else {
primaryKeys = nil
primaryLanguage = developmentLanguage
}
// Warnings about duplicates and empties
for ls in strings {
let filenameLocale = ls.locale.withFilename(filename)
let groupedKeys = ls.dictionary.keys.grouped(bySwiftIdentifier: { $0 })
groupedKeys.printWarningsForDuplicatesAndEmpties(source: "string", container: "in \(filenameLocale)", result: "key")
// Save uniques
for key in groupedKeys.uniques {
if let (params, commentValue) = ls.dictionary[key] {
if let _ = allParams[key] {
allParams[key]?.append((ls.locale, commentValue, params))
}
else {
allParams[key] = [(ls.locale, commentValue, params)]
}
}
}
}
// Warnings about missing translations
for (locale, lss) in strings.grouped(by: { $0.locale }) {
let filenameLocale = locale.withFilename(filename)
let sourceKeys = primaryKeys ?? Set(allParams.keys)
let missing = sourceKeys.subtracting(lss.flatMap { $0.dictionary.keys })
if missing.isEmpty {
continue
}
let paddedKeys = missing.sorted().map { "'\($0)'" }
let paddedKeysString = paddedKeys.joined(separator: ", ")
warn("Strings file \(filenameLocale) is missing translations for keys: \(paddedKeysString)")
}
// Warnings about extra translations
for (locale, lss) in strings.grouped(by: { $0.locale }) {
let filenameLocale = locale.withFilename(filename)
let sourceKeys = primaryKeys ?? Set(allParams.keys)
let usedKeys = Set(lss.flatMap { $0.dictionary.keys })
let extra = usedKeys.subtracting(sourceKeys)
if extra.isEmpty {
continue
}
let paddedKeys = extra.sorted().map { "'\($0)'" }
let paddedKeysString = paddedKeys.joined(separator: ", ")
warn("Strings file \(filenameLocale) has extra translations (not in \(primaryLanguage)) for keys: \(paddedKeysString)")
}
// Only include translation if it exists in the primary language
func includeTranslation(_ key: String) -> Bool {
if let primaryKeys = primaryKeys {
return primaryKeys.contains(key)
}
return true
}
var results: [StringValues] = []
var badFormatSpecifiersKeys = Set<String>()
let filteredSortedParams = allParams
.map { $0 }
.filter { includeTranslation($0.0) }
.sorted(by: { $0.0 < $1.0 })
// Unify format specifiers
for (key, keyParams) in filteredSortedParams {
var params: [StringParam] = []
var areCorrectFormatSpecifiers = true
for (locale, _, ps) in keyParams {
if ps.contains(where: { $0.spec == FormatSpecifier.topType }) {
let name = locale.withFilename(filename)
warn("Skipping string \(key) in \(name), not all format specifiers are consecutive")
areCorrectFormatSpecifiers = false
}
}
if !areCorrectFormatSpecifiers { continue }
for (_, _, ps) in keyParams {
if let unified = params.unify(ps) {
params = unified
}
else {
badFormatSpecifiersKeys.insert(key)
areCorrectFormatSpecifiers = false
}
}
if !areCorrectFormatSpecifiers { continue }
let vals = keyParams.map { ($0.0, $0.1) }
let values = StringValues(key: key, params: params, tableName: filename, values: vals, developmentLanguage: developmentLanguage)
results.append(values)
}
for badKey in badFormatSpecifiersKeys.sorted() {
let fewParams = allParams.filter { $0.0 == badKey }.map { $0.1 }
if let params = fewParams.first {
let locales = params.compactMap { $0.0.localeDescription }.joined(separator: ", ")
warn("Skipping string for key \(badKey) (\(filename)), format specifiers don't match for all locales: \(locales)")
}
}
return results
}
private func stringLet(values: StringValues, at externalAccessLevel: AccessLevel) -> Let {
let escapedKey = values.key.escapedStringLiteral
let locales = values.values
.map { $0.0 }
.compactMap { $0.localeDescription }
.map { "\"\($0)\"" }
.joined(separator: ", ")
return Let(
comments: values.comments,
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: values.key),
typeDefinition: .inferred(Type.StringResource),
value: "Rswift.StringResource(key: \"\(escapedKey)\", tableName: \"\(values.tableName)\", bundle: R.hostingBundle, locales: [\(locales)], comment: nil)"
)
}
private func stringFunction(values: StringValues, at externalAccessLevel: AccessLevel) -> Function {
if values.params.isEmpty {
return stringFunctionNoParams(for: values, at: externalAccessLevel)
}
else {
return stringFunctionParams(for: values, at: externalAccessLevel)
}
}
private func stringFunctionNoParams(for values: StringValues, at externalAccessLevel: AccessLevel) -> Function {
return Function(
availables: [],
comments: values.comments,
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: values.key),
generics: nil,
parameters: [
Function.Parameter(
name: "preferredLanguages",
type: Type._Array.withGenericArgs([Type._String]).asOptional(),
defaultValue: "nil"
)
],
doesThrow: false,
returnType: Type._String,
body: """
guard let preferredLanguages = preferredLanguages else {
return \(values.swiftCode(bundle: "hostingBundle"))
}
guard let (_, bundle) = localeBundle(tableName: "\(values.tableName)", preferredLanguages: preferredLanguages) else {
return "\(values.key.escapedStringLiteral)"
}
return \(values.swiftCode(bundle: "bundle"))
""",
os: []
)
}
private func stringFunctionParams(for values: StringValues, at externalAccessLevel: AccessLevel) -> Function {
var params = values.params.enumerated().map { arg -> Function.Parameter in
let (ix, param) = arg
let argumentLabel = param.name ?? "_"
let valueName = "value\(ix + 1)"
return Function.Parameter(name: argumentLabel, localName: valueName, type: param.spec.type)
}
let args = params.map { $0.localName ?? $0.name }.joined(separator: ", ")
let prefereredLanguages = Function.Parameter(
name: "preferredLanguages",
type: Type._Array.withGenericArgs([Type._String]).asOptional(),
defaultValue: "nil"
)
params.append(prefereredLanguages)
return Function(
availables: [],
comments: values.comments,
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: values.key),
generics: nil,
parameters: params,
doesThrow: false,
returnType: Type._String,
body: """
guard let preferredLanguages = preferredLanguages else {
let format = \(values.swiftCode(bundle: "hostingBundle"))
return String(format: format, locale: applicationLocale, \(args))
}
guard let (locale, bundle) = localeBundle(tableName: "\(values.tableName)", preferredLanguages: preferredLanguages) else {
return "\(values.key)"
}
let format = \(values.swiftCode(bundle: "bundle"))
return String(format: format, locale: locale, \(args))
""",
os: []
)
}
}
extension Locale {
func withFilename(_ filename: String) -> String {
switch self {
case .none:
return "'\(filename)'"
case .base:
return "'\(filename)' (Base)"
case .language(let language):
return "'\(filename)' (\(language))"
}
}
}
private struct StringValues {
let key: String
let params: [StringParam]
let tableName: String
let values: [(Locale, String)]
let developmentLanguage: String
func swiftCode(bundle: String) -> String {
let escapedKey = key.escapedStringLiteral
var valueArgument: String = ""
if let value = baseLanguageValue {
valueArgument = ", value: \"\(value.escapedStringLiteral)\""
}
if tableName == "Localizable" {
return "NSLocalizedString(\"\(escapedKey)\", bundle: \(bundle)\(valueArgument), comment: \"\")"
}
else {
return "NSLocalizedString(\"\(escapedKey)\", tableName: \"\(tableName)\", bundle: \(bundle)\(valueArgument), comment: \"\")"
}
}
var baseLanguageValue: String? {
return values.filter { $0.0.isBase }.map { $0.1 }.first
}
private var primaryLanguageValues: [(Locale, String)] {
return values.filter { $0.0.isBase } + values.filter { $0.0.language == developmentLanguage }
}
var comments: [String] {
var results: [String] = []
let anyNone = values.contains { $0.0.isNone }
let vs = primaryLanguageValues + values
if let (locale, value) = vs.first {
if let localeDescription = locale.localeDescription {
let str = "\(localeDescription) translation: \(value)".commentString
results.append(str)
}
else {
let str = "Value: \(value)".commentString
results.append(str)
}
}
if !anyNone {
if !results.isEmpty {
results.append("")
}
let locales = values.compactMap { $0.0.localeDescription }
results.append("Locales: \(locales.joined(separator: ", "))")
}
return results
}
}
| mit | f9210f3b5995ed19bfa077c611660cc6 | 31.894872 | 173 | 0.645023 | 4.385983 | false | false | false | false |
wolfposd/DynamicFeedback | DynamicFeedbackSheets/DynamicFeedbackSheets/Controller/StartUpViewController.swift | 1 | 2533 | //
// StartUpViewController.swift
// DynamicFeedbackSheets
//
// Created by Jan Hennings on 09/06/14.
// Copyright (c) 2014 Jan Hennings. All rights reserved.
//
import UIKit
class StartUpViewController: UIViewController, FeedbackSheetManagerDelegate, FeedbackSheetViewControllerDelegate {
// MARK: Properties
let manager = FeedbackSheetManager(baseURL: "http://beeqn.informatik.uni-hamburg.de/feedback/rest.php/")
let sheetID = "3"
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: IBActions
@IBAction func startFetch(sender: UIButton) {
manager.startFetchingSheetWithID("3")
}
// MARK: FeedbackSheetManagerDelegate
func feedbackSheetManager(manager: FeedbackSheetManager, didFinishFetchingSheet sheet: FeedbackSheet) {
performSegueWithIdentifier("presentFeedbackSheet", sender: sheet)
}
func feedbackSheetManager(manager: FeedbackSheetManager, didPostSheetWithSuccess success: Bool) {
println("Posting successful")
}
func feedbackSheetManager(manager: FeedbackSheetManager, didFailWithError error: NSError) {
println("Error (feedbackSheetManager didFailWithError) \(error)")
}
// MARK: FeedbackSheetViewControllerDelegate
func feedbackSheetViewController(controller: FeedbackSheetViewController, finishedWithResponse response: NSDictionary!) {
// next step: posting response
println("posting \(response)")
manager.postResponseWithSheetID(sheetID, response: response)
}
func feedbackSheetViewController(controller: FeedbackSheetViewController, didFailWithError error: NSError) {
// Error handling
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "presentFeedbackSheet" {
if let navigationController = segue.destinationViewController as? UINavigationController {
if let sheetViewController = navigationController.topViewController as? FeedbackSheetViewController {
sheetViewController.sheet = sender as FeedbackSheet
sheetViewController.delegate = self
}
}
}
}
}
| gpl-2.0 | 93a16f508dd09b834a87f191c2bd9642 | 32.773333 | 125 | 0.684564 | 5.435622 | false | false | false | false |
muukii/RealmDefaults | Example/Tests/TestsMyAccount.swift | 1 | 1060 | import UIKit
import XCTest
import RealmDefaults
class Tests: XCTestCase {
override func setUp() {
super.setUp()
MyAccount.purge()
}
override func tearDown() {
super.tearDown()
}
func testFirstAccess() {
XCTAssert(MyAccount.instance.name == nil, "")
XCTAssert(MyAccount.instance.age == 0, "")
XCTAssert(MyAccount.instance.phoneNumber == nil, "")
}
func testWrite() {
MyAccount.write { account in
account.name = "muukii"
account.age = 25
account.phoneNumber = "080-0000-0000"
}
XCTAssert(MyAccount.instance.name == "muukii", "")
XCTAssert(MyAccount.instance.age == 25, "")
XCTAssert(MyAccount.instance.phoneNumber == "080-0000-0000", "")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit | 8ed694d3ce72e0a362bc35866ac4864d | 23.651163 | 72 | 0.551887 | 4.774775 | false | true | false | false |
CaiMiao/CGSSGuide | DereGuide/Toolbox/ToolboxTableViewCell.swift | 1 | 993 | //
// ToolboxTableViewCell.swift
// DereGuide
//
// Created by zzk on 16/8/13.
// Copyright © 2016年 zzk. All rights reserved.
//
import UIKit
import SnapKit
class ToolboxTableViewCell: UITableViewCell {
var icon: CGSSCardIconView!
var descLabel: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
icon = CGSSCardIconView.init(frame: CGRect(x: 10, y: 10, width: 48, height: 48))
icon.isUserInteractionEnabled = false
descLabel = UILabel.init(frame: CGRect(x: 68, y: 25, width: CGSSGlobal.width - 78, height: 18))
descLabel.font = UIFont.systemFont(ofSize: 16)
descLabel.textAlignment = .left
descLabel.backgroundColor = UIColor.white
contentView.addSubview(icon)
contentView.addSubview(descLabel)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | d4ef4da0c83bfa6a4a05b18bd15a3f00 | 29 | 103 | 0.670707 | 4.285714 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Toolbox/Colleague/Composing/View/CenterWantedItemView.swift | 1 | 2850 | //
// CenterWantedItemView.swift
// DereGuide
//
// Created by zzk on 2017/8/4.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
class CenterWantedItemView: UIView {
private var cardView: CenterWantedCardView!
private var placeholderImageView: UIImageView!
private var cardPlaceholder: UIView!
private var typeIcon: UIImageView!
private(set) var cardID: Int!
private(set) var minLevel: Int!
override init(frame: CGRect) {
super.init(frame: frame)
cardView = CenterWantedCardView()
cardView.icon.isUserInteractionEnabled = false
addSubview(cardView)
cardView.snp.makeConstraints { (make) in
make.top.equalTo(2)
make.left.right.equalToSuperview()
make.height.greaterThanOrEqualTo(cardView.snp.width).offset(14.5)
}
typeIcon = UIImageView()
addSubview(typeIcon)
typeIcon.snp.makeConstraints { (make) in
make.height.width.equalTo(20)
make.top.equalTo(cardView.snp.bottom).offset(5)
make.centerX.equalToSuperview()
make.bottom.equalToSuperview()
}
cardPlaceholder = UIView()
addSubview(cardPlaceholder)
cardPlaceholder.snp.makeConstraints { (make) in
make.edges.equalTo(cardView.icon.snp.edges)
}
cardPlaceholder.layer.masksToBounds = true
cardPlaceholder.layer.cornerRadius = 4
cardPlaceholder.layer.borderWidth = 1 / Screen.scale
cardPlaceholder.layer.borderColor = UIColor.border.cgColor
placeholderImageView = UIImageView(image: #imageLiteral(resourceName: "436-plus").withRenderingMode(.alwaysTemplate))
cardPlaceholder.addSubview(placeholderImageView)
placeholderImageView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.height.width.equalToSuperview().dividedBy(3)
}
placeholderImageView.tintColor = .lightGray
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(with liveType: CGSSLiveTypes) {
typeIcon.image = liveType.icon
}
func setupWith(cardID: Int, minLevel: Int = 0) {
self.cardID = cardID
self.minLevel = minLevel
if cardID != 0 {
showsPlaceholder = false
cardView.setupWith(cardID: cardID, minLevel: minLevel)
} else {
showsPlaceholder = true
}
}
var showsPlaceholder: Bool = true {
didSet {
cardPlaceholder.isHidden = !showsPlaceholder
cardView.isHidden = showsPlaceholder
bringSubview(toFront: showsPlaceholder ? cardPlaceholder : cardView)
}
}
}
| mit | 445eeb3876545cfa06517091e16d3383 | 30.988764 | 125 | 0.631542 | 4.809122 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.