repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kingslay/KSSwiftExtension
|
refs/heads/master
|
Core/Source/KSDebugStatusBar.swift
|
mit
|
1
|
//
// KSDebugStatusBar.swift
// KSSwiftExtension
//
// Created by king on 16/3/29.
// Copyright © 2016年 king. All rights reserved.
//
import UIKit
public class KSDebugStatusBar: UIWindow {
static let shareInstance = KSDebugStatusBar()
public static func post(message: String) {
shareInstance.post(message)
}
var messageQueue = [String]()
var messageLabel: UILabel
private init() {
let statusBarFrame = CGRect(x: 0,y: 0,width: KS.SCREEN_WIDTH,height: 20)
self.messageLabel = UILabel(frame: statusBarFrame)
super.init(frame: statusBarFrame)
self.windowLevel = UIWindowLevelStatusBar + 1
self.backgroundColor = UIColor.clearColor();
self.userInteractionEnabled = false
self.messageLabel.font = UIFont.systemFontOfSize(13)
self.messageLabel.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
self.messageLabel.alpha = 0
self.messageLabel.textAlignment = .Center;
self.messageLabel.textColor = UIColor.whiteColor()
self.addSubview(self.messageLabel)
var keyWindow = UIApplication.sharedApplication().keyWindow
if keyWindow == nil, let delegate = UIApplication.sharedApplication().delegate {
keyWindow = delegate.window!
}
self.makeKeyAndVisible()
keyWindow?.makeKeyAndVisible()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func post(message: String) {
self.messageQueue.append(message)
if self.messageQueue.count == 1 {
self.showNextMessage()
}
}
private func showNextMessage() {
self.messageLabel.text = self.messageQueue.first
self.messageLabel.alpha = 1
self.hidden = false
let transition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionFade
self.messageLabel.layer.addAnimation(transition, forKey: nil)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
self.messageQueue.removeFirst()
if self.messageQueue.count == 0 {
self.messageLabel.alpha = 0
self.hidden = true
}else{
self.showNextMessage()
}
}
}
}
|
f540c9a3fea35a950d9b7493841b503e
| 33.955882 | 110 | 0.637779 | false | false | false | false |
WeltN24/Carlos
|
refs/heads/master
|
Tests/CarlosTests/StringConvertibleTests.swift
|
mit
|
1
|
import Foundation
import Nimble
import Quick
import Carlos
final class StringConvertibleTests: QuickSpec {
override func spec() {
describe("String values") {
let value = "this is the value"
it("should return self") {
expect(value.toString()) == value
}
}
describe("NSString values") {
let value = "this is the value"
it("should return self") {
expect(value.toString()) == value
}
}
}
}
|
726c0e41979de0235201f75d45b6e099
| 16.846154 | 47 | 0.599138 | false | false | false | false |
cenfoiOS/ImpesaiOSCourse
|
refs/heads/master
|
Translate/Translate/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// Translate
//
// Created by Cesar Brenes on 6/1/17.
// Copyright © 2017 César Brenes Solano. All rights reserved.
//
import Foundation
struct Constants{
static let API_KEY = "NXrPcrRP7ImshGC3WtYKTWhgLT6Hp1ITgE0jsncYik9Kxxjjhm"
static let API_URL = "https://gybra-trans-lator.p.mashape.com/"
static let DIRS_KEY = "dirs"
static let LANGUAGE_KEY = "langs"
static let LANGUAGES_ARRAY_KEY = "LANGUAGES_ARRAY_KEY"
static let GET_LANGUAGES_NOTIFICATION = "GET_LANGUAGES_NOTIFICATION"
static let ERROR_FOUND_NOTIFICATION = "ERROR_FOUND_NOTIFICATION"
static let GET_TRANSLATE_NOTIFICATION = "GET_TRANSLATE_NOTIFICATION"
static let TRANSLATE_RESULT_KEY = "TRANSLATE_RESULT_KEY"
static let TEXT_TRANSLATED_KEY = "text"
static let API_HEADER_KEY = "X-Mashape-Key"
enum LanguageType: Int {
case origin = 0, destination
}
}
|
74bf9dc21489ac927721d2e3756cc09b
| 29.3 | 77 | 0.705171 | false | false | false | false |
brandhill/WeatherMap
|
refs/heads/master
|
WeatherAroundUs/WeatherAroundUs/DigestWeatherView.swift
|
apache-2.0
|
3
|
//
// DigestWeatherView.swift
// WeatherAroundUs
//
// Created by Wang Yu on 4/24/15.
// Copyright (c) 2015 Kedan Li. All rights reserved.
//
import UIKit
import Spring
import Shimmer
class DigestWeatherView: DesignableView {
@IBOutlet var line: UIImageView!
var parentController: CityDetailViewController!
var tempRange: SpringLabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup(forecastInfos: [[String: AnyObject]]) {
let todayTemp = forecastInfos[0]["temp"] as! [String: AnyObject]
let todayWeather = ((WeatherInfo.citiesAroundDict[WeatherInfo.currentCityID] as! [String : AnyObject])["weather"] as! [AnyObject])[0] as! [String : AnyObject]
let beginY = line.frame.origin.y + line.frame.height
let beginX = line.frame.origin.x
//digest icon
let weatherIcon = SpringImageView(frame: CGRectMake(beginX + line.frame.width / 12, beginY + 8, self.frame.height * 2 / 3, self.frame.height * 2 / 3))
weatherIcon.image = UIImage(named: todayWeather["icon"] as! String)
self.addSubview(weatherIcon)
weatherIcon.animation = "zoomIn"
weatherIcon.animate()
//digest current weather condition
let labelView = UIView(frame: CGRectMake(beginX + line.frame.width / 2, beginY, self.frame.width / 2, self.frame.height))
self.addSubview(labelView)
let shimmerWeatherDescription = FBShimmeringView(frame: CGRectMake(0, 26, line.frame.width / 2, 30))
labelView.addSubview(shimmerWeatherDescription)
let cityDisplay = SpringLabel(frame: CGRectMake(0, 0, line.frame.width / 2, 30))
cityDisplay.text = (WeatherInfo.citiesAroundDict[parentController.cityID] as! [String: AnyObject])["name"]! as? String
cityDisplay.textAlignment = .Left
cityDisplay.font = UIFont(name: "AvenirNext-Medium", size: 18)
cityDisplay.adjustsFontSizeToFitWidth = true
cityDisplay.textColor = UIColor.whiteColor()
shimmerWeatherDescription.addSubview(cityDisplay)
cityDisplay.animation = "fadeIn"
cityDisplay.delay = 0.1
cityDisplay.animate()
shimmerWeatherDescription.contentView = cityDisplay
shimmerWeatherDescription.shimmering = true
//digest tempature range for the day
let shimmerTempRange = FBShimmeringView(frame: CGRectMake(0, self.frame.height / 5 - 5, line.frame.width / 2, self.frame.height / 2))
labelView.addSubview(shimmerTempRange)
tempRange = SpringLabel(frame: CGRectMake(0, 0, line.frame.width / 2, self.frame.height / 2))
let minTemp = todayTemp["min"]!.doubleValue
let maxTemp = todayTemp["max"]!.doubleValue
tempRange.font = UIFont(name: "AvenirNext-Regular", size: 24)
tempRange.adjustsFontSizeToFitWidth = true
tempRange.textAlignment = .Left
tempRange.textColor = UIColor.whiteColor()
let unit = parentController.unit.stringValue
tempRange.text = "\(WeatherMapCalculations.kelvinConvert(minTemp, unit: parentController.unit))° ~ \(WeatherMapCalculations.kelvinConvert(maxTemp, unit: parentController.unit))°\(unit)"
shimmerTempRange.addSubview(tempRange)
tempRange.animation = "fadeIn"
tempRange.delay = 0.2
tempRange.animate()
shimmerTempRange.contentView = tempRange
shimmerTempRange.shimmering = true
//digest the main weather of the day
let mainWeather = SpringLabel(frame: CGRectMake(0, beginY + self.frame.height / 5 + 18 - beginY, line.frame.width / 2 + 10, self.frame.height / 2))
mainWeather.font = UIFont(name: "AvenirNext-Regular", size: 14)
mainWeather.textAlignment = .Left
mainWeather.textColor = UIColor.whiteColor()
mainWeather.text = (todayWeather["description"] as? String)?.capitalizedString
labelView.addSubview(mainWeather)
mainWeather.animation = "fadeIn"
mainWeather.delay = 0.3
mainWeather.animate()
}
func reloadTemperature(forecastInfos: [[String: AnyObject]]) {
let todayTemp = forecastInfos[0]["temp"] as! [String: AnyObject]
let minTemp = todayTemp["min"]!.doubleValue
let maxTemp = todayTemp["max"]!.doubleValue
var unit = parentController.unit.stringValue
tempRange.text = "\(WeatherMapCalculations.kelvinConvert(minTemp, unit: parentController.unit))° ~ \(WeatherMapCalculations.kelvinConvert(maxTemp, unit: parentController.unit))°\(unit)"
setNeedsDisplay()
}
}
|
77f31eef96fb663d6c572d56eb5d78aa
| 47.421053 | 193 | 0.681304 | false | false | false | false |
zxpLearnios/MyProject
|
refs/heads/master
|
test_projectDemo1/HUD/MyProgressHUD.swift
|
mit
|
1
|
//
// MyProgressHUD.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/7/14.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// 1. 此弹出框, 可以在任何地方初始化,可以在任何地方使用,包括didFinishLaunching里。但在didFinishLaunching使用第一方式且调用的是showProgressImage方法,则当lanunchImage加载完毕后,虽然进度图片消失了但主窗口仍不能与用户交互,故须在合适的时候主动调用dismiss方法, 调用的是其他展示方法时,没有任何问题,因为它们都会自动消失,但是总共需要2s,之后窗口才可与用户交互。外部无须在主动调用dismiss了;故第一种方式不如第二种好。
// 2. isShow, 控制消失动画完成后才可再次显示,避免不停地显示
// 3. 并行队列同步操作:和主线程同步执行且不会阻塞主线程
// 4. 默认的是第一种方式
// 5. swift已经不远onceToken来创建单例了,直接使用全局let量即可
// 6. 只有展示进度图片即showProgressImage时不会自动消失,其余展示情况全都自动消失. 即showProgressImage后,需要用户自行调用dismiss,并看好使用的是第一还是第二种方式. 外部若无使用show....,则不要调用dismiss,不会出错但是会展示缩放过程了,不好。
// 7. 在展示过程中,window皆不可与用户交互,展示结束后,window才可以与用户交互
import UIKit
class MyProgressHUD: NSObject {
private let view = UIView(), titleLab = UILabel(), imgV = UIImageView(), alertWindow = UIWindow.init(frame: kbounds)
private let width:CGFloat = 100, fontSize:CGFloat = 15, animateTime = 0.25, aniKey = "aniKey_rotation_forImageView"
private var imgWH:CGFloat = 0, ani:CAKeyframeAnimation!
private var isFirstMethod = false // 是否是第一种方式
private var isShow = false // 在 doShowAnimate 和 doDismissAnimate里使用
private var isImgVHidden = false // 用此量来使展示成功的图片文字、失败时的图片文字也自动消失, 在doDismissAnimate里使用
// 当其指向类对象时,并不会添加类对象的引用计数;
// 当其指向的类对象不存在时,ARC会自动把weak reference设置为nil;
// unowned 不会引起对象引用计数的变化, 不会将之置为nil
weak var superView:UIView!
/** 第一种方式. 外部传入view非window,只在当前view中显示谈出框 */
// 重写父类方法
private override init (){
super.init()
}
/** -1. 外部的初始化方法,用于第一种方式 */
convenience init(superView:UIView) {
self.init()
self.superView = superView
doInit()
}
// 用于第一种方式的。
private func doInit(){
// 0.
isFirstMethod = true
// 1.
superView.addSubview(view)
// 这段没用
// let frontToBackWindows = UIApplication.sharedApplication().windows.reverse()
//
// for window in frontToBackWindows {
// if window.windowLevel == UIWindowLevelNormal {
// window.addSubview(view)
// }
// }
view.frame = CGRect(x: UIScreen.main.bounds.width/2 - width/2, y: UIScreen.main.bounds.height/2 - width/2, width: width, height: width)
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 10
// 2.
view.addSubview(imgV)
imgWH = width * 4 / 5
imgV.center = CGPoint(x: width/2, y: 10 + imgWH/2)
imgV.bounds = CGRect(x: 0, y: 0, width: imgWH, height: imgWH)
imgV.image = UIImage(named: "progress_circular") // progress_circular 实际上是一个PDF,PDF竟然也可以这样用
// 3.
view.addSubview(titleLab)
titleLab.textAlignment = .center
titleLab.textColor = UIColor.red
titleLab.font = UIFont.systemFont(ofSize: fontSize)
titleLab.numberOfLines = 0
// titleLab.text = "最终加载最终加载最终加载"
// let bestSize = titleLab.sizeThatFits(CGSizeMake(width, width))
// titleLab.frame = CGRectMake(0, imgV.frame.maxY + 10, width, bestSize.height)
//
// // 4.
// var gap:CGFloat = 0
// // 此时需增加view的高度
// if titleLab.frame.maxY > width {
// gap = titleLab.frame.maxY - width
//
// }
// view.height += gap
// 5.
// doShowAnimate(true, isKeyWindowEnable: false)
}
/** 0. 第二种方式. 外部无须传参,此弹出框加在alertWindow上,此弹出框在当前window的所有页面都展示直至弹出框自己消失 */
private static var obj = MyProgressHUD()
class var sharedInstance: MyProgressHUD {
return MyProgressHUD.obj
}
// 用于第二种方式的,外部必须调用此法,然后才可以使用此弹出框
func hudInit() {
// 0.
isFirstMethod = false
// 此时 此window在kwyWindow上,若要kwyWindow不能交互则必须设置kwyWindow不能交互
alertWindow.backgroundColor = UIColor.clear
alertWindow.windowLevel = UIWindowLevelAlert // 最高级别
alertWindow.addSubview(view)
alertWindow.makeKeyAndVisible()
view.frame = CGRect(x: UIScreen.main.bounds.width/2 - width/2, y: UIScreen.main.bounds.height/2 - width/2, width: width, height: width)
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 10
// 2.
view.addSubview(imgV)
imgWH = width * 4 / 5
imgV.center = CGPoint(x: width/2, y: imgWH/2)
imgV.bounds = CGRect(x:0, y:0, width:imgWH, height:imgWH)
imgV.image = UIImage(named: "progress_circular")
// 3.
view.addSubview(titleLab)
titleLab.textAlignment = .center
titleLab.textColor = UIColor.red
titleLab.font = UIFont.systemFont(ofSize: fontSize)
titleLab.numberOfLines = 0
}
// ------------------------ 外部调用 ------------------------ //
/**
1. 只展示提示信息, 此时字体变大了、字居view的中间显示、隐藏了图片。展示完后自动消失
*/
func showPromptText(_ text:String) {
// 全局并行队列(同步、异步都在主线程中,前者不会死锁)
let que = DispatchQueue.global()
que.sync(execute: { // 同步操作\同步任务
self.imgV.isHidden = true
self.titleLab.isHidden = false
// 以使其在缩小动画后自动消失
isImgVHidden = true
self.titleLab.font = UIFont.systemFont(ofSize: self.fontSize + 10)
self.titleLab.text = text
let bestSize = self.titleLab.sizeThatFits(CGSize(width: kwidth - 20, height: CGFloat(MAXFLOAT)))
self.view.height = bestSize.height + 20
self.view.width = bestSize.width + 20
self.titleLab.center = CGPoint(x: self.view.width / 2, y: self.view.height / 2)
self.titleLab.bounds = CGRect(x: 0, y: 0, width: bestSize.width, height: bestSize.height)
// self.imgV.setNeedsLayout()
// self.view.setNeedsLayout()
// self.titleLab.setNeedsLayout()
})
if !isShow {
doShowAnimate(false, isKeyWindowEnable: true)
}
}
/**
2. 只展示图片, 图片居中、隐藏了titleLab,展示完后不会自动消失
*/
func showProgressImage(_ image:UIImage) {
// 和主线程同步执行且不会阻塞主线程
let que = DispatchQueue(label: "myque1", attributes: DispatchQueue.Attributes.concurrent) // 并行队列
que.sync(execute: { // 同步操作\同步任务
self.titleLab.isHidden = true
self.imgV.isHidden = false
// 以使其在 外部调用dismiss时, 执行缩小动画doDismissAnimate后, 自动消失
isImgVHidden = true
self.imgV.image = image
self.view.width = self.imgWH + 20
self.view.height = self.imgWH + 20
self.imgV.center = CGPoint(x: self.view.width/2, y: self.view.height/2)
})
if !isShow {
doShowAnimate(true, isKeyWindowEnable: false)
}
}
/**
3。成功时的图片和文字 ,展示完后自动消失
*/
func showSuccessText(_ text:String, successImage image:UIImage) {
// 和主线程同步执行且不会阻塞主线程
let que = DispatchQueue(label: "myque2", attributes: DispatchQueue.Attributes.concurrent) // 并行队列
que.sync(execute: { // 同步操作\同步任务
self.imgV.isHidden = false
self.titleLab.isHidden = false
// 以使其在缩小动画后自动消失
isImgVHidden = true
self.imgV.image = image
self.titleLab.text = text
let bestSize = self.titleLab.sizeThatFits(CGSize(width: self.width, height: self.width))
self.titleLab.frame = CGRect(x: 0, y: self.imgV.frame.maxY + 10, width: self.width, height: bestSize.height)
var gap:CGFloat = 20 // 确保顶部、底部都有间距 10
// 此时需增加view的高度
if self.titleLab.frame.maxY > self.width {
gap = self.titleLab.frame.maxY - self.width + 10
}
self.view.height += gap
})
if !isShow {
doShowAnimate(false, isKeyWindowEnable: false)
}
}
/**
4. 失败时的图片和文字 ,展示完后自动消失
*/
func showFailedText(_ text:String, failedImage image:UIImage) {
let que = DispatchQueue(label: "myque3", attributes: DispatchQueue.Attributes.concurrent) // 并行队列
que.sync(execute: { // 同步操作\同步任务
self.imgV.isHidden = false
self.titleLab.isHidden = false
// 以使其在缩小动画后自动消失
isImgVHidden = true
self.imgV.image = image
self.titleLab.text = text
let bestSize = self.titleLab.sizeThatFits(CGSize(width: self.width, height: self.width))
self.titleLab.frame = CGRect(x: 0, y: self.imgV.frame.maxY + 10, width: self.width, height: bestSize.height)
var gap:CGFloat = 20 // 确保顶部、底部都有间距 10
// 此时需增加view的高度
if self.titleLab.frame.maxY > self.width {
gap = self.titleLab.frame.maxY - self.width + 10
}
self.view.height += gap
})
if !isShow {
doShowAnimate(false, isKeyWindowEnable: false)
}
}
/**
5. 消失 ; isForFirstMethod:用于哪种方式的消失.
* 只有展示进度图片时,外部需要调此法,其余展示情况内部已经处理让其自动消失了
*/
func dismiss(_ isForFirstMethod:Bool = true) {
self.isFirstMethod = isForFirstMethod
self.doDismissAnimate(isKeyWindowEnable: true)
}
// ------------------------ private ------------------------ //
/** 显示动画
- parameter isForTitleLab: 为图片 还是 文字执行动画
- parameter enable: 主窗口是否可与用户交互
*/
private func doShowAnimate(_ isForImageView:Bool, isKeyWindowEnable enable:Bool){
isShow = true
if isFirstMethod {
// 重新添加view
superView.addSubview(view)
// 主窗口不可交互
kwindow?.isUserInteractionEnabled = enable
}else{
// 设置它无用, 也不用设置
// alertWindow.userInteractionEnabled = enable
// 重新显示 alertWindow
self.alertWindow.isHidden = false
// 主窗口不可交互
beforWindow.isUserInteractionEnabled = enable
}
view.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
UIView.animate(withDuration: animateTime, animations: {
self.view.transform = CGAffineTransform.identity
}, completion: { (bl) in
if isForImageView { // 只有图片时的情况
// 给图片加旋转动画
if self.ani == nil {
self.ani = CAKeyframeAnimation.init(keyPath: "transform.rotation")
self.ani.duration = 1
// self.ani.rotationMode = kCAAnimationDiscrete // 此属性貌似无用
// self.ani.timingFunctions = [CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)] // 这个有用
// self.ani.calculationMode = kCAAnimationDiscrete
self.ani.values = [0, M_PI * 2]
self.ani.repeatCount = MAXFLOAT
}
self.imgV.layer.add(self.ani, forKey: self.aniKey)
}else{
// 2s后消失(提示label、 成功图片加label、失败图片加label)
let time = DispatchTime.now() + Double(Int64(2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.doDismissAnimate(isKeyWindowEnable: true)
}
}
})
}
/** 消失动画
- parameter isForTitleLab: 为图片 还是 文字执行动画
- parameter enable: 主窗口是否可与用户交互
*/
private func doDismissAnimate(isKeyWindowEnable enable:Bool){
UIView.animate(withDuration: animateTime, animations: {
self.view.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
}, completion: { (bl) in
// 移除图片的旋转动画
self.imgV.layer.removeAnimation(forKey: self.aniKey)
if self.isFirstMethod {
// 主窗口可交互
kwindow?.isUserInteractionEnabled = enable
// 移除、主窗口恢复
self.view.removeFromSuperview()
}else{
beforWindow.isUserInteractionEnabled = enable
// 上面此时只显示了提醒文字,故需要2s后自动消失;其他情况,都不消失的
if self.isImgVHidden {
self.alertWindow.isHidden = true
}
}
// 消失动画完成后才可再次显示,避免不停地显示
self.isShow = false
})
}
deinit{
}
}
|
e703b87b87ebfa7bcc8ca8086052829c
| 32.790816 | 254 | 0.542881 | false | false | false | false |
NoryCao/zhuishushenqi
|
refs/heads/master
|
zhuishushenqi/TXTReader/Reader/Service/ZSReaderManager.swift
|
mit
|
1
|
//
// ZSReaderManager.swift
// zhuishushenqi
//
// Created by yung on 2018/7/9.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
final class ZSReaderManager {
var cachedChapter:[String:QSChapter] = [:]
// 获取下一个页面
func getNextPage(record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){
//2.获取当前阅读的章节与页码,这里由于是网络小说,有几种情况
//(1).当前章节信息为空,那么这一章只有一页,翻页直接进入了下一页,章节加一
//(2).当前章节信息不为空,说明已经请求成功了,那么计算当前页码是否为该章节的最后一页
//这是2(2)
if let chapterModel = record.chapterModel {
let page = record.page
if page < chapterModel.pages.count - 1 {
let pageIndex = page + 1
let pageModel = chapterModel.pages[pageIndex]
callback?(pageModel)
} else { // 新的章节
getNewChapter(chapterOffset: 1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
} else {
getNewChapter(chapterOffset: 1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
}
func getLastPage(record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){
if let chapterModel = record.chapterModel {
let page = record.page
if page > 0 {
// 当前页存在
let pageIndex = page - 1
let pageModel = chapterModel.pages[pageIndex]
callback?(pageModel)
} else {// 当前章节信息不存在,必然是新的章节
getNewChapter(chapterOffset: -1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
} else {
getNewChapter(chapterOffset: -1,record: record,chaptersInfo: chaptersInfo,callback: callback)
}
}
func getNewChapter(chapterOffset:Int,record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){
let chapter = record.chapter + chapterOffset
if chapter > 0 && chapter < (chaptersInfo?.count ?? 0) {
if let chapterInfo = chaptersInfo?[chapter] {
let link = chapterInfo.link
// 内存缓存
if let model = cachedChapter[link] {
callback?(model.pages.first)
} else {
callback?(nil)
// viewModel.fetchChapter(key: link, { (body) in
// if let bodyInfo = body {
// if let network = self.cacheChapter(body: bodyInfo, index: chapter) {
// callback?(network.pages.first)
// }
// }
// })
}
}
}
}
}
|
c0d9b42f5a8060f73a38c3da4c473e2f
| 36.712329 | 129 | 0.550672 | false | false | false | false |
mleiv/MEGameTracker
|
refs/heads/master
|
MEGameTracker/Views/Common/Markupable/MarkupLabel.swift
|
mit
|
1
|
//
// MarkupLabel.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/17/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
// right now labels won't have clickable links, so stick to text views unless you don't want clicks
final public class MarkupLabel: IBStyledLabel, Markupable {
public override var text: String? {
didSet {
guard !isInsideSetter else { return }
unmarkedText = text
applyMarkup()
}
}
public var useAttributedText: NSAttributedString? {
get { return attributedText }
set {
isInsideSetter = true
attributedText = newValue
// does not apply styles unless explicitly run in main queue,
// which dies because already in main queue.
isInsideSetter = false
}
}
public var unmarkedText: String?
public var isInsideSetter = false
/// I expect this to only be called on main/UI dispatch queue, otherwise bad things will happen.
/// I can't dispatch to main async or layout does not render properly.
public func applyMarkup() {
guard !UIWindow.isInterfaceBuilder else { return }
markup()
}
}
|
5731d94b3571e201c5e71ab1e9dfa6e2
| 24.928571 | 99 | 0.717172 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Rules/Idiomatic/DiscouragedOptionalBooleanRuleExamples.swift
|
mit
|
1
|
internal struct DiscouragedOptionalBooleanRuleExamples {
static let nonTriggeringExamples = [
// Global variable
Example("var foo: Bool"),
Example("var foo: [String: Bool]"),
Example("var foo: [Bool]"),
Example("let foo: Bool = true"),
Example("let foo: Bool = false"),
Example("let foo: [String: Bool] = [:]"),
Example("let foo: [Bool] = []"),
// Computed get variable
Example("var foo: Bool { return true }"),
Example("let foo: Bool { return false }()"),
// Free function return
Example("func foo() -> Bool {}"),
Example("func foo() -> [String: Bool] {}"),
Example("func foo() -> ([Bool]) -> String {}"),
// Free function parameter
Example("func foo(input: Bool = true) {}"),
Example("func foo(input: [String: Bool] = [:]) {}"),
Example("func foo(input: [Bool] = []) {}"),
// Method return
wrapExample("class", "func foo() -> Bool {}"),
wrapExample("class", "func foo() -> [String: Bool] {}"),
wrapExample("class", "func foo() -> ([Bool]) -> String {}"),
wrapExample("struct", "func foo() -> Bool {}"),
wrapExample("struct", "func foo() -> [String: Bool] {}"),
wrapExample("struct", "func foo() -> ([Bool]) -> String {}"),
wrapExample("enum", "func foo() -> Bool {}"),
wrapExample("enum", "func foo() -> [String: Bool] {}"),
wrapExample("enum", "func foo() -> ([Bool]) -> String {}"),
// Method parameter
wrapExample("class", "func foo(input: Bool = true) {}"),
wrapExample("class", "func foo(input: [String: Bool] = [:]) {}"),
wrapExample("class", "func foo(input: [Bool] = []) {}"),
wrapExample("struct", "func foo(input: Bool = true) {}"),
wrapExample("struct", "func foo(input: [String: Bool] = [:]) {}"),
wrapExample("struct", "func foo(input: [Bool] = []) {}"),
wrapExample("enum", "func foo(input: Bool = true) {}"),
wrapExample("enum", "func foo(input: [String: Bool] = [:]) {}"),
wrapExample("enum", "func foo(input: [Bool] = []) {}")
]
static let triggeringExamples = [
// Global variable
Example("var foo: ↓Bool?"),
Example("var foo: [String: ↓Bool?]"),
Example("var foo: [↓Bool?]"),
Example("let foo: ↓Bool? = nil"),
Example("let foo: [String: ↓Bool?] = [:]"),
Example("let foo: [↓Bool?] = []"),
Example("let foo = ↓Optional.some(false)"),
Example("let foo = ↓Optional.some(true)"),
// Computed Get Variable
Example("var foo: ↓Bool? { return nil }"),
Example("let foo: ↓Bool? { return nil }()"),
// Free function return
Example("func foo() -> ↓Bool? {}"),
Example("func foo() -> [String: ↓Bool?] {}"),
Example("func foo() -> [↓Bool?] {}"),
Example("static func foo() -> ↓Bool? {}"),
Example("static func foo() -> [String: ↓Bool?] {}"),
Example("static func foo() -> [↓Bool?] {}"),
Example("func foo() -> (↓Bool?) -> String {}"),
Example("func foo() -> ([Int]) -> ↓Bool? {}"),
// Free function parameter
Example("func foo(input: ↓Bool?) {}"),
Example("func foo(input: [String: ↓Bool?]) {}"),
Example("func foo(input: [↓Bool?]) {}"),
Example("static func foo(input: ↓Bool?) {}"),
Example("static func foo(input: [String: ↓Bool?]) {}"),
Example("static func foo(input: [↓Bool?]) {}"),
// Instance variable
wrapExample("class", "var foo: ↓Bool?"),
wrapExample("class", "var foo: [String: ↓Bool?]"),
wrapExample("class", "let foo: ↓Bool? = nil"),
wrapExample("class", "let foo: [String: ↓Bool?] = [:]"),
wrapExample("class", "let foo: [↓Bool?] = []"),
wrapExample("struct", "var foo: ↓Bool?"),
wrapExample("struct", "var foo: [String: ↓Bool?]"),
wrapExample("struct", "let foo: ↓Bool? = nil"),
wrapExample("struct", "let foo: [String: ↓Bool?] = [:]"),
wrapExample("struct", "let foo: [↓Bool?] = []"),
// Instance computed variable
wrapExample("class", "var foo: ↓Bool? { return nil }"),
wrapExample("class", "let foo: ↓Bool? { return nil }()"),
wrapExample("struct", "var foo: ↓Bool? { return nil }"),
wrapExample("struct", "let foo: ↓Bool? { return nil }()"),
wrapExample("enum", "var foo: ↓Bool? { return nil }"),
wrapExample("enum", "let foo: ↓Bool? { return nil }()"),
// Method return
wrapExample("class", "func foo() -> ↓Bool? {}"),
wrapExample("class", "func foo() -> [String: ↓Bool?] {}"),
wrapExample("class", "func foo() -> [↓Bool?] {}"),
wrapExample("class", "static func foo() -> ↓Bool? {}"),
wrapExample("class", "static func foo() -> [String: ↓Bool?] {}"),
wrapExample("class", "static func foo() -> [↓Bool?] {}"),
wrapExample("class", "func foo() -> (↓Bool?) -> String {}"),
wrapExample("class", "func foo() -> ([Int]) -> ↓Bool? {}"),
wrapExample("struct", "func foo() -> ↓Bool? {}"),
wrapExample("struct", "func foo() -> [String: ↓Bool?] {}"),
wrapExample("struct", "func foo() -> [↓Bool?] {}"),
wrapExample("struct", "static func foo() -> ↓Bool? {}"),
wrapExample("struct", "static func foo() -> [String: ↓Bool?] {}"),
wrapExample("struct", "static func foo() -> [↓Bool?] {}"),
wrapExample("struct", "func foo() -> (↓Bool?) -> String {}"),
wrapExample("struct", "func foo() -> ([Int]) -> ↓Bool? {}"),
wrapExample("enum", "func foo() -> ↓Bool? {}"),
wrapExample("enum", "func foo() -> [String: ↓Bool?] {}"),
wrapExample("enum", "func foo() -> [↓Bool?] {}"),
wrapExample("enum", "static func foo() -> ↓Bool? {}"),
wrapExample("enum", "static func foo() -> [String: ↓Bool?] {}"),
wrapExample("enum", "static func foo() -> [↓Bool?] {}"),
wrapExample("enum", "func foo() -> (↓Bool?) -> String {}"),
wrapExample("enum", "func foo() -> ([Int]) -> ↓Bool? {}"),
// Method parameter
wrapExample("class", "func foo(input: ↓Bool?) {}"),
wrapExample("class", "func foo(input: [String: ↓Bool?]) {}"),
wrapExample("class", "func foo(input: [↓Bool?]) {}"),
wrapExample("class", "static func foo(input: ↓Bool?) {}"),
wrapExample("class", "static func foo(input: [String: ↓Bool?]) {}"),
wrapExample("class", "static func foo(input: [↓Bool?]) {}"),
wrapExample("struct", "func foo(input: ↓Bool?) {}"),
wrapExample("struct", "func foo(input: [String: ↓Bool?]) {}"),
wrapExample("struct", "func foo(input: [↓Bool?]) {}"),
wrapExample("struct", "static func foo(input: ↓Bool?) {}"),
wrapExample("struct", "static func foo(input: [String: ↓Bool?]) {}"),
wrapExample("struct", "static func foo(input: [↓Bool?]) {}"),
wrapExample("enum", "func foo(input: ↓Bool?) {}"),
wrapExample("enum", "func foo(input: [String: ↓Bool?]) {}"),
wrapExample("enum", "func foo(input: [↓Bool?]) {}"),
wrapExample("enum", "static func foo(input: ↓Bool?) {}"),
wrapExample("enum", "static func foo(input: [String: ↓Bool?]) {}"),
wrapExample("enum", "static func foo(input: [↓Bool?]) {}"),
// Optional chaining
Example("_ = ↓Bool?.values()")
]
}
// MARK: - Private
private func wrapExample(_ type: String, _ test: String, file: StaticString = #file, line: UInt = #line) -> Example {
return Example("\(type) Foo {\n\t\(test)\n}", file: file, line: line)
}
|
da50623c97b4019a31d0e255b97dfc9f
| 45.011905 | 117 | 0.513195 | false | false | false | false |
scottsievert/swix
|
refs/heads/master
|
swix/swix/swix/matrix/m-operators.swift
|
mit
|
2
|
//
// twoD-operators.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func make_operator(_ lhs: matrix, operation: String, rhs: matrix)->matrix{
assert(lhs.shape.0 == rhs.shape.0, "Sizes must match!")
assert(lhs.shape.1 == rhs.shape.1, "Sizes must match!")
var result = zeros_like(lhs) // real result
let lhsM = lhs.flat
let rhsM = rhs.flat
var resM:vector = zeros_like(lhsM) // flat vector
if operation=="+" {resM = lhsM + rhsM}
else if operation=="-" {resM = lhsM - rhsM}
else if operation=="*" {resM = lhsM * rhsM}
else if operation=="/" {resM = lhsM / rhsM}
else if operation=="<" {resM = lhsM < rhsM}
else if operation==">" {resM = lhsM > rhsM}
else if operation==">=" {resM = lhsM >= rhsM}
else if operation=="<=" {resM = lhsM <= rhsM}
result.flat.grid = resM.grid
return result
}
func make_operator(_ lhs: matrix, operation: String, rhs: Double)->matrix{
var result = zeros_like(lhs) // real result
// var lhsM = asmatrix(lhs.grid) // flat
let lhsM = lhs.flat
var resM:vector = zeros_like(lhsM) // flat matrix
if operation=="+" {resM = lhsM + rhs}
else if operation=="-" {resM = lhsM - rhs}
else if operation=="*" {resM = lhsM * rhs}
else if operation=="/" {resM = lhsM / rhs}
else if operation=="<" {resM = lhsM < rhs}
else if operation==">" {resM = lhsM > rhs}
else if operation==">=" {resM = lhsM >= rhs}
else if operation=="<=" {resM = lhsM <= rhs}
result.flat.grid = resM.grid
return result
}
func make_operator(_ lhs: Double, operation: String, rhs: matrix)->matrix{
var result = zeros_like(rhs) // real result
// var rhsM = asmatrix(rhs.grid) // flat
let rhsM = rhs.flat
var resM:vector = zeros_like(rhsM) // flat matrix
if operation=="+" {resM = lhs + rhsM}
else if operation=="-" {resM = lhs - rhsM}
else if operation=="*" {resM = lhs * rhsM}
else if operation=="/" {resM = lhs / rhsM}
else if operation=="<" {resM = lhs < rhsM}
else if operation==">" {resM = lhs > rhsM}
else if operation==">=" {resM = lhs >= rhsM}
else if operation=="<=" {resM = lhs <= rhsM}
result.flat.grid = resM.grid
return result
}
// DOUBLE ASSIGNMENT
func <- (lhs:inout matrix, rhs:Double){
let assign = ones((lhs.shape)) * rhs
lhs = assign
}
// SOLVE
infix operator !/ : Multiplicative
func !/ (lhs: matrix, rhs: vector) -> vector{
return solve(lhs, b: rhs)}
// EQUALITY
func ~== (lhs: matrix, rhs: matrix) -> Bool{
return (rhs.flat ~== lhs.flat)}
infix operator == : ComparisonPrecedence
func == (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat == rhs.flat).reshape(lhs.shape)
}
infix operator !== : ComparisonPrecedence
func !== (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat !== rhs.flat).reshape(lhs.shape)
}
/// ELEMENT WISE OPERATORS
// PLUS
infix operator + : Additive
func + (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
// MINUS
infix operator - : Additive
func - (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
// TIMES
infix operator * : Multiplicative
func * (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
// DIVIDE
infix operator / : Multiplicative
func / (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)
}
func / (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
func / (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
// LESS THAN
infix operator < : ComparisonPrecedence
func < (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
// GREATER THAN
infix operator > : ComparisonPrecedence
func > (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
// GREATER THAN OR EQUAL
infix operator >= : ComparisonPrecedence
func >= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
func >= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
func >= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
// LESS THAN OR EQUAL
infix operator <= : ComparisonPrecedence
func <= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
func <= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
func <= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
|
a6b3d9cbafefc0d9ef9acee5ab9fd990
| 37.263158 | 74 | 0.627235 | false | false | false | false |
benlangmuir/swift
|
refs/heads/master
|
test/SILGen/dynamic_callable_attribute.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-emit-silgen -verify %s | %FileCheck %s
// Check that dynamic calls resolve to the right `dynamicallyCall` method in SIL.
@dynamicCallable
public struct Callable {
func dynamicallyCall(withArguments: [Int]) {}
func dynamicallyCall(withKeywordArguments: KeyValuePairs<String, Int>) {}
}
@_silgen_name("foo")
public func foo(a: Callable) {
// The first two calls should resolve to the `withArguments:` method.
a()
a(1, 2, 3)
// The last call should resolve to the `withKeywordArguments:` method.
a(1, 2, 3, label: 4)
}
// CHECK-LABEL: sil [ossa] @foo
// CHECK: bb0(%0 : $Callable):
// CHECK: [[DYN_CALL_1:%.*]] = function_ref @$s26dynamic_callable_attribute8CallableV15dynamicallyCall13withArgumentsySaySiG_tF
// CHECK-NEXT: apply [[DYN_CALL_1]]
// CHECK: [[DYN_CALL_2:%.*]] = function_ref @$s26dynamic_callable_attribute8CallableV15dynamicallyCall13withArgumentsySaySiG_tF
// CHECK-NEXT: apply [[DYN_CALL_2]]
// CHECK: [[DYN_CALL_3:%.*]] = function_ref @$s26dynamic_callable_attribute8CallableV15dynamicallyCall20withKeywordArgumentsys13KeyValuePairsVySSSiG_tF
@dynamicCallable
public struct Callable2 {
func dynamicallyCall(withKeywordArguments: KeyValuePairs<String, Any>) {}
}
// CHECK-LABEL: sil [ossa] @keywordCoerceBug
// CHECK:[[DYN_CALL:%.*]] = function_ref @$s26dynamic_callable_attribute9Callable2V15dynamicallyCall20withKeywordArgumentsys13KeyValuePairsVySSypG_tF
@_silgen_name("keywordCoerceBug")
public func keywordCoerceBug(a: Callable2, s: Int) {
a(s)
}
@dynamicCallable
struct S {
func dynamicallyCall(withArguments x: [Int]) -> Int! { nil }
}
@dynamicCallable
protocol P1 {
func dynamicallyCall(withKeywordArguments: [String: Any])
}
@dynamicCallable
protocol P2 {
func dynamicallyCall(withArguments x: [Int]) -> Self
}
@dynamicCallable
class C {
func dynamicallyCall(withKeywordArguments x: [String: String]) -> Self { return self }
}
// CHECK-LABEL: sil hidden [ossa] @$s26dynamic_callable_attribute05test_A10_callablesyyAA1SV_AA2P1_pAA2P2_pxtAA1CCRbzlF : $@convention(thin) <T where T : C> (S, @in_guaranteed any P1, @in_guaranteed any P2, @guaranteed T) -> ()
func test_dynamic_callables<T : C>(_ s: S, _ p1: P1, _ p2: P2, _ t: T) {
// SR-12615: Compiler crash on @dynamicCallable IUO.
// CHECK: function_ref @$s26dynamic_callable_attribute1SV15dynamicallyCall13withArgumentsSiSgSaySiG_tF : $@convention(method) (@guaranteed Array<Int>, S) -> Optional<Int>
// CHECK: switch_enum %{{.+}} : $Optional<Int>
let _: Int = s(0)
// CHECK: witness_method $@opened({{.+}} any P1) Self, #P1.dynamicallyCall : <Self where Self : P1> (Self) -> ([String : Any]) -> ()
p1(x: 5)
// CHECK: witness_method $@opened({{.+}} any P2) Self, #P2.dynamicallyCall : <Self where Self : P2> (Self) -> ([Int]) -> Self
_ = p2()
// CHECK: class_method %{{.+}} : $C, #C.dynamicallyCall : (C) -> ([String : String]) -> @dynamic_self C, $@convention(method) (@guaranteed Dictionary<String, String>, @guaranteed C) -> @owned C
// CHECK: unchecked_ref_cast %{{.+}} : $C to $T
_ = t("")
}
|
c102125917aec666a43aef3172357949
| 38.205128 | 227 | 0.700458 | false | false | false | false |
knehez/edx-app-ios
|
refs/heads/master
|
Source/CourseOutline.swift
|
apache-2.0
|
2
|
//
// CourseOutline.swift
// edX
//
// Created by Akiva Leffert on 4/29/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
public typealias CourseBlockID = String
public struct CourseOutline {
public let root : CourseBlockID
public let blocks : [CourseBlockID:CourseBlock]
private let parents : [CourseBlockID:CourseBlockID]
public init(root : CourseBlockID, blocks : [CourseBlockID:CourseBlock]) {
self.root = root
self.blocks = blocks
var parents : [CourseBlockID:CourseBlockID] = [:]
for (blockID, block) in blocks {
for child in block.children {
parents[child] = blockID
}
}
self.parents = parents
}
public init?(json : JSON) {
if let root = json["root"].string, blocks = json["blocks+navigation"].dictionaryObject {
var validBlocks : [CourseBlockID:CourseBlock] = [:]
for (blockID, blockBody) in blocks {
let body = JSON(blockBody)
let webURL = NSURL(string: body["web_url"].stringValue)
let children = body["descendants"].arrayObject as? [String] ?? []
let name = body["display_name"].string ?? ""
let blockURL = body["block_url"].string.flatMap { NSURL(string:$0) }
let format = body["format"].string
let type : CourseBlockType
let typeName = body["type"].string ?? ""
let isResponsive = body["responsive_ui"].bool ?? true
let blockCounts : [String:Int] = (body["block_count"].object as? NSDictionary)?.mapValues {
$0 as? Int ?? 0
} ?? [:]
let graded = body["graded"].bool ?? false
if let category = CourseBlock.Category(rawValue: typeName) {
switch category {
case CourseBlock.Category.Course:
type = .Course
case CourseBlock.Category.Chapter:
type = .Chapter
case CourseBlock.Category.Section:
type = .Section
case CourseBlock.Category.Unit:
type = .Unit
case CourseBlock.Category.HTML:
type = .HTML
case CourseBlock.Category.Problem:
type = .Problem
case CourseBlock.Category.Video :
let bodyData = (body["block_json"].object as? NSDictionary).map { ["summary" : $0 ] }
let summary = OEXVideoSummary(dictionary: bodyData ?? [:], videoID: blockID, name : name)
type = .Video(summary)
}
}
else {
type = .Unknown(typeName)
}
validBlocks[blockID] = CourseBlock(
type: type,
children: children,
blockID: blockID,
name: name,
blockCounts : blockCounts,
blockURL : blockURL,
webURL: webURL,
format : format,
isResponsive : isResponsive,
graded : graded
)
}
self = CourseOutline(root: root, blocks: validBlocks)
}
else {
return nil
}
}
func parentOfBlockWithID(blockID : CourseBlockID) -> CourseBlockID? {
return self.parents[blockID]
}
}
public enum CourseBlockType {
case Unknown(String)
case Course
case Chapter
case Section
case Unit
case Video(OEXVideoSummary)
case Problem
case HTML
public var asVideo : OEXVideoSummary? {
switch self {
case let .Video(summary):
return summary
default:
return nil
}
}
}
public class CourseBlock {
/// Simple list of known block categories strings
public enum Category : String {
case Chapter = "chapter"
case Course = "course"
case HTML = "html"
case Problem = "problem"
case Section = "sequential"
case Unit = "vertical"
case Video = "video"
}
public let type : CourseBlockType
public let blockID : CourseBlockID
/// Children in the navigation hierarchy.
/// Note that this may be different than the block's list of children, server side
/// Since we flatten out the hierarchy for display
public let children : [CourseBlockID]
/// User visible name of the block.
public let name : String
/// TODO: Match final API name
/// The type of graded component
public let format : String?
/// Mapping between block types and number of blocks of that type in this block's
/// descendants (recursively) for example ["video" : 3]
public let blockCounts : [String:Int]
/// Just the block content itself as a web page.
/// Suitable for embedding in a web view.
public let blockURL : NSURL?
/// If this is web content, can we actually display it.
public let isResponsive : Bool
/// A full web page for the block.
/// Suitable for opening in a web browser.
public let webURL : NSURL?
/// Whether or not the block is graded.
/// TODO: Match final API name
public let graded : Bool?
public init(type : CourseBlockType,
children : [CourseBlockID],
blockID : CourseBlockID,
name : String,
blockCounts : [String:Int] = [:],
blockURL : NSURL? = nil,
webURL : NSURL? = nil,
format : String? = nil,
isResponsive : Bool = true,
graded : Bool = false) {
self.type = type
self.children = children
self.name = name
self.blockCounts = blockCounts
self.blockID = blockID
self.blockURL = blockURL
self.webURL = webURL
self.graded = graded
self.format = format
self.isResponsive = isResponsive
}
}
|
72614c65482b30ea9c09f90d8f743eef
| 32.408602 | 113 | 0.53653 | false | false | false | false |
ACChe/eidolon
|
refs/heads/master
|
Kiosk/App/Networking/RAC+JSONAble.swift
|
mit
|
7
|
import Foundation
import Moya
import ReactiveCocoa
extension RACSignal {
/// Get given JSONified data, pass back objects
func mapToObject(classType: JSONAble.Type) -> RACSignal {
func resultFromJSON(object:[String: AnyObject], classType: JSONAble.Type) -> AnyObject {
return classType.fromJSON(object)
}
return tryMap({ (object, error) -> AnyObject! in
if let dict = object as? [String:AnyObject] {
return resultFromJSON(dict, classType: classType)
}
if error != nil {
error.memory = NSError(domain: MoyaErrorDomain, code: MoyaErrorCode.Data.rawValue, userInfo: ["data": object])
}
return nil
})
}
/// Get given JSONified data, pass back objects as an array
func mapToObjectArray(classType: JSONAble.Type) -> RACSignal {
func resultFromJSON(object:[String: AnyObject], classType: JSONAble.Type) -> AnyObject {
return classType.fromJSON(object)
}
return tryMap({ (object, error) -> AnyObject! in
if let dicts = object as? Array<Dictionary<String, AnyObject>> {
let jsonables:[JSONAble] = dicts.map({ return classType.fromJSON($0) })
return jsonables
}
if error != nil {
error.memory = NSError(domain: MoyaErrorDomain, code: MoyaErrorCode.Data.rawValue, userInfo: ["data": object])
}
return nil
})
}
}
|
ebade705c9dab5840043c08b27310ee4
| 31.425532 | 126 | 0.591864 | false | false | false | false |
netguru/inbbbox-ios
|
refs/heads/develop
|
Unit Tests/PageableProviderSpec.swift
|
gpl-3.0
|
1
|
//
// PageableProviderSpec.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 05/02/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Nimble
import Quick
import PromiseKit
import Mockingjay
import SwiftyJSON
@testable import Inbbbox
class PageableProviderSpec: QuickSpec {
override func spec() {
var sut: PageableProvider!
beforeEach {
sut = PageableProvider()
}
afterEach {
sut = nil
}
describe("when init with custom initializer") {
beforeEach {
sut = PageableProvider(page: 2, pagination: 10)
}
it("should have properly set page") {
expect(sut.page).to(equal(2))
}
it("should have properly set pagination") {
expect(sut.pagination).to(equal(10))
}
}
describe("when init with default initializer") {
beforeEach {
sut = PageableProvider()
}
it("should have properly set page") {
expect(sut.page).to(equal(1))
}
it("should have properly set pagination") {
expect(sut.pagination).to(equal(30))
}
}
describe("when providing first page with success") {
var result: [ModelMock]?
beforeEach {
self.stub(everything, json([self.fixtureJSON]))
}
afterEach {
result = nil
self.removeAllStubs()
}
it("result should be properly returned") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _result in
result = _result
}.catch { _ in fail() }
expect(result).toEventuallyNot(beNil())
expect(result).toEventually(haveCount(1))
}
context("then next/previous page with unavailable pageable") {
var error: Error!
afterEach {
error = nil
}
it("error should appear") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.nextPageFor(ModelMock.self)
}.then { _ -> Void in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
it("error should appear") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.previousPageFor(ModelMock.self)
}.then { _ -> Void in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
}
context("then next/previous page with available pageable components") {
beforeEach {
self.removeAllStubs()
self.stub(everything, json([self.fixtureJSON], headers: self.fixtureHeader))
}
it("results from next page should be properly returned") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.nextPageFor(ModelMock.self)
}.then { _result -> Void in
result = _result
}.catch { _ in fail() }
expect(result).toEventuallyNot(beNil())
expect(result).toEventually(haveCount(1))
}
it("results from next page should be properly returned") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
sut.previousPageFor(ModelMock.self)
}.then { _result -> Void in
result = _result
}.catch { _ in fail() }
expect(result).toEventuallyNot(beNil())
expect(result).toEventually(haveCount(1))
}
}
}
describe("when providing first page with network error") {
var error: Error!
beforeEach {
let error = NSError(domain: "", code: 0, userInfo: nil)
self.stub(everything, failure(error))
}
afterEach {
error = nil
self.removeAllStubs()
}
it("error should appear") {
let promise: Promise<[ModelMock]?> = sut.firstPageForQueries([QueryMock()], withSerializationKey: nil)
promise.then { _ in
fail()
}.catch { _error in
error = _error
}
expect(error).toEventuallyNot(beNil())
}
}
describe("when providing next/previous page without using firstPage method first") {
var error: Error?
afterEach {
error = nil
}
it("error should appear") {
sut.nextPageFor(ModelMock.self).then { _ in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
it("error should appear") {
sut.previousPageFor(ModelMock.self).then { _ in
fail()
}.catch { _error in
error = _error
}
expect(error is PageableProviderError).toEventually(beTruthy())
}
}
}
}
private struct ModelMock: Mappable {
let identifier: String
let title: String?
static var map: (JSON) -> ModelMock {
return { json in
return ModelMock(
identifier: json["identifier"].stringValue,
title: json["title"].stringValue
)
}
}
}
private extension PageableProviderSpec {
var fixtureJSON: [String: AnyObject] {
return [
"identifier" : "fixture.identifier" as AnyObject,
"title" : "fixture.title" as AnyObject
]
}
var fixtureHeader: [String: String] {
return [
"Link" :
"<https://fixture.host/v1/fixture.path?page=1&per_page=100>; rel=\"prev\"," +
"<https://fixture.host/v1/fixture.path?page=3&per_page=100>; rel=\"next\""
]
}
}
private struct QueryMock: Query {
let path = "/fixture/path"
var parameters = Parameters(encoding: .json)
let method = Method.POST
}
|
a2c3339ccf8b484392151b9b9f0672b1
| 30.850394 | 122 | 0.436959 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
refs/heads/main
|
Swift/longest-palindromic-substring.swift
|
mit
|
2
|
/**
* Problem Link: https://leetcode.com/problems/longest-palindromic-substring/
*
*
*/
class Solution {
func longestPalindrome(_ s: String) -> String {
let list = s.characters.map(){"\($0)"}
var ret = ""
for i in 0..<list.count {
let s1 = findPalindromString(at: i, and: i, for: list)
let s2 = findPalindromString(at: i, and: i+1, for: list)
if s1.characters.count > ret.characters.count {
ret = s1
}
if s2.characters.count > ret.characters.count {
ret = s2
}
}
return ret
}
private func findPalindromString(at left: Int, and right: Int, for s: [String]) -> String {
var l = left
var r = right
var ret = ""
while(l>=0 && r < s.count && s[l] == s[r]) {
if l != r {
ret = s[l] + ret + s[r]
} else {
ret += s[l]
}
l -= 1
r += 1
}
return ret
}
}
/**
* https://leetcode.com/problems/longest-palindromic-substring/
*
*
*/
// Date: Tue Jan 19 09:21:21 PST 2021
class Solution {
func longestPalindrome(_ s: String) -> String {
let n = s.count
let s = Array(s)
var dp = Array(repeating: Array(repeating: false, count: n), count: n)
var ret = (0, 0)
for len in 1 ... n {
for start in 0 ... (n - len) {
var end = start + len - 1
if len > 2 {
dp[start][end] = dp[start + 1][end - 1] && (s[start] == s[end])
} else {
dp[start][end] = (s[start] == s[end])
}
if dp[start][end], ret.1 - ret.0 + 1 < len {
ret = (start, end)
}
}
}
return String(s[ret.0 ... ret.1])
}
}/**
* https://leetcode.com/problems/longest-palindromic-substring/
*
*
*/
// Date: Tue Jan 19 09:47:54 PST 2021
class Solution {
func longestPalindrome(_ s: String) -> String {
let list = Array(s)
var ret = (0, 0)
for center in 0 ..< list.count {
var left = center
var right = center
while left >= 0, right < list.count, list[left] == list[right] {
left -= 1
right += 1
}
left += 1
right -= 1
if right - left > ret.1 - ret.0 {
ret = (left, right)
}
left = center
right = center + 1
while left >= 0, right < list.count, list[left] == list[right] {
left -= 1
right += 1
}
left += 1
right -= 1
if right - left > ret.1 - ret.0 {
ret = (left, right)
}
}
return String(list[ret.0 ... ret.1])
}
}
|
0cb80aec7c84a266b5aa39c6bd910eac
| 27.601942 | 95 | 0.424788 | false | false | false | false |
StephenVinouze/ios-charts
|
refs/heads/master
|
Advanced/Pods/Charts/Charts/Classes/Renderers/PieChartRenderer.swift
|
apache-2.0
|
5
|
//
// PieChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class PieChartRenderer: ChartDataRendererBase
{
public weak var chart: PieChartView?
public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
public override func drawData(context context: CGContext)
{
guard let chart = chart else { return }
let pieData = chart.data
if (pieData != nil)
{
for set in pieData!.dataSets as! [IPieChartDataSet]
{
if set.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set)
}
}
}
}
public func calculateMinimumRadiusForSpacedSlice(
center center: CGPoint,
radius: CGFloat,
angle: CGFloat,
arcStartPointX: CGFloat,
arcStartPointY: CGFloat,
startAngle: CGFloat,
sweepAngle: CGFloat) -> CGFloat
{
let angleMiddle = startAngle + sweepAngle / 2.0
// Other point of the arc
let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
// Middle point on the arc
let arcMidPointX = center.x + radius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcMidPointY = center.y + radius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
// This is the base of the contained triangle
let basePointsDistance = sqrt(
pow(arcEndPointX - arcStartPointX, 2) +
pow(arcEndPointY - arcStartPointY, 2))
// After reducing space from both sides of the "slice",
// the angle of the contained triangle should stay the same.
// So let's find out the height of that triangle.
let containedTriangleHeight = (basePointsDistance / 2.0 *
tan((180.0 - angle) / 2.0 * ChartUtils.Math.FDEG2RAD))
// Now we subtract that from the radius
var spacedRadius = radius - containedTriangleHeight
// And now subtract the height of the arc that's between the triangle and the outer circle
spacedRadius -= sqrt(
pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) +
pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2))
return spacedRadius
}
public func drawDataSet(context context: CGContext, dataSet: IPieChartDataSet)
{
guard let
chart = chart,
data = chart.data,
animator = animator
else {return }
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
var drawAngles = chart.drawAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : dataSet.sliceSpace
CGContextSaveGState(context)
for j in 0 ..< entryCount
{
let sliceAngle = drawAngles[j]
var innerRadius = userInnerRadius
guard let e = dataSet.entryForIndex(j) else { continue }
// draw only if the value is greater than zero
if ((abs(e.value) > 0.000001))
{
if (!chart.needsHighlight(xIndex: e.xIndex,
dataSetIndex: data.indexOfDataSet(dataSet)))
{
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let path = CGPathCreateMutable()
CGPathMoveToPoint(
path,
nil,
arcStartPointX,
arcStartPointY)
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
radius,
startAngleOuter * ChartUtils.Math.FDEG2RAD,
sweepAngleOuter * ChartUtils.Math.FDEG2RAD)
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
CGPathAddLineToPoint(
path,
nil,
center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
innerRadius,
endAngleInner * ChartUtils.Math.FDEG2RAD,
-sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let sliceSpaceOffset =
calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
CGPathAddLineToPoint(
path,
nil,
arcEndPointX,
arcEndPointY)
}
else
{
CGPathAddLineToPoint(
path,
nil,
center.x,
center.y)
}
}
CGPathCloseSubpath(path)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextEOFillPath(context)
}
}
angle += sliceAngle * phaseX
}
CGContextRestoreGState(context)
}
public override func drawValues(context context: CGContext)
{
guard let
chart = chart,
data = chart.data,
animator = animator
else { return }
let center = chart.centerCircleBox
// get whole the radius
var r = chart.radius
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var off = r / 10.0 * 3.0
if chart.drawHoleEnabled
{
off = (r - (r * chart.holeRadiusPercent)) / 2.0
}
r -= off; // offset to keep things inside the chart
var dataSets = data.dataSets
let yValueSum = (data as! PieChartData).yValueSum
let drawXVals = chart.isDrawSliceTextEnabled
let usePercentValuesEnabled = chart.usePercentValuesEnabled
var angle: CGFloat = 0.0
var xIndex = 0
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue }
let drawYVals = dataSet.isDrawValuesEnabled
if (!drawYVals && !drawXVals)
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
for j in 0 ..< dataSet.entryCount
{
if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil))
{
continue
}
guard let e = dataSet.entryForIndex(j) else { continue }
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceAngle = drawAngles[xIndex]
let sliceSpace = dataSet.sliceSpace
let sliceSpaceMiddleAngle = sliceSpace / (ChartUtils.Math.FDEG2RAD * r)
// offset needed to center the drawn text in the slice
let offset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0
angle = angle + offset
// calculate the text position
let x = r
* cos((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD)
+ center.x
var y = r
* sin((rotationAngle + angle * phaseY) * ChartUtils.Math.FDEG2RAD)
+ center.y
let value = usePercentValuesEnabled ? e.value / yValueSum * 100.0 : e.value
let val = formatter.stringFromNumber(value)!
let lineHeight = valueFont.lineHeight
y -= lineHeight
// draw everything, depending on settings
if (drawXVals && drawYVals)
{
ChartUtils.drawText(
context: context,
text: val,
point: CGPoint(x: x, y: y),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
if (j < data.xValCount && data.xVals[j] != nil)
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
else if (drawXVals)
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
else if (drawYVals)
{
ChartUtils.drawText(
context: context,
text: val,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
xIndex += 1
}
}
}
public override func drawExtras(context context: CGContext)
{
drawHole(context: context)
drawCenterText(context: context)
}
/// draws the hole in the center of the chart and the transparent circle / hole
private func drawHole(context context: CGContext)
{
guard let
chart = chart,
animator = animator
else { return }
if (chart.drawHoleEnabled)
{
CGContextSaveGState(context)
let radius = chart.radius
let holeRadius = radius * chart.holeRadiusPercent
let center = chart.centerCircleBox
if let holeColor = chart.holeColor
{
if holeColor != NSUIColor.clearColor()
{
// draw the hole-circle
CGContextSetFillColorWithColor(context, chart.holeColor!.CGColor)
CGContextFillEllipseInRect(context, CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0))
}
}
// only draw the circle if it can be seen (not covered by the hole)
if let transparentCircleColor = chart.transparentCircleColor
{
if transparentCircleColor != NSUIColor.clearColor() &&
chart.transparentCircleRadiusPercent > chart.holeRadiusPercent
{
let alpha = animator.phaseX * animator.phaseY
let secondHoleRadius = radius * chart.transparentCircleRadiusPercent
// make transparent
CGContextSetAlpha(context, alpha);
CGContextSetFillColorWithColor(context, transparentCircleColor.CGColor)
// draw the transparent-circle
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, CGRect(
x: center.x - secondHoleRadius,
y: center.y - secondHoleRadius,
width: secondHoleRadius * 2.0,
height: secondHoleRadius * 2.0))
CGContextAddEllipseInRect(context, CGRect(
x: center.x - holeRadius,
y: center.y - holeRadius,
width: holeRadius * 2.0,
height: holeRadius * 2.0))
CGContextEOFillPath(context)
}
}
CGContextRestoreGState(context)
}
}
/// draws the description text in the center of the pie chart makes most sense when center-hole is enabled
private func drawCenterText(context context: CGContext)
{
guard let
chart = chart,
centerAttributedText = chart.centerAttributedText
else { return }
if chart.drawCenterTextEnabled && centerAttributedText.length > 0
{
let center = chart.centerCircleBox
let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius
let holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0)
var boundingRect = holeRect
if (chart.centerTextRadiusPercent > 0.0)
{
boundingRect = CGRectInset(boundingRect, (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0)
}
let textBounds = centerAttributedText.boundingRectWithSize(boundingRect.size, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil)
var drawingRect = boundingRect
drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0
drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0
drawingRect.size = textBounds.size
CGContextSaveGState(context)
let clippingPath = CGPathCreateWithEllipseInRect(holeRect, nil)
CGContextBeginPath(context)
CGContextAddPath(context, clippingPath)
CGContextClip(context)
centerAttributedText.drawWithRect(drawingRect, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil)
CGContextRestoreGState(context)
}
}
public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight])
{
guard let
chart = chart,
data = chart.data,
animator = animator
else { return }
CGContextSaveGState(context)
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
for i in 0 ..< indices.count
{
// get the index to highlight
let xIndex = indices[i].xIndex
if (xIndex >= drawAngles.count)
{
continue
}
guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue }
if !set.isHighlightEnabled
{
continue
}
let entryCount = set.entryCount
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = set.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace
let sliceAngle = drawAngles[xIndex]
var innerRadius = userInnerRadius
let shift = set.selectionShift
let highlightedRadius = radius + shift
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
CGContextSetFillColorWithColor(context, set.colorAt(xIndex).CGColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let sliceSpaceAngleShifted = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * highlightedRadius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * phaseY
var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * phaseY
if (sweepAngleShifted < 0.0)
{
sweepAngleShifted = 0.0
}
let path = CGPathCreateMutable()
CGPathMoveToPoint(
path,
nil,
center.x + highlightedRadius * cos(startAngleShifted * ChartUtils.Math.FDEG2RAD),
center.y + highlightedRadius * sin(startAngleShifted * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
highlightedRadius,
startAngleShifted * ChartUtils.Math.FDEG2RAD,
sweepAngleShifted * ChartUtils.Math.FDEG2RAD)
var sliceSpaceRadius: CGFloat = 0.0
if accountForSliceSpacing
{
sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD),
arcStartPointY: center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD),
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
}
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = sliceSpaceRadius
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
CGPathAddLineToPoint(
path,
nil,
center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
innerRadius,
endAngleInner * ChartUtils.Math.FDEG2RAD,
-sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
CGPathAddLineToPoint(
path,
nil,
arcEndPointX,
arcEndPointY)
}
else
{
CGPathAddLineToPoint(
path,
nil,
center.x,
center.y)
}
}
CGPathCloseSubpath(path)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextEOFillPath(context)
}
CGContextRestoreGState(context)
}
}
|
54d214ed71e192a0edd4dff08ac690f1
| 38.311707 | 220 | 0.484895 | false | false | false | false |
ip3r/Cart
|
refs/heads/master
|
Cart/Checkout/UI/AmountTitle.swift
|
mit
|
1
|
//
// AmountTitle.swift
// Cart
//
// Created by Jens Meder on 12.06.17.
// Copyright © 2017 Jens Meder. All rights reserved.
//
import UIKit
internal final class AmountTitle: ViewDelegate {
private let amount: Amount
private let currencies: Currencies
// MARK: Init
internal required init(amount: Amount, currencies: Currencies) {
self.amount = amount
self.currencies = currencies
}
// MARK: ViewDelegate
func viewWillAppear(viewController: UIViewController, animated: Bool) {
let total = amount.value * currencies.current.rate
let code = currencies.current.sign.stringValue
viewController.title = String(format: "%.2f %@", arguments: [total, code])
}
}
|
ed1366389989f74645db9e579e80160d
| 23.413793 | 76 | 0.699153 | false | false | false | false |
czechboy0/Redbird
|
refs/heads/main
|
Sources/Redis/RedisID.swift
|
mit
|
1
|
import Foundation
import Vapor
/// A type-safe representation of a String representing individual identifiers of separate Redis connections and configurations.
///
/// It is recommended to define static extensions for your definitions to make it easier at call sites to reference them.
///
/// For example:
/// ```swift
/// extension RedisID { static let oceanic = RedisID("oceanic") }
/// app.redis(.oceanic) // Application.Redis instance
/// ```
public struct RedisID: Hashable,
Codable,
RawRepresentable,
ExpressibleByStringLiteral,
ExpressibleByStringInterpolation,
CustomStringConvertible,
Comparable {
public let rawValue: String
public init(stringLiteral: String) {
self.rawValue = stringLiteral
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(_ string: String) {
self.rawValue = string
}
public var description: String { rawValue }
public static func < (lhs: RedisID, rhs: RedisID) -> Bool { lhs.rawValue < rhs.rawValue }
public static let `default`: RedisID = "default"
}
extension Application {
/// The default Redis connection.
///
/// If different Redis configurations are in use, use the `redis(_:)` method to match by `RedisID` instead.
public var redis: Redis {
redis(.default)
}
/// Returns the Redis connection for the given ID.
/// - Parameter id: The Redis ID that identifies the specific connection to be used.
/// - Returns: A Redis connection that is identified by the given `id`.
public func redis(_ id: RedisID) -> Redis {
.init(application: self, redisID: id)
}
}
extension Request {
/// The default Redis connection.
///
/// If different Redis configurations are in use, use the `redis(_:)` method to match by `RedisID` instead.
public var redis: Redis {
redis(.default)
}
/// Returns the Redis connection for the given ID.
/// - Parameter id: The Redis ID that identifies the specific connection to be used.
/// - Returns: A Redis connection that is identified by the given `id`.
public func redis(_ id: RedisID) -> Redis {
.init(request: self, id: id)
}
}
|
35fe53a3c7df3125b5e075f38d203939
| 31.873239 | 128 | 0.634533 | false | false | false | false |
Sharelink/Bahamut
|
refs/heads/master
|
Bahamut/BahamutCommon/AppRateHelper.swift
|
mit
|
1
|
//
// AppRateHelper.swift
// snakevsblock
//
// Created by Alex Chow on 2017/7/8.
// Copyright © 2017年 Bahamut. All rights reserved.
//
import Foundation
let AppRateNotification = Notification.Name("AppRateNotification")
let kAppRateNotificationEvent = "kAppRateNotificationEvent"
class AppRateHelper:NSObject {
static let shared:AppRateHelper = {
return AppRateHelper()
}()
private static var appId:String!
private static var nextRateAlertDays:Int = 1
private var lastShowDate:NSNumber{
get{
let date = UserDefaults.standard.double(forKey: "AppRateLastDate")
return NSNumber(value: date)
}
set{
UserDefaults.standard.set(newValue.doubleValue, forKey: "AppRateLastDate")
}
}
private(set) var isUserRated:Bool{
get{
return UserDefaults.standard.bool(forKey: "AppRateHelper_USER_RATED_US")
}
set{
UserDefaults.standard.set(newValue, forKey: "AppRateHelper_USER_RATED_US")
}
}
func configure(appId:String,nextRateAlertDays:Int){
if lastShowDate.doubleValue < 100 {
lastShowDate = NSNumber(value: Date().timeIntervalSince1970)
}
AppRateHelper.nextRateAlertDays = nextRateAlertDays
AppRateHelper.appId = appId
}
private(set) var rateusShown = false
class RateAlertModel {
var title:String!
var message:String!
var actionGoRateTitle:String!
var actionRejectTitle:String!
var actionCancelTitle:String!
var showConfrimRejectRateUs = false
var confirmRejectTitle:String!
var confirmRejectMessage:String!
var actionConfirmRejectGoRate:String!
var actionConfirmRejectNoRate:String!
}
func shouldShowRateAlert() -> Bool {
return !rateusShown && !isUserRated && lastShowDate.int64Value + 24 * 3600 * Int64(AppRateHelper.nextRateAlertDays) < Int64(Date().timeIntervalSince1970)
}
func clearRatedRecord() {
isUserRated = false
}
@discardableResult
func tryShowRateUsAlert(vc:UIViewController,alertModel:RateAlertModel) -> Bool {
if shouldShowRateAlert() {
let like = UIAlertAction(title: alertModel.actionGoRateTitle, style: .default, handler: { (ac) in
self.postEvent(event: "like_it")
self.rateus()
})
let hate = UIAlertAction(title: alertModel.actionRejectTitle, style: .default, handler: { (ac) in
self.postEvent(event: "hate_it")
if alertModel.showConfrimRejectRateUs{
let ok = UIAlertAction(title: alertModel.actionConfirmRejectGoRate, style: .default, handler: { (a) in
self.rateus()
})
let no = UIAlertAction(title: alertModel.actionConfirmRejectNoRate, style: .cancel, handler: { (a) in
})
vc.showAlert(alertModel.confirmRejectTitle, msg: alertModel.confirmRejectMessage, actions: [ok,no])
}
})
let nextTime = UIAlertAction(title: alertModel.actionCancelTitle, style: .cancel, handler: { (ac) in
self.postEvent(event: "next_time")
})
vc.showAlert(alertModel.title, msg: alertModel.message, actions: [like,hate,nextTime])
lastShowDate = NSNumber(value: Date().timeIntervalSince1970)
rateusShown = true
return true
}
return false
}
func rateus() {
let url = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=\(AppRateHelper.appId ?? "")"
let _ = UIApplication.shared.openURL(URL(string: url)!)
UserDefaults.standard.set(true, forKey: "AppRateHelper_USER_RATED_US")
postEvent(event: "go_rate")
}
private func postEvent(event:String) {
NotificationCenter.default.post(name: AppRateNotification, object: AppRateHelper.shared, userInfo: [kAppRateNotificationEvent:event])
}
}
private let eventFirebase = "eventFirebase"
extension AppRateHelper{
func addRateFirebaseEvent() {
NotificationCenter.default.addObserver(self, selector: #selector(AppRateHelper.onFirebaseEvent(a:)), name: AppRateNotification, object: eventFirebase)
}
func removeFirebaseEvent() {
NotificationCenter.default.removeObserver(self, name: AppRateNotification, object: eventFirebase)
}
@objc func onFirebaseEvent(a:Notification) {
if let event = a.userInfo?[kAppRateNotificationEvent] as? String{
AnManager.shared.firebaseEvent(event: event)
}
}
}
|
efbc8d618447d70453450b7acdb5c679
| 34.449275 | 161 | 0.62592 | false | false | false | false |
klaus01/Centipede
|
refs/heads/master
|
Centipede/Foundation/CE_NSMetadataQuery.swift
|
mit
|
1
|
//
// CE_NSMetadataQuery.swift
// Centipede
//
// Created by kelei on 2016/9/15.
// Copyright (c) 2016年 kelei. All rights reserved.
//
import Foundation
extension NSMetadataQuery {
private struct Static { static var AssociationKey: UInt8 = 0 }
private var _delegate: NSMetadataQuery_Delegate? {
get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? NSMetadataQuery_Delegate }
set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
private var ce: NSMetadataQuery_Delegate {
if let obj = _delegate {
return obj
}
if let obj: AnyObject = self.delegate {
if obj is NSMetadataQuery_Delegate {
return obj as! NSMetadataQuery_Delegate
}
}
let obj = getDelegateInstance()
_delegate = obj
return obj
}
private func rebindingDelegate() {
let delegate = ce
self.delegate = nil
self.delegate = delegate
}
internal func getDelegateInstance() -> NSMetadataQuery_Delegate {
return NSMetadataQuery_Delegate()
}
@discardableResult
public func ce_metadataQuery_replacementObjectForResultObject(handle: @escaping (NSMetadataQuery, NSMetadataItem) -> Any) -> Self {
ce._metadataQuery_replacementObjectForResultObject = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_metadataQuery_replacementValueForAttribute(handle: @escaping (NSMetadataQuery, String, Any) -> Any) -> Self {
ce._metadataQuery_replacementValueForAttribute = handle
rebindingDelegate()
return self
}
}
internal class NSMetadataQuery_Delegate: NSObject, NSMetadataQueryDelegate {
var _metadataQuery_replacementObjectForResultObject: ((NSMetadataQuery, NSMetadataItem) -> Any)?
var _metadataQuery_replacementValueForAttribute: ((NSMetadataQuery, String, Any) -> Any)?
override func responds(to aSelector: Selector!) -> Bool {
let funcDic1: [Selector : Any?] = [
#selector(metadataQuery(_:replacementObjectForResultObject:)) : _metadataQuery_replacementObjectForResultObject,
#selector(metadataQuery(_:replacementValueForAttribute:value:)) : _metadataQuery_replacementValueForAttribute,
]
if let f = funcDic1[aSelector] {
return f != nil
}
return super.responds(to: aSelector)
}
@objc func metadataQuery(_ query: NSMetadataQuery, replacementObjectForResultObject result: NSMetadataItem) -> Any {
return _metadataQuery_replacementObjectForResultObject!(query, result)
}
@objc func metadataQuery(_ query: NSMetadataQuery, replacementValueForAttribute attrName: String, value attrValue: Any) -> Any {
return _metadataQuery_replacementValueForAttribute!(query, attrName, attrValue)
}
}
|
d1f78006a709106d61f9596277612caa
| 34.809524 | 135 | 0.672207 | false | false | false | false |
abunur/quran-ios
|
refs/heads/master
|
Pods/GenericDataSources/Sources/UICollectionView+CollectionView.swift
|
gpl-3.0
|
3
|
//
// UICollectionView+CollectionView.swift
// GenericDataSource
//
// Created by Mohamed Afifi on 4/11/16.
// Copyright © 2016 mohamede1945. All rights reserved.
//
import Foundation
extension UICollectionView: GeneralCollectionView {
/**
Represents the underlying scroll view. Use this method if you want to get the
`UICollectionView`/`UITableView` itself not a wrapper.
So, if you have for example an instance like the following
```
let generalCollectionView: GeneralCollectionView = <...>
// Not Recommented, can result crashes if there is a CompositeDataSource.
let underlyingTableView = generalCollectionView as! UITableView
// Recommended, safer
let underlyingTableView = generalCollectionView.ds_scrollView as! UITableView
```
The later can result a crash if the scroll view is a UICollectionView not a UITableView.
*/
open var ds_scrollView: UIScrollView { return self }
/**
Just calls the corresponding method `registerNib(nib, forCellWithReuseIdentifier: identifier)`.
*/
open func ds_register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) {
register(nib, forCellWithReuseIdentifier: identifier)
}
/**
Just calls the corresponding method `registerClass(cellClass, forCellWithReuseIdentifier: identifier)`.
*/
open func ds_register(_ cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String) {
register(cellClass, forCellWithReuseIdentifier: identifier)
}
/**
Just calls the corresponding method `reloadData()`.
*/
open func ds_reloadData() {
reloadData()
}
/**
Just calls the corresponding method `performBatchUpdates(updates, completion: completion)`.
*/
open func ds_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) {
internal_performBatchUpdates(updates, completion: completion)
}
/**
Just calls the corresponding method `insertSections(sections)`.
*/
open func ds_insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
insertSections(sections)
}
/**
Just calls the corresponding method `deleteSections(sections)`.
*/
open func ds_deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
deleteSections(sections)
}
/**
Just calls the corresponding method `reloadSections(sections)`.
*/
open func ds_reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
reloadSections(sections)
}
/**
Just calls the corresponding method `moveSection(section, toSection: newSection)`.
*/
open func ds_moveSection(_ section: Int, toSection newSection: Int) {
moveSection(section, toSection: newSection)
}
/**
Just calls the corresponding method `insertItemsAtIndexPaths(indexPaths)`.
*/
open func ds_insertItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
insertItems(at: indexPaths)
}
/**
Just calls the corresponding method `deleteItemsAtIndexPaths(indexPaths)`.
*/
open func ds_deleteItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
deleteItems(at: indexPaths)
}
/**
Just calls the corresponding method `reloadItemsAtIndexPaths(indexPaths)`.
*/
open func ds_reloadItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) {
reloadItems(at: indexPaths)
}
/**
Just calls the corresponding method `moveItemAt(indexPath, toIndexPath: newIndexPath)`.
*/
open func ds_moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath) {
moveItem(at: indexPath, to: newIndexPath)
}
/**
Just calls the corresponding method `scrollToItemAt(indexPath, atScrollPosition: scrollPosition, animated: animated)`.
*/
open func ds_scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) {
scrollToItem(at: indexPath, at: scrollPosition, animated: animated)
}
/**
Just calls the corresponding method `selectItemAt(indexPath, animated: animated, scrollPosition: scrollPosition)`.
*/
open func ds_selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition) {
selectItem(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
/**
Just calls the corresponding method `deselectItemAt(indexPath, animated: animated)`.
*/
open func ds_deselectItem(at indexPath: IndexPath, animated: Bool) {
deselectItem(at: indexPath, animated: animated)
}
/**
Just calls the corresponding method `return dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)`.
*/
open func ds_dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableCell {
return dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
}
/**
Just calls the corresponding method `dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)`.
*/
open func ds_dequeueReusableSupplementaryView(ofKind kind: String, withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableSupplementaryView {
return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier, for: indexPath)
}
/**
Just calls the corresponding method `return indexPathForCell(cell)`.
*/
open func ds_indexPath(for reusableCell: ReusableCell) -> IndexPath? {
let cell: UICollectionViewCell = cast(reusableCell, message: "Cell '\(reusableCell)' should be of type UICollectionViewCell.")
return indexPath(for: cell)
}
/**
Just calls the corresponding method `return indexPathForItemAtPoint(point)`.
*/
open func ds_indexPathForItem(at point: CGPoint) -> IndexPath? {
return indexPathForItem(at: point)
}
/**
Just calls the corresponding method `return numberOfSections()`.
*/
open func ds_numberOfSections() -> Int {
return numberOfSections
}
/**
Just calls the corresponding method `return numberOfItemsInSection(section)`.
*/
open func ds_numberOfItems(inSection section: Int) -> Int {
return numberOfItems(inSection: section)
}
/**
Just calls the corresponding method `return cellForItemAt(indexPath)`.
*/
open func ds_cellForItem(at indexPath: IndexPath) -> ReusableCell? {
return cellForItem(at: indexPath)
}
/**
Just calls the corresponding method `visibleCells()`.
*/
open func ds_visibleCells() -> [ReusableCell] {
let cells = visibleCells
var reusableCells = [ReusableCell]()
for cell in cells {
reusableCells.append(cell)
}
return reusableCells
}
/**
Just calls the corresponding method `return indexPathsForVisibleItems()`.
*/
open func ds_indexPathsForVisibleItems() -> [IndexPath] {
return indexPathsForVisibleItems
}
/**
Just calls the corresponding method `return indexPathsForSelectedItems() ?? []`.
*/
open func ds_indexPathsForSelectedItems() -> [IndexPath] {
return indexPathsForSelectedItems ?? []
}
/**
Always returns the same value passed.
*/
open func ds_localIndexPathForGlobalIndexPath(_ globalIndex: IndexPath) -> IndexPath {
return globalIndex
}
/**
Always returns the same value passed.
*/
open func ds_globalIndexPathForLocalIndexPath(_ localIndex: IndexPath) -> IndexPath {
return localIndex
}
/**
Always returns the same value passed.
*/
open func ds_globalSectionForLocalSection(_ localSection: Int) -> Int {
return localSection
}
}
|
07dc4ac2eb8d005a6578e4d74df4d6dc
| 33.431034 | 162 | 0.686655 | false | false | false | false |
North-American-Signs/DKImagePickerController
|
refs/heads/develop
|
Sources/DKImagePickerController/View/Cell/DKAssetGroupDetailImageCell.swift
|
mit
|
2
|
//
// DKAssetGroupDetailImageCell.swift
// DKImagePickerController
//
// Created by ZhangAo on 07/12/2016.
// Copyright © 2016 ZhangAo. All rights reserved.
//
import UIKit
@objcMembers
public class DKAssetGroupDetailImageCell: DKAssetGroupDetailBaseCell {
public class override func cellReuseIdentifier() -> String {
return "DKImageAssetIdentifier"
}
override init(frame: CGRect) {
super.init(frame: frame)
self.thumbnailImageView.frame = self.bounds
self.thumbnailImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.contentView.addSubview(self.thumbnailImageView)
self.checkView.frame = self.bounds
self.checkView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.checkView.checkImageView.tintColor = nil
self.checkView.checkLabel.font = UIFont.boldSystemFont(ofSize: 14)
self.checkView.checkLabel.textColor = UIColor.white
self.contentView.addSubview(self.checkView)
self.contentView.accessibilityIdentifier = "DKImageAssetAccessibilityIdentifier"
self.contentView.isAccessibilityElement = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open class DKImageCheckView: UIView {
internal lazy var checkImageView: UIImageView = {
let imageView = UIImageView(image: DKImagePickerControllerResource.checkedImage())
return imageView
}()
internal lazy var checkLabel: UILabel = {
let label = UILabel()
label.textAlignment = .right
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.checkImageView)
self.addSubview(self.checkLabel)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func layoutSubviews() {
super.layoutSubviews()
self.checkImageView.frame = self.bounds
self.checkLabel.frame = CGRect(x: 0, y: 5, width: self.bounds.width - 5, height: 20)
}
} /* DKImageCheckView */
override public var thumbnailImage: UIImage? {
didSet {
self.thumbnailImageView.image = self.thumbnailImage
}
}
override public var selectedIndex: Int {
didSet {
self.checkView.checkLabel.text = "\(self.selectedIndex + 1)"
}
}
internal lazy var _thumbnailImageView: UIImageView = {
let thumbnailImageView = UIImageView()
thumbnailImageView.contentMode = .scaleAspectFill
thumbnailImageView.clipsToBounds = true
return thumbnailImageView
}()
override public var thumbnailImageView: UIImageView {
get {
return _thumbnailImageView
}
}
public let checkView = DKImageCheckView()
override public var isSelected: Bool {
didSet {
self.checkView.isHidden = !super.isSelected
}
}
} /* DKAssetGroupDetailCell */
|
294b91ddb851bb77fea8c63efc3f8661
| 30.132075 | 96 | 0.619697 | false | false | false | false |
CGLueng/DYTV
|
refs/heads/master
|
DYZB/DYZB/Classes/Main/Controller/BasicAnchorViewController.swift
|
mit
|
1
|
//
// BasicAnchorViewController.swift
// DYZB
//
// Created by CGLueng on 2016/12/24.
// Copyright © 2016年 com.ruixing. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin) * 0.5
private let kNormalItemH = kItemW * 3 / 4
private let kPrettyItemH = kItemW * 4 / 3
private let kheaderH : CGFloat = 50
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
private let kHeaderViewID = "kHeaderViewID"
class BasicAnchorViewController: UIViewController {
// MARK:- 定义属性
var basicVM : BasicViewModel!
lazy var collectionView : UICollectionView = {[unowned self] in
//创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kheaderH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
//创建collectionview
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
//宽高随着父控件拉伸而拉伸
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
//注册 cell
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
//注册组头
// collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName: "HomeCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK:- 设置 UI
extension BasicAnchorViewController {
func setupUI() {
view.addSubview(collectionView)
}
}
// MARK:- 请求数据
extension BasicAnchorViewController {
func loadData() {
}
}
// MARK:- 遵守 UIcollectionview 的数据源
extension BasicAnchorViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return basicVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return basicVM.anchorGroups[section].anchorArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
//设置数据
cell.anchor = basicVM.anchorGroups[indexPath.section].anchorArr[indexPath.item]
return cell;
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! HomeCollectionHeaderView
headView.group = basicVM.anchorGroups[indexPath.section]
return headView
}
}
// MARK:- 遵守 UIcollectionview 的代理
extension BasicAnchorViewController : UICollectionViewDelegate {
}
|
0bf47197de60719b9d2fc07d07191f48
| 36.953271 | 190 | 0.721005 | false | false | false | false |
xlexi/Textual-Inline-Media
|
refs/heads/master
|
Textual Inline Media/Inline Media Handlers/Wikipedia.swift
|
bsd-3-clause
|
1
|
/*
Copyright (c) 2015, Alex S. Glomsaas
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
class Wikipedia: NSObject, InlineMediaHandler {
static func name() -> String {
return "Wikipedia"
}
static func icon() -> NSImage? {
return NSImage.fromAssetCatalogue("Wikipedia")
}
required convenience init(url: NSURL, controller: TVCLogController, line: String) {
self.init()
if let query = url.pathComponents?[2] {
let requestString = "format=json&action=query&exsentences=4&prop=extracts|pageimages&titles=\(query)&pithumbsize=200"
.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let subdomain = url.host?.componentsSeparatedByString(".")[0]
guard subdomain != nil else {
return
}
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["User-Agent": "TextualInlineMedia/1.0 (https://github.com/xlexi/Textual-Inline-Media/; alex@sorlie.co.uk)"]
let session = NSURLSession(configuration: config)
if let requestUrl = NSURL(string: "https://\(subdomain!).wikipedia.org/w/api.php?\(requestString)") {
session.dataTaskWithURL(requestUrl, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard data != nil else {
return
}
do {
/* Attempt to serialise the JSON results into a dictionary. */
let root = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
guard let query = root["query"] as? Dictionary<String, AnyObject> else {
return
}
guard let pages = query["pages"] as? Dictionary<String, AnyObject> else {
WebRequest(url: response!.URL!, controller: controller, line: line).start()
return
}
let page = pages.first!
if page.0 != "-1" {
guard let article = page.1 as? Dictionary<String, AnyObject> else {
return
}
let title = article["title"] as? String
let description = article["extract"] as? String
var thumbnailUrl = ""
if let thumbnail = article["thumbnail"] as? Dictionary<String, AnyObject> {
guard let source = thumbnail["source"] as? String else {
return
}
thumbnailUrl = source
}
self.performBlockOnMainThread({
let document = controller.webView.mainFrameDocument
/* Create the container for the entire inline media element. */
let wikiContainer = document.createElement("a")
wikiContainer.setAttribute("href", value: url.absoluteString)
wikiContainer.className = "inline_media_wiki"
/* If we found a preview image element, we will add it. */
if thumbnailUrl.characters.count > 0 {
let previewImage = document.createElement("img")
previewImage.className = "inline_media_wiki_thumbnail"
previewImage.setAttribute("src", value: thumbnailUrl)
wikiContainer.appendChild(previewImage)
}
/* Create the container that holds the title and description. */
let infoContainer = document.createElement("div")
infoContainer.className = "inline_media_wiki_info"
wikiContainer.appendChild(infoContainer)
/* Create the title element */
let titleElement = document.createElement("div")
titleElement.className = "inline_media_wiki_title"
titleElement.appendChild(document.createTextNode(title))
infoContainer.appendChild(titleElement)
/* If we found a description, create the description element. */
if description!.characters.count > 0 {
let descriptionElement = document.createElement("div")
descriptionElement.className = "inline_media_wiki_desc"
descriptionElement.innerHTML = description
infoContainer.appendChild(descriptionElement)
}
controller.insertInlineMedia(line, node: wikiContainer, url: url.absoluteString)
})
}
} catch {
return
}
}).resume()
}
}
}
static func matchesServiceSchema(url: NSURL) -> Bool {
if url.host?.hasSuffix(".wikipedia.org") == true && url.pathComponents?.count === 3 {
return url.pathComponents![1] == "wiki"
}
return false
}
}
|
84106b3350e082434d899a1d2423a2f3
| 53.111888 | 151 | 0.519773 | false | false | false | false |
lennet/proNotes
|
refs/heads/master
|
app/proNotes/DocumentOverview/RenameDocumentManager.swift
|
mit
|
1
|
//
// RenameDocumentManager.swift
// proNotes
//
// Created by Leo Thomas on 19/09/2016.
// Copyright © 2016 leonardthomas. All rights reserved.
//
import UIKit
struct RenameDocumentManager {
var oldURL: URL
var newName: String
weak var viewController: UIViewController?
var completion: ((Bool, URL?) -> ())
var documentManager: DocumentManager {
return DocumentManager.sharedInstance
}
func rename() {
if documentManager.fileNameExistsInObjects(newName) {
showFileExistsAlert(to: viewController)
} else {
moveDocument()
}
}
private func moveDocument() {
let newURL = DocumentManager.sharedInstance.getDocumentURL(newName, uniqueFileName: true)
documentManager.moveObject(fromURL: oldURL, to: newURL, completion: { (success, error) in
if success && error == nil {
self.callCompletion(success: true, url: newURL)
} else {
self.showUnknownErrorMessage()
}
})
}
private func override() {
let newURL = DocumentManager.sharedInstance.getDocumentURL(newName, uniqueFileName: false)
guard let object = documentManager.objectForURL(newURL) else {
showUnknownErrorMessage()
return
}
documentManager.deleteObject(object) { (success, error) in
DispatchQueue.main.async(execute: {
if success && error == nil {
self.moveDocument()
} else {
self.showUnknownErrorMessage()
}
})
}
}
func showFileExistsAlert(to viewController: UIViewController?) {
let alertView = UIAlertController(title: nil, message: NSLocalizedString("ErrorFileAlreadyExists", comment:"error message if a file with the given name already exists & ask for override"), preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: NSLocalizedString("Override", comment:""), style: .destructive, handler: {
(action) -> Void in
self.override()
}))
alertView.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:""), style: .cancel, handler: {
(action) -> Void in
self.callCompletion(success: false, url: nil)
}))
viewController?.present(alertView, animated: true, completion: nil)
}
func showUnknownErrorMessage() {
let alertView = UIAlertController(title: nil, message: NSLocalizedString("ErrorUnknown", comment:""), preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: NSLocalizedString("Ok", comment:""), style: .default, handler: {
(action) -> Void in
self.callCompletion(success: false, url: nil)
}))
viewController?.present(alertView, animated: true, completion: nil)
}
func callCompletion(success: Bool, url: URL?) {
DispatchQueue.main.async(execute: {
self.completion(success, url)
})
}
}
|
e961e382e476049b2ba2aa0538e98e77
| 35.127907 | 220 | 0.612488 | false | false | false | false |
stulevine/firefox-ios
|
refs/heads/master
|
Storage/SQL/SQLFavicons.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
/**
* The sqlite-backed implementation of the favicons protocol.
*/
public class SQLiteFavicons : Favicons {
let files: FileAccessor
let db: BrowserDB
let table = JoinedFaviconsHistoryTable<(Site, Favicon)>()
lazy public var defaultIcon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
required public init(files: FileAccessor) {
self.files = files
self.db = BrowserDB(files: files)!
db.createOrUpdate(table)
}
public func clear(options: QueryOptions?, complete: ((success: Bool) -> Void)?) {
var err: NSError? = nil
let res = db.delete(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: nil, err: &err)
}
files.remove("favicons")
dispatch_async(dispatch_get_main_queue()) {
complete?(success: err == nil)
return
}
}
public func get(options: QueryOptions?, complete: (data: Cursor) -> Void) {
var err: NSError? = nil
let res = db.query(&err) { connection, err in
return self.table.query(connection, options: options)
}
dispatch_async(dispatch_get_main_queue()) {
complete(data: res)
}
}
public func add(icon: Favicon, site: Site, complete: ((success: Bool) -> Void)?) {
var err: NSError? = nil
let res = db.insert(&err) { (conn, inout err: NSError?) -> Int in
return self.table.insert(conn, item: (icon: icon, site: site), err: &err)
}
dispatch_async(dispatch_get_main_queue()) {
complete?(success: err == nil)
return
}
}
private let debug_enabled = false
private func debug(msg: String) {
if debug_enabled {
println("FaviconsSqlite: " + msg)
}
}
}
|
9c78c466961c19a92f74c8ba6fee20a1
| 29.26087 | 86 | 0.588602 | false | false | false | false |
mbogh/ProfileKit
|
refs/heads/master
|
ProfileKit/Profile.swift
|
mit
|
1
|
//
// Profile.swift
// ProfileKit
//
// Created by Morten Bøgh on 25/01/15.
// Copyright (c) 2015 Morten Bøgh. All rights reserved.
//
import Foundation
public enum ProfileStatus {
case Expired
case OK
var description: String {
switch self {
case .Expired: return "Expired"
case .OK: return "OK"
}
}
}
public struct Profile {
public let filePath: String
public let name: String
public let creationDate: NSDate
public let expirationDate: NSDate
public let teamName: String?
public let teamID: String?
public var status: ProfileStatus {
return (expirationDate.compare(NSDate()) != .OrderedDescending) ? .Expired : .OK
}
/// Designated initializer
public init?(filePath path: String, data: NSDictionary) {
filePath = path
if data["Name"] == nil { return nil }
if data["CreationDate"] == nil { return nil }
if data["ExpirationDate"] == nil { return nil }
name = data["Name"] as String
creationDate = data["CreationDate"] as NSDate
expirationDate = data["ExpirationDate"] as NSDate
teamName = data["TeamName"] as? String
teamID = bind(data["TeamIdentifier"]) { teamIdentifiers in (teamIdentifiers as [String]).first }
}
}
|
1b7e1baacb70514184046cfb8e148817
| 24.076923 | 104 | 0.629317 | false | false | false | false |
HongliYu/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/TemporaryDocument.swift
|
mpl-2.0
|
3
|
/* 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 Deferred
import Shared
private let temporaryDocumentOperationQueue = OperationQueue()
class TemporaryDocument: NSObject {
fileprivate let request: URLRequest
fileprivate let filename: String
fileprivate var session: URLSession?
fileprivate var downloadTask: URLSessionDownloadTask?
fileprivate var localFileURL: URL?
fileprivate var pendingResult: Deferred<URL>?
init(preflightResponse: URLResponse, request: URLRequest) {
self.request = request
self.filename = preflightResponse.suggestedFilename ?? "unknown"
super.init()
self.session = URLSession(configuration: .default, delegate: self, delegateQueue: temporaryDocumentOperationQueue)
}
deinit {
// Delete the temp file.
if let url = localFileURL {
try? FileManager.default.removeItem(at: url)
}
}
func getURL() -> Deferred<URL> {
if let url = localFileURL {
let result = Deferred<URL>()
result.fill(url)
return result
}
if let result = pendingResult {
return result
}
let result = Deferred<URL>()
pendingResult = result
downloadTask = session?.downloadTask(with: request)
downloadTask?.resume()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
return result
}
}
extension TemporaryDocument: URLSessionTaskDelegate, URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
ensureMainThread {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// If we encounter an error downloading the temp file, just return with the
// original remote URL so it can still be shared as a web URL.
if error != nil, let remoteURL = request.url {
pendingResult?.fill(remoteURL)
pendingResult = nil
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TempDocs")
let url = tempDirectory.appendingPathComponent(filename)
try? FileManager.default.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil)
try? FileManager.default.removeItem(at: url)
do {
try FileManager.default.moveItem(at: location, to: url)
localFileURL = url
pendingResult?.fill(url)
pendingResult = nil
} catch {
// If we encounter an error downloading the temp file, just return with the
// original remote URL so it can still be shared as a web URL.
if let remoteURL = request.url {
pendingResult?.fill(remoteURL)
pendingResult = nil
}
}
}
}
|
76fdaaa84680d720e3282e98bf2bf9c5
| 32.8 | 122 | 0.657428 | false | false | false | false |
Baza207/Alamofire
|
refs/heads/Doharmony
|
Alamofire/Tests/ServerTrustPolicyTests.swift
|
apache-2.0
|
15
|
// MultipartFormDataTests.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
private struct TestCertificates {
// Root Certificates
static let RootCA = TestCertificates.certificateWithFileName("alamofire-root-ca")
// Intermediate Certificates
static let IntermediateCA1 = TestCertificates.certificateWithFileName("alamofire-signing-ca1")
static let IntermediateCA2 = TestCertificates.certificateWithFileName("alamofire-signing-ca2")
// Leaf Certificates - Signed by CA1
static let LeafWildcard = TestCertificates.certificateWithFileName("wildcard.alamofire.org")
static let LeafMultipleDNSNames = TestCertificates.certificateWithFileName("multiple-dns-names")
static let LeafSignedByCA1 = TestCertificates.certificateWithFileName("signed-by-ca1")
static let LeafDNSNameAndURI = TestCertificates.certificateWithFileName("test.alamofire.org")
// Leaf Certificates - Signed by CA2
static let LeafExpired = TestCertificates.certificateWithFileName("expired")
static let LeafMissingDNSNameAndURI = TestCertificates.certificateWithFileName("missing-dns-name-and-uri")
static let LeafSignedByCA2 = TestCertificates.certificateWithFileName("signed-by-ca2")
static let LeafValidDNSName = TestCertificates.certificateWithFileName("valid-dns-name")
static let LeafValidURI = TestCertificates.certificateWithFileName("valid-uri")
static func certificateWithFileName(fileName: String) -> SecCertificate {
class Bundle {}
let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
let data = NSData(contentsOfFile: filePath)!
let certificate = SecCertificateCreateWithData(nil, data)!
return certificate
}
}
// MARK: -
private struct TestPublicKeys {
// Root Public Keys
static let RootCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.RootCA)
// Intermediate Public Keys
static let IntermediateCA1 = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA1)
static let IntermediateCA2 = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA2)
// Leaf Public Keys - Signed by CA1
static let LeafWildcard = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafWildcard)
static let LeafMultipleDNSNames = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafMultipleDNSNames)
static let LeafSignedByCA1 = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafSignedByCA1)
static let LeafDNSNameAndURI = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafDNSNameAndURI)
// Leaf Public Keys - Signed by CA2
static let LeafExpired = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafExpired)
static let LeafMissingDNSNameAndURI = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafMissingDNSNameAndURI)
static let LeafSignedByCA2 = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafSignedByCA2)
static let LeafValidDNSName = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafValidDNSName)
static let LeafValidURI = TestPublicKeys.publicKeyForCertificate(TestCertificates.LeafValidURI)
static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
SecTrustCreateWithCertificates(certificate, policy, &trust)
let publicKey = SecTrustCopyPublicKey(trust!)!
return publicKey
}
}
// MARK: -
private enum TestTrusts {
// Leaf Trusts - Signed by CA1
case LeafWildcard
case LeafMultipleDNSNames
case LeafSignedByCA1
case LeafDNSNameAndURI
// Leaf Trusts - Signed by CA2
case LeafExpired
case LeafMissingDNSNameAndURI
case LeafSignedByCA2
case LeafValidDNSName
case LeafValidURI
// Invalid Trusts
case LeafValidDNSNameMissingIntermediate
case LeafValidDNSNameWithIncorrectIntermediate
var trust: SecTrust {
let trust: SecTrust
switch self {
case .LeafWildcard:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafWildcard,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafMultipleDNSNames:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafMultipleDNSNames,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafSignedByCA1:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafSignedByCA1,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafDNSNameAndURI:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafDNSNameAndURI,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
case .LeafExpired:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafExpired,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafMissingDNSNameAndURI:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafMissingDNSNameAndURI,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafSignedByCA2:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafSignedByCA2,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafValidDNSName:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case .LeafValidURI:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidURI,
TestCertificates.IntermediateCA2,
TestCertificates.RootCA
])
case LeafValidDNSNameMissingIntermediate:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.RootCA
])
case LeafValidDNSNameWithIncorrectIntermediate:
trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
}
return trust
}
static func trustWithCertificates(certificates: [SecCertificate]) -> SecTrust {
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
SecTrustCreateWithCertificates(certificates, policy, &trust)
return trust!
}
}
// MARK: - Basic X509 and SSL Exploration Tests -
class ServerTrustPolicyTestCase: BaseTestCase {
func setRootCertificateAsLoneAnchorCertificateForTrust(trust: SecTrust) {
SecTrustSetAnchorCertificates(trust, [TestCertificates.RootCA])
SecTrustSetAnchorCertificatesOnly(trust, true)
}
func trustIsValid(trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType(kSecTrustResultInvalid)
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType(kSecTrustResultUnspecified)
let proceed = SecTrustResultType(kSecTrustResultProceed)
isValid = result == unspecified || result == proceed
}
return isValid
}
}
// MARK: -
class ServerTrustPolicyExplorationBasicX509PolicyValidationTestCase: ServerTrustPolicyTestCase {
func testThatAnchoredRootCertificatePassesBasicX509ValidationWithRootInTrust() {
// Given
let trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafDNSNameAndURI,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatAnchoredRootCertificatePassesBasicX509ValidationWithoutRootInTrust() {
// Given
let trust = TestTrusts.LeafDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatCertificateMissingDNSNamePassesBasicX509Validation() {
// Given
let trust = TestTrusts.LeafMissingDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatExpiredCertificateFailsBasicX509Validation() {
// Given
let trust = TestTrusts.LeafExpired.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateBasicX509()]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
}
// MARK: -
class ServerTrustPolicyExplorationSSLPolicyValidationTestCase: ServerTrustPolicyTestCase {
func testThatAnchoredRootCertificatePassesSSLValidationWithRootInTrust() {
// Given
let trust = TestTrusts.trustWithCertificates([
TestCertificates.LeafDNSNameAndURI,
TestCertificates.IntermediateCA1,
TestCertificates.RootCA
])
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatAnchoredRootCertificatePassesSSLValidationWithoutRootInTrust() {
// Given
let trust = TestTrusts.LeafDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatCertificateMissingDNSNameFailsSSLValidation() {
// Given
let trust = TestTrusts.LeafMissingDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
func testThatWildcardCertificatePassesSSLValidation() {
// Given
let trust = TestTrusts.LeafWildcard.trust // *.alamofire.org
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatDNSNameCertificatePassesSSLValidation() {
// Given
let trust = TestTrusts.LeafValidDNSName.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should be valid")
}
func testThatURICertificateFailsSSLValidation() {
// Given
let trust = TestTrusts.LeafValidURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
func testThatMultipleDNSNamesCertificatePassesSSLValidationForAllEntries() {
// Given
let trust = TestTrusts.LeafMultipleDNSNames.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [
SecPolicyCreateSSL(true, "test.alamofire.org"),
SecPolicyCreateSSL(true, "blog.alamofire.org"),
SecPolicyCreateSSL(true, "www.alamofire.org")
]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should not be valid")
}
func testThatPassingNilForHostParameterAllowsCertificateMissingDNSNameToPassSSLValidation() {
// Given
let trust = TestTrusts.LeafMissingDNSNameAndURI.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, nil)]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertTrue(trustIsValid(trust), "trust should not be valid")
}
func testThatExpiredCertificateFailsSSLValidation() {
// Given
let trust = TestTrusts.LeafExpired.trust
setRootCertificateAsLoneAnchorCertificateForTrust(trust)
// When
let policies = [SecPolicyCreateSSL(true, "test.alamofire.org")]
SecTrustSetPolicies(trust, policies)
// Then
XCTAssertFalse(trustIsValid(trust), "trust should not be valid")
}
}
// MARK: - Server Trust Policy Tests -
class ServerTrustPolicyPerformDefaultEvaluationTestCase: ServerTrustPolicyTestCase {
// MARK: Do NOT Validate Host
func testThatValidCertificateChainPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatNonAnchoredRootCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA2
])
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingDNSNameLeafCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafMissingDNSNameAndURI.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatExpiredCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingIntermediateCertificateInChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: false)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
// MARK: Validate Host
func testThatValidCertificateChainPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatNonAnchoredRootCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.trustWithCertificates([
TestCertificates.LeafValidDNSName,
TestCertificates.IntermediateCA2
])
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingDNSNameLeafCertificateFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafMissingDNSNameAndURI.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatWildcardedLeafCertificateChainPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafWildcard.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatExpiredCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatMissingIntermediateCertificateInChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let serverTrustPolicy = ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyPinCertificatesTestCase: ServerTrustPolicyTestCase {
// MARK: Validate Certificate Chain Without Validating Host
func testThatPinnedLeafCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedIntermediateCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedRootCertificatePassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafCertificateNotInCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateNotInCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA1]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningExpiredLeafCertificateFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateWithExpiredLeafCertificateFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
// MARK: Validate Certificate Chain and Host
func testThatPinnedLeafCertificatePassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedIntermediateCertificatePassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedRootCertificatePassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafCertificateNotInCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateNotInCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA1]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningExpiredLeafCertificateFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateWithExpiredLeafCertificateFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: true,
validateHost: true
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
// MARK: Do NOT Validate Certificate Chain or Host
func testThatPinnedLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedIntermediateCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinnedRootCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafCertificateNotInCertificateChainWithoutCertificateChainValidationFailsEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningIntermediateCertificateNotInCertificateChainWithoutCertificateChainValidationFailsEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let certificates = [TestCertificates.IntermediateCA1]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateCertificateWithExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootCertificateWithExpiredLeafCertificateWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [TestCertificates.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningMultipleCertificatesWithoutCertificateChainValidationPassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let certificates = [
TestCertificates.LeafMultipleDNSNames, // not in certificate chain
TestCertificates.LeafSignedByCA1, // not in certificate chain
TestCertificates.LeafExpired, // in certificate chain 👍🏼👍🏼
TestCertificates.LeafWildcard, // not in certificate chain
TestCertificates.LeafDNSNameAndURI, // not in certificate chain
]
let serverTrustPolicy = ServerTrustPolicy.PinCertificates(
certificates: certificates,
validateCertificateChain: false,
validateHost: false
)
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyPinPublicKeysTestCase: ServerTrustPolicyTestCase {
// MARK: Validate Certificate Chain Without Validating Host
func testThatPinningLeafKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningKeyNotInCertificateChainFailsEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningBackupKeyPassesEvaluationWithoutHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA1, TestPublicKeys.IntermediateCA1, TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
// MARK: Validate Certificate Chain and Host
func testThatPinningLeafKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningKeyNotInCertificateChainFailsEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningBackupKeyPassesEvaluationWithHostValidation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let publicKeys = [TestPublicKeys.LeafSignedByCA1, TestPublicKeys.IntermediateCA1, TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: true,
validateHost: true
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
// MARK: Do NOT Validate Certificate Chain or Host
func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithMissingIntermediateCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyWithoutCertificateChainValidationFailsEvaluationWithMissingIntermediateCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithIncorrectIntermediateCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameWithIncorrectIntermediate.trust
let publicKeys = [TestPublicKeys.LeafValidDNSName]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningLeafKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let publicKeys = [TestPublicKeys.LeafExpired]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningIntermediateKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let publicKeys = [TestPublicKeys.IntermediateCA2]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatPinningRootKeyWithoutCertificateChainValidationPassesEvaluationWithExpiredLeafCertificate() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let publicKeys = [TestPublicKeys.RootCA]
let serverTrustPolicy = ServerTrustPolicy.PinPublicKeys(
publicKeys: publicKeys,
validateCertificateChain: false,
validateHost: false
)
// When
setRootCertificateAsLoneAnchorCertificateForTrust(serverTrust)
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyDisableEvaluationTestCase: ServerTrustPolicyTestCase {
func testThatCertificateChainMissingIntermediateCertificatePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSNameMissingIntermediate.trust
let serverTrustPolicy = ServerTrustPolicy.DisableEvaluation
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatExpiredLeafCertificatePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafExpired.trust
let serverTrustPolicy = ServerTrustPolicy.DisableEvaluation
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyCustomEvaluationTestCase: ServerTrustPolicyTestCase {
func testThatReturningTrueFromClosurePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.CustomEvaluation { _, _ in
return true
}
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertTrue(serverTrustIsValid, "server trust should pass evaluation")
}
func testThatReturningFalseFromClosurePassesEvaluation() {
// Given
let host = "test.alamofire.org"
let serverTrust = TestTrusts.LeafValidDNSName.trust
let serverTrustPolicy = ServerTrustPolicy.CustomEvaluation { _, _ in
return false
}
// When
let serverTrustIsValid = serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host)
// Then
XCTAssertFalse(serverTrustIsValid, "server trust should not pass evaluation")
}
}
// MARK: -
class ServerTrustPolicyCertificatesInBundleTestCase: ServerTrustPolicyTestCase {
func testOnlyValidCertificatesAreDetected() {
// Given
// Files present in bundle in the form of type+encoding+extension [key|cert][DER|PEM].[cer|crt|der|key|pem]
// certDER.cer: DER-encoded well-formed certificate
// certDER.crt: DER-encoded well-formed certificate
// certDER.der: DER-encoded well-formed certificate
// certPEM.*: PEM-encoded well-formed certificates, expected to fail: Apple API only handles DER encoding
// devURandomGibberish.crt: Random data, should fail
// keyDER.der: DER-encoded key, not a certificate, should fail
// When
let certificates = ServerTrustPolicy.certificatesInBundle(
NSBundle(forClass: ServerTrustPolicyCertificatesInBundleTestCase.self)
)
// Then
// Expectation: 18 well-formed certificates in the test bundle plus 4 invalid certificates.
#if os(OSX)
// For some reason, OSX is allowing all certificates to be considered valid. Need to file a
// rdar demonstrating this behavior.
XCTAssertEqual(certificates.count, 22, "Expected 22 well-formed certificates")
#else
XCTAssertEqual(certificates.count, 18, "Expected 18 well-formed certificates")
#endif
}
}
|
b9992b2415e2f7f7870410bed56f5c95
| 37.684767 | 126 | 0.702142 | false | true | false | false |
Killectro/RxGrailed
|
refs/heads/master
|
RxGrailed/RxGrailed/ViewModels/ListingViewModel.swift
|
mit
|
1
|
//
// ListingViewModel.swift
// RxGrailed
//
// Created by DJ Mitchell on 2/25/17.
// Copyright © 2017 Killectro. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import Kingfisher
/// Defines the basic information necessary to display a listing
protocol ListingDisplayable {
var image: Driver<UIImage?> { get }
var price: String { get }
var designer: String { get }
var title: String { get }
var description: String { get }
var size: String { get }
var titleAndSize: String { get }
var sellerName: String { get }
}
final class ListingViewModel: ListingDisplayable {
// MARK: Public properties
let image: Driver<UIImage?>
let price: String
let designer: String
let title: String
let description: String
let size: String
let titleAndSize: String
let sellerName: String
// MARK: Private properties
private let listing: Listing
// MARK: Initialization
init(listing: Listing) {
self.listing = listing
image = KingfisherManager.shared.rx
.image(URL: listing.imageUrl, optionsInfo: [.backgroundDecode])
.retry(3)
.map(Optional.some)
// When an image fetch is cancelled it returns an error, but we don't want to
// bind that error to our UI so we catch it here and just return `nil`
.asDriver(onErrorJustReturn: nil)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 0
// Force unwrap here is safe because we have an integer, which
// can always be turned into a currency value
price = formatter.string(from: listing.price as NSNumber)!
designer = listing.designer.uppercased()
title = listing.title
description = listing.description
size = listing.size.uppercased()
titleAndSize = title + " size " + size
sellerName = listing.sellerName.uppercased()
}
}
|
aa5d39b5e6bd49a9842a5f83dc7ec6d8
| 26.958333 | 89 | 0.653254 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/Interpreter/imported_objc_generics.swift
|
apache-2.0
|
35
|
// RUN: %empty-directory(%t)
//
// RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o
// RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ %t/ObjCClasses.o %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import StdlibUnittest
import ObjCClasses
var ImportedObjCGenerics = TestSuite("ImportedObjCGenerics")
ImportedObjCGenerics.test("Creation") {
let cs = Container<NSString>(object: "i-just-met-you")
expectEqual("i-just-met-you", cs.object)
expectTrue(type(of: cs) === Container<NSString>.self)
expectTrue(type(of: cs) === Container<AnyObject>.self)
}
ImportedObjCGenerics.test("Blocks") {
let cs = Container<NSString>(object: "and-this-is-crazy")
var fromBlock: NSString = ""
cs.processObject { fromBlock = $0 }
expectEqual("and-this-is-crazy", fromBlock)
cs.updateObject { "but-heres-my-number" }
expectEqual("but-heres-my-number", cs.object)
}
ImportedObjCGenerics.test("Categories") {
let cs = Container<NSString>(cat1: "so-call-me-maybe")
expectEqual("so-call-me-maybe", cs.getCat1())
cs.setCat1("its-hard-to-look-right")
expectEqual("its-hard-to-look-right", cs.cat1Property)
}
ImportedObjCGenerics.test("Subclasses") {
let subContainer = SubContainer<NSString>(object: "at-you-baby")
expectEqual("at-you-baby", subContainer.object)
let nestedContainer = NestedContainer<NSString>(object: Container(object: "but-heres-my-number"))
expectEqual("but-heres-my-number", nestedContainer.object.object)
let stringContainer = StringContainer(object: "so-call-me-maybe")
expectEqual("so-call-me-maybe", stringContainer.object)
}
ImportedObjCGenerics.test("SwiftGenerics") {
func openContainer<T: AnyObject>(_ x: Container<T>) -> T {
return x.object
}
func openStringContainer<T: Container<NSString>>(_ x: T) -> NSString {
return x.object
}
func openArbitraryContainer<S: AnyObject, T: Container<S>>(_ x: T) -> S {
return x.object
}
let scs = SubContainer<NSString>(object: "before-you-came-into-my-life")
expectEqual("before-you-came-into-my-life", openContainer(scs))
expectEqual("before-you-came-into-my-life", openStringContainer(scs))
expectEqual("before-you-came-into-my-life", openArbitraryContainer(scs))
let cs = Container<NSString>(object: "i-missed-you-so-bad")
expectEqual("i-missed-you-so-bad", openContainer(cs))
expectEqual("i-missed-you-so-bad", openStringContainer(cs))
expectEqual("i-missed-you-so-bad", openArbitraryContainer(cs))
let strContainer = SubContainer<NSString>(object: "i-missed-you-so-so-bad")
expectEqual("i-missed-you-so-so-bad", openContainer(strContainer))
expectEqual("i-missed-you-so-so-bad", openStringContainer(strContainer))
expectEqual("i-missed-you-so-so-bad", openArbitraryContainer(strContainer))
let numContainer = Container<NSNumber>(object: NSNumber(value: 21))
expectEqual(NSNumber(value: 21), openContainer(numContainer))
expectEqual(NSNumber(value: 21), openArbitraryContainer(numContainer))
let subNumContainer = SubContainer<NSNumber>(object: NSNumber(value: 22))
expectEqual(NSNumber(value: 22), openContainer(subNumContainer))
expectEqual(NSNumber(value: 22), openArbitraryContainer(subNumContainer))
}
ImportedObjCGenerics.test("SwiftGenerics/Creation") {
func makeContainer<T: AnyObject>(_ x: T) -> Container<T> {
return Container(object: x)
}
let c = makeContainer(NSNumber(value: 22))
expectEqual(NSNumber(value: 22), c.object)
}
ImportedObjCGenerics.test("ProtocolConstraints") {
func copyContainerContents<T: NSCopying>(_ x: CopyingContainer<T>) -> T {
return x.object.copy(with: nil) as! T
}
let cs = CopyingContainer<NSString>(object: "Happy 2012")
expectEqual("Happy 2012", copyContainerContents(cs))
}
ImportedObjCGenerics.test("ClassConstraints") {
func makeContainedAnimalMakeNoise<T>(x: AnimalContainer<T>) -> NSString {
return x.object.noise as NSString
}
let petCarrier = AnimalContainer(object: Dog())
expectEqual("woof", makeContainedAnimalMakeNoise(x: petCarrier))
}
@objc @objcMembers class ClassWithMethodsUsingObjCGenerics: NSObject {
func copyContainer(_ x: CopyingContainer<NSString>) -> CopyingContainer<NSString> {
return x
}
func maybeCopyContainer(_ x: CopyingContainer<NSString>) -> CopyingContainer<NSString>? {
return x
}
}
ImportedObjCGenerics.test("ClassWithMethodsUsingObjCGenerics") {
let x: AnyObject = ClassWithMethodsUsingObjCGenerics()
let y = CopyingContainer<NSString>(object: "")
let z = x.copyContainer(y)
expectTrue(y === z)
let w = x.perform(#selector(ClassWithMethodsUsingObjCGenerics.copyContainer), with: y).takeUnretainedValue()
expectTrue(y === w)
let zq = x.maybeCopyContainer(y)
expectTrue(y === zq!)
let wq = x.perform(#selector(ClassWithMethodsUsingObjCGenerics.maybeCopyContainer), with: y).takeUnretainedValue()
expectTrue(y === wq)
}
ImportedObjCGenerics.test("InheritanceFromNongeneric") {
// Test NSObject methods inherited into Container<>
let gc = Container<NSString>(object: "")
expectTrue(gc.description.range(of: "Container") != nil)
expectTrue(type(of: gc).superclass() == NSObject.self)
expectTrue(Container<NSString>.superclass() == NSObject.self)
expectTrue(Container<NSObject>.superclass() == NSObject.self)
expectTrue(Container<NSObject>.self == Container<NSString>.self)
}
public class InheritInSwift: Container<NSString> {
public override init(object: NSString) {
super.init(object: object.lowercased as NSString)
}
public override var object: NSString {
get {
return super.object.uppercased as NSString
}
set {
super.object = newValue.lowercased as NSString
}
}
public var superObject: NSString {
get {
return super.object as NSString
}
}
}
ImportedObjCGenerics.test("InheritInSwift") {
let s = InheritInSwift(object: "HEllo")
let sup: Container = s
expectEqual(s.superObject, "hello")
expectEqual(s.object, "HELLO")
expectEqual(sup.object, "HELLO")
s.object = "GOodbye"
expectEqual(s.superObject, "goodbye")
expectEqual(s.object, "GOODBYE")
expectEqual(sup.object, "GOODBYE")
s.processObject { o in
expectEqual(o, "GOODBYE")
}
s.updateObject { "Aloha" }
expectEqual(s.superObject, "aloha")
expectEqual(s.object, "ALOHA")
expectEqual(sup.object, "ALOHA")
}
ImportedObjCGenerics.test("BridgedInitializer") {
let strings: [NSString] = ["hello", "world"]
let s = BridgedInitializer(array: strings)
expectEqual(s.count, 2)
}
runAllTests()
|
62ed5387387f23aa7c0b87ce70fac061
| 32.614213 | 116 | 0.728179 | false | true | false | false |
Ezimetzhan/XMLParser
|
refs/heads/master
|
XMLParser/XMLParser.swift
|
mit
|
4
|
//
// XMLParser.swift
// XMLParser
//
// Created by Eugene Mozharovsky on 8/29/15.
// Copyright © 2015 DotMyWay LCC. All rights reserved.
//
import Foundation
/// A parser class supposed to provide features for (de)coding
/// data into XML and vice versa.
/// The class provides a singleton.
public class XMLParser: XMLCoder, XMLDecoder {
/// A singleton accessor.
public static let sharedParser = XMLParser()
// MARK: - XMLCoder & XMLDecoder
/// Encodes a dictionary into an XML string.
/// - parameter data: A generic dictionary. Generally, the **Key** should be hashable and
/// in most of cases it must be a **String**. The value
/// might vary.
/// - parameter header: A header for the XML string.
/// - returns: A converted XML string.
public func encode<Key : Hashable, Value>(data: Dictionary<Key, Value>, header: String = "") -> String {
guard let tries = data.generateTries() else {
return ""
}
return header + tries.map { $0.parsedRequestBody() }.reduce("", combine: +)
}
/// Decodes the given input into the specified output.
/// - parameter data: An input data, *String* type.
/// - returns: An array of string values.
public func decode(data: String) -> Dictionary<String, [String]> {
return findTags(data)
}
// MARK: - Initialization
/// A private initializer for singleton implementation.
private init() { }
// MARK: - Utils
/// Finds XML tags in a given string (supposed to be previously parsed into XML format).
/// - parameter body: A given XML parsed string.
/// - returns: A dictionary with arrays of values.
private func findTags(body: String) -> [String : [String]] {
var keys: [String] = []
var write = false
var char = ""
var value = ""
var values: [String : [String]] = [:]
for ch in body.characters {
if ch == "<" {
write = true
} else if ch == ">" {
write = false
}
if ch == "\n" {
continue
}
if write {
if let last = keys.last where value != "" {
if let _ = values[last.original()] {
values[last.original()]! += [value]
} else {
values[last.original()] = []
values[last.original()]! += [value]
}
value = ""
}
char += String(ch)
} else {
if char != "" {
char += String(ch)
keys += [char]
char = ""
} else if let last = keys.last where last == last.original().startHeader() {
if ch == " " && (value.characters.last == " " || value.characters.last == "\n" || value.characters.count == 0) {
continue
}
value += String(ch)
}
}
}
return values
}
}
|
a096474ae5d806c09acc3e24d8e54f11
| 31.66 | 133 | 0.482854 | false | false | false | false |
Sorix/CloudCore
|
refs/heads/master
|
Source/Classes/Setup Operation/UploadAllLocalDataOperation.swift
|
mit
|
1
|
//
// UploadAllLocalDataOperation.swift
// CloudCore
//
// Created by Vasily Ulianov on 12/12/2017.
// Copyright © 2017 Vasily Ulianov. All rights reserved.
//
import Foundation
import CoreData
class UploadAllLocalDataOperation: Operation {
let managedObjectModel: NSManagedObjectModel
let parentContext: NSManagedObjectContext
var errorBlock: ErrorBlock? {
didSet {
converter.errorBlock = errorBlock
cloudSaveOperationQueue.errorBlock = errorBlock
}
}
private let converter = ObjectToRecordConverter()
private let cloudSaveOperationQueue = CloudSaveOperationQueue()
init(parentContext: NSManagedObjectContext, managedObjectModel: NSManagedObjectModel) {
self.parentContext = parentContext
self.managedObjectModel = managedObjectModel
}
override func main() {
super.main()
CloudCore.delegate?.willSyncToCloud()
defer {
CloudCore.delegate?.didSyncToCloud()
}
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = parentContext
var allManagedObjects = Set<NSManagedObject>()
for entity in managedObjectModel.cloudCoreEnabledEntities {
guard let entityName = entity.name else { continue }
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
do {
guard let fetchedObjects = try childContext.fetch(fetchRequest) as? [NSManagedObject] else {
continue
}
allManagedObjects.formUnion(fetchedObjects)
} catch {
errorBlock?(error)
}
}
converter.setUnconfirmedOperations(inserted: allManagedObjects, updated: Set<NSManagedObject>(), deleted: Set<NSManagedObject>())
let recordsToSave = converter.confirmConvertOperationsAndWait(in: childContext).recordsToSave
cloudSaveOperationQueue.addOperations(recordsToSave: recordsToSave, recordIDsToDelete: [RecordIDWithDatabase]())
cloudSaveOperationQueue.waitUntilAllOperationsAreFinished()
do {
try childContext.save()
} catch {
errorBlock?(error)
}
}
override func cancel() {
cloudSaveOperationQueue.cancelAllOperations()
super.cancel()
}
}
|
f22755fd16b8ae3f51afecdd56c9d48d
| 26.415584 | 131 | 0.766461 | false | false | false | false |
tassiahmed/SplitScreen
|
refs/heads/master
|
OSX/SplitScreen/MouseDragEventHandling.swift
|
apache-2.0
|
1
|
//
// MouseDragEventHandling.swift
// SplitScreen
//
// Created by Evan Thompson on 10/13/15.
// Copyright © 2015 SplitScreen. All rights reserved.
//
import Foundation
import AppKit
import Carbon
private var current_window_position: CGPoint?
private var new_window_position: CGPoint?
private var drawing: Bool = false
private var mouse_seen: Bool = false
private var mouse_up_pos: NSPoint?
private var callback_seen: Bool = false
private var callback_executed: Bool = false
/**
Returns the current top application by pid
- Returns: The pid that is the top application
*/
func get_focused_pid() -> pid_t {
let info = NSWorkspace.shared.frontmostApplication
// If the focused app is `SplitScreen` return a `pid` of 0
if(info == NSRunningApplication()) {
return pid_t(0)
}
return (info?.processIdentifier)!
}
/**
Compares the coordinates of `current_window_position` with the coordinates of `new_position`
- Parameter new_position: The `CGPoint` whose coordinates to compare w/ those of `current_window_position`
- Returns: `true` or `false` depending on whether `current_window_position` and `new_position` have the same coordinates
*/
func comparePosition() -> Bool {
return (current_window_position!.x == new_window_position!.x && current_window_position!.y == new_window_position!.y)
}
/**
Moves and Resizes the current window depending on the location of where the mouse up location was
*/
func move_and_resize() {
let loc: (CGFloat, CGFloat) = (mouse_up_pos!.x, mouse_up_pos!.y)
if layout.is_hardpoint(loc.0, y: loc.1) {
let resize = layout.get_snap_dimensions(loc.0, y: loc.1)
print(" ++ \(resize)")
if resize.0 == -1 || resize.1 == -1 || resize.2 == -1 || resize.3 == -1 {
return
}
// Gets the focused app
let focused_pid = get_focused_pid()
// Stops if there was no focused app to resize
if(focused_pid == pid_t(0)) {
return
}
// Moves and resizes the focused window
move_focused_window(CFloat(resize.0), CFloat(resize.1), focused_pid)
resize_focused_window(CFloat(resize.2), CFloat(resize.3), focused_pid)
}
}
/**
Starts the drawing process for the highlighting window
*/
func start_drawing() {
//begin drawing again
drawing = true
//adds the dimensions info so that a window can be created
snapHighlighter.update_window(layout.get_snap_dimensions(lastKnownMouseDrag!.x, y: lastKnownMouseDrag!.y))
snapHighlighter.draw_create()
}
/**
Handles the dragging of mouse
- Parameter event: the input event for mouse dragging
*/
func mouse_dragged_handler(_ event: NSEvent) {
//holds a reference to the last position of a drag
lastKnownMouseDrag = CGPoint(x: event.locationInWindow.x, y: event.locationInWindow.y)
if callback_seen {
if drawing {
//if still in a position that requires highlighting
if layout.is_hardpoint(event.locationInWindow.x, y: event.locationInWindow.y) {
snapHighlighter.update_window(layout.get_snap_dimensions(event.locationInWindow.x, y: event.locationInWindow.y))
print(layout.get_snap_dimensions(event.locationInWindow.x, y: event.locationInWindow.y))
} else {
snapHighlighter.draw_destroy()
drawing = false
}
} else if layout.is_hardpoint(event.locationInWindow.x, y: event.locationInWindow.y) {
drawing = true
//prevents annoying immediate display during quick motions
//also prevents lag on highligh window creation
snapHighlighter.delay_update(0.2)
}
}
}
/**
Handles the event of user releasing the mouse
- Parameter event: `NSEvent` that is received when user releases the mouse
*/
func mouse_up_handler(_ event: NSEvent) {
print("mouse up")
mouse_up_pos = event.locationInWindow
mouse_seen = true
if drawing {
//end the drawing
snapHighlighter.kill_delay_create()
snapHighlighter.draw_destroy()
drawing = false
}
// Check if the callback was executed too early
if callback_seen && callback_executed == false {
callback_seen = false
move_and_resize()
} else {
callback_executed = false
callback_seen = false
}
}
/**
Call back function for when a specific window moves
*/
func moved_callback(_ observer: AXObserver, element: AXUIElement, notificationName: CFString, contextData: UnsafeMutableRawPointer?) -> Void {
AXObserverRemoveNotification(observer, element, kAXMovedNotification as CFString);
if callback_seen == false {
callback_seen = true
} else {
return
}
callback_executed = false
// Check if the mouse up handler was executed
if mouse_seen == false {
//handle highlighting
if drawing == false && layout.is_hardpoint(lastKnownMouseDrag!.x, y: lastKnownMouseDrag!.y) {
snapHighlighter = SnapHighlighter()
start_drawing()
}
return
}
callback_executed = true
move_and_resize();
}
/**
Sets up the observer for the moved notification
*/
func setup_observer(_ pid: pid_t) {
var frontMostApp: AXUIElement
let frontMostWindow: UnsafeMutablePointer<AnyObject?> = UnsafeMutablePointer<AnyObject?>.allocate(capacity: 1)
frontMostApp = AXUIElementCreateApplication(pid)
AXUIElementCopyAttributeValue(frontMostApp, kAXFocusedWindowAttribute as CFString, frontMostWindow);
// Check if the frontMostWindow object is nil or not
if let placeHolder = frontMostWindow.pointee {
let frontMostWindow_true: AXUIElement = placeHolder as! AXUIElement
let observer: UnsafeMutablePointer<AXObserver?> = UnsafeMutablePointer<AXObserver?>.allocate(capacity: 1)
AXObserverCreate(pid, moved_callback as AXObserverCallback, observer)
let observer_true: AXObserver = observer.pointee!
let data_ptr: UnsafeMutablePointer<UInt16> = UnsafeMutablePointer<UInt16>.allocate(capacity: 1)
AXObserverAddNotification(observer_true, frontMostWindow_true, kAXMovedNotification as CFString, data_ptr);
CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer_true), CFRunLoopMode.defaultMode);
}
}
/**
Handles the mouse down event
*/
func mouse_down_handler(_ event: NSEvent) {
// Reset all of the sync checks
mouse_seen = false
callback_seen = false
drawing = false
callback_executed = false
setup_observer(get_focused_pid())
}
|
8e0b861becbc1ca94fbcb4165df81f59
| 29.480583 | 142 | 0.714286 | false | false | false | false |
jfrowies/iEMI
|
refs/heads/master
|
iEMI/Parking.swift
|
apache-2.0
|
1
|
//
// Parking.swift
// iEMI
//
// Created by Fer Rowies on 8/19/15.
// Copyright © 2015 Rowies. All rights reserved.
//
import UIKit
class Parking: NSObject {
var number: String = ""
var year: String = ""
var serie: String = ""
init(json:[String:AnyObject]) {
//The service returns "TarNro" or "Tarnro"
if let number = json["TarNro"] as? String {
self.number = number
}
if let number = json["Tarnro"] as? String {
self.number = number
}
//The service returns "TarAno" or "Tarano"
if let year = json["TarAno"] as? String {
self.year = year
}
if let year = json["TarAno"] as? Int {
self.year = String(year)
}
if let year = json["Tarano"] as? String {
self.year = year
}
if let year = json["Tarano"] as? Int {
self.year = String(year)
}
//The service returns "TarSerie" or "Tarserie"
if let serie = json["TarSerie"] as? String {
self.serie = serie
}
if let serie = json["Tarserie"] as? String {
self.serie = serie
}
}
init(number:String, year:String, serie:String) {
self.number = number
self.year = year
self.serie = serie
}
}
|
8499d242ad9e4da43adb0afd40e4f5c3
| 22.633333 | 54 | 0.485896 | false | false | false | false |
zSher/BulletThief
|
refs/heads/master
|
BulletThief/BulletThief/Enemy.swift
|
mit
|
1
|
//
// Enemy.swift
// BulletThief
//
// Created by Zachary on 5/6/15.
// Copyright (c) 2015 Zachary. All rights reserved.
//
import Foundation
import SpriteKit
class Enemy: SKSpriteNode {
var gun:Gun!
var movementPath:UIBezierPath?
var weakened:Bool = false //flag to be stolen
//MARK: - Init -
convenience override init(){
var bulletEffects: [BulletEffectProtocol] = [TextureBulletEffect(textureName: "lineBullet"), FireDelayBulletEffect(delay: 3.5), SpeedBulletEffect(speed: 8), LinePathBulletEffect(direction: Directions.Down), StandardSpawnBulletEffect()]
self.init(textureName: "enemy", bulletEffects: bulletEffects, numBullets: 1, bulletCount: 20, speed: 5, name: "enemy")
}
//Init using set properties
init(textureName: String, bulletEffects: [BulletEffectProtocol], numBullets:UInt, bulletCount: UInt, speed:CGFloat, name:String) {
var texture = SKTexture(imageNamed: textureName)
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.gun = Gun(initialEffects: bulletEffects, numberOfBulletsToFire: numBullets, bulletCount: bulletCount, owner: self)
self.gun.setPhysicsBody(CollisionCategories.EnemyBullet, contactBit: CollisionCategories.Player, collisionBit: CollisionCategories.None)
self.speed = speed
self.name = name
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody?.dynamic = true
self.physicsBody?.categoryBitMask = CollisionCategories.Enemy
self.physicsBody?.contactTestBitMask = CollisionCategories.PlayerBullet
self.physicsBody?.collisionBitMask = CollisionCategories.None
self.physicsBody?.usesPreciseCollisionDetection = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
//MARK: - Methods -
//Add path for movement
func addPath(path:UIBezierPath) {
self.movementPath = path
}
//MARK: - Update -
func update(deltaTime: CFTimeInterval){
gun.update(deltaTime)
//Shoot whenever you can
if gun.canShoot && !weakened {
gun.shoot()
}
}
//Function to perform when player steals this character's ability
func steal(player:Player){
}
//Function called when about to die
func willDie(){
self.removeAllActions()
self.removeFromParent()
bulletManager.returnBullets(gun.bulletPool)
}
//separate add function to add all components before being put onto screen
func addToScene(scene:SKScene){
var moveAction = SKAction.followPath(movementPath!.CGPath, asOffset: true, orientToPath: true, speed: self.speed)
var removeAction = SKAction.removeFromParent()
var onScreenActionGrp = SKAction.sequence([moveAction, removeAction])
scene.addChild(self)
self.runAction(onScreenActionGrp)
}
}
|
04a9f10df5756ae4132ca2826c3666d9
| 35.843373 | 243 | 0.682368 | false | false | false | false |
dleonard00/firebase-user-signup
|
refs/heads/master
|
firebase-user-signup/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// firebase-user-signup
//
// Created by doug on 3/11/16.
// Copyright © 2016 Weave. All rights reserved.
//
import UIKit
import Material
import Firebase
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextField: TextField!
@IBOutlet weak var emailTextField: TextField!
@IBOutlet weak var passwordTextField: TextField!
@IBOutlet weak var signupButton: FabButton!
override func viewDidLoad() {
super.viewDidLoad()
setTextFieldDelegates()
setupView()
}
func setupView(){
usernameTextField.placeholder = "Username"
usernameTextField.placeholderTextColor = MaterialColor.grey.base
usernameTextField.font = RobotoFont.regularWithSize(20)
usernameTextField.textColor = MaterialColor.black
usernameTextField.borderStyle = .None
usernameTextField.titleLabel = UILabel()
usernameTextField.titleLabel!.font = RobotoFont.mediumWithSize(12)
usernameTextField.titleLabelColor = MaterialColor.grey.base
usernameTextField.titleLabelActiveColor = MaterialColor.blue.accent3
emailTextField.placeholder = "Email"
emailTextField.placeholderTextColor = MaterialColor.grey.base
emailTextField.font = RobotoFont.regularWithSize(20)
emailTextField.textColor = MaterialColor.black
emailTextField.borderStyle = .None
emailTextField.titleLabel = UILabel()
emailTextField.titleLabel!.font = RobotoFont.mediumWithSize(12)
emailTextField.titleLabelColor = MaterialColor.grey.base
emailTextField.titleLabelActiveColor = MaterialColor.blue.accent3
passwordTextField.placeholder = "Password"
passwordTextField.placeholderTextColor = MaterialColor.grey.base
passwordTextField.font = RobotoFont.regularWithSize(20)
passwordTextField.textColor = MaterialColor.black
passwordTextField.borderStyle = .None
passwordTextField.titleLabel = UILabel()
passwordTextField.titleLabel!.font = RobotoFont.mediumWithSize(12)
passwordTextField.titleLabelColor = MaterialColor.grey.base
passwordTextField.titleLabelActiveColor = MaterialColor.blue.accent3
let image = UIImage(named: "ic_close_white")?.imageWithRenderingMode(.AlwaysTemplate)
let clearButton: FlatButton = FlatButton()
clearButton.pulseColor = MaterialColor.grey.base
clearButton.pulseScale = false
clearButton.tintColor = MaterialColor.grey.base
clearButton.setImage(image, forState: .Normal)
clearButton.setImage(image, forState: .Highlighted)
usernameTextField.clearButton = clearButton
emailTextField.clearButton = clearButton
passwordTextField.clearButton = clearButton
signupButton.setTitle("Sign up", forState: .Normal)
signupButton.titleLabel!.font = RobotoFont.mediumWithSize(15)
}
@IBAction func signupButtonWasTapped(sender: AnyObject) {
dismissKeyboard()
let failureClosure: (NSError) -> () = { error in
self.handleSignUpError(error)
}
guard let email = emailTextField.text, username = usernameTextField.text?.lowercaseString, password = passwordTextField.text else {
alertError("Please fill out the all fields, then try signing up again.")
return
}
if email.isEmpty || password.isEmpty || username.isEmpty {
alertError("Please fill out the all fields, then try signing up again.")
}
if username.characters.count > 15 {
alertError("Usernames must be less than 15 characters.")
return
}
//TODO check for conflicts.
if !isOnlyAlphaNumeric(username){
print("username must be only alpha numeric characters")
return
}
let usernameIndexRef = FirebaseRefManager.myRootRef.childByAppendingPath("username/\(username)")
usernameIndexRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull { //check that username doesnt already exist.
let successClosure = {
//Do something successful
}
let failureClosure: (NSError) -> () = { error in
self.handleSignUpError(error)
}
createNewUser(email, username: username, password: password, success: successClosure, failure: failureClosure)
} else {
self.alertError("Username has already been taken, please pick a new username and try again.")
return
}
})
}
func handleSignUpError(error: NSError){
if let errorCode = FAuthenticationError(rawValue: error.code) {
switch errorCode {
case .ProviderDisabled:
print("ProviderDisabled")
alertError("The requested authentication provider is currently disabled for this app.")
case .InvalidConfiguration:
print("InvalidConfiguration")
alertError("The requested authentication provider is misconfigured, and the request cannot complete.")
case .InvalidOrigin:
print("InvalidOrigin")
alertError("A security error occurred while processing the authentication request. The web origin for the request is not in your list of approved request origins.")
case .InvalidProvider:
print("InvalidProvider")
alertError("The requested authentication provider does not exist. Send mean tweets to @bettrnetHQ")
case .InvalidEmail:
print("InvalidEmail")
alertError("The specified email is not a valid email.")
case .InvalidPassword:
print("InvalidPassword")
alertError("The specified user account password is invalid.")
case .InvalidToken:
print("InvalidToken")
alertError("The specified authentication token is invalid.")
case .EmailTaken:
print("EmailTaken")
alertError("The new user account cannot be created because the specified email address is already in use.")
case .NetworkError:
print("NetworkError")
alertError("An error occurred while attempting to contact the authentication server.")
case .Unknown:
print("Unknown")
alertError("Something went wrong, please try again later.")
default:
print("error - default situation")
alertError("Something went wrong, please try again later.")
}
}
}
func isOnlyAlphaNumeric(stringInQuestion: String) -> Bool{
let regex = try! NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: NSRegularExpressionOptions())
if regex.firstMatchInString(stringInQuestion, options: NSMatchingOptions(), range:NSMakeRange(0, stringInQuestion.characters.count)) != nil {
print("could not handle special characters")
alertError("Use only alpha-numeric characters in preferred name.")
return false
}
return true
}
func alertError(message: String){
let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
switch(textField){
case self.usernameTextField:
self.emailTextField.becomeFirstResponder()
case self.emailTextField:
self.passwordTextField.becomeFirstResponder()
case self.passwordTextField:
self.passwordTextField.resignFirstResponder()
self.signupButtonWasTapped(textField)
default:
self.signupButtonWasTapped(textField)
}
return true
}
func setTextFieldDelegates(){
emailTextField.delegate = self
passwordTextField.delegate = self
usernameTextField.delegate = self
}
func dismissKeyboard(){
self.emailTextField.resignFirstResponder()
self.passwordTextField.resignFirstResponder()
self.usernameTextField.resignFirstResponder()
}
}
|
3ee7eda0c5ab1579fdbb022d9903cbe8
| 40.809524 | 180 | 0.644077 | false | false | false | false |
coach-plus/ios
|
refs/heads/master
|
Floral/Pods/Hero/Sources/Animator/HeroAnimatorViewContext.swift
|
mit
|
4
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <me@lkzhao.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 UIKit
internal class HeroAnimatorViewContext {
weak var animator: HeroAnimator?
let snapshot: UIView
let appearing: Bool
var targetState: HeroTargetState
var duration: TimeInterval = 0
// computed
var currentTime: TimeInterval {
return snapshot.layer.convertTime(CACurrentMediaTime(), from: nil)
}
var container: UIView? {
return animator?.hero.context.container
}
class func canAnimate(view: UIView, state: HeroTargetState, appearing: Bool) -> Bool {
return false
}
func apply(state: HeroTargetState) {
}
func changeTarget(state: HeroTargetState, isDestination: Bool) {
}
func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval {
return 0
}
func seek(timePassed: TimeInterval) {
}
func clean() {
animator = nil
}
func startAnimations() -> TimeInterval {
return 0
}
required init(animator: HeroAnimator, snapshot: UIView, targetState: HeroTargetState, appearing: Bool) {
self.animator = animator
self.snapshot = snapshot
self.targetState = targetState
self.appearing = appearing
}
}
|
b01f0482f4e2b6f7b8e5ba3e396769b4
| 30.788732 | 106 | 0.734603 | false | false | false | false |
gobetti/Swift
|
refs/heads/master
|
SQLite/SQLite/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SQLite
//
// Created by Carlos Butron on 06/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// 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 UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var statement = COpaquePointer()
var data: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
loadTabla()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadTabla(){
let db_path = NSBundle.mainBundle().pathForResource("FilmCollection", ofType: "sqlite")
print(NSBundle.mainBundle())
var db = COpaquePointer()
let status = sqlite3_open(db_path!, &db)
if(status == SQLITE_OK){
//bbdd open
print("open")
}
else{
//bbdd error
print("open error")
}
let query_stmt = "select * from film"
if(sqlite3_prepare_v2(db, query_stmt, -1, &statement, nil) == SQLITE_OK){
data.removeAllObjects()
while(sqlite3_step(statement) == SQLITE_ROW){
let Dictionary = NSMutableDictionary()
let director = sqlite3_column_text(statement, 1)
let buf_director = String.fromCString(UnsafePointer<CChar>(director))
let image = sqlite3_column_text(statement, 2)
let buf_image = String.fromCString(UnsafePointer<CChar>(image))
let title = sqlite3_column_text(statement, 3)
let buf_title = String.fromCString(UnsafePointer<CChar>(title))
let year = sqlite3_column_text(statement, 4)
let buf_year = String.fromCString(UnsafePointer<CChar>(year))
Dictionary.setObject(buf_director!, forKey:"director")
Dictionary.setObject(buf_image!, forKey: "image")
Dictionary.setObject(buf_title!, forKey: "title")
Dictionary.setObject(buf_year!, forKey: "year")
data.addObject(Dictionary)
//process data
}
sqlite3_finalize(statement)
}
else{
print("ERROR")
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell") as! MyTableViewCell
let aux: AnyObject = data[indexPath.row]
let table_director = aux["director"]
cell.director.text = table_director as? String
//var aux1: AnyObject = data[indexPath.row]
let table_image = aux["image"]
cell.myImage.image = UIImage(named:table_image as! String)
let aux3: AnyObject = data[indexPath.row]
let table_title = aux["title"]
cell.title.text = table_title as? String
//var aux4: AnyObject = data[indexPath.row]
let table_year = aux3["year"]
cell.year.text = table_year as? String
return cell
}
}
|
35bebf7a6ad086ef69e2bfef59b65794
| 31.777778 | 121 | 0.589831 | false | false | false | false |
LYM-mg/DemoTest
|
refs/heads/master
|
其他功能/MGBookViews/MGBookViews/表格/UICollectionGridViewController.swift
|
mit
|
1
|
// UICollectionGridViewController.swift
// MGBookViews
// Created by i-Techsys.com on 2017/11/15.
// Copyright © 2017年 i-Techsys. All rights reserved.
// https://github.com/LYM-mg
// http://www.jianshu.com/u/57b58a39b70e
import UIKit
//表格排序协议
protocol UICollectionGridViewSortDelegate {
func sort(colIndex: Int, asc: Bool, rows: [[Any]]) -> [[Any]]
}
//多列表格组件(通过CollectionView实现)
class UICollectionGridViewController: UICollectionViewController {
//表头数据
var cols: [String]! = []
//行数据
var rows: [[Any]]! = []
//排序代理
var sortDelegate: UICollectionGridViewSortDelegate!
//选中的表格列(-1表示没有选中的)
private var selectedColIdx = -1
//列排序顺序
private var asc = true
init() {
//初始化表格布局
let layout = UICollectionGridViewLayout()
super.init(collectionViewLayout: layout)
layout.viewController = self
collectionView!.backgroundColor = UIColor.white
collectionView!.register(UICollectionGridViewCell.self,
forCellWithReuseIdentifier: "cell")
collectionView!.delegate = self
collectionView!.dataSource = self
collectionView!.isDirectionalLockEnabled = true
//collectionView!.contentInset = UIEdgeInsetsMake(0, 10, 0, 10)
collectionView!.bounces = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("UICollectionGridViewController.init(coder:) has not been implemented")
}
//设置列头数据
func setColumns(columns: [String]) {
cols = columns
}
//添加行数据
func addRow(row: [Any]) {
rows.append(row)
collectionView!.collectionViewLayout.invalidateLayout()
collectionView!.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
collectionView!.frame = CGRect(x:0, y:0,
width:view.frame.width, height:view.frame.height)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//返回表格总行数
override func numberOfSections(in collectionView: UICollectionView) -> Int {
if cols.isEmpty {
return 0
}
//总行数是:记录数+1个表头
return rows.count + 1
}
//返回表格的列数
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return cols.count
}
//单元格内容创建
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
for: indexPath) as! UICollectionGridViewCell
//设置列头单元格,内容单元格的数据
if indexPath.section == 0 {
cell.label.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold)
cell.label.text = cols[indexPath.row]
cell.label.textColor = UIColor.white
} else {
cell.label.font = UIFont.systemFont(ofSize: 15)
cell.label.text = "\(rows[indexPath.section-1][indexPath.row])"
cell.label.textColor = UIColor.black
}
//表头单元格背景色
if indexPath.section == 0 {
cell.backgroundColor = UIColor(red: 0x91/255, green: 0xDA/255, blue: 0x51/255, alpha: 1)
//排序列列头显示升序降序图标
if indexPath.row == selectedColIdx {
let iconType = asc ? FAType.FALongArrowUp : FAType.FALongArrowDown
cell.imageView.setFAIconWithName(icon: iconType, textColor: UIColor.white)
}else{
cell.imageView.image = nil
}
}
//内容单元格背景色
else {
cell.imageView.image = nil
//排序列的单元格背景会变色
if indexPath.row == selectedColIdx {
//排序列的单元格背景会变色
cell.backgroundColor = UIColor(red: 0xCC/255, green: 0xF8/255, blue: 0xFF/255,
alpha: 1)
}
//数据区域每行单元格背景色交替显示
else if indexPath.section % 2 == 0 {
cell.backgroundColor = UIColor(white: 242/255.0, alpha: 1)
} else {
cell.backgroundColor = UIColor.white
}
}
return cell
}
//单元格选中事件
override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
//打印出点击单元格的[行,列]坐标
print("点击单元格的[行,列]坐标: [\(indexPath.section),\(indexPath.row)]")
if indexPath.section == 0 && sortDelegate != nil {
//如果点击的是表头单元格,则默认该列升序排列,再次点击则变降序排列,以此交替
asc = (selectedColIdx != indexPath.row) ? true : !asc
selectedColIdx = indexPath.row
rows = sortDelegate.sort(colIndex: indexPath.row, asc: asc, rows: rows)
collectionView.reloadData()
}
}
}
|
f0f772d888810290f24c12022d5cae68
| 33.206667 | 100 | 0.578055 | false | false | false | false |
inket/stts
|
refs/heads/master
|
stts/Services/Super/PayPal.swift
|
mit
|
1
|
//
// PayPal.swift
// stts
//
import Kanna
typealias PayPal = BasePayPal & RequiredServiceProperties & RequiredPayPalProperties
enum PayPalEnvironment: String {
case sandbox
case production
}
enum PayPalComponent {
case product(PayPalEnvironment)
case api(PayPalEnvironment)
var category: String {
switch self {
case .product: return "product"
case .api: return "api"
}
}
var environment: PayPalEnvironment {
switch self {
case let .product(environment): return environment
case let .api(environment): return environment
}
}
}
protocol RequiredPayPalProperties {
var component: PayPalComponent { get }
}
class BasePayPal: BaseService {
private enum PayPalStatus: String, ComparableStatus {
case operational
case underMaintenance = "under_maintenance"
case serviceDisruption = "service_disruption"
case serviceOutage = "service_outage"
case informational
var serviceStatus: ServiceStatus {
switch self {
case .operational, .informational:
return .good
case .underMaintenance:
return .maintenance
case .serviceDisruption:
return .minor
case .serviceOutage:
return .major
}
}
var statusMessage: String {
switch self {
case .operational, .informational: return "Operational"
case .underMaintenance: return "Under Maintenance"
case .serviceDisruption: return "Service Disruption"
case .serviceOutage: return "Service Outage"
}
}
}
var url: URL {
guard let paypal = self as? PayPal else { fatalError("BasePayPal should not be used directly") }
var components = URLComponents()
components.scheme = "https"
components.host = "www.paypal-status.com"
components.path = "/\(paypal.component.category)/\(paypal.component.environment.rawValue)"
return components.url!
}
override func updateStatus(callback: @escaping (BaseService) -> Void) {
guard let realSelf = self as? PayPal else { fatalError("BasePayPal should not be used directly.") }
let apiURL = URL(string: "https://www.paypal-status.com/api/v1/components")!
loadData(with: apiURL) { [weak realSelf] data, _, error in
guard let strongSelf = realSelf else { return }
defer { callback(strongSelf) }
guard let data = data else { return strongSelf._fail(error) }
let json = try? JSONSerialization.jsonObject(with: data, options: [])
guard
let dict = json as? [String: Any],
let resultArray = dict["result"] as? [[String: Any]]
else { return strongSelf._fail("Unexpected data") }
let statuses = resultArray.compactMap {
strongSelf.status(fromResultItem: $0, component: strongSelf.component)
}
guard let highestStatus = statuses.max() else { return strongSelf._fail("Unexpected data") }
strongSelf.status = highestStatus.serviceStatus
strongSelf.message = highestStatus.statusMessage
}
}
private func status(fromResultItem resultItem: [String: Any], component: PayPalComponent) -> PayPalStatus? {
guard
let categoryDict = resultItem["category"] as? [String: Any],
categoryDict["name"] as? String == component.category,
let statusDict = resultItem["status"] as? [String: String],
let statusString = statusDict[component.environment.rawValue]
else { return nil }
let sanitizedStatusString = statusString.replacingOccurrences(of: " ", with: "_").lowercased()
return PayPalStatus(rawValue: sanitizedStatusString)
}
}
|
aad668c6e6fec4556d675e698144c5fa
| 32.305085 | 112 | 0.620102 | false | false | false | false |
GreenvilleCocoa/ChristmasDelivery
|
refs/heads/master
|
ChristmasDelivery/GameViewController.swift
|
mit
|
1
|
//
// GameViewController.swift
// ChristmasDelivery
//
// Created by Marcus Smith on 12/8/14.
// Copyright (c) 2014 GreenvilleCocoaheads. All rights reserved.
//
import UIKit
import SpriteKit
var totalScore: Int = 0
class GameViewController: UIViewController {
override func loadView() {
let skView = SKView()
view = skView
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let skView: SKView = self.view as! SKView
if (skView.scene == nil) {
skView.showsFPS = true
skView.showsNodeCount = true
// skView.ignoresSiblingOrder = true
// skView.showsPhysics = true
let scene: GameScene = GameScene(size: skView.frame.size, level: 1)
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Landscape
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
8a1f529585cb0e287bde69178b20f50f
| 23.172414 | 82 | 0.608417 | false | false | false | false |
karstengresch/trhs-ios
|
refs/heads/master
|
InteractiveStory/InteractiveStory/PageController.swift
|
unlicense
|
1
|
//
// PageController.swift
// InteractiveStory
//
// Created by Karsten Gresch on 15.03.17.
// Copyright © 2017 Closure One. All rights reserved.
//
import UIKit
extension NSAttributedString {
var stringRange: NSRange {
return NSMakeRange(0, self.length)
}
}
extension Story {
var attributedText: NSAttributedString {
let attributedString = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: attributedString.stringRange)
return attributedString
}
}
extension Page {
func story(attributed: Bool) -> NSAttributedString {
if attributed {
return story.attributedText
}
else {
return NSAttributedString(string: story.text)
}
}
}
class PageController: UIViewController {
var page: Page?
let soundsEffectsPlayer = SoundsEffectsPlayer()
// MARK: User Interface Properties
lazy var artworkView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = self.page?.story.artwork
return imageView
}()
lazy var storyLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.attributedText = self.page?.story(attributed: true)
return label
}()
lazy var firstChoiceButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
let title = self.page?.firstChoice?.title ?? "Play Again"
let selector = self.page?.firstChoice != nil ? #selector(PageController.loadFirstChoice) : #selector(PageController.playAgain)
button.setTitle(title, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
return button
}()
lazy var secondChoiceButton: UIButton = {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(self.page?.secondChoice?.title, for: .normal)
button.addTarget(self, action: #selector(PageController.loadSecondChoice), for: .touchUpInside)
return button
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(xPage: Page) {
page = xPage
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
view.addSubview(artworkView)
NSLayoutConstraint.activate([
artworkView.topAnchor.constraint(equalTo: view.topAnchor),
artworkView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
artworkView.rightAnchor.constraint(equalTo: view.rightAnchor),
artworkView.leftAnchor.constraint(equalTo: view.leftAnchor)
])
view.addSubview(storyLabel)
NSLayoutConstraint.activate([
storyLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16.0),
storyLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16.0),
storyLabel.topAnchor.constraint(equalTo: view.centerYAnchor, constant: -48.0)
])
view.addSubview(firstChoiceButton)
firstChoiceButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
firstChoiceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
firstChoiceButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -80.0)
])
view.addSubview(secondChoiceButton)
secondChoiceButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
secondChoiceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
secondChoiceButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32.0)
])
}
func loadFirstChoice() {
if let page = page, let firstChoice = page.firstChoice {
let nextPage = firstChoice.page
let pageController = PageController(xPage: nextPage)
soundsEffectsPlayer.playSound(for: firstChoice.page.story)
navigationController?.pushViewController(pageController, animated: true)
}
}
func loadSecondChoice() {
if let page = page, let secondChoice = page.secondChoice {
let nextPage = secondChoice.page
let pageController = PageController(xPage: nextPage)
soundsEffectsPlayer.playSound(for: secondChoice.page.story)
navigationController?.pushViewController(pageController, animated: true)
}
}
func playAgain() {
navigationController?.popToRootViewController(animated: true)
}
}
|
2aefe24bf85af8bbc4b88b307205906d
| 26.282609 | 130 | 0.705976 | false | false | false | false |
zbw209/-
|
refs/heads/master
|
StudyNotes/StudyNotes/知识点/NavigationController/SecondVC.swift
|
mit
|
1
|
//
// SecondVC.swift
// StudyNotes
//
// Created by 周必稳 on 2017/4/19.
// Copyright © 2017年 zhou. All rights reserved.
//
import UIKit
class SecondVC: UIViewController {
var abc : String?
override func viewDidLoad() {
super.viewDidLoad()
print("\((#file).components(separatedBy: "/").last!) \(#line) \(#function) \(String(describing: self.navigationController))")
var image = UIImage.init(named: "icon_back_normal")
image = image?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
// image?.renderingMode = UIImageRenderingMode.alwaysOriginal
self.navigationController?.navigationBar.backIndicatorImage = image
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = image
// self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "1", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
let label = UILabel.init(frame: CGRect.zero)
label.textColor = UIColor.red
label.text = "测试"
label.sizeToFit()
let barButtonItem = UIBarButtonItem.init(customView: label)
self.navigationItem.leftBarButtonItem = barButtonItem
self.navigationItem.leftItemsSupplementBackButton = true
self.navigationController?.delegate = self
}
}
extension SecondVC : UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return nil
}
}
|
06f1a281ecacc8b71330c5dcc4f274d6
| 31.653846 | 209 | 0.682568 | false | false | false | false |
rentpath/Atlas
|
refs/heads/master
|
AtlasTests/UInt+AtlasMapTests.swift
|
mit
|
1
|
//
// UInt+AtlasMapTests.swift
// Atlas
//
// Created by Jeremy Fox on 8/5/16.
// Copyright © 2016 RentPath. All rights reserved.
//
import XCTest
@testable import Atlas
class UInt_AtlasMapTests: XCTestCase {
var json: JSON!
let ui: UInt = 0
let ui8: UInt8 = 0
let ui16: UInt16 = 0
let ui32: UInt32 = 0
let ui64: UInt64 = 0
override func setUp() {
super.setUp()
let i: UInt = 702888806
let i8: UInt8 = 70
let i16: UInt16 = 7028
let i32: UInt32 = 702888806
let i64: UInt64 = 70288880664460
let dict: [String: Any] = [
"ui": NSNumber(value: i as UInt),
"ui8": NSNumber(value: i8 as UInt8),
"ui16": NSNumber(value: i16 as UInt16),
"ui32": NSNumber(value: i32 as UInt32),
"ui64": NSNumber(value: i64 as UInt64)
]
let data = try! JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: 0))
json = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as JSON
}
override func tearDown() {
json = nil
super.tearDown()
}
func testUIntMappingMapsIntegerValuesWithinManAndMaxRange() {
let min = UInt.min
let max = UInt.max
XCTAssertEqual(UInt(min), UInt.min)
XCTAssertEqual(UInt(max), UInt.max)
}
func testIntMappingPerformance() {
self.measure {
for _ in 0..<100_000 {
let _ = UInt(702888806)
}
}
}
func testUIntMappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt(json: (json as AnyObject)["ui"] ?? ui)!, ui)
}
func testUInt64MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt64(json: (json as AnyObject)["ui64"] ?? ui64)!, ui64)
}
func testUInt32MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt32(json: (json as AnyObject)["ui32"] ?? ui32)!, ui32)
}
func testUInt16MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt16(json: (json as AnyObject)["ui16"] ?? ui16)!, ui16)
}
func testUInt8MappingThrowsErrorIfUnableToMap() {
XCTAssertGreaterThan(try UInt8(json: (json as AnyObject)["ui8"] ?? ui8)!, ui8)
}
}
|
088d54dfe1400853fb7119407b404bf1
| 28.658228 | 124 | 0.614597 | false | true | false | false |
gautier-gdx/Hexacon
|
refs/heads/master
|
Hexacon/HexagonalPattern.swift
|
mit
|
1
|
//
// HegagonalDirection.swift
// Hexacon
//
// Created by Gautier Gdx on 06/02/16.
// Copyright © 2016 Gautier. All rights reserved.
//
import UIKit
final class HexagonalPattern {
// MARK: - typeAlias
typealias HexagonalPosition = (center: CGPoint,ring: Int)
// MARK: - data
internal var repositionCenter: ((CGPoint, Int, Int) -> ())?
fileprivate var position: HexagonalPosition! {
didSet {
//while our position is bellow the size we can continue
guard positionIndex < size else {
reachedLastPosition = true
return
}
//each time a new center is set we are sending it back to the scrollView
repositionCenter?(position.center, position.ring, positionIndex)
positionIndex += 1
}
}
fileprivate var directionFromCenter: HexagonalDirection
fileprivate var reachedLastPosition = false
fileprivate var positionIndex = 0
fileprivate let sideNumber: Int = 6
//properties
fileprivate let size: Int
fileprivate let itemSpacing: CGFloat
fileprivate let maxRadius: Int
// MARK: - init
init(size: Int, itemSpacing: CGFloat, itemSize: CGFloat) {
self.size = size
self.itemSpacing = itemSpacing + itemSize - 8
maxRadius = size/6 + 1
directionFromCenter = .right
}
// MARK: - instance methods
/**
calculate the theorical size of the grid
- returns: the size of the grid
*/
func sizeForGridSize() -> CGFloat {
return 2*itemSpacing*CGFloat(maxRadius)
}
/**
create the grid with a circular pattern beginning from the center
in each loop we are sending back a center for a new View
*/
func createGrid(FromCenter newCenter: CGPoint) {
//initializing the algorythm
start(newCenter)
//for each radius
for radius in 0...maxRadius {
guard reachedLastPosition == false else { continue }
//we are creating a ring
createRing(withRadius: radius)
//then jumping to the next one
jumpToNextRing()
}
}
// MARK: - configuration methods
fileprivate func neighbor(origin: CGPoint,direction: HexagonalDirection) -> CGPoint {
//take the current direction
let direction = direction.direction()
//then multiply it to find the new center
return CGPoint(x: origin.x + itemSpacing*direction.x,y: origin.y + itemSpacing*direction.y)
}
fileprivate func start(_ newCenter: CGPoint) {
//initializing with the center given
position = (center: newCenter,ring: 0)
//then jump on the first ring
position = (center: neighbor(origin: position.center,direction: .leftDown),ring: 1)
}
fileprivate func createRing(withRadius radius: Int) {
//for each side of the ring
for _ in 0...(sideNumber - 1) {
//in each posion in the side
for directionIndex in 0...radius {
//stop if we are at the end of the ring
guard !(directionIndex == radius && directionFromCenter == .rightDown) else { continue }
//or add a new point
position = (center: neighbor(origin: position.center,direction: directionFromCenter),ring: radius + 1)
}
//then move to another position
directionFromCenter.move()
}
}
fileprivate func jumpToNextRing() {
//the next ring is always two position bellow the previous one
position = (center: CGPoint(x: position.center.x ,y: position.center.y + 2*itemSpacing),ring: position.ring + 1)
}
}
|
920f0e0dcccee10e58d6e1ad4e6f1595
| 29.614173 | 120 | 0.592335 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Models/Notifications/NotificationSettings.swift
|
gpl-2.0
|
1
|
import Foundation
/// The goal of this class is to encapsulate all of the User's Notification Settings in a generic way.
/// Settings are grouped into different Channels. A Channel is considered anything that might produce
/// Notifications: a WordPress blog, Third Party Sites or WordPress.com.
/// Each channel may support different streams, such as: Email + Push Notifications + Timeline.
///
open class NotificationSettings {
/// Represents the Channel to which the current settings are associated.
///
open let channel: Channel
/// Contains an array of the available Notification Streams.
///
open let streams: [Stream]
/// Maps to the associated blog, if any.
///
open let blog: Blog?
/// Designated Initializer
///
/// - Parameters:
/// - channel: The related Notifications Channel
/// - streams: An array of all of the involved streams
/// - blog: The associated blog, if any
///
public init(channel: Channel, streams: [Stream], blog: Blog?) {
self.channel = channel
self.streams = streams
self.blog = blog
}
/// Returns the localized description for any given preference key
///
open func localizedDescription(_ preferenceKey: String) -> String {
return Keys.localizedDescriptionMap[preferenceKey] ?? String()
}
/// Returns the details for a given preference key
///
open func localizedDetails(_ preferenceKey: String) -> String? {
return Keys.localizedDetailsMap[preferenceKey]
}
/// Returns an array of the sorted Preference Keys
///
open func sortedPreferenceKeys(_ stream: Stream?) -> [String] {
switch channel {
case .blog:
// Email Streams require a special treatment
return stream?.kind == .Email ? blogEmailPreferenceKeys : blogPreferenceKeys
case .other:
return otherPreferenceKeys
case .wordPressCom:
return wpcomPreferenceKeys
}
}
/// Represents a communication channel that may post notifications to the user.
///
public enum Channel: Equatable {
case blog(blogId: Int)
case other
case wordPressCom
/// Returns the localized description of the current enum value
///
func description() -> String {
switch self {
case .blog:
return NSLocalizedString("WordPress Blog", comment: "Settings for a Wordpress Blog")
case .other:
return NSLocalizedString("Comments on Other Sites", comment: "Notification Settings Channel")
case .wordPressCom:
return NSLocalizedString("Email from WordPress.com", comment: "Notification Settings Channel")
}
}
}
/// Contains the Notification Settings collection for a specific communications stream.
///
open class Stream {
open var kind: Kind
open var preferences: [String : Bool]?
/// Designated Initializer
///
/// - Parameters:
/// - kind: The Kind of stream we're currently dealing with
/// - preferences: Raw remote preferences, retrieved from the backend
///
public init(kind: String, preferences: [String : Bool]?) {
self.kind = Kind(rawValue: kind) ?? .Email
self.preferences = preferences
}
/// Enumerates all of the possible Stream Kinds
///
public enum Kind: String {
case Timeline = "timeline"
case Email = "email"
case Device = "device"
/// Returns the localized description of the current enum value
///
func description() -> String {
switch self {
case .Timeline:
return NSLocalizedString("Notifications Tab", comment: "WordPress.com Notifications Timeline")
case .Email:
return NSLocalizedString("Email", comment: "Email Notifications Channel")
case .Device:
return NSLocalizedString("Push Notifications", comment: "Mobile Push Notifications")
}
}
static let allValues = [ Timeline, Email, Device ]
}
}
// MARK: - Private Properties
fileprivate let blogPreferenceKeys = [Keys.commentAdded, Keys.commentLiked, Keys.postLiked, Keys.follower, Keys.achievement, Keys.mention]
fileprivate let blogEmailPreferenceKeys = [Keys.commentAdded, Keys.commentLiked, Keys.postLiked, Keys.follower, Keys.mention]
fileprivate let otherPreferenceKeys = [Keys.commentLiked, Keys.commentReplied]
fileprivate let wpcomPreferenceKeys = [Keys.marketing, Keys.research, Keys.community]
// MARK: - Setting Keys
fileprivate struct Keys {
static let commentAdded = "new_comment"
static let commentLiked = "comment_like"
static let commentReplied = "comment_reply"
static let postLiked = "post_like"
static let follower = "follow"
static let achievement = "achievement"
static let mention = "mentions"
static let marketing = "marketing"
static let research = "research"
static let community = "community"
static let localizedDescriptionMap = [
commentAdded: NSLocalizedString("Comments on my site",
comment: "Setting: indicates if New Comments will be notified"),
commentLiked: NSLocalizedString("Likes on my comments",
comment: "Setting: indicates if Comment Likes will be notified"),
postLiked: NSLocalizedString("Likes on my posts",
comment: "Setting: indicates if Replies to your comments will be notified"),
follower: NSLocalizedString("Site follows",
comment: "Setting: indicates if New Follows will be notified"),
achievement: NSLocalizedString("Site achievements",
comment: "Setting: indicates if Achievements will be notified"),
mention: NSLocalizedString("Username mentions",
comment: "Setting: indicates if Mentions will be notified"),
commentReplied: NSLocalizedString("Replies to your comments",
comment: "Setting: indicates if Replies to Comments will be notified"),
marketing: NSLocalizedString("Suggestions",
comment: "Setting: WordPress.com Suggestions"),
research: NSLocalizedString("Research",
comment: "Setting: WordPress.com Surveys"),
community: NSLocalizedString("Community",
comment: "Setting: WordPress.com Community")
]
static let localizedDetailsMap = [
marketing: NSLocalizedString("Tips for getting the most out of WordPress.com.",
comment: "WordPress.com Marketing Footer Text"),
research: NSLocalizedString("Opportunities to participate in WordPress.com research & surveys.",
comment: "WordPress.com Research Footer Text"),
community: NSLocalizedString("Information on WordPress.com courses and events (online & in-person).",
comment: "WordPress.com Community Footer Text")
]
}
}
/// Swift requires this method to be implemented globally. Sorry about that!
///
public func ==(first: NotificationSettings.Channel, second: NotificationSettings.Channel) -> Bool {
switch (first, second) {
case (let .blog(firstBlogId), let .blog(secondBlogId)) where firstBlogId == secondBlogId:
return true
case (.other, .other):
return true
case (.wordPressCom, .wordPressCom):
return true
default:
return false
}
}
|
6a0d0b0038b0e8e1cbb05cd15f3722a2
| 40.41206 | 147 | 0.594224 | false | false | false | false |
rmavani/SocialQP
|
refs/heads/master
|
QPrint/Controllers/NearbyStore/NearbyStoresViewController.swift
|
mit
|
1
|
//
// NearbyStoresViewController.swift
// QPrint
//
// Created by Admin on 23/02/17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
// MARK: - NearbyStoresCell
class NearbyStoresCell : UITableViewCell {
// MARK: - Initialize IBOutlets
@IBOutlet var lblStoreName : UILabel!
@IBOutlet var lblStoreLocation : UILabel!
@IBOutlet var lblDistance : UILabel!
}
// MARK: - NearbyStoresViewController
class NearbyStoresViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: - Initialize IBOutlets
@IBOutlet var lblTitle : UILabel!
@IBOutlet var tblList : UITableView!
// MARK: - Initialize Variables
// MARK: - Initialize
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
lblTitle.layer.shadowOpacity = 0.5
lblTitle.layer.shadowOffset = CGSize(width : 0.5, height : 0.5)
lblTitle.layer.shadowColor = UIColor.darkGray.cgColor
self.getNearByData()
}
// MARK: - UIButton Click Events
//MARK: - UITableView Delegate & DataSource Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell : NearbyStoresCell = tblList.dequeueReusableCell(withIdentifier: "NearbyStoresCell", for: indexPath) as! NearbyStoresCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
// MARK: - API Methods
// MARK: getNearByData
func getNearByData() {
if AppUtilities.isConnectedToNetwork() {
AppUtilities.sharedInstance.showLoader()
let strLatitude = UserDefaults.standard.object(forKey: "latitude")
let strLongitude = UserDefaults.standard.object(forKey: "longitude")
let str = NSString(format: "method=searchnear&latitude=\(strLatitude)&longitude=\(strLongitude)" as NSString)
AppUtilities.sharedInstance.dataTask(request: request, method: "POST", params: str, completion: { (success, object) in
DispatchQueue.main.async( execute: {
AppUtilities.sharedInstance.hideLoader()
if success
{
print("object ",object!)
print("move it to home page")
if(object?.value(forKeyPath: "error") as! String == "0")
{
}
else
{
let msg = object!.value(forKeyPath: "message") as! String
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: msg as NSString)
}
}
})
})
}
else
{
AppUtilities.sharedInstance.showAlert(title: App_Title as NSString, msg: "No Internet Connection!")
}
}
// MARK: - Other Methods
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
00fe2faec3554808507ab21931e7c877
| 33.579439 | 138 | 0.590811 | false | false | false | false |
eraydiler/password-locker
|
refs/heads/master
|
PasswordLockerSwift/Classes/Controller/Password/PasswordCreationViewController.swift
|
mit
|
1
|
//
// PasswordCreationViewController.swift
// PasswordLockerSwift
//
// Created by Eray on 21/04/15.
// Copyright (c) 2015 Eray. All rights reserved.
//
import UIKit
import CoreData
class PasswordCreationViewController: UIViewController {
@IBOutlet weak var passwordTextField: UITextField!
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
configureView()
}
// MARK: - Configuration
func configureView() {
passwordTextField.textColor = .gray
passwordTextField.tintColor = UIColor.gray
passwordTextField.delegate = self
}
// MARK: - IBActions
@IBAction func checkButtonPressed(_ sender: AnyObject) {
guard let retrieveString = KeychainService.value(forKey: KeychainService.appPasswordKey) else {
return
}
print("\(retrieveString)")
}
@IBAction func addPassLockButtonPressed(_ sender: AnyObject) {
attemptToSavePassword()
}
@IBAction func viewTapped(_ sender: AnyObject) {
passwordTextField.resignFirstResponder()
}
// MARK: - Private methods
@discardableResult
fileprivate func attemptToSavePassword() -> Bool {
guard let text = passwordTextField.text, !text.isEmpty else {
print(">>> TEXT FIELD IS EMPTY")
return false
}
let isSaved: Bool = KeychainService.set(value: text, forKey: KeychainService.appPasswordKey)
guard isSaved else {
print(">>> AN ERROR OCCURED WHILE SAVING PASSWORD")
return false
}
print(">>> PASSWORD SAVED SUCCESSFULLY")
displaySuccessAlert()
return true
}
func displaySuccessAlert() {
fatalError("Must be implemented by subclasses")
}
// MARK: - Subclass methods
func performSuccessAction() {
fatalError("Must be implemented by subclasses")
}
}
// MARK: - Text field delegate
extension PasswordCreationViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return attemptToSavePassword()
}
}
|
f8e28a778784916f75bc06d3e8abf639
| 23.806452 | 103 | 0.619419 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/decl/init/cf-types.swift
|
apache-2.0
|
25
|
// RUN: %target-typecheck-verify-swift
// REQUIRES: OS=macosx
import CoreGraphics
extension CGMutablePath {
public convenience init(p: Bool) { // expected-error{{convenience initializers are not supported in extensions of CF types}}
self.init()
}
public convenience init?(maybe: Bool) { // expected-error{{convenience initializers are not supported in extensions of CF types}}
self.init()
}
public convenience init(toss: Bool) throws { // expected-error{{convenience initializers are not supported in extensions of CF types}}
self.init()
}
public init(simple: Bool) { // expected-error{{designated initializer cannot be declared in an extension of 'CGMutablePath'}}{{none}}
// expected-error @-1 {{designated initializer for 'CGMutablePath' cannot delegate (with 'self.init')}}{{none}}
self.init() // expected-note {{delegation occurs here}}
}
public init?(value: Bool) { // expected-error{{designated initializer cannot be declared in an extension of 'CGMutablePath'}}{{none}}
// expected-error @-1 {{designated initializer for 'CGMutablePath' cannot delegate (with 'self.init')}}{{none}}
self.init() // expected-note {{delegation occurs here}}
}
public init?(string: String) { // expected-error{{designated initializer cannot be declared in an extension of 'CGMutablePath'}}{{none}}
let _ = string
}
}
public func useInit() {
let _ = CGMutablePath(p: true)
let _ = CGMutablePath(maybe: true)
let _ = try! CGMutablePath(toss: true)
let _ = CGMutablePath(simple: true)
let _ = CGMutablePath(value: true)
let _ = CGMutablePath(string: "value")
}
|
c481ae6e72083a0cdf459cd6b4659641
| 40.8 | 141 | 0.683014 | false | false | false | false |
dsay/POPDataSource
|
refs/heads/master
|
DataSources/Example/Models/Models.swift
|
mit
|
1
|
import UIKit
struct Artist {
var name: String
var id: Int
var albums = [Album]()
init(_ name: String, _ id: Int) {
self.name = name
self.id = id
}
}
struct Genre {
var name: String
var albums = [Album]()
init(_ genre: String) {
self.name = genre
}
}
struct Album {
var name: String
var releaseDate: Date
var trackCount: Int
var genre: String
var artistName: String
init(_ name: String, _ artistName: String, _ releaseDate: Date, _ trackCount: Int, _ genre: String) {
self.name = name
self.artistName = artistName
self.releaseDate = releaseDate
self.trackCount = trackCount
self.genre = genre
}
}
struct Parser {
var fileURL: URL
func parse() -> ([Album], [Artist])? {
let data = try? Data(contentsOf: fileURL)
var json: [[String : AnyObject]]? = nil
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String : AnyObject]]
} catch {
json = nil
}
guard let parsed = json else {
return nil
}
var albums = [Album]()
var artists = [Artist]()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
for representation in parsed {
let artist = Artist(representation["artistName"] as! String,
representation["artistId"] as! Int)
artists.append(artist)
let date = representation["releaseDate"] as! String
let album = Album(representation["collectionName"] as! String,
representation["artistName"] as! String,
dateFormatter.date(from: date)!,
representation["trackCount"] as! Int,
representation["primaryGenreName"] as! String)
albums.append(album)
}
return (albums, Array(Set(artists)))
}
}
struct LedZeppelin {
fileprivate static let parser: Parser = {
let path = Bundle.main.url(forResource: "Albums", withExtension: "json")
return Parser(fileURL: path!)
}()
fileprivate static let data = LedZeppelin.parser.parse()
static let genres: [Genre] = {
let genreNames = Set(LedZeppelin.data!.0.map { $0.genre })
return genreNames.map { name -> Genre in
var genre = Genre(name)
genre.albums = LedZeppelin.data!.0.filter { $0.genre == name }
return genre
}
}()
static var artists: [Artist] {
var artists = [Artist]()
for artist in LedZeppelin.data!.1 {
var artistWithAlbums = artist
artistWithAlbums.albums = LedZeppelin.data!.0.filter { $0.artistName == artist.name }
artists.append(artistWithAlbums)
}
return artists
}
static let albums: [Album] = {
return LedZeppelin.data!.0
}()
}
func ==(lhs: Album, rhs: Album) -> Bool {
return (lhs.name == rhs.name) && (lhs.trackCount == rhs.trackCount) &&
(lhs.genre == rhs.genre) && (lhs.artistName == rhs.artistName) &&
(lhs.releaseDate == rhs.releaseDate)
}
extension Album: Hashable {
var hashValue: Int {
return self.artistName.hashValue ^ self.genre.hashValue ^ self.name.hashValue ^ self.releaseDate.hashValue ^ self.trackCount.hashValue
}
}
func ==(lhs: Artist, rhs: Artist) -> Bool {
return (lhs.name == rhs.name) && (lhs.id == rhs.id) && (lhs.albums == rhs.albums)
}
extension Artist: Hashable {
var hashValue: Int {
return self.name.hashValue ^ self.id.hashValue ^ self.albums.count.hashValue
}
}
|
c8118dff30aaef889432e8d098781bb3
| 28.082707 | 142 | 0.558428 | false | false | false | false |
pksprojects/ElasticSwift
|
refs/heads/master
|
Sources/ElasticSwiftCore/Http/HTTPResponse.swift
|
mit
|
1
|
//
// HTTPResponse.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 6/16/19.
//
import Foundation
import Logging
import NIOHTTP1
// MARK: - HTTPResponse
/// Represents a HTTPResponse returned from Elasticsearch
public struct HTTPResponse {
public let request: HTTPRequest
public let status: HTTPResponseStatus
public let headers: HTTPHeaders
public var body: Data?
public init(request: HTTPRequest, status: HTTPResponseStatus, headers: HTTPHeaders, body: Data?) {
self.status = status
self.headers = headers
self.body = body
self.request = request
}
internal init(withBuilder builder: HTTPResponseBuilder) throws {
guard builder.request != nil else {
throw HTTPResponseBuilderError.missingRequiredField("request")
}
guard builder.headers != nil else {
throw HTTPResponseBuilderError.missingRequiredField("headers")
}
guard builder.status != nil else {
throw HTTPResponseBuilderError.missingRequiredField("status")
}
self.init(request: builder.request!, status: builder.status!, headers: builder.headers!, body: builder.body)
}
}
extension HTTPResponse: Equatable {}
// MARK: - HTTPResponseBuilder
/// Builder for `HTTPResponse`
public class HTTPResponseBuilder {
private var _request: HTTPRequest?
private var _status: HTTPResponseStatus?
private var _headers: HTTPHeaders?
private var _body: Data?
public init() {}
@discardableResult
public func set(headers: HTTPHeaders) -> HTTPResponseBuilder {
_headers = headers
return self
}
@discardableResult
public func set(request: HTTPRequest) -> HTTPResponseBuilder {
_request = request
return self
}
@discardableResult
public func set(status: HTTPResponseStatus) -> HTTPResponseBuilder {
_status = status
return self
}
@discardableResult
public func set(body: Data) -> HTTPResponseBuilder {
_body = body
return self
}
public var request: HTTPRequest? {
return _request
}
public var status: HTTPResponseStatus? {
return _status
}
public var headers: HTTPHeaders? {
return _headers
}
public var body: Data? {
return _body
}
public func build() throws -> HTTPResponse {
return try HTTPResponse(withBuilder: self)
}
}
// MARK: - HTTPResponseStatus
/// Helper extention for HTTPResponseStatus
public extension HTTPResponseStatus {
func is1xxInformational() -> Bool {
return code >= 100 && code < 200
}
func is2xxSuccessful() -> Bool {
return code >= 200 && code < 300
}
func is3xxRedirection() -> Bool {
return code >= 300 && code < 400
}
func is4xxClientError() -> Bool {
return code >= 400 && code < 500
}
func is5xxServerError() -> Bool {
return code >= 500 && code < 600
}
func isError() -> Bool {
return is4xxClientError() || is5xxServerError()
}
}
|
27399f1e2fd8fb0efdf87254f31038cb
| 22.687023 | 116 | 0.638737 | false | false | false | false |
Chris-Perkins/Lifting-Buddy
|
refs/heads/master
|
Lifting Buddy/WorkoutSessionTableViewCell.swift
|
mit
|
1
|
//
// WorkoutSessionTableViewCell.swift
// Lifting Buddy
//
// Created by Christopher Perkins on 9/10/17.
// Copyright © 2017 Christopher Perkins. All rights reserved.
//
import UIKit
import Realm
import RealmSwift
class WorkoutSessionTableViewCell: UITableViewCell {
// MARK: View properties
// Padding between views
private static let viewPadding: CGFloat = 15.0
// IndexPath of this cell in the tableview
public var indexPath: IndexPath?
// Delegate we use to change height of cells
public var delegate: WorkoutSessionTableViewCellDelegate?
// The delegate we use to indicate that a cell was deleted
public var deletionDelegate: CellDeletionDelegate?
// Delegate we inform where to scroll
public var scrollDelegate: UITableViewScrollDelegate?
// the button we press to toggle this cell. It's invisible (basically)
private let invisButton: UIButton
// The button indicating we can expand this cell
public let expandImage: UIImageView
// the title of this cell, holds the title of the exercise name
public let cellTitle: UILabel
// Cell contents on expand
public let setLabel: UILabel
// add a set to the table
public let addSetButton: PrettyButton
// The actual table view where we input data
public let setTableView: SetTableView
// The height of our tableview
private var tableViewHeightConstraint: NSLayoutConstraint?
// Exercise assigned to this cell
private var exercise: Exercise
// Whether or not this exercise is complete
private var isComplete: Bool
// Whether or not this view is toggled
public var isToggled: Bool
// The current set we're doing
private var curSet: Int
// MARK: Init Functions
init(exercise: Exercise, style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
self.exercise = exercise
invisButton = UIButton()
cellTitle = UILabel()
expandImage = UIImageView(image: #imageLiteral(resourceName: "DownArrow"))
setLabel = UILabel()
addSetButton = PrettyButton()
setTableView = SetTableView(forExercise: exercise)
// Initialize to minimum height of the cell label + the viewPadding associated
// between the two views.
curSet = 0
isComplete = false
isToggled = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(invisButton)
addSubview(expandImage)
addSubview(cellTitle)
addSubview(setTableView)
addSubview(addSetButton)
createAndActivateInvisButtonConstraints()
createAndActivateExpandImageConstraints()
createAndActivateCellTitleConstraints()
createAndActivateAddSetButtonConstraints()
createAndActivateSetTableViewConstraints()
invisButton.addTarget( self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
addSetButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
setTableView.completedSetCountDelegate = self
setTableView.cellDeletionDelegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View overrides
override func layoutSubviews() {
super.layoutSubviews()
// Checks if it's safe to use exercise. Otherwise, delete this cell
if exercise.isInvalidated {
self.deletionDelegate?.deleteData(at: indexPath!.row)
}
// Self stuff
selectionStyle = .none
clipsToBounds = true
// Invis Button
// Invis Button has to be "visible" to be pressed. So, 0.001
invisButton.backgroundColor = UIColor.lightGray.withAlphaComponent(0.001)
// Cell Title
curSet = setTableView.completedSetCount
let reqSet = exercise.getSetCount()
/*
* Text depends on whether or not we have a required set amount.
* If we do, a format example is [1/2]
* If we don't, the same example is [1]
*/
cellTitle.text = reqSet > 0 ?
"[\(curSet)/\(reqSet)] \(exercise.getName()!)":
"[\(curSet)] \(exercise.getName()!)"
cellTitle.font = UIFont.boldSystemFont(ofSize: 18.0)
// Add Set button
addSetButton.setDefaultProperties()
addSetButton.setTitle(NSLocalizedString("SessionView.Button.AddSet", comment: ""), for: .normal)
// Exercisehistory table
setTableView.isScrollEnabled = false
// Different states for whether the cell is complete or not.
// If complete: cell turns green, title color turns white to be visible.
// If not complete: Cell is white
if isComplete {
backgroundColor = UIColor.niceGreen.withAlphaComponent(0.75)
cellTitle.textColor = .white
} else {
backgroundColor = .primaryBlackWhiteColor
cellTitle.textColor = .niceBlue
}
updateCompleteStatus()
}
// MARK: View functions
// Sets the exercise for this cell
public func setExercise(_ exercise: Exercise) {
self.exercise = exercise
}
// Update the complete status (call when some value changed)
public func updateCompleteStatus() {
let newComplete = setTableView.completedSetCount >= exercise.getSetCount()
// We updated our completed status! So inform the delegate.
if newComplete != isComplete {
isComplete = newComplete
delegate?.cellCompleteStatusChanged(complete: isComplete)
// We only display the message if the exercise is complete and > 0 sets to do
if isComplete && exercise.getSetCount() != 0 {
MessageQueue.shared.append(Message(type: .exerciseComplete,
identifier: exercise.getName(),
value: nil))
}
layoutSubviews()
} else if curSet != setTableView.completedSetCount {
layoutSubviews()
}
}
// Changes whether or not this cell is toggled
public func updateToggledStatus() {
if indexPath != nil {
delegate?.cellHeightDidChange(height: getHeight(),
indexPath: indexPath!)
expandImage.transform = CGAffineTransform(scaleX: 1,
y: isToggled ? -1 : 1)
}
}
// gets the height of this cell when expanded or hidden
private func getHeight() -> CGFloat {
if isToggled {
// total padding for this view. Incremement by one per each "cell" of this view
var totalPadding = 0
let titleBarHeight = UITableViewCell.defaultHeight
let addSetButtonHeight = PrettyButton.defaultHeight
let totalTableViewHeight = tableViewHeightConstraint!.constant
totalPadding += 1
return titleBarHeight + totalTableViewHeight + addSetButtonHeight +
CGFloat(totalPadding) * WorkoutSessionTableViewCell.viewPadding
} else {
return UITableViewCell.defaultHeight
}
}
// Should be called whenever the height constraint may change
public func heightConstraintConstantCouldChange() {
if let tableViewHeightConstraint = tableViewHeightConstraint
{
tableViewHeightConstraint.constant = setTableView.getHeight()
delegate?.cellHeightDidChange(height: getHeight(), indexPath: indexPath!)
UIView.animate(withDuration: 0.25, animations: {
self.layoutIfNeeded()
})
}
}
// MARK: Event functions
// Generic button press event
@objc private func buttonPress(sender: UIButton) {
switch(sender) {
case invisButton:
isToggled = !isToggled
updateToggledStatus()
scrollDelegate?.scrollToCell(atIndexPath: indexPath!,
position: .top, animated: false)
case addSetButton:
setTableView.appendDataPiece(ExerciseHistoryEntry())
heightConstraintConstantCouldChange()
// Don't animate as we would cause the tableview to scroll way down every time.
// that's bad.
scrollDelegate?.scrollToCell(atIndexPath: indexPath!,
position: .bottom, animated: false)
default:
fatalError("Button pressed did not exist?")
}
}
// MARK: Encapsulated methods
// Returns whether or not this exercise is complete (did all sets)
public func getIsComplete() -> Bool {
return isComplete
}
// MARK: Constraints
// Cling to top, left, right of self ; height default
private func createAndActivateInvisButtonConstraints() {
invisButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: invisButton,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: invisButton,
withCopyView: self,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: invisButton,
withCopyView: self,
attribute: .right).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: invisButton,
height: UITableViewCell.defaultHeight
).isActive = true
}
// Place below view top, cling to left, right ; height of default height
private func createAndActivateCellTitleConstraints() {
cellTitle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitle,
withCopyView: self,
attribute: .left,
plusConstant: 10).isActive = true
NSLayoutConstraint(item: expandImage,
attribute: .left,
relatedBy: .equal,
toItem: cellTitle,
attribute: .right,
multiplier: 1,
constant: 10).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: cellTitle,
height: UITableViewCell.defaultHeight).isActive = true
}
// Cling to top, right ; height 8.46 ; width 16
private func createAndActivateExpandImageConstraints() {
expandImage.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage,
withCopyView: self,
attribute: .top,
plusConstant: 20.77).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: expandImage,
withCopyView: self,
attribute: .right,
plusConstant: -10).isActive = true
NSLayoutConstraint.createWidthConstraintForView(view: expandImage,
width: 16).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: expandImage,
height: 8.46).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: cellTitle,
height: UITableViewCell.defaultHeight
).isActive = true
}
// center horiz to self ; width of addset ; place below addset ; height of tableviewheight
private func createAndActivateSetTableViewConstraints() {
setTableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: setTableView,
withCopyView: self,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: setTableView,
withCopyView: self,
attribute: .width).isActive = true
NSLayoutConstraint.createViewBelowViewConstraint(view: setTableView,
belowView: cellTitle,
withPadding: WorkoutSessionTableViewCell.viewPadding
).isActive = true
tableViewHeightConstraint =
NSLayoutConstraint.createHeightConstraintForView(view: setTableView,
height: 0)
tableViewHeightConstraint!.isActive = true
}
// Place below the input content view
private func createAndActivateAddSetButtonConstraints() {
addSetButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: addSetButton,
withCopyView: self,
attribute: .centerX).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: addSetButton,
withCopyView: setTableView,
attribute: .width).isActive = true
NSLayoutConstraint.createViewBelowViewConstraint(view: addSetButton,
belowView: setTableView).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: addSetButton,
height: PrettyButton.defaultHeight).isActive = true
}
}
// MARK: HistoryEntryDelegate Extension
extension WorkoutSessionTableViewCell: ExerciseHistoryEntryTableViewDelegate {
// Called when a cell is deleted
func dataDeleted(deletedData: ExerciseHistoryEntry) {
exercise.removeExerciseHistoryEntry(deletedData)
heightConstraintConstantCouldChange()
updateCompleteStatus()
}
}
// MARK: SetTableViewDelegate
extension WorkoutSessionTableViewCell: SetTableViewDelegate {
func completedSetCountChanged() {
updateCompleteStatus()
}
}
extension WorkoutSessionTableViewCell: CellDeletionDelegate {
func deleteData(at index: Int) {
tableViewHeightConstraint?.constant -= SetTableViewCell.getHeight(forExercise: exercise)
heightConstraintConstantCouldChange()
scrollDelegate?.scrollToCell(atIndexPath: indexPath!, position: .none, animated: false)
}
}
|
4fdad081b45b18d81e326f7432abb08f
| 42.23822 | 111 | 0.567234 | false | false | false | false |
TheBudgeteers/CartTrackr
|
refs/heads/master
|
CartTrackr/Carthage/Checkouts/SwiftyCam/Source/SwiftyCamViewController.swift
|
mit
|
1
|
/*Copyright (c) 2016, Andrew Walz.
Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import AVFoundation
// MARK: View Controller Declaration
/// A UIViewController Camera View Subclass
open class SwiftyCamViewController: UIViewController {
// MARK: Enumeration Declaration
/// Enumeration for Camera Selection
public enum CameraSelection {
/// Camera on the back of the device
case rear
/// Camera on the front of the device
case front
}
/// Enumeration for video quality of the capture session. Corresponds to a AVCaptureSessionPreset
public enum VideoQuality {
/// AVCaptureSessionPresetHigh
case high
/// AVCaptureSessionPresetMedium
case medium
/// AVCaptureSessionPresetLow
case low
/// AVCaptureSessionPreset352x288
case resolution352x288
/// AVCaptureSessionPreset640x480
case resolution640x480
/// AVCaptureSessionPreset1280x720
case resolution1280x720
/// AVCaptureSessionPreset1920x1080
case resolution1920x1080
/// AVCaptureSessionPreset3840x2160
case resolution3840x2160
/// AVCaptureSessionPresetiFrame960x540
case iframe960x540
/// AVCaptureSessionPresetiFrame1280x720
case iframe1280x720
}
/**
Result from the AVCaptureSession Setup
- success: success
- notAuthorized: User denied access to Camera of Microphone
- configurationFailed: Unknown error
*/
fileprivate enum SessionSetupResult {
case success
case notAuthorized
case configurationFailed
}
// MARK: Public Variable Declarations
/// Public Camera Delegate for the Custom View Controller Subclass
public var cameraDelegate: SwiftyCamViewControllerDelegate?
/// Maxiumum video duration if SwiftyCamButton is used
public var maximumVideoDuration : Double = 0.0
/// Video capture quality
public var videoQuality : VideoQuality = .high
/// Sets whether flash is enabled for photo and video capture
public var flashEnabled = false
/// Sets whether Pinch to Zoom is enabled for the capture session
public var pinchToZoom = true
/// Sets the maximum zoom scale allowed during Pinch gesture
public var maxZoomScale = CGFloat(4.0)
/// Sets whether Tap to Focus and Tap to Adjust Exposure is enabled for the capture session
public var tapToFocus = true
/// Sets whether the capture session should adjust to low light conditions automatically
///
/// Only supported on iPhone 5 and 5C
public var lowLightBoost = true
/// Set whether SwiftyCam should allow background audio from other applications
public var allowBackgroundAudio = true
/// Sets whether a double tap to switch cameras is supported
public var doubleTapCameraSwitch = true
/// Set default launch camera
public var defaultCamera = CameraSelection.rear
/// Sets wether the taken photo or video should be oriented according to the device orientation
public var shouldUseDeviceOrientation = false
// MARK: Public Get-only Variable Declarations
/// Returns true if video is currently being recorded
private(set) public var isVideoRecording = false
/// Returns true if the capture session is currently running
private(set) public var isSessionRunning = false
/// Returns the CameraSelection corresponding to the currently utilized camera
private(set) public var currentCamera = CameraSelection.rear
// MARK: Private Constant Declarations
/// Current Capture Session
fileprivate let session = AVCaptureSession()
/// Serial queue used for setting up session
fileprivate let sessionQueue = DispatchQueue(label: "session queue", attributes: [])
// MARK: Private Variable Declarations
/// Variable for storing current zoom scale
fileprivate var zoomScale = CGFloat(1.0)
/// Variable for storing initial zoom scale before Pinch to Zoom begins
fileprivate var beginZoomScale = CGFloat(1.0)
/// Returns true if the torch (flash) is currently enabled
fileprivate var isCameraTorchOn = false
/// Variable to store result of capture session setup
fileprivate var setupResult = SessionSetupResult.success
/// BackgroundID variable for video recording
fileprivate var backgroundRecordingID : UIBackgroundTaskIdentifier? = nil
/// Video Input variable
fileprivate var videoDeviceInput : AVCaptureDeviceInput!
/// Movie File Output variable
fileprivate var movieFileOutput : AVCaptureMovieFileOutput?
/// Photo File Output variable
fileprivate var photoFileOutput : AVCaptureStillImageOutput?
/// Video Device variable
fileprivate var videoDevice : AVCaptureDevice?
/// PreviewView for the capture session
fileprivate var previewLayer : PreviewView!
/// UIView for front facing flash
fileprivate var flashView : UIView?
/// Last changed orientation
fileprivate var deviceOrientation : UIDeviceOrientation?
/// Disable view autorotation for forced portrait recorindg
override open var shouldAutorotate: Bool {
return false
}
// MARK: ViewDidLoad
/// ViewDidLoad Implementation
override open func viewDidLoad() {
super.viewDidLoad()
previewLayer = PreviewView(frame: self.view.frame)
// Add Gesture Recognizers
addGestureRecognizersTo(view: previewLayer)
self.view.addSubview(previewLayer)
previewLayer.session = session
// Test authorization status for Camera and Micophone
switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo){
case .authorized:
// already authorized
break
case .notDetermined:
// not yet determined
sessionQueue.suspend()
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self] granted in
if !granted {
self.setupResult = .notAuthorized
}
self.sessionQueue.resume()
})
default:
// already been asked. Denied access
setupResult = .notAuthorized
}
sessionQueue.async { [unowned self] in
self.configureSession()
}
}
// MARK: ViewDidAppear
/// ViewDidAppear(_ animated:) Implementation
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Subscribe to device rotation notifications
if shouldUseDeviceOrientation {
subscribeToDeviceOrientationChangeNotifications()
}
// Set background audio preference
setBackgroundAudioPreference()
sessionQueue.async {
switch self.setupResult {
case .success:
// Begin Session
self.session.startRunning()
self.isSessionRunning = self.session.isRunning
case .notAuthorized:
// Prompt to App Settings
self.promptToAppSettings()
case .configurationFailed:
// Unknown Error
DispatchQueue.main.async(execute: { [unowned self] in
let message = NSLocalizedString("Unable to capture media", comment: "Alert message when something goes wrong during capture session configuration")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
})
}
}
}
// MARK: ViewDidDisappear
/// ViewDidDisappear(_ animated:) Implementation
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// If session is running, stop the session
if self.isSessionRunning == true {
self.session.stopRunning()
self.isSessionRunning = false
}
//Disble flash if it is currently enabled
disableFlash()
// Unsubscribe from device rotation notifications
if shouldUseDeviceOrientation {
unsubscribeFromDeviceOrientationChangeNotifications()
}
}
// MARK: Public Functions
/**
Capture photo from current session
UIImage will be returned with the SwiftyCamViewControllerDelegate function SwiftyCamDidTakePhoto(photo:)
*/
public func takePhoto() {
guard let device = videoDevice else {
return
}
if device.hasFlash == true && flashEnabled == true /* TODO: Add Support for Retina Flash and add front flash */ {
changeFlashSettings(device: device, mode: .on)
capturePhotoAsyncronously(completionHandler: { (_) in })
} else if device.hasFlash == false && flashEnabled == true && currentCamera == .front {
flashView = UIView(frame: view.frame)
flashView?.alpha = 0.0
flashView?.backgroundColor = UIColor.white
previewLayer.addSubview(flashView!)
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: {
self.flashView?.alpha = 1.0
}, completion: { (_) in
self.capturePhotoAsyncronously(completionHandler: { (success) in
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: {
self.flashView?.alpha = 0.0
}, completion: { (_) in
self.flashView?.removeFromSuperview()
})
})
})
} else {
if device.isFlashActive == true {
changeFlashSettings(device: device, mode: .off)
}
capturePhotoAsyncronously(completionHandler: { (_) in })
}
}
/**
Begin recording video of current session
SwiftyCamViewControllerDelegate function SwiftyCamDidBeginRecordingVideo() will be called
*/
public func startVideoRecording() {
guard let movieFileOutput = self.movieFileOutput else {
return
}
if currentCamera == .rear && flashEnabled == true {
enableFlash()
}
if currentCamera == .front && flashEnabled == true {
flashView = UIView(frame: view.frame)
flashView?.backgroundColor = UIColor.white
flashView?.alpha = 0.85
previewLayer.addSubview(flashView!)
}
sessionQueue.async { [unowned self] in
if !movieFileOutput.isRecording {
if UIDevice.current.isMultitaskingSupported {
self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
}
// Update the orientation on the movie file output video connection before starting recording.
let movieFileOutputConnection = self.movieFileOutput?.connection(withMediaType: AVMediaTypeVideo)
//flip video output if front facing camera is selected
if self.currentCamera == .front {
movieFileOutputConnection?.isVideoMirrored = true
}
movieFileOutputConnection?.videoOrientation = self.getVideoOrientation()
// Start recording to a temporary file.
let outputFileName = UUID().uuidString
let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)
self.isVideoRecording = true
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didBeginRecordingVideo: self.currentCamera)
}
}
else {
movieFileOutput.stopRecording()
}
}
}
/**
Stop video recording video of current session
SwiftyCamViewControllerDelegate function SwiftyCamDidFinishRecordingVideo() will be called
When video has finished processing, the URL to the video location will be returned by SwiftyCamDidFinishProcessingVideoAt(url:)
*/
public func stopVideoRecording() {
if self.movieFileOutput?.isRecording == true {
self.isVideoRecording = false
movieFileOutput!.stopRecording()
disableFlash()
if currentCamera == .front && flashEnabled == true && flashView != nil {
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveEaseInOut, animations: {
self.flashView?.alpha = 0.0
}, completion: { (_) in
self.flashView?.removeFromSuperview()
})
}
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFinishRecordingVideo: self.currentCamera)
}
}
}
/**
Switch between front and rear camera
SwiftyCamViewControllerDelegate function SwiftyCamDidSwitchCameras(camera: will be return the current camera selection
*/
public func switchCamera() {
guard isVideoRecording != true else {
//TODO: Look into switching camera during video recording
print("[SwiftyCam]: Switching between cameras while recording video is not supported")
return
}
switch currentCamera {
case .front:
currentCamera = .rear
case .rear:
currentCamera = .front
}
session.stopRunning()
sessionQueue.async { [unowned self] in
// remove and re-add inputs and outputs
for input in self.session.inputs {
self.session.removeInput(input as! AVCaptureInput)
}
self.addInputs()
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didSwitchCameras: self.currentCamera)
}
self.session.startRunning()
}
// If flash is enabled, disable it as the torch is needed for front facing camera
disableFlash()
}
// MARK: Private Functions
/// Configure session, add inputs and outputs
fileprivate func configureSession() {
guard setupResult == .success else {
return
}
// Set default camera
currentCamera = defaultCamera
// begin configuring session
session.beginConfiguration()
configureVideoPreset()
addVideoInput()
addAudioInput()
configureVideoOutput()
configurePhotoOutput()
session.commitConfiguration()
}
/// Add inputs after changing camera()
fileprivate func addInputs() {
session.beginConfiguration()
configureVideoPreset()
addVideoInput()
addAudioInput()
session.commitConfiguration()
}
// Front facing camera will always be set to VideoQuality.high
// If set video quality is not supported, videoQuality variable will be set to VideoQuality.high
/// Configure image quality preset
fileprivate func configureVideoPreset() {
if currentCamera == .front {
session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high)
} else {
if session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality)) {
session.sessionPreset = videoInputPresetFromVideoQuality(quality: videoQuality)
} else {
session.sessionPreset = videoInputPresetFromVideoQuality(quality: .high)
}
}
}
/// Add Video Inputs
fileprivate func addVideoInput() {
switch currentCamera {
case .front:
videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .front)
case .rear:
videoDevice = SwiftyCamViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: .back)
}
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusModeSupported(.continuousAutoFocus) {
device.focusMode = .continuousAutoFocus
if device.isSmoothAutoFocusSupported {
device.isSmoothAutoFocusEnabled = true
}
}
if device.isExposureModeSupported(.continuousAutoExposure) {
device.exposureMode = .continuousAutoExposure
}
if device.isWhiteBalanceModeSupported(.continuousAutoWhiteBalance) {
device.whiteBalanceMode = .continuousAutoWhiteBalance
}
if device.isLowLightBoostSupported && lowLightBoost == true {
device.automaticallyEnablesLowLightBoostWhenAvailable = true
}
device.unlockForConfiguration()
} catch {
print("[SwiftyCam]: Error locking configuration")
}
}
do {
let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice)
if session.canAddInput(videoDeviceInput) {
session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
} else {
print("[SwiftyCam]: Could not add video device input to the session")
print(session.canSetSessionPreset(videoInputPresetFromVideoQuality(quality: videoQuality)))
setupResult = .configurationFailed
session.commitConfiguration()
return
}
} catch {
print("[SwiftyCam]: Could not create video device input: \(error)")
setupResult = .configurationFailed
return
}
}
/// Add Audio Inputs
fileprivate func addAudioInput() {
do {
let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice)
if session.canAddInput(audioDeviceInput) {
session.addInput(audioDeviceInput)
}
else {
print("[SwiftyCam]: Could not add audio device input to the session")
}
}
catch {
print("[SwiftyCam]: Could not create audio device input: \(error)")
}
}
/// Configure Movie Output
fileprivate func configureVideoOutput() {
let movieFileOutput = AVCaptureMovieFileOutput()
if self.session.canAddOutput(movieFileOutput) {
self.session.addOutput(movieFileOutput)
if let connection = movieFileOutput.connection(withMediaType: AVMediaTypeVideo) {
if connection.isVideoStabilizationSupported {
connection.preferredVideoStabilizationMode = .auto
}
}
self.movieFileOutput = movieFileOutput
}
}
/// Configure Photo Output
fileprivate func configurePhotoOutput() {
let photoFileOutput = AVCaptureStillImageOutput()
if self.session.canAddOutput(photoFileOutput) {
photoFileOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
self.session.addOutput(photoFileOutput)
self.photoFileOutput = photoFileOutput
}
}
/// Orientation management
fileprivate func subscribeToDeviceOrientationChangeNotifications() {
self.deviceOrientation = UIDevice.current.orientation
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
fileprivate func unsubscribeFromDeviceOrientationChangeNotifications() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
self.deviceOrientation = nil
}
@objc fileprivate func deviceDidRotate() {
if !UIDevice.current.orientation.isFlat {
self.deviceOrientation = UIDevice.current.orientation
}
}
fileprivate func getVideoOrientation() -> AVCaptureVideoOrientation {
guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return previewLayer!.videoPreviewLayer.connection.videoOrientation }
switch deviceOrientation {
case .landscapeLeft:
return .landscapeRight
case .landscapeRight:
return .landscapeLeft
case .portraitUpsideDown:
return .portraitUpsideDown
default:
return .portrait
}
}
fileprivate func getImageOrientation(forCamera: CameraSelection) -> UIImageOrientation {
guard shouldUseDeviceOrientation, let deviceOrientation = self.deviceOrientation else { return forCamera == .rear ? .right : .leftMirrored }
switch deviceOrientation {
case .landscapeLeft:
return forCamera == .rear ? .up : .downMirrored
case .landscapeRight:
return forCamera == .rear ? .down : .upMirrored
case .portraitUpsideDown:
return forCamera == .rear ? .left : .rightMirrored
default:
return forCamera == .rear ? .right : .leftMirrored
}
}
/**
Returns a UIImage from Image Data.
- Parameter imageData: Image Data returned from capturing photo from the capture session.
- Returns: UIImage from the image data, adjusted for proper orientation.
*/
fileprivate func processPhoto(_ imageData: Data) -> UIImage {
let dataProvider = CGDataProvider(data: imageData as CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
// Set proper orientation for photo
// If camera is currently set to front camera, flip image
let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: self.getImageOrientation(forCamera: self.currentCamera))
return image
}
fileprivate func capturePhotoAsyncronously(completionHandler: @escaping(Bool) -> ()) {
if let videoConnection = photoFileOutput?.connection(withMediaType: AVMediaTypeVideo) {
photoFileOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in
if (sampleBuffer != nil) {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let image = self.processPhoto(imageData!)
// Call delegate and return new image
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didTake: image)
}
completionHandler(true)
} else {
completionHandler(false)
}
})
} else {
completionHandler(false)
}
}
/// Handle Denied App Privacy Settings
fileprivate func promptToAppSettings() {
// prompt User with UIAlertView
DispatchQueue.main.async(execute: { [unowned self] in
let message = NSLocalizedString("AVCam doesn't have permission to use the camera, please change privacy settings", comment: "Alert message when the user has denied access to the camera")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Settings", comment: "Alert button to open Settings"), style: .default, handler: { action in
if #available(iOS 10.0, *) {
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
} else {
if let appSettings = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(appSettings)
}
}
}))
self.present(alertController, animated: true, completion: nil)
})
}
/**
Returns an AVCapturePreset from VideoQuality Enumeration
- Parameter quality: ViewQuality enum
- Returns: String representing a AVCapturePreset
*/
fileprivate func videoInputPresetFromVideoQuality(quality: VideoQuality) -> String {
switch quality {
case .high: return AVCaptureSessionPresetHigh
case .medium: return AVCaptureSessionPresetMedium
case .low: return AVCaptureSessionPresetLow
case .resolution352x288: return AVCaptureSessionPreset352x288
case .resolution640x480: return AVCaptureSessionPreset640x480
case .resolution1280x720: return AVCaptureSessionPreset1280x720
case .resolution1920x1080: return AVCaptureSessionPreset1920x1080
case .iframe960x540: return AVCaptureSessionPresetiFrame960x540
case .iframe1280x720: return AVCaptureSessionPresetiFrame1280x720
case .resolution3840x2160:
if #available(iOS 9.0, *) {
return AVCaptureSessionPreset3840x2160
}
else {
print("[SwiftyCam]: Resolution 3840x2160 not supported")
return AVCaptureSessionPresetHigh
}
}
}
/// Get Devices
fileprivate class func deviceWithMediaType(_ mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice? {
if let devices = AVCaptureDevice.devices(withMediaType: mediaType) as? [AVCaptureDevice] {
return devices.filter({ $0.position == position }).first
}
return nil
}
/// Enable or disable flash for photo
fileprivate func changeFlashSettings(device: AVCaptureDevice, mode: AVCaptureFlashMode) {
do {
try device.lockForConfiguration()
device.flashMode = mode
device.unlockForConfiguration()
} catch {
print("[SwiftyCam]: \(error)")
}
}
/// Enable flash
fileprivate func enableFlash() {
if self.isCameraTorchOn == false {
toggleFlash()
}
}
/// Disable flash
fileprivate func disableFlash() {
if self.isCameraTorchOn == true {
toggleFlash()
}
}
/// Toggles between enabling and disabling flash
fileprivate func toggleFlash() {
guard self.currentCamera == .rear else {
// Flash is not supported for front facing camera
return
}
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
// Check if device has a flash
if (device?.hasTorch)! {
do {
try device?.lockForConfiguration()
if (device?.torchMode == AVCaptureTorchMode.on) {
device?.torchMode = AVCaptureTorchMode.off
self.isCameraTorchOn = false
} else {
do {
try device?.setTorchModeOnWithLevel(1.0)
self.isCameraTorchOn = true
} catch {
print("[SwiftyCam]: \(error)")
}
}
device?.unlockForConfiguration()
} catch {
print("[SwiftyCam]: \(error)")
}
}
}
/// Sets whether SwiftyCam should enable background audio from other applications or sources
fileprivate func setBackgroundAudioPreference() {
guard allowBackgroundAudio == true else {
return
}
do{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord,
with: [.duckOthers, .defaultToSpeaker])
session.automaticallyConfiguresApplicationAudioSession = false
}
catch {
print("[SwiftyCam]: Failed to set background audio preference")
}
}
}
extension SwiftyCamViewController : SwiftyCamButtonDelegate {
/// Sets the maximum duration of the SwiftyCamButton
public func setMaxiumVideoDuration() -> Double {
return maximumVideoDuration
}
/// Set UITapGesture to take photo
public func buttonWasTapped() {
takePhoto()
}
/// Set UILongPressGesture start to begin video
public func buttonDidBeginLongPress() {
startVideoRecording()
}
/// Set UILongPressGesture begin to begin end video
public func buttonDidEndLongPress() {
stopVideoRecording()
}
/// Called if maximum duration is reached
public func longPressDidReachMaximumDuration() {
stopVideoRecording()
}
}
// MARK: AVCaptureFileOutputRecordingDelegate
extension SwiftyCamViewController : AVCaptureFileOutputRecordingDelegate {
/// Process newly captured video and write it to temporary directory
public func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
if let currentBackgroundRecordingID = backgroundRecordingID {
backgroundRecordingID = UIBackgroundTaskInvalid
if currentBackgroundRecordingID != UIBackgroundTaskInvalid {
UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)
}
}
if error != nil {
print("[SwiftyCam]: Movie file finishing error: \(error)")
} else {
//Call delegate function with the URL of the outputfile
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFinishProcessVideoAt: outputFileURL)
}
}
}
}
// Mark: UIGestureRecognizer Declarations
extension SwiftyCamViewController {
/// Handle pinch gesture
@objc fileprivate func zoomGesture(pinch: UIPinchGestureRecognizer) {
guard pinchToZoom == true && self.currentCamera == .rear else {
//ignore pinch if pinchToZoom is set to false
return
}
do {
let captureDevice = AVCaptureDevice.devices().first as? AVCaptureDevice
try captureDevice?.lockForConfiguration()
zoomScale = min(maxZoomScale, max(1.0, min(beginZoomScale * pinch.scale, captureDevice!.activeFormat.videoMaxZoomFactor)))
captureDevice?.videoZoomFactor = zoomScale
// Call Delegate function with current zoom scale
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didChangeZoomLevel: self.zoomScale)
}
captureDevice?.unlockForConfiguration()
} catch {
print("[SwiftyCam]: Error locking configuration")
}
}
/// Handle single tap gesture
@objc fileprivate func singleTapGesture(tap: UITapGestureRecognizer) {
guard tapToFocus == true else {
// Ignore taps
return
}
let screenSize = previewLayer!.bounds.size
let tapPoint = tap.location(in: previewLayer!)
let x = tapPoint.y / screenSize.height
let y = 1.0 - tapPoint.x / screenSize.width
let focusPoint = CGPoint(x: x, y: y)
if let device = videoDevice {
do {
try device.lockForConfiguration()
if device.isFocusPointOfInterestSupported == true {
device.focusPointOfInterest = focusPoint
device.focusMode = .autoFocus
}
device.exposurePointOfInterest = focusPoint
device.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device.unlockForConfiguration()
//Call delegate function and pass in the location of the touch
DispatchQueue.main.async {
self.cameraDelegate?.swiftyCam(self, didFocusAtPoint: tapPoint)
}
}
catch {
// just ignore
}
}
}
/// Handle double tap gesture
@objc fileprivate func doubleTapGesture(tap: UITapGestureRecognizer) {
guard doubleTapCameraSwitch == true else {
return
}
switchCamera()
}
/**
Add pinch gesture recognizer and double tap gesture recognizer to currentView
- Parameter view: View to add gesture recognzier
*/
fileprivate func addGestureRecognizersTo(view: UIView) {
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(zoomGesture(pinch:)))
pinchGesture.delegate = self
view.addGestureRecognizer(pinchGesture)
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTapGesture(tap:)))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.delegate = self
view.addGestureRecognizer(singleTapGesture)
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapGesture(tap:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.delegate = self
view.addGestureRecognizer(doubleTapGesture)
}
}
// MARK: UIGestureRecognizerDelegate
extension SwiftyCamViewController : UIGestureRecognizerDelegate {
/// Set beginZoomScale when pinch begins
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKind(of: UIPinchGestureRecognizer.self) {
beginZoomScale = zoomScale;
}
return true
}
}
|
6a5b985e2aad77ab75de71d8e1eb7e30
| 27.868101 | 189 | 0.740797 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
validation-test/compiler_crashers_2_fixed/0019-rdar21511651.swift
|
apache-2.0
|
10
|
// RUN: not %target-swift-frontend %s -parse
internal protocol _SequenceWrapperType {
typealias Base : SequenceType
typealias Generator : GeneratorType = Base.Generator
var _base: Base {get}
}
extension SequenceType
where Self : _SequenceWrapperType, Self.Generator == Self.Base.Generator {
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> Base.Generator {
return self._base.generate()
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
public func _customContainsEquatableElement(
element: Base.Generator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `CollectionType`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(preprocess: (Self)->R) -> R? {
return _base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Generator.Element> {
return _base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _initializeTo(ptr: UnsafeMutablePointer<Base.Generator.Element>) {
return _base._initializeTo(ptr)
}
}
internal protocol _CollectionWrapperType : _SequenceWrapperType {
typealias Base : CollectionType
typealias Index : ForwardIndexType = Base.Index
var _base: Base {get}
}
extension CollectionType
where Self : _CollectionWrapperType, Self.Index == Self.Base.Index {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Base.Index {
return _base.endIndex
}
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Base.Generator.Element {
return _base[position]
}
}
//===--- New stuff --------------------------------------------------------===//
public protocol _prext_LazySequenceType : SequenceType {
/// A SequenceType that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazySequence` layer.
typealias Elements: SequenceType = Self
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing a `_prext_LazySequence`
/// layer.
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements {get}
/// An Array, created on-demand, containing the elements of this
/// lazy SequenceType.
///
/// Note: this property need not be implemented by conforming types, it has a
/// default implementation in a protocol extension.
var array: [Generator.Element] {get}
}
extension _prext_LazySequenceType {
/// an Array, created on-demand, containing the elements of this
/// lazy SequenceType.
public var array: [Generator.Element] {
return Array(self)
}
}
extension _prext_LazySequenceType where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazySequenceType where Self : _SequenceWrapperType {
public var elements: Base { return _base }
}
/// A sequence that forwards its implementation to an underlying
/// sequence instance while exposing lazy computations as methods.
public struct _prext_LazySequence<Base_ : SequenceType> : _SequenceWrapperType {
var _base: Base_
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<S : SequenceType>(s: S) -> _prext_LazySequence<S> {
return _prext_LazySequence(_base: s)
}
public extension SequenceType
where Self.Generator == Self, Self : GeneratorType {
public func generate() -> Self {
return self
}
}
//===--- LazyCollection.swift ---------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
public protocol _prext_LazyCollectionType : CollectionType, _prext_LazySequenceType {
/// A CollectionType that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazyCollection` layer.
typealias Elements: CollectionType = Self
}
extension _prext_LazyCollectionType where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazyCollectionType where Self : _CollectionWrapperType {
public var elements: Base { return _base }
}
/// A collection that forwards its implementation to an underlying
/// collection instance while exposing lazy computations as methods.
public struct _prext_LazyCollection<Base_ : CollectionType>
: /*_prext_LazyCollectionType,*/ _CollectionWrapperType {
typealias Base = Base_
typealias Index = Base.Index
/// Construct an instance with `base` as its underlying Collection
/// instance.
public init(_ base: Base_) {
self._base = base
}
public var _base: Base_
// FIXME: Why is this needed?
// public var elements: Base { return _base }
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<Base: CollectionType>(s: Base) -> _prext_LazyCollection<Base> {
return _prext_LazyCollection(s)
}
//===--- New stuff --------------------------------------------------------===//
/// The `GeneratorType` used by `_prext_MapSequence` and `_prext_MapCollection`.
/// Produces each element by passing the output of the `Base`
/// `GeneratorType` through a transform function returning `T`.
public struct _prext_MapGenerator<
Base: GeneratorType, T
> : GeneratorType, SequenceType {
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
let x = _base.next()
if x != nil {
return _transform(x!)
}
return nil
}
var _base: Base
var _transform: (Base.Element)->T
}
//===--- Sequences --------------------------------------------------------===//
/// A `SequenceType` whose elements consist of those in a `Base`
/// `SequenceType` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapSequence<Base : SequenceType, T>
: _prext_LazySequenceType, _SequenceWrapperType {
typealias Elements = _prext_MapSequence
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> _prext_MapGenerator<Base.Generator,T> {
return _prext_MapGenerator(
_base: _base.generate(), _transform: _transform)
}
var _base: Base
var _transform: (Base.Generator.Element)->T
}
//===--- Collections ------------------------------------------------------===//
/// A `CollectionType` whose elements consist of those in a `Base`
/// `CollectionType` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapCollection<Base : CollectionType, T>
: _prext_LazyCollectionType, _CollectionWrapperType {
public var startIndex: Base.Index { return _base.startIndex }
public var endIndex: Base.Index { return _base.endIndex }
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> T {
return _transform(_base[position])
}
/// Returns a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> _prext_MapGenerator<Base.Generator, T> {
return _prext_MapGenerator(_base: _base.generate(), _transform: _transform)
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
var _base: Base
var _transform: (Base.Generator.Element)->T
}
//===--- Support for lazy(s) ----------------------------------------------===//
extension _prext_LazySequenceType {
/// Return a `_prext_MapSequence` over this `Sequence`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_MapSequence<Self.Elements, U> {
return _prext_MapSequence(_base: self.elements, _transform: transform)
}
}
extension _prext_LazyCollectionType {
/// Return a `_prext_MapCollection` over this `Collection`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_MapCollection<Self.Elements, U> {
return _prext_MapCollection(_base: self.elements, _transform: transform)
}
}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
//===--- New stuff --------------------------------------------------------===//
internal protocol __prext_ReverseCollectionType : _prext_LazyCollectionType {
typealias Base : CollectionType
var _base : Base {get}
}
/// A wrapper for a `BidirectionalIndexType` that reverses its
/// direction of traversal.
public struct _prext_ReverseIndex<I : BidirectionalIndexType> : BidirectionalIndexType {
var _base: I
init(_ _base: I) { self._base = _base }
/// Returns the next consecutive value after `self`.
///
/// - Requires: The next value is representable.
public func successor() -> _prext_ReverseIndex {
return _prext_ReverseIndex(_base.predecessor())
}
/// Returns the previous consecutive value before `self`.
///
/// - Requires: The previous value is representable.
public func predecessor() -> _prext_ReverseIndex {
return _prext_ReverseIndex(_base.successor())
}
/// A type that can represent the number of steps between pairs of
/// `_prext_ReverseIndex` values where one value is reachable from the other.
typealias Distance = I.Distance
}
/// A wrapper for a `${IndexProtocol}` that reverses its
/// direction of traversal.
public struct _prext_ReverseRandomAccessIndex<I : RandomAccessIndexType> : RandomAccessIndexType {
var _base: I
init(_ _base: I) { self._base = _base }
/// Returns the next consecutive value after `self`.
///
/// - Requires: The next value is representable.
public func successor() -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.predecessor())
}
/// Returns the previous consecutive value before `self`.
///
/// - Requires: The previous value is representable.
public func predecessor() -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.successor())
}
/// A type that can represent the number of steps between pairs of
/// `_prext_ReverseRandomAccessIndex` values where one value is reachable from the other.
typealias Distance = I.Distance
/// Return the minimum number of applications of `successor` or
/// `predecessor` required to reach `other` from `self`.
///
/// - Complexity: O(1).
public func distanceTo(other: _prext_ReverseRandomAccessIndex) -> Distance {
return other._base.distanceTo(_base)
}
/// Return `self` offset by `n` steps.
///
/// - Returns: If `n > 0`, the result of applying `successor` to
/// `self` `n` times. If `n < 0`, the result of applying
/// `predecessor` to `self` `-n` times. Otherwise, `self`.
///
/// - Complexity: O(1).
public func advancedBy(amount: Distance) -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.advancedBy(-amount))
}
}
public func == <I> (lhs: _prext_ReverseIndex<I>, rhs: _prext_ReverseIndex<I>) -> Bool {
return lhs._base == rhs._base
}
public func == <I> (lhs: _prext_ReverseRandomAccessIndex<I>, rhs: _prext_ReverseRandomAccessIndex<I>) -> Bool {
return lhs._base == rhs._base
}
extension CollectionType
where Self : __prext_ReverseCollectionType, Self.Base.Index : BidirectionalIndexType {
public var startIndex : _prext_ReverseIndex<Base.Index> {
return _prext_ReverseIndex<Base.Index>(_base.endIndex)
}
public var endIndex : _prext_ReverseIndex<Base.Index> {
return _prext_ReverseIndex<Base.Index>(_base.startIndex)
}
public subscript(position: _prext_ReverseIndex<Base.Index>) -> Base.Generator.Element {
return _base[position._base.predecessor()]
}
}
extension CollectionType
where Self : __prext_ReverseCollectionType, Self.Base.Index : RandomAccessIndexType {
public var startIndex : _prext_ReverseRandomAccessIndex<Base.Index> {
return _prext_ReverseRandomAccessIndex<Base.Index>(_base.endIndex)
}
public var endIndex : _prext_ReverseRandomAccessIndex<Base.Index> {
return _prext_ReverseRandomAccessIndex<Base.Index>(_base.startIndex)
}
public subscript(position: _prext_ReverseRandomAccessIndex<Base.Index>) -> Base.Generator.Element {
return _base[position._base.predecessor()]
}
}
/// The lazy `CollectionType` returned by `reverse(c)` where `c` is a
/// `CollectionType` with an `Index` conforming to `${IndexProtocol}`.
public struct _prext_ReverseCollection<Base : CollectionType>
: CollectionType, __prext_ReverseCollectionType {
public init(_ _base: Base) {
self._base = _base
}
internal var _base: Base
}
|
915f9be1030fc8d7c66c2430484a0e2c
| 32.748858 | 111 | 0.674537 | false | false | false | false |
PJayRushton/TeacherTools
|
refs/heads/master
|
TeacherTools/IAPHelper.swift
|
mit
|
1
|
//
// IAPHelper.swift
// TeacherTools
//
// Created by Parker Rushton on 12/2/16.
// Copyright © 2016 AppsByPJ. All rights reserved.
//
import StoreKit
public typealias ProductIdentifier = String
public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> ()
open class IAPHelper: NSObject {
fileprivate let productIdentifiers: Set<ProductIdentifier>
fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>()
fileprivate var productsRequest: SKProductsRequest?
fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler?
var core = App.core
public init(productIds: Set<ProductIdentifier>) {
productIdentifiers = productIds
for productIdentifier in productIds {
if let user = core.state.currentUser, user.purchases.map( { $0.productId }).contains(productIdentifier) {
purchasedProductIdentifiers.insert(productIdentifier)
print("Previously purchased: \(productIdentifier)")
} else {
print("Not purchased: \(productIdentifier)")
}
}
super.init()
SKPaymentQueue.default().add(self)
}
}
// MARK: - StoreKit API
extension IAPHelper {
public func requestProducts(completionHandler: @escaping ProductsRequestCompletionHandler) {
productsRequest?.cancel()
productsRequestCompletionHandler = completionHandler
productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
productsRequest?.delegate = self
productsRequest?.start()
}
public func buyProduct(_ product: SKProduct) {
print("Buying \(product.productIdentifier)...")
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool {
return purchasedProductIdentifiers.contains(productIdentifier)
}
public class func canMakePayments() -> Bool {
return SKPaymentQueue.canMakePayments()
}
public func restorePurchases() {
SKPaymentQueue.default().restoreCompletedTransactions()
}
}
// MARK: - SKProductsRequestDelegate
extension IAPHelper: SKProductsRequestDelegate {
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let products = response.products
productsRequestCompletionHandler?(true, products)
clearRequestAndHandler()
for p in products {
print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)")
}
}
public func request(_ request: SKRequest, didFailWithError error: Error) {
AnalyticsHelper.logEvent(.productRequestFailure)
productsRequestCompletionHandler?(false, nil)
clearRequestAndHandler()
}
private func clearRequestAndHandler() {
productsRequest = nil
productsRequestCompletionHandler = nil
}
}
// MARK: - SKPaymentTransactionObserver
extension IAPHelper: SKPaymentTransactionObserver {
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .purchased:
complete(transaction: transaction)
case .restored:
restore(transaction: transaction)
case .failed:
fail(transaction: transaction)
case .deferred, .purchasing:
break
}
}
}
public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
print("Finished restoring completed transactions\(queue)")
}
public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
AnalyticsHelper.logEvent(.productRestoreFailiure)
print("Restore **FAILED**\n\(queue)\n\(error)")
}
private func complete(transaction: SKPaymentTransaction) {
deliverPurchaseNotification(for: transaction.payment.productIdentifier)
SKPaymentQueue.default().finishTransaction(transaction)
}
private func restore(transaction: SKPaymentTransaction) {
AnalyticsHelper.logEvent(.proRestored)
let productIdentifier = transaction.original?.payment.productIdentifier ?? transaction.payment.productIdentifier
deliverPurchaseNotification(for: productIdentifier)
SKPaymentQueue.default().finishTransaction(transaction)
}
private func fail(transaction: SKPaymentTransaction) {
AnalyticsHelper.logEvent(.productPurchaseFailure)
if let transactionError = transaction.error as NSError? {
if transactionError.code != SKError.paymentCancelled.rawValue {
print("Transaction Error: \(String(describing: transaction.error?.localizedDescription))")
}
}
SKPaymentQueue.default().finishTransaction(transaction)
}
private func deliverPurchaseNotification(for identifier: String) {
purchasedProductIdentifiers.insert(identifier)
core.fire(command: MarkUserPro())
}
}
|
0981950e809c2e16be6013abb839f52d
| 34.176471 | 120 | 0.683389 | false | false | false | false |
lucascarletti/Pruuu
|
refs/heads/master
|
Pruuu/API/PRAPI.swift
|
mit
|
1
|
//
// PRAPI.swift
// Pruuu
//
// Created by Lucas Teixeira Carletti on 16/10/2017.
// Copyright © 2017 PR. All rights reserved.
//
import Alamofire
class API {
static let `default` = API()
static let MAIN_URL = ""
static internal func print(response: DataResponse<String>) {
Swift.print("===================== Response ===================")
if let absoluteURL = response.response?.url?.absoluteString {
Swift.print("URL: \(absoluteURL)")
}
if let method = response.request?.httpMethod {
Swift.print("Method: \(method)")
}
if let statusCode = response.response?.statusCode {
Swift.print("StatusCode: \(statusCode)")
}
if let httpHeader = response.request?.allHTTPHeaderFields {
Swift.print("HTTP Header: \(httpHeader)")
}
if let dataBody = response.request?.httpBody, let body = String(data: dataBody, encoding: .utf8) {
Swift.print("HTTP Body: \(body)")
}
if let value = response.result.value {
Swift.print("Response String: \(value)")
}
Swift.print("==================================================")
}
func get(endPoint: String, params: [String: Any]? = nil, headers: [String: String]? = nil) -> DataRequest {
let request = Alamofire.request(API.MAIN_URL + endPoint, parameters: params, headers: headers)
#if DEBUG
request.responseString {
response in
API.print(response: response)
}
#endif
return request
}
func post(endPoint: String, params: [String: Any]? = nil, headers: [String: String]? = nil) -> DataRequest {
let request = Alamofire.request(API.MAIN_URL + endPoint, method: .post, parameters: params, headers: headers)
#if DEBUG
request.responseString {
response in
API.print(response: response)
}
#endif
return request
}
private var defaultHeader : [String: String]? {
guard let token = PRUser.shared.token else {
return nil
}
return ["Authorization":"Bearer " + token]
}
private var defaultParams : [String: Any] {
return ["":""]
}
}
|
7ad21f80718ffbe644ecbe232fe4e971
| 30.824324 | 117 | 0.537155 | false | false | false | false |
hibu/apptentive-ios
|
refs/heads/master
|
Demo/iOSDemo/EventsViewController.swift
|
bsd-3-clause
|
1
|
//
// EventsViewController.swift
// iOS Demo
//
// Created by Frank Schmitt on 4/27/16.
// Copyright © 2016 Apptentive, Inc. All rights reserved.
//
import UIKit
private let EventsKey = "events"
class EventsViewController: UITableViewController {
private var events = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem()
updateEventList()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(EventsViewController.updateEventList), name: NSUserDefaultsDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Event", forIndexPath: indexPath)
cell.textLabel?.text = events[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
events.removeAtIndex(indexPath.row)
saveEventList()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
// MARK: Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if self.editing {
if let navigationController = self.storyboard?.instantiateViewControllerWithIdentifier("StringNavigation") as? UINavigationController, let eventViewController = navigationController.viewControllers.first as? StringViewController {
eventViewController.string = self.events[indexPath.row]
eventViewController.title = "Edit Event"
self.presentViewController(navigationController, animated: true, completion: nil)
}
} else {
Apptentive.sharedConnection().engage(events[indexPath.row], fromViewController: self)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let navigationController = segue.destinationViewController as? UINavigationController, let eventViewController = navigationController.viewControllers.first {
eventViewController.title = "New Event"
}
}
@IBAction func returnToEventList(sender: UIStoryboardSegue) {
if let name = (sender.sourceViewController as? StringViewController)?.string {
if let selectedIndex = self.tableView.indexPathForSelectedRow?.row {
events[selectedIndex] = name
} else {
events.append(name)
}
events.sortInPlace()
saveEventList()
tableView.reloadSections(NSIndexSet(index:0), withRowAnimation: .Automatic)
}
}
// MARK: - Private
@objc private func updateEventList() {
if let events = NSUserDefaults.standardUserDefaults().arrayForKey(EventsKey) as? [String] {
self.events = events
}
}
private func saveEventList() {
NSUserDefaults.standardUserDefaults().setObject(events, forKey: EventsKey)
}
}
|
fcd867392ffd822bc7aaa51c0ceb31c3
| 31.419048 | 233 | 0.749412 | false | false | false | false |
squall09s/VegOresto
|
refs/heads/master
|
VegoResto/Comment/CreateCommentStep2UserViewController.swift
|
gpl-3.0
|
1
|
//
// CreateCommentStep2UserViewController.swift
// VegoResto
//
// Created by Nicolas on 24/10/2017.
// Copyright © 2017 Nicolas Laurent. All rights reserved.
//
import UIKit
import SkyFloatingLabelTextField
protocol CreateCommentStep2UserViewControllerProtocol {
func getCurrentEmail() -> String
func getCurrentName() -> String
func get_tfName() -> UITextField?
func get_tfMail() -> UITextField?
}
class CreateCommentStep2UserViewController: UIViewController, CreateCommentStep2UserViewControllerProtocol, UITextFieldDelegate {
@IBOutlet weak var tf_name: SkyFloatingLabelTextFieldWithIcon?
@IBOutlet weak var tf_mail: SkyFloatingLabelTextFieldWithIcon?
func get_tfName() -> UITextField? {
return self.tf_name
}
func get_tfMail() -> UITextField? {
return self.tf_mail
}
func getCurrentEmail() -> String {
return self.tf_mail?.text ?? ""
}
func getCurrentName() -> String {
return self.tf_name?.text ?? ""
}
override func viewDidLoad() {
super.viewDidLoad()
if let _user_mail = UserDefaults.standard.string(forKey: "USER_SAVE_MAIL") as? String {
self.tf_mail?.text = _user_mail
}
if let _user_name = UserDefaults.standard.string(forKey: "USER_SAVE_NAME") as? String {
self.tf_name?.text = _user_name
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.tf_name {
textField.resignFirstResponder()
self.tf_mail?.becomeFirstResponder()
} else if textField == self.tf_mail {
textField.resignFirstResponder()
if let parent = self.parent as? AddCommentContainerViewController {
parent.nextAction(sender: nil)
}
}
return true
}
}
|
a11a97cc2e7ceb09e493a96a98c1b3f5
| 23.52 | 129 | 0.647227 | false | false | false | false |
ahoppen/swift
|
refs/heads/main
|
test/SILOptimizer/inline_self.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -O -emit-sil -primary-file %s | %FileCheck %s
//
// This is a .swift test because the SIL parser does not support Self.
// Do not inline C.factory into main. Doing so would lose the ability
// to materialize local Self metadata.
class C {
required init() {}
}
class SubC : C {}
var g: AnyObject = SubC()
@inline(never)
func gen<R>() -> R {
return g as! R
}
extension C {
@inline(__always)
class func factory(_ z: Int) -> Self {
return gen()
}
}
// Call the function so it can be inlined.
var x = C()
var x2 = C.factory(1)
@inline(never)
func callIt(fn: () -> ()) {
fn()
}
protocol Use {
func use<T>(_ t: T)
}
var user: Use? = nil
class BaseZ {
final func baseCapturesSelf() -> Self {
let fn = { [weak self] in _ = self }
callIt(fn: fn)
return self
}
}
// Do not inline C.capturesSelf() into main either. Doing so would lose the ability
// to materialize local Self metadata.
class Z : BaseZ {
@inline(__always)
final func capturesSelf() -> Self {
let fn = { [weak self] in _ = self }
callIt(fn: fn)
user?.use(self)
return self
}
// Inline captureSelf into callCaptureSelf,
// because their respective Self types refer to the same type.
final func callCapturesSelf() -> Self {
return capturesSelf()
}
final func callBaseCapturesSelf() -> Self {
return baseCapturesSelf()
}
}
_ = Z().capturesSelf()
// CHECK-LABEL: sil {{.*}}@main : $@convention(c)
// CHECK: function_ref static inline_self.C.factory(Swift.Int) -> Self
// CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1CC7factory{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Int, @thick C.Type) -> @owned C
// CHECK: apply [[F]](%{{.+}}, %{{.+}}) : $@convention(method) (Int, @thick C.Type) -> @owned C
// CHECK: [[Z:%.*]] = alloc_ref $Z
// CHECK: function_ref inline_self.Z.capturesSelf() -> Self
// CHECK: [[F:%[0-9]+]] = function_ref @$s11inline_self1ZC12capturesSelfACXDyF : $@convention(method) (@guaranteed Z) -> @owned Z
// CHECK: apply [[F]]([[Z]]) : $@convention(method) (@guaranteed Z) -> @owned
// CHECK: return
// CHECK-LABEL: sil hidden @$s11inline_self1ZC16callCapturesSelfACXDyF : $@convention(method)
// CHECK-NOT: function_ref @$s11inline_self1ZC12capturesSelfACXDyF :
// CHECK: }
// CHECK-LABEL: sil hidden @$s11inline_self1ZC20callBaseCapturesSelfACXDyF
// CHECK-NOT: function_ref @$s11inline_self5BaseZC16baseCapturesSelfACXDyF :
// CHECK: }
|
c4798f652a7d34a90a4ae0d3f96a0ec0
| 26.10989 | 141 | 0.64694 | false | false | false | false |
peferron/algo
|
refs/heads/master
|
EPI/Strings/Test palindromicity/swift/main.swift
|
mit
|
1
|
// swiftlint:disable variable_name
func isAlphanumeric(_ character: Character) -> Bool {
return "0" <= character && character <= "9" ||
"a" <= character && character <= "z" ||
"A" <= character && character <= "Z"
}
public func isPalindromeSimple(_ string: String) -> Bool {
let cleanedCharacters = string.lowercased().filter(isAlphanumeric)
return cleanedCharacters == String(cleanedCharacters.reversed())
}
public func isPalindromeSmart(_ string: String) -> Bool {
guard string != "" else {
return true
}
// Iterate from both ends of the string towards the center. Non-alphanumeric characters are
// skipped, and alphanumeric characters are compared case-insensitively.
var start = string.startIndex
var end = string.index(before: string.endIndex)
while true {
while start < end && !isAlphanumeric(string[start]) {
start = string.index(after: start)
}
while start < end && !isAlphanumeric(string[end]) {
end = string.index(before: end)
}
guard start < end else {
return true
}
guard String(string[start]).lowercased() == String(string[end]).lowercased() else {
return false
}
start = string.index(after: start)
end = string.index(before: end)
}
}
|
f1ec3a5a84d4720ba5ed3783e1ff9af4
| 29.75 | 95 | 0.614191 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Services/Stories/StoryEditor.swift
|
gpl-2.0
|
1
|
import Foundation
import Kanvas
/// An story editor which displays the Kanvas camera + editing screens.
class StoryEditor: CameraController {
var post: AbstractPost = AbstractPost()
private static let directoryName = "Stories"
/// A directory to temporarily hold imported media.
/// - Throws: Any errors resulting from URL or directory creation.
/// - Returns: A URL with the media cache directory.
static func mediaCacheDirectory() throws -> URL {
let storiesURL = try MediaFileManager.cache.directoryURL().appendingPathComponent(directoryName, isDirectory: true)
try FileManager.default.createDirectory(at: storiesURL, withIntermediateDirectories: true, attributes: nil)
return storiesURL
}
/// A directory to temporarily hold saved archives.
/// - Throws: Any errors resulting from URL or directory creation.
/// - Returns: A URL with the save directory.
static func saveDirectory() throws -> URL {
let saveDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(directoryName, isDirectory: true)
try FileManager.default.createDirectory(at: saveDirectory, withIntermediateDirectories: true, attributes: nil)
return saveDirectory
}
var onClose: ((Bool, Bool) -> Void)? = nil
var editorSession: PostEditorAnalyticsSession
let navigationBarManager: PostEditorNavigationBarManager? = nil
fileprivate(set) lazy var debouncer: Debouncer = {
return Debouncer(delay: PostEditorDebouncerConstants.autoSavingDelay, callback: debouncerCallback)
}()
private(set) lazy var postEditorStateContext: PostEditorStateContext = {
return PostEditorStateContext(post: post, delegate: self)
}()
var verificationPromptHelper: VerificationPromptHelper? = nil
var analyticsEditorSource: String {
return "stories"
}
private var cameraHandler: CameraHandler?
private var poster: StoryPoster?
private lazy var storyLoader: StoryMediaLoader = {
return StoryMediaLoader()
}()
private static let useMetal = false
static var cameraSettings: CameraSettings {
let settings = CameraSettings()
settings.features.ghostFrame = true
settings.features.metalPreview = useMetal
settings.features.metalFilters = useMetal
settings.features.openGLPreview = !useMetal
settings.features.openGLCapture = !useMetal
settings.features.cameraFilters = false
settings.features.experimentalCameraFilters = true
settings.features.editor = true
settings.features.editorGIFMaker = false
settings.features.editorFilters = false
settings.features.editorText = true
settings.features.editorMedia = true
settings.features.editorDrawing = false
settings.features.editorMedia = false
settings.features.mediaPicking = true
settings.features.editorPostOptions = false
settings.features.newCameraModes = true
settings.features.gifs = false
settings.features.multipleExports = true
settings.features.editorConfirmAtTop = true
settings.features.muteButton = true
settings.crossIconInEditor = true
settings.enabledModes = [.normal]
settings.defaultMode = .normal
settings.features.scaleMediaToFill = true
settings.features.resizesFonts = false
settings.animateEditorControls = false
settings.exportStopMotionPhotoAsVideo = false
settings.fontSelectorUsesFont = true
settings.aspectRatio = 9/16
return settings
}
enum EditorCreationError: Error {
case unsupportedDevice
}
typealias UpdateResult = Result<String, PostCoordinator.SavingError>
typealias UploadResult = Result<Void, PostCoordinator.SavingError>
static func editor(blog: Blog,
context: NSManagedObjectContext,
updated: @escaping (UpdateResult) -> Void) throws -> StoryEditor {
let post = PostService(managedObjectContext: context).createDraftPost(for: blog)
return try editor(post: post, mediaFiles: nil, publishOnCompletion: true, updated: updated)
}
static func editor(post: AbstractPost,
mediaFiles: [MediaFile]?,
publishOnCompletion: Bool = false,
updated: @escaping (UpdateResult) -> Void) throws -> StoryEditor {
guard !UIDevice.isPad() else {
throw EditorCreationError.unsupportedDevice
}
let controller = StoryEditor(post: post,
onClose: nil,
settings: cameraSettings,
stickerProvider: nil,
analyticsProvider: nil,
quickBlogSelectorCoordinator: nil,
tagCollection: nil,
mediaFiles: mediaFiles,
publishOnCompletion: publishOnCompletion,
updated: updated)
controller.modalPresentationStyle = .fullScreen
controller.modalTransitionStyle = .crossDissolve
return controller
}
init(post: AbstractPost,
onClose: ((Bool, Bool) -> Void)?,
settings: CameraSettings,
stickerProvider: StickerProvider?,
analyticsProvider: KanvasAnalyticsProvider?,
quickBlogSelectorCoordinator: KanvasQuickBlogSelectorCoordinating?,
tagCollection: UIView?,
mediaFiles: [MediaFile]?,
publishOnCompletion: Bool,
updated: @escaping (UpdateResult) -> Void) {
self.post = post
self.onClose = onClose
self.editorSession = PostEditorAnalyticsSession(editor: .stories, post: post)
Kanvas.KanvasColors.shared = KanvasCustomUI.shared.cameraColors()
Kanvas.KanvasFonts.shared = KanvasCustomUI.shared.cameraFonts()
Kanvas.KanvasImages.shared = KanvasCustomUI.shared.cameraImages()
Kanvas.KanvasStrings.shared = KanvasStrings(
cameraPermissionsTitleLabel: NSLocalizedString("Post to WordPress", comment: "Title of camera permissions screen"),
cameraPermissionsDescriptionLabel: NSLocalizedString("Allow access so you can start taking photos and videos.", comment: "Message on camera permissions screen to explain why the app needs camera and microphone permissions")
)
let saveDirectory: URL?
do {
saveDirectory = try Self.saveDirectory()
} catch let error {
assertionFailure("Should be able to create a save directory in Documents \(error)")
saveDirectory = nil
}
super.init(settings: settings,
mediaPicker: WPMediaPickerForKanvas.self,
stickerProvider: nil,
analyticsProvider: KanvasAnalyticsHandler(),
quickBlogSelectorCoordinator: nil,
tagCollection: nil,
saveDirectory: saveDirectory)
cameraHandler = CameraHandler(created: { [weak self] media in
self?.poster = StoryPoster(context: post.blog.managedObjectContext ?? ContextManager.shared.mainContext, mediaFiles: mediaFiles)
let postMedia: [StoryPoster.MediaItem] = media.compactMap { result in
switch result {
case .success(let item):
guard let item = item else { return nil }
return StoryPoster.MediaItem(url: item.output, size: item.size, archive: item.archive, original: item.unmodified)
case .failure:
return nil
}
}
guard let self = self else { return }
let uploads: (String, [Media])? = try? self.poster?.add(mediaItems: postMedia, post: post)
let content = uploads?.0 ?? ""
updated(.success(content))
if publishOnCompletion {
// Replace the contents if we are publishing a new post
post.content = content
do {
try post.managedObjectContext?.save()
} catch let error {
assertionFailure("Failed to save post during story update: \(error)")
}
self.publishPost(action: .publish, dismissWhenDone: true, analyticsStat:
.editorPublishedPost)
} else {
self.dismiss(animated: true, completion: nil)
}
})
self.delegate = cameraHandler
}
func present(on: UIViewController, with files: [MediaFile]) {
storyLoader.download(files: files, for: post) { [weak self] output in
guard let self = self else { return }
DispatchQueue.main.async {
self.show(media: output)
on.present(self, animated: true, completion: {})
}
}
}
func trackOpen() {
editorSession.start()
}
}
extension StoryEditor: PublishingEditor {
var prepublishingIdentifiers: [PrepublishingIdentifier] {
return [.title, .visibility, .schedule, .tags, .categories]
}
var prepublishingSourceView: UIView? {
return nil
}
var alertBarButtonItem: UIBarButtonItem? {
return nil
}
var isUploadingMedia: Bool {
return false
}
var postTitle: String {
get {
return post.postTitle ?? ""
}
set {
post.postTitle = newValue
}
}
func getHTML() -> String {
return post.content ?? ""
}
func cancelUploadOfAllMedia(for post: AbstractPost) {
}
func publishingDismissed() {
hideLoading()
}
var wordCount: UInt {
return post.content?.wordCount() ?? 0
}
}
extension StoryEditor: PostEditorStateContextDelegate {
func context(_ context: PostEditorStateContext, didChangeAction: PostEditorAction) {
}
func context(_ context: PostEditorStateContext, didChangeActionAllowed: Bool) {
}
}
|
83ebd8720ad4e4890659af204a643629
| 37.007299 | 235 | 0.623968 | false | false | false | false |
stack-this/hunter-price
|
refs/heads/master
|
ios/Store.swift
|
apache-2.0
|
1
|
//
// Store.swift
// HunterPrice
//
// Created by Gessy on 9/10/16.
// Copyright © 2016 GetsemaniAvila. All rights reserved.
//
import Foundation
class StoreData{
class Store{
let name : String
let latitude : String
let longitude : String
let address : String
let phone : String
init(name:String,latitude:String,longitude:String,address:String,phone:String) {
self.name = name
self.latitude = latitude
self.longitude = longitude
self.address = address
self.phone = phone
}
}
}
|
b20956705d9ae4b04a45b364c269e1d6
| 20.862069 | 88 | 0.563091 | false | false | false | false |
mcxiaoke/learning-ios
|
refs/heads/master
|
cocoa_programming_for_osx/33_CoreAnimation/Scattered/Scattered/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// Scattered
//
// Created by mcxiaoke on 16/5/24.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
var textLayer: CATextLayer!
var text: String? {
didSet {
let font = NSFont.systemFontOfSize(textLayer.fontSize)
let attributes = [NSFontAttributeName: font]
var size = text?.sizeWithAttributes(attributes) ?? CGSize.zero
size.width = ceil(size.width)
size.height = ceil(size.height)
textLayer.bounds = CGRect(origin: CGPoint.zero, size: size)
textLayer.superlayer?.bounds = CGRect(x: 0, y: 0, width: size.width + 16, height: size.height + 20)
textLayer.string = text
}
}
func thumbImageFromImage(image: NSImage) -> NSImage {
let targetHeight: CGFloat = 200.0
let imageSize = image.size
let smallerSize = NSSize(width: targetHeight * imageSize.width / imageSize.height, height: targetHeight)
let smallerImage = NSImage(size: smallerSize, flipped: false) { (rect) -> Bool in
image.drawInRect(rect)
return true
}
return smallerImage
}
func presentImage(image: NSImage, fileName:String) {
let superLayerBounds = view.layer!.bounds
let center = CGPoint(x: superLayerBounds.midX, y: superLayerBounds.midY)
let imageBounds = CGRect(origin: CGPoint.zero, size: image.size)
let randomPoint = CGPoint(x: CGFloat(arc4random_uniform(UInt32(superLayerBounds.maxX))),
y: CGFloat(arc4random_uniform(UInt32(superLayerBounds.maxY))))
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let positionAnimation = CABasicAnimation()
positionAnimation.fromValue = NSValue(point: center)
positionAnimation.duration = 2
positionAnimation.timingFunction = timingFunction
let boundsAnimation = CABasicAnimation()
boundsAnimation.fromValue = NSValue(rect: CGRect.zero)
boundsAnimation.duration = 2
boundsAnimation.timingFunction = timingFunction
let layer = CALayer()
layer.contents = image
layer.actions = [
"position" : positionAnimation,
"bounds" : boundsAnimation
]
let nameLayer = CATextLayer()
let font = NSFont.systemFontOfSize(12)
let attributes = [NSFontAttributeName: font]
var size = fileName.sizeWithAttributes(attributes) ?? CGSize.zero
size.width = ceil(size.width)
size.height = ceil(size.height)
nameLayer.fontSize = 12
nameLayer.position = randomPoint
nameLayer.zPosition = 0
nameLayer.bounds = CGRect(origin: CGPoint.zero, size: size)
nameLayer.foregroundColor = NSColor.redColor().CGColor
nameLayer.string = fileName
layer.addSublayer(nameLayer)
CATransaction.begin()
view.layer!.addSublayer(layer)
layer.position = randomPoint
layer.bounds = imageBounds
CATransaction.commit()
}
func addImagesFromFolderURL(folderURL: NSURL) {
let t0 = NSDate.timeIntervalSinceReferenceDate()
let fileManager = NSFileManager()
let directoryEnumerator = fileManager.enumeratorAtURL(folderURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil)!
var allowedFiles = 10
while let url = directoryEnumerator.nextObject() as? NSURL {
var isDirectoryValue: AnyObject?
_ = try? url.getResourceValue(&isDirectoryValue, forKey: NSURLIsDirectoryKey)
if let isDirectory = isDirectoryValue as? NSNumber
where isDirectory.boolValue == false {
let image = NSImage(contentsOfURL:url)
if let image = image {
allowedFiles -= 1
if allowedFiles < 0 {
break
}
let thumbImage = thumbImageFromImage(image)
var fileNameValue: AnyObject?
_ = try? url.getResourceValue(&fileNameValue, forKey: NSURLNameKey)
if let fileName = fileNameValue as? String {
print("fileName: \(fileName)")
presentImage(thumbImage, fileName: fileName)
let t1 = NSDate.timeIntervalSinceReferenceDate()
let interval = t1 - t0
text = String(format: "%0.1fs", interval)
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.layer = CALayer()
view.wantsLayer = true
let tc = CALayer()
tc.anchorPoint = CGPoint.zero
tc.position = CGPointMake(10, 10)
tc.zPosition = 100
tc.backgroundColor = NSColor.blackColor().CGColor
tc.borderColor = NSColor.whiteColor().CGColor
tc.borderWidth = 2
tc.cornerRadius = 15
tc.shadowOpacity = 0.5
view.layer!.addSublayer(tc)
let tl = CATextLayer()
tl.anchorPoint = CGPoint.zero
tl.position = CGPointMake(10, 6)
tl.zPosition = 100
tl.fontSize = 24
tl.foregroundColor = NSColor.whiteColor().CGColor
self.textLayer = tl
tc.addSublayer(tl)
text = "Loading..."
let url = NSURL(fileURLWithPath: "/Library/Desktop Pictures")
addImagesFromFolderURL(url)
}
}
|
900bc09ea91868ff82fa7b3cbea364c4
| 32.513158 | 178 | 0.675893 | false | false | false | false |
natecook1000/swift
|
refs/heads/master
|
stdlib/public/core/Sort.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// sorted()/sort()
//===----------------------------------------------------------------------===//
extension Sequence where Element: Comparable {
/// Returns the elements of the sequence, sorted.
///
/// You can sort any sequence of elements that conform to the `Comparable`
/// protocol by calling this method. Elements are sorted in ascending order.
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements that compare equal.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let sortedStudents = students.sorted()
/// print(sortedStudents)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your sequence in descending order, pass the
/// greater-than operator (`>`) to the `sorted(by:)` method.
///
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Returns: A sorted array of the sequence's elements.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.
@inlinable
public func sorted() -> [Element] {
return sorted(by: <)
}
}
extension Sequence {
/// Returns the elements of the sequence, sorted using the given predicate as
/// the comparison between elements.
///
/// When you want to sort a sequence of elements that don't conform to the
/// `Comparable` protocol, pass a predicate to this method that returns
/// `true` when the first element passed should be ordered before the
/// second. The elements of the resulting array are ordered according to the
/// given predicate.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements for which `areInIncreasingOrder` does not
/// establish an order.
///
/// In the following example, the predicate provides an ordering for an array
/// of a custom `HTTPResponse` type. The predicate orders errors before
/// successes and sorts the error responses by their error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// let sortedResponses = responses.sorted {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(sortedResponses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// You also use this method to sort elements that conform to the
/// `Comparable` protocol in descending order. To sort your sequence in
/// descending order, pass the greater-than operator (`>`) as the
/// `areInIncreasingOrder` parameter.
///
/// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// let descendingStudents = students.sorted(by: >)
/// print(descendingStudents)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// Calling the related `sorted()` method is equivalent to calling this
/// method and passing the less-than operator (`<`) as the predicate.
///
/// print(students.sorted())
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
/// print(students.sorted(by: <))
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: A sorted array of the sequence's elements.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.
@inlinable
public func sorted(
by areInIncreasingOrder:
(Element, Element) throws -> Bool
) rethrows -> [Element] {
var result = ContiguousArray(self)
try result.sort(by: areInIncreasingOrder)
return Array(result)
}
}
extension MutableCollection
where Self: RandomAccessCollection, Element: Comparable {
/// Sorts the collection in place.
///
/// You can sort any mutable collection of elements that conform to the
/// `Comparable` protocol by calling this method. Elements are sorted in
/// ascending order.
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements that compare equal.
///
/// Here's an example of sorting a list of students' names. Strings in Swift
/// conform to the `Comparable` protocol, so the names are sorted in
/// ascending order according to the less-than operator (`<`).
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort()
/// print(students)
/// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
///
/// To sort the elements of your collection in descending order, pass the
/// greater-than operator (`>`) to the `sort(by:)` method.
///
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the collection.
@inlinable
public mutating func sort() {
sort(by: <)
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Sorts the collection in place, using the given predicate as the
/// comparison between elements.
///
/// When you want to sort a collection of elements that doesn't conform to
/// the `Comparable` protocol, pass a closure to this method that returns
/// `true` when the first element passed should be ordered before the
/// second.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
/// (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// The sorting algorithm is not stable. A nonstable sort may change the
/// relative order of elements for which `areInIncreasingOrder` does not
/// establish an order.
///
/// In the following example, the closure provides an ordering for an array
/// of a custom enumeration that describes an HTTP response. The predicate
/// orders errors before successes and sorts the error responses by their
/// error code.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
/// responses.sort {
/// switch ($0, $1) {
/// // Order errors by code
/// case let (.error(aCode), .error(bCode)):
/// return aCode < bCode
///
/// // All successes are equivalent, so none is before any other
/// case (.ok, .ok): return false
///
/// // Order errors before successes
/// case (.error, .ok): return true
/// case (.ok, .error): return false
/// }
/// }
/// print(responses)
/// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
///
/// Alternatively, use this method to sort a collection of elements that do
/// conform to `Comparable` when you want the sort to be descending instead
/// of ascending. Pass the greater-than operator (`>`) operator as the
/// predicate.
///
/// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`. If `areInIncreasingOrder` throws an error during
/// the sort, the elements may be in a different order, but none will be
/// lost.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of the collection.
@inlinable
public mutating func sort(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let didSortUnsafeBuffer = try _withUnsafeMutableBufferPointerIfSupported {
buffer -> Void? in
try buffer.sort(by: areInIncreasingOrder)
}
if didSortUnsafeBuffer == nil {
try _introSort(within: startIndex..<endIndex, by: areInIncreasingOrder)
}
}
}
extension MutableCollection where Self: BidirectionalCollection {
@inlinable
internal mutating func _insertionSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
guard !range.isEmpty else { return }
let start = range.lowerBound
// Keep track of the end of the initial sequence of sorted elements. One
// element is trivially already-sorted, thus pre-increment Continue until
// the sorted elements cover the whole sequence
var sortedEnd = index(after: start)
while sortedEnd != range.upperBound {
// get the first unsorted element
// FIXME: by stashing the element, instead of using indexing and swapAt,
// this method won't work for collections of move-only types.
let x = self[sortedEnd]
// Look backwards for x's position in the sorted sequence,
// moving elements forward to make room.
var i = sortedEnd
repeat {
let j = index(before: i)
let predecessor = self[j]
// If closure throws, put the element at right place and rethrow.
do {
// if x doesn't belong before y, we've found its position
if try !areInIncreasingOrder(x, predecessor) {
break
}
} catch {
self[i] = x
throw error
}
// Move y forward
self[i] = predecessor
i = j
} while i != start
if i != sortedEnd {
// Plop x into position
self[i] = x
}
formIndex(after: &sortedEnd)
}
}
}
extension MutableCollection {
/// Sorts the elements at `elements[a]`, `elements[b]`, and `elements[c]`.
/// Stable.
///
/// The indices passed as `a`, `b`, and `c` do not need to be consecutive, but
/// must be in strict increasing order.
///
/// - Precondition: `a < b && b < c`
/// - Postcondition: `self[a] <= self[b] && self[b] <= self[c]`
@inlinable
public // @testable
mutating func _sort3(
_ a: Index, _ b: Index, _ c: Index,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// There are thirteen possible permutations for the original ordering of
// the elements at indices `a`, `b`, and `c`. The comments in the code below
// show the relative ordering of the three elements using a three-digit
// number as shorthand for the position and comparative relationship of
// each element. For example, "312" indicates that the element at `a` is the
// largest of the three, the element at `b` is the smallest, and the element
// at `c` is the median. This hypothetical input array has a 312 ordering for
// `a`, `b`, and `c`:
//
// [ 7, 4, 3, 9, 2, 0, 3, 7, 6, 5 ]
// ^ ^ ^
// a b c
//
// - If each of the three elements is distinct, they could be ordered as any
// of the permutations of 1, 2, and 3: 123, 132, 213, 231, 312, or 321.
// - If two elements are equivalent and one is distinct, they could be
// ordered as any permutation of 1, 1, and 2 or 1, 2, and 2: 112, 121, 211,
// 122, 212, or 221.
// - If all three elements are equivalent, they are already in order: 111.
switch try (areInIncreasingOrder(self[b], self[a]),
areInIncreasingOrder(self[c], self[b])) {
case (false, false):
// 0 swaps: 123, 112, 122, 111
break
case (true, true):
// 1 swap: 321
// swap(a, c): 312->123
swapAt(a, c)
case (true, false):
// 1 swap: 213, 212 --- 2 swaps: 312, 211
// swap(a, b): 213->123, 212->122, 312->132, 211->121
swapAt(a, b)
if try areInIncreasingOrder(self[c], self[b]) {
// 132 (started as 312), 121 (started as 211)
// swap(b, c): 132->123, 121->112
swapAt(b, c)
}
case (false, true):
// 1 swap: 132, 121 --- 2 swaps: 231, 221
// swap(b, c): 132->123, 121->112, 231->213, 221->212
swapAt(b, c)
if try areInIncreasingOrder(self[b], self[a]) {
// 213 (started as 231), 212 (started as 221)
// swap(a, b): 213->123, 212->122
swapAt(a, b)
}
}
}
}
extension MutableCollection where Self: RandomAccessCollection {
/// Reorders the collection and returns an index `p` such that every element
/// in `range.lowerBound..<p` is less than every element in
/// `p..<range.upperBound`.
///
/// - Precondition: The count of `range` must be >= 3 i.e.
/// `distance(from: range.lowerBound, to: range.upperBound) >= 3`
@inlinable
internal mutating func _partition(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Index {
var lo = range.lowerBound
var hi = index(before: range.upperBound)
// Sort the first, middle, and last elements, then use the middle value
// as the pivot for the partition.
let half = distance(from: lo, to: hi) / 2
let mid = index(lo, offsetBy: half)
try _sort3(lo, mid, hi, by: areInIncreasingOrder)
let pivot = self[mid]
// Loop invariants:
// * lo < hi
// * self[i] < pivot, for i in range.lowerBound..<lo
// * pivot <= self[i] for i in hi..<range.upperBound
Loop: while true {
FindLo: do {
formIndex(after: &lo)
while lo != hi {
if try !areInIncreasingOrder(self[lo], pivot) { break FindLo }
formIndex(after: &lo)
}
break Loop
}
FindHi: do {
formIndex(before: &hi)
while hi != lo {
if try areInIncreasingOrder(self[hi], pivot) { break FindHi }
formIndex(before: &hi)
}
break Loop
}
swapAt(lo, hi)
}
return lo
}
@inlinable
public // @testable
mutating func _introSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
let n = distance(from: range.lowerBound, to: range.upperBound)
guard n > 1 else { return }
// Set max recursion depth to 2*floor(log(N)), as suggested in the introsort
// paper: http://www.cs.rpi.edu/~musser/gp/introsort.ps
let depthLimit = 2 * n._binaryLogarithm()
try _introSortImpl(
within: range,
by: areInIncreasingOrder,
depthLimit: depthLimit)
}
@inlinable
internal mutating func _introSortImpl(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool,
depthLimit: Int
) rethrows {
// Insertion sort is better at handling smaller regions.
if distance(from: range.lowerBound, to: range.upperBound) < 20 {
try _insertionSort(within: range, by: areInIncreasingOrder)
} else if depthLimit == 0 {
try _heapSort(within: range, by: areInIncreasingOrder)
} else {
// Partition and sort.
// We don't check the depthLimit variable for underflow because this
// variable is always greater than zero (see check above).
let partIdx = try _partition(within: range, by: areInIncreasingOrder)
try _introSortImpl(
within: range.lowerBound..<partIdx,
by: areInIncreasingOrder,
depthLimit: depthLimit &- 1)
try _introSortImpl(
within: partIdx..<range.upperBound,
by: areInIncreasingOrder,
depthLimit: depthLimit &- 1)
}
}
@inlinable
internal mutating func _siftDown(
_ idx: Index,
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var i = idx
var countToIndex = distance(from: range.lowerBound, to: i)
var countFromIndex = distance(from: i, to: range.upperBound)
// Check if left child is within bounds. If not, stop iterating, because
// there are no children of the given node in the heap.
while countToIndex + 1 < countFromIndex {
let left = index(i, offsetBy: countToIndex + 1)
var largest = i
if try areInIncreasingOrder(self[largest], self[left]) {
largest = left
}
// Check if right child is also within bounds before trying to examine it.
if countToIndex + 2 < countFromIndex {
let right = index(after: left)
if try areInIncreasingOrder(self[largest], self[right]) {
largest = right
}
}
// If a child is bigger than the current node, swap them and continue sifting
// down.
if largest != i {
swapAt(idx, largest)
i = largest
countToIndex = distance(from: range.lowerBound, to: i)
countFromIndex = distance(from: i, to: range.upperBound)
} else {
break
}
}
}
@inlinable
internal mutating func _heapify(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
// Here we build a heap starting from the lowest nodes and moving to the
// root. On every step we sift down the current node to obey the max-heap
// property:
// parent >= max(leftChild, rightChild)
//
// We skip the rightmost half of the array, because these nodes don't have
// any children.
let root = range.lowerBound
let half = distance(from: range.lowerBound, to: range.upperBound) / 2
var node = index(root, offsetBy: half)
while node != root {
formIndex(before: &node)
try _siftDown(node, within: range, by: areInIncreasingOrder)
}
}
@inlinable
internal mutating func _heapSort(
within range: Range<Index>,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows {
var hi = range.upperBound
let lo = range.lowerBound
try _heapify(within: range, by: areInIncreasingOrder)
formIndex(before: &hi)
while hi != lo {
swapAt(lo, hi)
try _siftDown(lo, within: lo..<hi, by: areInIncreasingOrder)
formIndex(before: &hi)
}
}
}
|
821a78fe594b09b2d5202f3910ab87c0
| 36.217235 | 91 | 0.608249 | false | false | false | false |
eriklu/qch
|
refs/heads/master
|
View/QCHDefaultTextViewDelegate.swift
|
mit
|
1
|
import UIKit
class QCHDefaultTextViewDelegate : NSObject, UITextViewDelegate {
//按回车键退出编辑状态
var isResignFirstResponderOnReturn: Bool = true
//是否允许输入emoji
var isAllowEmoji: Bool = false
//最大允许长度. <=0:无限制;其他:允许最大长度
var maxLength: Int = 0
//错误提示函数
var funcShowTip: ((String) -> Void)?
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// if textView.markedTextRange != nil {
// return true
// }
if isResignFirstResponderOnReturn && text == "\n" {
textView.resignFirstResponder()
return false
}
if !isAllowEmoji && text.qch_containsEmoji {
return false
}
return true
}
func textViewDidChange(_ textView: UITextView) {
if textView.markedTextRange != nil {
return
}
if maxLength > 0 {
let text = textView.text!
if text.characters.count > maxLength {
textView.text = text.substring(to: text.index(text.startIndex, offsetBy: maxLength))
funcShowTip?("内容超过最大允许长度\(maxLength)")
}
}
}
}
|
114cc7ce544a392b203d67ac985ca875
| 26 | 116 | 0.545525 | false | false | false | false |
AssistoLab/DropDown
|
refs/heads/master
|
DropDown/helpers/DPDUIView+Extension.swift
|
mit
|
2
|
//
// UIView+Constraints.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
#if os(iOS)
import UIKit
//MARK: - Constraints
internal extension UIView {
func addConstraints(format: String, options: NSLayoutConstraint.FormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) {
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views))
}
func addUniversalConstraints(format: String, options: NSLayoutConstraint.FormatOptions = [], metrics: [String: AnyObject]? = nil, views: [String: UIView]) {
addConstraints(format: "H:\(format)", options: options, metrics: metrics, views: views)
addConstraints(format: "V:\(format)", options: options, metrics: metrics, views: views)
}
}
//MARK: - Bounds
internal extension UIView {
var windowFrame: CGRect? {
return superview?.convert(frame, to: nil)
}
}
internal extension UIWindow {
static func visibleWindow() -> UIWindow? {
var currentWindow = UIApplication.shared.keyWindow
if currentWindow == nil {
let frontToBackWindows = Array(UIApplication.shared.windows.reversed())
for window in frontToBackWindows {
if window.windowLevel == UIWindow.Level.normal {
currentWindow = window
break
}
}
}
return currentWindow
}
}
#endif
|
fc66fe439e5bbcba1faf17a6bd524bc8
| 22.147541 | 157 | 0.705382 | false | false | false | false |
TwoRingSoft/shared-utils
|
refs/heads/master
|
Sources/PippinAdapters/XCGLogger/XCGLoggerAdapter.swift
|
mit
|
1
|
//
// XCGLoggerAdapter.swift
// Pippin
//
// Created by Andrew McKnight on 1/28/17.
// Copyright © 2017 Two Ring Software. All rights reserved.
//
import Foundation
import Pippin
import PippinLibrary
import XCGLogger
extension LogLevel {
func xcgLogLevel() -> XCGLogger.Level {
switch self {
case .unknown: return XCGLogger.Level.info // default to info
case .verbose: return XCGLogger.Level.verbose
case .debug: return XCGLogger.Level.debug
case .info: return XCGLogger.Level.info
case .warning: return XCGLogger.Level.warning
case .error: return XCGLogger.Level.error
}
}
init?(xcgLevel: XCGLogger.Level) {
switch xcgLevel {
case .verbose: self = .verbose
case .debug: self = .debug
case .info: self = .info
case .warning: self = .warning
case .error: self = .error
case .severe: self = .error
case .none: self = .info // default to info
case .notice, .alert, .emergency: return nil
}
}
}
public final class XCGLoggerAdapter: NSObject {
public var environment: Environment?
fileprivate var _logLevel: LogLevel = .info
fileprivate var logFileURL: URL?
fileprivate var xcgLogger = XCGLogger(identifier: XCGLogger.Constants.fileDestinationIdentifier, includeDefaultDestinations: true)
public init(name: String, logLevel: LogLevel) {
super.init()
guard let logFileURL = urlForFilename(fileName: "\(name).log", inDirectoryType: .libraryDirectory) else {
reportMissingLogFile()
return
}
self.logFileURL = logFileURL
self.logLevel = logLevel
xcgLogger.setup(level: logLevel.xcgLogLevel(),
showLogIdentifier: false,
showFunctionName: false,
showThreadName: false,
showLevel: true,
showFileNames: false,
showLineNumbers: false,
showDate: true,
writeToFile: logFileURL,
fileLevel: logLevel.xcgLogLevel()
)
}
}
// MARK: Logger
extension XCGLoggerAdapter: Logger {
public var logLevel: LogLevel {
get {
return _logLevel
}
set(newValue) {
_logLevel = newValue
xcgLogger.outputLevel = newValue.xcgLogLevel()
}
}
@objc public func logDebug(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.debug)
}
@objc public func logInfo(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.info)
}
@objc public func logWarning(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.warning)
}
@objc public func logVerbose(message: String) {
self.log(message: message, logLevel: XCGLogger.Level.verbose)
}
@objc public func logError(message: String, error: Error) {
let messageWithErrorDescription = String(format: "%@: %@", message, error as NSError)
self.log(message: messageWithErrorDescription, logLevel: XCGLogger.Level.error)
environment?.crashReporter?.recordNonfatalError(error: error, metadata: nil)
}
public func logContents() -> String? {
var logContentsString = String()
if let logContents = getContentsOfLog() {
logContentsString.append(logContents)
logContentsString.append("\n")
}
return logContentsString
}
public func resetLogs() {
resetContentsOfLog()
}
}
// MARK: Private
private extension XCGLoggerAdapter {
func resetContentsOfLog() {
guard let logFileURL = logFileURL else {
reportMissingLogFile()
return
}
do {
try FileManager.default.removeItem(at: logFileURL)
} catch {
logError(message: String(format: "[%@] failed to delete log file at %@", instanceType(self), logFileURL.absoluteString), error: error)
}
}
func getContentsOfLog() -> String? {
var contents: String?
do {
if let logFileURL = logFileURL {
contents = try String(contentsOf: logFileURL, encoding: .utf8)
}
} catch {
logError(message: String(format: "[%@] Could not read logging file: %@.", instanceType(self), error as NSError), error: error)
}
return contents
}
func log(message: String, logLevel: XCGLogger.Level) {
self.xcgLogger.logln(message, level: logLevel)
if self.logLevel.xcgLogLevel() >= logLevel {
environment?.crashReporter?.log(message: String(format: "[%@] %@", logLevel.description, message))
}
}
func reportMissingLogFile() {
logError(message: String(format: "[%@] Could not locate log file.", instanceType(self)), error: LoggerError.noLoggingFile("Could not locate log file."))
}
private func urlForFilename(fileName: String, inDirectoryType directoryType: FileManager.SearchPathDirectory) -> URL? {
return FileManager.default.urls(for: directoryType, in: .userDomainMask).last?.appendingPathComponent(fileName)
}
}
// MARK: Debuggable
extension XCGLoggerAdapter: Debuggable {
public func debuggingControlPanel() -> UIView {
let titleLabel = UILabel.label(withText: "Logger:", font: environment!.fonts.title, textColor: .black)
func makeButton(title: String, action: Selector) -> UIButton {
let button = UIButton(type: .custom)
button.setTitle(title, for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
let stack = UIStackView(arrangedSubviews: [
titleLabel,
makeButton(title: "Log Verbose", action: #selector(debugLogVerbose)),
makeButton(title: "Log Debug", action: #selector(debugLogDebug)),
makeButton(title: "Log Info", action: #selector(debugLogInfo)),
makeButton(title: "Log Warning", action: #selector(debugLogWarning)),
makeButton(title: "Log Error", action: #selector(debugLogError)),
])
stack.axis = .vertical
stack.spacing = 20
return stack
}
@objc private func debugLogVerbose() {
logVerbose(message: "Debug Verbose level log message.")
}
@objc private func debugLogDebug() {
logDebug(message: "Debug Debug level log message.")
}
@objc private func debugLogInfo() {
logInfo(message: "Debug Info level log message.")
}
@objc private func debugLogWarning() {
logWarning(message: "Debug Warning level log message.")
}
@objc private func debugLogError() {
enum Error: Swift.Error {
case debugError
}
logError(message: "Debug Error level log message.", error: Error.debugError)
}
}
|
ac955dd0d2c489f3f4228a959fb19007
| 31.154545 | 160 | 0.617331 | false | false | false | false |
wangzheng0822/algo
|
refs/heads/master
|
swift/08_stack/StackBasedOnLinkedList.swift
|
apache-2.0
|
1
|
//
// Created by Jiandan on 2018/10/12.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
struct StackBasedOnLinkedList<Element>: Stack {
private var head = Node<Element>() // 哨兵结点,不存储内容
// MARK: Protocol: Stack
var isEmpty: Bool { return head.next == nil }
var size: Int {
var count = 0
var cur = head.next
while cur != nil {
count += 1
cur = cur?.next
}
return count
}
var peek: Element? { return head.next?.value }
func push(newElement: Element) -> Bool {
let node = Node(value: newElement)
node.next = head.next
head.next = node
return true
}
func pop() -> Element? {
let node = head.next
head.next = node?.next
return node?.value
}
}
|
000c9df62cbaa75c3b6cded272103233
| 20.897436 | 52 | 0.537471 | false | false | false | false |
Nykho/Swifternalization
|
refs/heads/master
|
SwifternalizationTests/RegexExpressionMatcherTests.swift
|
mit
|
4
|
//
// RegexExpressionMatcherTests.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import UIKit
import XCTest
class RegexExpressionMatcherTests: XCTestCase {
func testValidation1() {
let matcher = InequalityExpressionParser("ie:x=3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("3"), "should be true")
XCTAssertFalse(matcher.validate("5"), "should be true")
}
func testValidation2() {
let matcher = InequalityExpressionParser("ie:x<=3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("3"), "should be true")
XCTAssertTrue(matcher.validate("2"), "should be true")
}
func testValidation3() {
let matcher = InequalityExpressionParser("ie:x>=3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("3"), "should be true")
XCTAssertTrue(matcher.validate("4"), "should be true")
}
func testValidation4() {
let matcher = InequalityExpressionParser("ie:x>3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("4"), "should be true")
XCTAssertFalse(matcher.validate("3"), "should be true")
}
func testValidation5() {
let matcher = InequalityExpressionParser("ie:x<3").parse() as! InequalityExpressionMatcher
XCTAssertTrue(matcher.validate("2"), "should be true")
XCTAssertFalse(matcher.validate("3"), "should be true")
}
}
|
380a430923b63faafba3bcd1f78c8f14
| 35.674419 | 99 | 0.673431 | false | true | false | false |
VojtechBartos/Weather-App
|
refs/heads/master
|
WeatherApp/Classes/Controller/WEAForecastTableViewController.swift
|
mit
|
1
|
//
// WEAForecastTableViewController.swift
// WeatherApp
//
// Created by Vojta Bartos on 13/04/15.
// Copyright (c) 2015 Vojta Bartos. All rights reserved.
//
import UIKit
let WEA_FORECAST_CELL_IDENTIFIER = "WEAForecastCell"
class WEAForecastTableViewController: UITableViewController {
let config: WEAConfig = WEAConfig.sharedInstance
var days: [WEAForecast] = []
// MARK: - Screen life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.reload()
}
// MARK: - Setup
func setup() {
let cellNib: UINib = UINib(nibName: "WEATableViewCell", bundle: nil)
self.tableView.registerNib(cellNib, forCellReuseIdentifier: WEA_FORECAST_CELL_IDENTIFIER)
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.tableView.allowsSelection = false
self.tableView.editing = false
}
func setupObservers() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "reload", name: "cz.vojtechbartos.WeatherApp.locationDidChange", object: nil
)
}
// MARK: - Helpers
func reload() {
if let city: WEACity = WEACity.getCurrent() {
// set navigation title
self.navigationItem.title = city.name
// load updated forecast for next days
self.days = city.orderedForecast()
self.tableView.reloadData()
}
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.days.count
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: WEAForecastTableViewCell = tableView.dequeueReusableCellWithIdentifier(
WEA_FORECAST_CELL_IDENTIFIER, forIndexPath: indexPath
) as! WEAForecastTableViewCell
return self.configure(cell, indexPath: indexPath)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
// MARK: - Helpers
func configure(cell: WEAForecastTableViewCell, indexPath: NSIndexPath) -> WEAForecastTableViewCell {
var forecast: WEAForecast = self.days[indexPath.row]
cell.imageIconView.image = forecast.imageIcon(WEAImage.Small)
cell.titleLabel.text = forecast.day
cell.descriptionLabel.text = forecast.info
cell.temperatureLabel.text = NSString(format: "%iº", forecast.temperatureIn(self.config.temperatureUnit).integerValue) as String
cell.userInteractionEnabled = false
return cell
}
// MARK: - System
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
873430c9881d2dffe5637d50f92a2b0c
| 29.336538 | 136 | 0.657369 | false | true | false | false |
NghiaTranUIT/Unofficial-Uber-macOS
|
refs/heads/master
|
UberGoCore/UberGoCore/ReceiptObj.swift
|
mit
|
1
|
//
// ReceiptObj.swift
// UberGoCore
//
// Created by Nghia Tran on 8/17/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Unbox
public final class ReceiptObj: Unboxable {
// MARK: - Variable
public let requestID: String
public let totalCharge: String
public let totalOwed: Float?
public let totalFare: String
public let currencyCode: String
public let chargeAdjustments: [String]
public let duration: String
public let distance: String
public let distanceLabel: String
// MARK: - Init
public required init(unboxer: Unboxer) throws {
requestID = try unboxer.unbox(key: Constants.Object.Receipt.RequestID)
totalCharge = try unboxer.unbox(key: Constants.Object.Receipt.TotalCharged)
totalOwed = unboxer.unbox(key: Constants.Object.Receipt.TotalOwed)
totalFare = try unboxer.unbox(key: Constants.Object.Receipt.TotalFare)
currencyCode = try unboxer.unbox(key: Constants.Object.Receipt.CurrencyCode)
chargeAdjustments = try unboxer.unbox(key: Constants.Object.Receipt.ChargeAdjustments)
duration = try unboxer.unbox(key: Constants.Object.Receipt.Duration)
distance = try unboxer.unbox(key: Constants.Object.Receipt.Distance)
distanceLabel = try unboxer.unbox(key: Constants.Object.Receipt.DistanceLabel)
}
}
|
8c32d565cf7f5ff57c2ac1830ef8fb27
| 36.583333 | 94 | 0.719143 | false | false | false | false |
xdkoooo/LiveDemo
|
refs/heads/master
|
LiveDemo/LiveDemo/Classes/Main/Model/AnchorModel.swift
|
mit
|
1
|
//
// AnchorModel.swift
// LiveDemo
//
// Created by BillBear on 2017/3/9.
// Copyright © 2017年 xdkoo. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
/// 房间ID
var room_id : String = ""
/// 房间图片对应的URLString
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
/// 0 : 电脑 1 : 手机直播
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 在线人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
|
ec4f8d40af2abae2b797d1b12afb782b
| 19.4 | 73 | 0.557423 | false | false | false | false |
xuephil/Perfect
|
refs/heads/master
|
Examples/Authenticator/Authenticator/LoginHandler.swift
|
agpl-3.0
|
1
|
//
// LoginHandler.swift
// Authenticator
//
// Created by Kyle Jessup on 2015-11-10.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// 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 Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
import PerfectLib
import Foundation
// Handler class
// When referenced in a mustache template, this class will be instantiated to handle the request
// and provide a set of values which will be used to complete the template.
class LoginHandler: AuthenticatingHandler { // all template handlers must inherit from PageHandler
// This is the function which all handlers must impliment.
// It is called by the system to allow the handler to return the set of values which will be used when populating the template.
// - parameter context: The MustacheEvaluationContext which provides access to the WebRequest containing all the information pertaining to the request
// - parameter collector: The MustacheEvaluationOutputCollector which can be used to adjust the template output. For example a `defaultEncodingFunc` could be installed to change how outgoing values are encoded.
override func valuesForResponse(context: MustacheEvaluationContext, collector: MustacheEvaluationOutputCollector) throws -> MustacheEvaluationContext.MapType {
var values = try super.valuesForResponse(context, collector: collector)
if let acceptStr = context.webRequest?.httpAccept() {
if acceptStr.contains("json") {
values["json"] = true
}
}
guard let user = self.authenticatedUser else {
// Our parent class will have set the web response code to trigger authentication.
values["message"] = "Not authenticated"
values["resultCode"] = 401
return values
}
// This handler is responsible for taking a user supplied username and the associated
// digest authentication information and validating it against the information in the database.
values["resultCode"] = 0
values["first"] = user.firstName
values["last"] = user.lastName
values["email"] = user.email
values["title"] = "Perfect Project Template"
values["message"] = "Logged in successfully!"
// Return the values
// These will be used to populate the template
return values
}
}
|
29b9e8d69a98e45c72be70fffe7e4868
| 42.771429 | 211 | 0.758159 | false | false | false | false |
bartekchlebek/SwiftHelpers
|
refs/heads/master
|
Example/Pods/Nimble/Sources/Nimble/Matchers/AllPass.swift
|
mit
|
1
|
import Foundation
public func allPass<T,U>
(_ passFunc: @escaping (T) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return allPass { (v: T?) -> Bool in v.map(passFunc) ?? false }
}
public func allPass<T,U>
(_ passName: String, _ passFunc: @escaping (T) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return allPass(passName) { (v: T?) -> Bool in v.map(passFunc) ?? false }
}
public func allPass<T,U>
(_ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return allPass("pass a condition", passFunc)
}
public func allPass<T,U>
(_ passName: String, _ passFunc: @escaping (T?) -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return createAllPassMatcher() {
expression, failureMessage in
failureMessage.postfixMessage = passName
return passFunc(try expression.evaluate())
}
}
public func allPass<U,V>
(_ matcher: V) -> NonNilMatcherFunc<U>
where U: Sequence, V: Matcher, U.Iterator.Element == V.ValueType
{
return createAllPassMatcher() {
try matcher.matches($0, failureMessage: $1)
}
}
private func createAllPassMatcher<T,U>
(_ elementEvaluator: @escaping (Expression<T>, FailureMessage) throws -> Bool) -> NonNilMatcherFunc<U>
where U: Sequence, U.Iterator.Element == T
{
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.actualValue = nil
if let actualValue = try actualExpression.evaluate() {
for currentElement in actualValue {
let exp = Expression(
expression: {currentElement}, location: actualExpression.location)
if try !elementEvaluator(exp, failureMessage) {
failureMessage.postfixMessage =
"all \(failureMessage.postfixMessage),"
+ " but failed first at element <\(stringify(currentElement))>"
+ " in <\(stringify(actualValue))>"
return false
}
}
failureMessage.postfixMessage = "all \(failureMessage.postfixMessage)"
} else {
failureMessage.postfixMessage = "all pass (use beNil() to match nils)"
return false
}
return true
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func allPassMatcher(_ matcher: NMBObjCMatcher) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try! actualExpression.evaluate()
var nsObjects = [NSObject]()
var collectionIsUsable = true
if let value = actualValue as? NSFastEnumeration {
let generator = NSFastEnumerationIterator(value)
while let obj = generator.next() {
if let nsObject = obj as? NSObject {
nsObjects.append(nsObject)
} else {
collectionIsUsable = false
break
}
}
} else {
collectionIsUsable = false
}
if !collectionIsUsable {
failureMessage.postfixMessage =
"allPass only works with NSFastEnumeration (NSArray, NSSet, ...) of NSObjects"
failureMessage.expected = ""
failureMessage.to = ""
return false
}
let expr = Expression(expression: ({ nsObjects }), location: location)
let elementEvaluator: (Expression<NSObject>, FailureMessage) -> Bool = {
expression, failureMessage in
return matcher.matches(
{try! expression.evaluate()}, failureMessage: failureMessage, location: expr.location)
}
return try! createAllPassMatcher(elementEvaluator).matches(
expr, failureMessage: failureMessage)
}
}
}
#endif
|
e6e0f6dcedf903ee1628e15b9629f2a3
| 36.026316 | 106 | 0.579957 | false | false | false | false |
noprom/Cocktail-Pro
|
refs/heads/master
|
smartmixer/smartmixer/UserCenter/UserHome.swift
|
apache-2.0
|
1
|
//
// UserHome.swift
// smartmixer
//
// Created by 姚俊光 on 14/9/29.
// Copyright (c) 2014年 smarthito. All rights reserved.
//
import UIKit
import CoreData
class UserHome: UIViewController,UIScrollViewDelegate,UITableViewDelegate,HistoryCellDelegate,NSFetchedResultsControllerDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate{
//用户信息的View
@IBOutlet var userInfoLayer:UIView!
//用户背景图片
@IBOutlet var userInfoBg:UIImageView!
//用户信息距顶部的控制
@IBOutlet var userInfoframe: UIView!
//信息的滚动
@IBOutlet var scollViewMap:UIScrollView!
//概览信息
@IBOutlet var sumInfo:UILabel!
//用户名字
@IBOutlet var userName:UILabel!
//用户头像
@IBOutlet var userImage:UIImageView!
//点击还原的我按钮
@IBOutlet var myButton:UIButton!
//没有数据时的提示
@IBOutlet var nodataTip:UILabel!
//历史信息的table
@IBOutlet var historyTableView:UITableView!
var clickGesture:UITapGestureRecognizer!
class func UserHomeRoot()->UIViewController{
let userCenterController = UIStoryboard(name:"UserCenter"+deviceDefine,bundle:nil).instantiateInitialViewController() as! UserHome
return userCenterController
}
override func viewDidLoad() {
super.viewDidLoad()
let fileManager = NSFileManager.defaultManager()
if(fileManager.isReadableFileAtPath(applicationDocumentsPath+"/mybg.png")){
userInfoBg.image = UIImage(contentsOfFile: applicationDocumentsPath+"/mybg.png")
}
userImage.image = UIImage(contentsOfFile: applicationDocumentsPath+"/myimage.png")
userName.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")!
self.userInfoframe.userInteractionEnabled = true
clickGesture = UITapGestureRecognizer()
clickGesture.addTarget(self, action: Selector("changeHomebg:"))
clickGesture?.delegate = self
self.userInfoframe.addGestureRecognizer(clickGesture!)
scollViewMap.contentSize = CGSize(width: 0, height: 350+CGFloat(numberOfObjects*50))
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tabBarController?.tabBar.hidden = true
self.hidesBottomBarWhenPushed = true
self.navigationController?.setNavigationBarHidden(true, animated: true)
let UserCook = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")
let UserFavor = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")
let UserHave = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")
let UserContainer = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")
sumInfo.text = "\(UserFavor)个收藏,\(UserCook)次制作,\(UserHave)种材料,\(UserContainer)种器具"
userImage.image = UIImage(contentsOfFile: applicationDocumentsPath+"/myimage.png")
userName.text = NSUserDefaults.standardUserDefaults().stringForKey("UserName")!
scollViewMap.contentSize = CGSize(width: 0, height: 350+CGFloat(numberOfObjects*50))
rootController.showOrhideToolbar(true)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
//@MARK:修改主页的背景选取照片
var imagePicker:UIImagePickerController!
var popview:UIPopoverController!
//修改主页的背景图片
func changeHomebg(sender:UITapGestureRecognizer){
if(scollViewMap.contentOffset.y>10){
UIView.animateWithDuration(0.3, animations: {
self.userInfoframe.frame = CGRect(x: self.userInfoframe.frame.origin.x, y: 0, width: self.userInfoframe.frame.width, height: self.userInfoframe.frame.height)
self.userInfoLayer.alpha = 1
self.myButton.hidden = true
self.setalpha = false
self.view.layoutIfNeeded()
})
self.scollViewMap.contentOffset.y = 0
}else{
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.modalTransitionStyle = UIModalTransitionStyle.CoverVertical
imagePicker.tabBarItem.title="请选择背景图片"
if(deviceDefine==""){
self.presentViewController(imagePicker, animated: true, completion: nil)
}else{
popview = UIPopoverController(contentViewController: imagePicker)
popview.presentPopoverFromRect(CGRect(x: 512, y: 50, width: 10, height: 10), inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
}
//写入Document中
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
userInfoBg.image = image
let imageData = UIImagePNGRepresentation(image)
imageData!.writeToFile(applicationDocumentsPath+"/mybg.png", atomically: false)
self.dismissViewControllerAnimated(true, completion: nil)
if(osVersion<8 && deviceDefine != ""){
popview.dismissPopoverAnimated(true)
}
}
//@MARK:点击商城
@IBAction func OnStoreClick(sender:UIButton){
let baike:WebView = WebView.WebViewInit()
baike.myWebTitle = "商城"
baike.WebUrl="http://www.smarthito.com"
rootController.showOrhideToolbar(false)
baike.showToolbar = true
self.navigationController?.pushViewController(baike, animated: true)
}
//@MARK:点击设置
var aboutview:UIViewController!
@IBAction func OnSettingClick(sender:UIButton){
if(deviceDefine==""){
aboutview = AboutViewPhone.AboutViewPhoneInit()
}else{
aboutview = AboutViewPad.AboutViewPadInit()
}
self.navigationController?.pushViewController(aboutview, animated: true)
rootController.showOrhideToolbar(false)
}
//#MARK:这里是处理滚动的处理向下向上滚动影藏控制栏
var lastPos:CGFloat = 0
//滚动开始记录开始偏移
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
lastPos = scrollView.contentOffset.y
}
var setalpha:Bool=false
func scrollViewDidScroll(scrollView: UIScrollView) {
let off = scrollView.contentOffset.y
if(off<=240 && off>0){//在区间0~240需要渐变处理
userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: -off, width: userInfoframe.frame.width, height: userInfoframe.frame.height)
userInfoLayer.alpha = 1-off/240
myButton.hidden = true
setalpha = false
}else if(off>240 && setalpha==false){//大于240区域
userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: -240, width: userInfoframe.frame.width, height: userInfoframe.frame.height)
userInfoLayer.alpha = 0
myButton.hidden = false
setalpha = true
}else if(off<0){
userInfoframe.frame = CGRect(x: userInfoframe.frame.origin.x, y: 0, width: userInfoframe.frame.width, height: userInfoframe.frame.height)
self.userInfoLayer.alpha = 1
self.myButton.hidden = true
self.setalpha = false
}
/**/
if((off-lastPos)>50 && off>50){//向下了
lastPos = off
rootController.showOrhideToolbar(false)
}else if((lastPos-off)>70){
lastPos = off
rootController.showOrhideToolbar(true)
}
}
var numberOfObjects:Int=0
//@MARK:这里是处理显示数据的
//告知窗口现在有多少个item需要添加
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
let sectionInfo = self.fetchedResultsController.sections!
let item = sectionInfo[section]
numberOfObjects = item.numberOfObjects
if(numberOfObjects==0){
nodataTip.hidden = false
}else{
nodataTip.hidden = true
}
historyTableView.contentSize = CGSize(width: 0, height: CGFloat(numberOfObjects*50))
return item.numberOfObjects
}
//处理单个View的添加
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History
var indentifier = "his-cook"
if(item.type==1){
indentifier="his-addfaver"
}else if(item.type==2){
indentifier="his-addhave"
}else if(item.type==3){
indentifier="his-addhave"
}
let cell :HistoryCell = tableView.dequeueReusableCellWithIdentifier(indentifier) as! HistoryCell
if(deviceDefine==""){
cell.scroll.contentSize = CGSize(width: 380, height: 50)
}else{
//cell.scroll.contentSize = CGSize(width: 1104, height: 50)
}
cell.name.text = item.name
cell.thumb.image = UIImage(named: item.thumb)
cell.time.text = formatDateString(item.addtime)
cell.delegate = self
return cell
}
var lastDayString:String!=nil
func formatDateString(date:NSDate)->String{
let formatter = NSDateFormatter()
formatter.dateFormat="yyyy.MM.dd"
let newstring = formatter.stringFromDate(date)
if(newstring != lastDayString){
lastDayString = newstring
return lastDayString
}else{
return "."
}
}
//要删除某个
func historyCell(sender:HistoryCell){
skipUpdate = true
let indexPath:NSIndexPath=self.historyTableView.indexPathForCell(sender)!
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History
managedObjectContext.deleteObject(item)
do {
try managedObjectContext.save()
}catch{
abort()
}
// if !managedObjectContext.save(&error) {
// abort()
// }
self.historyTableView?.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
}
//选中某个需要显示
func historyCell(sender:HistoryCell,show ShowCell:Bool){
self.navigationController?.setNavigationBarHidden(false, animated: false)
rootController.showOrhideToolbar(false)
let indexPath:NSIndexPath=self.historyTableView.indexPathForCell(sender)!
let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as! History
if(item.type==0||item.type==1){
let recipe=DataDAO.getOneRecipe(item.refid.integerValue)
if(deviceDefine==""){
let recipeDetail = RecipeDetailPhone.RecipesDetailPhoneInit()
recipeDetail.CurrentData = recipe
self.navigationController?.pushViewController(recipeDetail, animated: true)
}else{
let recipeDetail = RecipeDetailPad.RecipeDetailPadInit()
recipeDetail.CurrentData = recipe
self.navigationController?.pushViewController(recipeDetail, animated: true)
}
}else if(item.type==2){
let materials = IngredientDetail.IngredientDetailInit()
materials.ingridient=DataDAO.getOneIngridient(item.refid.integerValue)
self.navigationController?.pushViewController(materials, animated: true)
}else if(item.type==3){
let container = ContainerDetail.ContainerDetailInit()
container.CurrentContainer = DataDAO.getOneContainer(item.refid.integerValue)
self.navigationController?.pushViewController(container, animated: true)
}
}
//@MARK:历史数据的添加处理
class func addHistory(type:Int,id refId:Int,thumb imageThumb:String,name showName:String){
let history = NSEntityDescription.insertNewObjectForEntityForName("History", inManagedObjectContext: managedObjectContext) as! History
history.type = type
history.refid = refId
history.thumb = imageThumb
history.name = showName
history.addtime = NSDate()
if(type==0){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserCook")
do {
try managedObjectContext.save()
}catch{
abort()
}
// var error: NSError? = nil
// if !managedObjectContext.save(&error) {
// abort()
// }
}else if(type==1){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserFavor")
}else if(type==2){//添加了材料的拥有
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserHave")
DataDAO.updateRecipeCoverd(refId, SetHave: true)
}else{
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")+1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserContainer")
}
}
//历史数据的删除
class func removeHistory(type:Int,id refId:Int){
if(type==0){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserCook")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserCook")
}else if(type==1){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserFavor")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserFavor")
}else if(type==2){
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserHave")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserHave")
DataDAO.updateRecipeCoverd(refId, SetHave: false)
}else{
let usernum = NSUserDefaults.standardUserDefaults().integerForKey("UserContainer")-1
NSUserDefaults.standardUserDefaults().setInteger(usernum, forKey: "UserContainer")
}
}
//@MARK:数据的读取
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName("History", inManagedObjectContext: managedObjectContext)
fetchRequest.fetchBatchSize = 30
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "addtime", ascending: false)]
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
_fetchedResultsController = aFetchedResultsController
_fetchedResultsController?.delegate = self
do {
try self.fetchedResultsController.performFetch()
}catch{
abort()
}
// var error: NSError? = nil
// if !_fetchedResultsController!.performFetch(&error) {
// abort()
// }
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
var skipUpdate:Bool=false
func controllerDidChangeContent(controller: NSFetchedResultsController) {
if(skipUpdate){
skipUpdate=false
}else{
_fetchedResultsController = nil
historyTableView.reloadData()
lastDayString=nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
dc5b83882e5be4455553cd857af09640
| 40.426357 | 220 | 0.658496 | false | false | false | false |
vanshg/MacAssistant
|
refs/heads/master
|
MacAssistant/Assistant/AssistantViewController.swift
|
mit
|
1
|
//
// AssistantViewController.swift
// MacAssistant
//
// Created by Vansh Gandhi on 8/3/18.
// Copyright © 2018 Vansh Gandhi. All rights reserved.
//
import Cocoa
import Log
import SwiftGRPC
import WebKit
import SwiftyUserDefaults
// Eventual TODO: AssistantViewController should only interact with views
// Current Assistant.swift should be renamed to API.swift
// New Assistant.swift should handle business logic of mic/follow up/audio/
class AssistantViewController: NSViewController, AssistantDelegate, AudioDelegate {
let Log = Logger()
let assistant = Assistant()
var conversation: [ConversationEntry] = []
var currentAssistantCall: AssistCallContainer?
var followUpRequired = false
var micWasUsed = false
lazy var audioEngine = AudioEngine(delegate: self)
let conversationItemIdentifier = NSUserInterfaceItemIdentifier(rawValue: "ConversationItem")
@IBOutlet weak var initialPromptLabel: NSTextField!
@IBOutlet weak var conversationCollectionView: NSCollectionView!
@IBOutlet weak var keyboardInputField: NSTextField!
override func viewDidLoad() {
conversationCollectionView.dataSource = self
conversationCollectionView.delegate = self
conversationCollectionView.register(NSNib(nibNamed: "ConversationItem", bundle: nil), forItemWithIdentifier: conversationItemIdentifier)
}
override func viewDidAppear() {
if Defaults[.shouldListenOnMenuClick] {
onMicClicked()
}
}
override func viewDidDisappear() {
cancelCurrentRequest()
}
func onAssistantCallCompleted(result: CallResult) {
currentAssistantCall = nil
Log.debug("Assistant Call Completed. Description: \(result.description)")
if !result.success {
// TODO: show error (Create ErrorConversationEntry)
}
if let statusMessage = result.statusMessage {
Log.debug(statusMessage)
}
}
func onDoneListening() {
Log.debug("Done Listening")
audioEngine.stopRecording()
currentAssistantCall?.doneSpeaking = true
}
// Received text to display
func onDisplayText(text: String) {
Log.debug("Received display text: \(text)")
conversation.append(ConversationEntry(isFromUser: false, text: text))
conversationCollectionView.reloadBackground()
}
func onScreenOut(htmlData: String) {
// TODO: supplementalView to display screen out?
// TODO: Handle HTML Screen Out data
Log.info(htmlData)
}
func onTranscriptUpdate(transcript: String) {
Log.debug("Transcript update: \(transcript)")
conversation[conversation.count - 1].text = transcript
conversationCollectionView.reloadBackground()
}
func onAudioOut(audio: Data) {
Log.debug("Got audio")
audioEngine.playResponse(data: audio) { success in
if !success {
self.Log.error("Error playing audio out")
}
// Regardless of audio error, still follow up
if self.followUpRequired {
self.followUpRequired = false
if self.micWasUsed {
self.Log.debug("Following up with mic")
self.onMicClicked()
} // else, use text input
}
}
}
func onFollowUpRequired() {
Log.debug("Follow up needed")
followUpRequired = true // Will follow up after completion of audio out
}
func onError(error: Error) {
Log.error("Got error \(error.localizedDescription)")
}
// Called from AudioEngine (delegate method)
func onMicrophoneInputAudio(audioData: Data) {
if let call = currentAssistantCall {
// We don't want to continue sending data to servers once endOfUtterance has been received
if !call.doneSpeaking {
assistant.sendAudioChunk(streamCall: call.call, audio: audioData, delegate: self)
}
}
}
func cancelCurrentRequest() {
followUpRequired = false
audioEngine.stopPlayingResponse()
if let call = currentAssistantCall {
Log.debug("Cancelling current request")
call.call.cancel()
if (!call.doneSpeaking) {
conversation.removeLast()
conversationCollectionView.reloadBackground()
}
currentAssistantCall = nil
onDoneListening()
}
}
}
// UI Actions
extension AssistantViewController {
@IBAction func onEnterClicked(_ sender: Any) {
let query = keyboardInputField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
if query.isNotEmpty {
Log.debug("Processing text query: \(query)")
micWasUsed = false
conversation.append(ConversationEntry(isFromUser: true, text: query))
conversationCollectionView.reloadData()
let lastIndexPath = Set([IndexPath(item: conversation.count-1, section: 0)])
conversationCollectionView.scrollToItems(at: lastIndexPath, scrollPosition: .bottom)
assistant.sendTextQuery(text: query, delegate: self)
keyboardInputField.stringValue = ""
}
}
@IBAction func onMicClicked(_ sender: Any? = nil) {
Log.debug("Mic clicked")
audioEngine.playBeginPrompt()
micWasUsed = true
audioEngine.stopPlayingResponse()
currentAssistantCall = AssistCallContainer(call: assistant.initiateSpokenRequest(delegate: self))
audioEngine.startRecording()
conversation.append(ConversationEntry(isFromUser: true, text: "..."))
conversationCollectionView.reloadData()
}
// TODO: Link this up with the Mic Graph (Another TODO: Get the Mic Waveform working)
func onWaveformClicked(_ sender: Any?) {
Log.debug("Listening manually stopped")
audioEngine.stopRecording()
try? currentAssistantCall?.call.closeSend()
}
}
// CollectionView related methods
extension AssistantViewController: NSCollectionViewDataSource, NSCollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return conversation.count
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: conversationItemIdentifier, for: indexPath) as! ConversationItem
item.loadData(data: conversation[indexPath.item])
return item
}
// func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
//
//
// let myNib = NSNib(nibNamed: "ConversationItem", bundle: nil)!
// var myArray: NSArray!
// myNib.instantiate(withOwner: ConversationItem.self, topLevelObjects: &myArray) // instantiate view and put in myArray
// var item: ConversationItem? = nil
// for i in myArray {
// if let i = i as? ConversationItem {
// item = i
// }
// }
//// let item = myArray[2] as! ConversationItem
//
//// Bundle.main.loadNibNamed("ConversationItem", owner: self, topLevelObjects: &myArray)
//// let picker = NSBundle.mainBundle().loadNibNamed("advancedCellView", owner: nil, options: nil)
//// let item = myArray[0] as! ConversationItem
//
//// let item = collectionView.makeItem(withIdentifier: conversationItemIdentifier, for: IndexPath(item: 0, section: 0)) as! ConversationItem
//// let item = collectionView.item(at: indexPath)
// if let item = item as ConversationItem? {
// item.loadData(data: conversation[indexPath.item])
// let width = item.textField!.frame.size.width
// let newSize = item.textField!.sizeThatFits(NSSize(width: width, height: .greatestFiniteMagnitude))
// item.textField?.frame.size = NSSize(width: 300, height: newSize.height)
// print(item.textField!.frame.size)
// return item.textField!.frame.size
// }
//
// print("here 2")
// return NSSize(width: 300, height: 30)
//
// }
}
|
e7f1912c2a9e4738670c95d157298f69
| 37.209821 | 166 | 0.642832 | false | false | false | false |
cuappdev/tempo
|
refs/heads/master
|
Tempo/Controllers/LoginFlowViewController.swift
|
mit
|
1
|
import UIKit
protocol LoginFlowViewControllerDelegate: class {
func didFinishLoggingIn()
}
class LoginFlowViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let pageVCOffset: CGFloat = 40
var pageViewController: UIPageViewController!
var facebookLoginViewController: FacebookLoginViewController!
var createUsernameViewController: CreateUsernameViewController!
var spotifyLoginViewController: SpotifyLoginViewController!
var pages = [UIViewController]()
var pageControl: UIPageControl?
weak var delegate: LoginFlowViewControllerDelegate?
var currentlyDisplayingPageIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageViewController.dataSource = self
pageViewController.delegate = self
facebookLoginViewController = FacebookLoginViewController()
facebookLoginViewController.delegate = self
createUsernameViewController = CreateUsernameViewController()
createUsernameViewController.delegate = self
spotifyLoginViewController = SpotifyLoginViewController()
spotifyLoginViewController.delegate = self
pages = [facebookLoginViewController, createUsernameViewController, spotifyLoginViewController]
pageViewController.setViewControllers([facebookLoginViewController], direction: .forward, animated: false, completion: nil)
// Disable swiping and hide page control
pageViewController.disablePageViewControllerSwipeGesture()
pageViewController.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height + pageVCOffset)
pageViewController.hidePageControl()
addChildViewController(pageViewController)
view.addSubview(pageViewController.view)
pageViewController.didMove(toParentViewController: self)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let index = pages.index(of: viewController), index < pages.count - 1 {
return pages[index + 1]
}
return nil
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return pages.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return currentlyDisplayingPageIndex
}
}
extension LoginFlowViewController: FacebookLoginViewControllerDelegate {
func facebookLoginViewController(facebookLoginViewController: FacebookLoginViewController, didFinishLoggingInWithNewUserNamed name: String, withFacebookID fbid: String) {
createUsernameViewController.name = name
createUsernameViewController.fbid = fbid
currentlyDisplayingPageIndex += 1
pageViewController.setViewControllers([createUsernameViewController], direction: .forward, animated: true, completion: nil)
}
func facebookLoginViewController(facebookLoginViewController: FacebookLoginViewController, didFinishLoggingInWithPreviouslyRegisteredUserNamed name: String, withFacebookID fbid: String) {
delegate?.didFinishLoggingIn()
}
}
extension LoginFlowViewController: CreateUsernameViewControllerDelegate {
func createUsernameViewController(createUsernameViewController: CreateUsernameViewController, didFinishCreatingUsername username: String) {
currentlyDisplayingPageIndex += 1
pageViewController.setViewControllers([spotifyLoginViewController], direction: .forward, animated: true, completion: nil)
}
}
extension LoginFlowViewController: SpotifyLoginViewControllerDelegate {
func spotifyLoginViewController(spotifyLoginViewController: SpotifyLoginViewController, didFinishLoggingIntoSpotifyWithAccessToken token: String?) {
delegate?.didFinishLoggingIn()
}
}
extension UIPageViewController {
func disablePageViewControllerSwipeGesture() {
for subview in view.subviews {
if let scrollView = subview as? UIScrollView {
scrollView.isScrollEnabled = false
}
}
}
func hidePageControl() {
for subview in view.subviews {
if subview is UIPageControl {
subview.isHidden = true
}
}
}
}
|
f99aa635f5bf149bfa0b17864b04e64a
| 32.330769 | 188 | 0.811678 | false | false | false | false |
swiftingio/SwiftyStrings
|
refs/heads/master
|
SwiftyStrings/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SwiftyStrings
//
// Created by Maciej Piotrowski on 20/11/16.
// Copyright © 2016 Maciej Piotrowski. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configureNavigationItem()
configureViews()
configureConstraints()
}
}
extension ViewController {
fileprivate func configureViews() {
view.backgroundColor = .white
let color = UIColor(red:0.13, green:0.56, blue:0.93, alpha:1.00)
button = UIButton(frame: .zero)
button.setTitle(.ImpressMe, for: .normal)
button.setTitleColor(color, for: .normal)
button.sizeToFit()
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
view.addSubview(button)
}
fileprivate func configureConstraints() {
view.subviews.forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
let constraints: [NSLayoutConstraint] = NSLayoutConstraint.centerInSuperview(button)
NSLayoutConstraint.activate(constraints)
}
fileprivate func configureNavigationItem() {
title = .Hello
}
@objc fileprivate func buttonTapped(sender: UIButton) {
let alert = UIAlertController(title: .ThisApplicationIsCreated, message: .OpsNoFeature, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: .OK, style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
|
7ecd1fff054204639cf738c69cad1fd9
| 31.02 | 119 | 0.674578 | false | true | false | false |
icotting/Phocalstream.iOS
|
refs/heads/master
|
Phocalstream/CreateSiteController.swift
|
apache-2.0
|
1
|
//
// CreateSiteController.swift
// Phocalstream
//
// Created by Zach Christensen on 9/18/15.
// Copyright © 2015 JS Raikes School. All rights reserved.
//
import UIKit
import Foundation
import CoreLocation
class CreateSiteController : UIViewController, CLLocationManagerDelegate, UITextFieldDelegate, RequestManagerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var createButton: UIBarButtonItem!
@IBOutlet weak var closeButton: UIBarButtonItem!
@IBOutlet weak var siteNameField: UITextField!
@IBOutlet weak var siteLocationField: UITextField!
@IBOutlet weak var siteImageThumbnail: UIImageView!
var siteId: Int!
var siteName: String!
var siteLat: Double!
var siteLong: Double!
var county: String!
var state: String!
var siteImage: UIImage!
var dialog: LoadingDialog!
var geocoder: CLGeocoder!
var manager: CLLocationManager!
var mgr: RequestManager!
override func viewDidLoad() {
siteNameField.delegate = self
// Setup our Location Manager
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
// Init Geocoder
geocoder = CLGeocoder()
mgr = RequestManager(delegate: self)
}
override func viewDidAppear(animated: Bool) {
manager.startUpdatingLocation()
}
override func viewDidDisappear(animated: Bool) {
manager.stopUpdatingLocation()
}
func isSiteValid() -> Bool {
return (siteName != nil && siteLat != nil && siteLong != nil && county != nil && state != nil && siteImage != nil)
}
// MARK: Toolbar Actions
@IBAction func close(sender: AnyObject) {
}
@IBAction func create(sender: AnyObject) {
self.dialog = LoadingDialog(title: "Creating Site")
self.dialog.presentFromView(self.view)
//string siteName, double latitude, double longitude, string county, string state
let dictionary = NSMutableDictionary()
dictionary.setValue(self.siteName, forKeyPath: "SiteName")
dictionary.setValue(String(self.siteLat), forKeyPath: "Latitude")
dictionary.setValue(String(self.siteLong), forKeyPath: "Longitude")
dictionary.setValue("\(self.county) County", forKeyPath: "County")
dictionary.setValue(self.state, forKeyPath: "State")
self.mgr.postWithData("http://images.plattebasintimelapse.org/api/usercollection/CreateUserCameraSite", data: dictionary)
}
// MARK: Photo Capture
@IBAction func addPhoto(sender: AnyObject) {
if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
self.capturePhoto()
} else {
self.noCamera()
}
}
func choosePhotofromLibrary() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
imagePicker.allowsEditing = false
presentViewController(imagePicker, animated: true, completion: nil)
}
func capturePhoto() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.delegate = self
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func noCamera(){
let alert = UIAlertView(title: "No Camera", message: "Sorry, this device does not have a camera. Choose an image from photo library?", delegate: self, cancelButtonTitle: "No")
alert.addButtonWithTitle("Yes")
alert.show()
}
// MARK: UIImagePickerController Delegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
self.siteImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.siteImageThumbnail.image = self.siteImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
self.siteImage = nil
self.siteImageThumbnail.image = nil
}
// MARK: UIAlertView Delegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if alertView.title == "Upload a photo?" {
if buttonIndex == 1 {
self.capturePhoto()
}
}
else if alertView.title == "No Camera" {
if buttonIndex == 1 {
self.choosePhotofromLibrary()
}
}
}
// MARK: RequestManager Delegate Methods
func didFailWithResponseCode(code: Int, message: String?) {
dispatch_async(dispatch_get_main_queue(), {
print("\(code): \(message!)")
self.dialog.clearFromView()
})
}
func didSucceedWithBody(body: Array<AnyObject>?) {
// If the body is not nil, it is the first call to create the site
if body != nil {
let id = (body!.first as! String!)
self.siteId = Int(id)
self.dialog.updateTitle("Uploading Photo")
self.mgr.uploadPhoto("http://images.plattebasintimelapse.org/api/upload/upload?selectedCollectionID=\(self.siteId)", image: self.siteImage!)
}
}
func didSucceedWithObjectId(id: Int64) {
dispatch_async(dispatch_get_main_queue(), {
self.dialog.clearFromView()
})
performSegueWithIdentifier("UNWINDANDRELOAD", sender: self)
}
// MARK: CLLocationManagerDelete Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.siteLat = locations[0].coordinate.latitude
self.siteLong = locations[0].coordinate.longitude
siteLocationField.text = "( \(locations[0].coordinate.latitude), \(locations[0].coordinate.longitude) )"
self.geocoder.reverseGeocodeLocation(locations[0], completionHandler: {(placemarks, error) in
if let placemark: CLPlacemark = placemarks?[0] {
self.county = placemark.subAdministrativeArea!
self.state = placemark.administrativeArea!
self.createButton.enabled = self.isSiteValid()
}
})
}
//MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
}
func textFieldDidEndEditing(textField: UITextField) {
self.siteName = siteNameField.text
createButton.enabled = isSiteValid()
}
}
|
d75a476e8eca37635704c2b1489a9a94
| 31.95283 | 184 | 0.645956 | false | false | false | false |
frtlupsvn/Vietnam-To-Go
|
refs/heads/master
|
VietNamToGo/DPDConstants.swift
|
mit
|
1
|
//
// Constants.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
internal struct DPDConstant {
internal struct KeyPath {
static let Frame = "frame"
}
internal struct ReusableIdentifier {
static let DropDownCell = "DropDownCell"
}
internal struct UI {
static let BackgroundColor = colorBlue
static let SelectionBackgroundColor = UIColor(white: 0.89, alpha: 1)
static let SeparatorColor = UIColor.clearColor()
static let SeparatorStyle = UITableViewCellSeparatorStyle.None
static let SeparatorInsets = UIEdgeInsetsZero
static let CornerRadius: CGFloat = 0
static let RowHeight: CGFloat = 44
static let HeightPadding: CGFloat = 20
struct Shadow {
static let Color = UIColor.darkGrayColor().CGColor
static let Offset = CGSizeZero
static let Opacity: Float = 0.4
static let Radius: CGFloat = 8
}
}
internal struct Animation {
static let Duration = 0.15
static let EntranceOptions: UIViewAnimationOptions = [.AllowUserInteraction, .CurveEaseOut]
static let ExitOptions: UIViewAnimationOptions = [.AllowUserInteraction, .CurveEaseIn]
static let DownScaleTransform = CGAffineTransformMakeScale(0.9, 0.9)
}
}
|
dd90f0326235c4ce29a427a21e9de9f6
| 22 | 93 | 0.725719 | false | false | false | false |
kfix/MacPin
|
refs/heads/main
|
Sources/MacPinOSX/OmniBoxController.swift
|
gpl-3.0
|
1
|
/// MacPin OmniBoxController
///
/// Controls a textfield that displays a WebViewController's current URL and accepts editing to change loaded URL in WebView
import AppKit
import WebKit
extension WKWebView {
@objc override open func setValue(_ value: Any?, forUndefinedKey key: String) {
if key != "URL" { super.setValue(value, forUndefinedKey: key) } //prevents URLbox from trying to directly rewrite webView.URL
// copy by ref?
}
}
class URLAddressField: NSTextField { // FIXMEios UILabel + UITextField
@objc dynamic var isLoading: Bool = false { didSet { needsDisplay = true } } // cell.needsDisplay = true
@objc dynamic var progress: Double = Double(0.0) { didSet { needsDisplay = true } }
let thickness = CGFloat(3) // progress line thickness
//var baselineOffsetFromBottom: CGFloat { get } // http://www.openradar.me/36672952
//override init(frame frameRect: NSRect) {
// self.super(frame: frameRect)
func viewDidLoad() {
isSelectable = true
isEditable = true
}
override func draw(_ dirtyRect: NSRect) {
var bezel: NSBezierPath = NSBezierPath(roundedRect: NSInsetRect(bounds, 2, 2), xRadius: 5, yRadius: 5)
// approximating the geo of 10.10's .roundedBezel
NSColor.darkGray.set(); bezel.stroke() // draw bezel
bezel.addClip() // constrain further drawing within bezel
if isLoading {
// draw a Safari style progress-line along edge of the text box's focus ring
//var progressRect = NSOffsetRect(bounds, 0, 4) // top edge of bezel
var progressRect = NSOffsetRect(bounds, 0, NSMaxY(bounds) - (thickness + 2)) // bottom edge of bezel
progressRect.size.height = thickness
progressRect.size.width *= progress == 1.0 ? 0 : CGFloat(progress) // only draw line when downloading
//NSColor(calibratedRed:0.0, green: 0.0, blue: 1.0, alpha: 0.4).set() // transparent blue line
// FIXME alpha get overwhelmed when bg/appearance is light
NSColor.systemBlue.set() // matches "Highlight Color: Blue" from SysPrefs:General
progressRect.fill(using: .sourceOver)
} else {
NSColor.clear.setFill() // clear background
bounds.fill(using: .copy) // .clear
}
super.draw(dirtyRect) // draw control's built-in bezel, background (if not a rounded bezel), & text
}
// NSControl
override func validateProposedFirstResponder(_ responder: NSResponder, for event: NSEvent?) -> Bool {
//warn(event?.description ?? "")
//warn(obj: responder)
//warn(obj: event)
return true
}
// NSTextDelegate
//override func textShouldBeginEditing(_ textObject: NSText) -> Bool { warn(); return true } //allow editing
}
/* iOS progbar: http://stackoverflow.com/questions/29410849/unable-to-display-subview-added-to-wkwebview?rq=1
webview?.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
let progressView = UIProgressView(progressViewStyle: .Bar)
progressView.center = view.center
progressView.progress = 20.0/30.0
progressView.trackTintColor = UIColor.lightGrayColor()
progressView.tintColor = UIColor.blueColor()
webview?.addSubview(progressView)
*/
@objc class OmniBoxController: NSViewController {
let urlbox = URLAddressField()
@objc weak var webview: MPWebView? = nil {
didSet { //KVC to copy updates to webviews url & title (user navigations, history.pushState(), window.title=)
if let wv = webview {
view.bind(NSBindingName.toolTip, to: wv, withKeyPath: #keyPath(MPWebView.title), options: nil)
view.bind(NSBindingName.value, to: wv, withKeyPath: #keyPath(MPWebView.url), options: nil)
view.bind(NSBindingName.fontBold, to: wv, withKeyPath: #keyPath(MPWebView.hasOnlySecureContent), options: nil)
// TODO: mimic Safari UX for SSL sites: https://www.globalsign.com/en/blog/how-to-view-ssl-certificate-details/#safari
view.bind(NSBindingName("isLoading"), to: wv, withKeyPath: #keyPath(MPWebView.isLoading), options: nil)
view.bind(NSBindingName("progress"), to: wv, withKeyPath: #keyPath(MPWebView.estimatedProgress), options: nil)
view.nextResponder = wv // passthru uncaptured selectors from omnibox tf to webview
view.nextKeyView = wv
}
}
willSet(newwv) {
if let _ = webview {
// we had one already set, so unwind all its entanglements
view.nextResponder = nil
view.nextKeyView = nil
view.unbind(NSBindingName.toolTip)
view.unbind(NSBindingName.value)
view.unbind(NSBindingName.fontBold)
view.unbind(NSBindingName("progress"))
view.unbind(NSBindingName("isLoading"))
}
}
}
required init?(coder: NSCoder) { super.init(coder: coder) }
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName:nil, bundle:nil) } // calls loadView()
override func loadView() { view = urlbox } // NIBless
func popup(_ webview: MPWebView?) {
guard let webview = webview else { return }
MacPinApp.shared.appDelegate?.browserController.tabSelected = webview // EWW
}
/*
convenience init(webViewController: WebViewController?) {
self.init()
preferredContentSize = CGSize(width: 600, height: 24) //app hangs on view presentation without this!
if let wvc = webViewController { representedObject = wvc }
}
*/
convenience init() {
self.init(nibName:nil, bundle:nil)
preferredContentSize = CGSize(width: 600, height: 24) //app hangs on view presentation without this!
}
override func viewDidLoad() {
super.viewDidLoad()
// prepareForReuse() {...} ?
urlbox.isBezeled = true
urlbox.bezelStyle = .roundedBezel
let appearance = UserDefaults.standard.string(forKey: "AppleInterfaceStyle") ?? "Light"
if appearance == "Dark" {
urlbox.textColor = NSColor.labelColor
// BUG: 10.11 dark-dock + high-constrast mode set a black textColor on a black-menu-bar-bg
}
urlbox.toolTip = ""
urlbox.maximumNumberOfLines = 1
urlbox.importsGraphics = false
urlbox.allowsEditingTextAttributes = false
//urlbox.menu = NSMenu //ctrl-click context menu
// search with DuckDuckGo
// go to URL
// js: addOmniBoxActionHandler('send to app',handleCustomOmniAction)
// tab menu?
urlbox.delegate = self
if let cell = urlbox.cell as? NSTextFieldCell {
cell.placeholderString = "Navigate to URL"
cell.isScrollable = true
cell.action = #selector(OmniBoxController.userEnteredURL)
cell.target = self
cell.sendsActionOnEndEditing = false //only send action when Return is pressed
cell.usesSingleLineMode = true
cell.focusRingType = .none
//cell.currentEditor()?.delegate = self // do live validation of input URL before Enter is pressed
}
// should have a grid of all tabs below the urlbox, safari style. NSCollectionView?
// https://developer.apple.com/library/mac/samplecode/GridMenu/Listings/ReadMe_txt.html#//apple_ref/doc/uid/DTS40010559-ReadMe_txt-DontLinkElementID_14
// or just show a segmented tabcontrol if clicking in the urlbox?
}
override func viewWillAppear() {
super.viewWillAppear()
}
override func viewDidAppear() {
super.viewDidAppear()
}
@objc func userEnteredURL() {
if let tf = view as? NSTextField, let url = validateURL(tf.stringValue, fallback: { [unowned self] (urlstr: String) -> URL? in
if AppScriptRuntime.shared.anyHandled(.handleUserInputtedInvalidURL, urlstr as NSString, self.webview!) { return nil } // app.js did its own thing
if AppScriptRuntime.shared.anyHandled(.handleUserInputtedKeywords, urlstr as NSString, self.webview!) { return nil } // app.js did its own thing
//FIXME: it should be able to return URL<->NSURL
return searchForKeywords(urlstr)
}){
if let wv = webview { // FIXME: Selector(gotoURL:) to nextResponder
wv.notifier?.authorizeNotifications(fromOrigin: url) // user typed this address in so they "trust" it to not be spammy?
view.window?.makeFirstResponder(wv) // no effect if this vc was brought up as a modal sheet
warn(url.description)
wv.gotoURL(url)
cancelOperation(self)
} else if let parent = parent { // tab-less browser window ...
parent.addChild(WebViewControllerOSX(webview: MPWebView(url: url))) // is parentVC the toolbar or contentView VC??
} else if let presenter = presentingViewController { // urlbox is a popover/sheet ...
presenter.addChild(WebViewControllerOSX(webview: MPWebView(url: url)))
// need parent of the presenter?
} else {
warn("no webviews-tabs and no parentVC ... WTF!!")
if let win = view.window {
// win.performSelector(onMainThread: #selector(BrowserViewControllerOSX.newTabPrompt), with: nil, waitUntilDone: false, modes: nil)
// win's responderChain is useless ...
}
}
} else {
warn("invalid url was requested!")
//displayAlert
//NSBeep()
}
}
override func cancelOperation(_ sender: Any?) {
warn()
view.resignFirstResponder() // relinquish key focus to webview
presentingViewController?.dismiss(self) //if a thoust art a popover, close thyself
}
deinit { webview = nil; representedObject = nil }
}
extension OmniBoxController: NSTextFieldDelegate { //NSControl
//func controlTextDidBeginEditing(_ obj: NSNotification)
//func controlTextDidChange(_ obj: NSNotification)
//func controlTextDidEndEditing(_ obj: NSNotification)
}
/*
replace textvalue with URL value, might be bound to title
"smart search" behavior:
if url was a common search provider query...
duckduckgo.com/?q=...
www.google.com/search?q=...
then extract the first query param, decode, and set the text value to that
*/
/*
//func textDidChange(aNotification: NSNotification)
@objc func textShouldEndEditing(_ textObject: NSText) -> Bool { //user attempting to focus out of field
if let _ = validateURL(textObject.string) { return true } //allow focusout
warn("invalid url entered: \(textObject.string)")
return false //NSBeep()s, keeps focus
}
//func textDidEndEditing(aNotification: NSNotification) { }
*/
@objc extension OmniBoxController: NSControlTextEditingDelegate {
//func control(_ control: NSControl, isValidObject obj: AnyObject) -> Bool
//func control(_ control: NSControl, didFailToFormatString string: String, errorDescription error: String?) -> Bool
func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool { warn(); return true }
//func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool
//func control(_ control: NSControl, textView textView: NSTextView, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer<Int>) -> [String]
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
warn(commandSelector.description)
switch commandSelector {
case "noop:":
if let event = Application.shared.currentEvent, event.modifierFlags.contains(.command) {
guard let url = validateURL(control.stringValue) else { return false }
popup(webview?.wkclone(.URL(url))) // cmd-enter pops open a new tab
}
fallthrough
//case "insertLineBreak:":
// .ShiftKeyMask gotoURL privately (Safari opens new window with Shift)
// .AltKeyMask // gotoURL w/ new session privately (Safari downloads with Alt
// when Selector("insertTab:"):
// scrollToBeginningOfDocument: scrollToEndOfDocument:
default: return false
}
}
}
extension OmniBoxController: NSPopoverDelegate {
func popoverWillShow(_ notification: Notification) {
//urlbox.sizeToFit() //fixme: makes the box undersized sometimes
}
}
|
b7c9eafea5494468987a68771bd60840
| 40.810219 | 202 | 0.72486 | false | false | false | false |
buscarini/miscel
|
refs/heads/master
|
Miscel/Classes/Extensions/String.swift
|
mit
|
1
|
//
// String.swift
// Miscel
//
// Created by Jose Manuel Sánchez Peñarroja on 11/11/15.
// Copyright © 2015 vitaminew. All rights reserved.
//
import UIKit
public extension String {
public static func length(_ string: String) -> Int {
return string.characters.count
}
public static func empty(_ string: String) -> Bool {
return self.length(string) == 0
}
public static func isBlank(_ string: String?) -> Bool {
guard let string = string else { return true }
return trimmed(string).characters.count == 0
}
public static func trimmed(_ string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
public static func joined(_ components: [String?], separator: String = "\n") -> String {
return components.flatMap {$0}
.filter(not(isBlank))
.joined(separator: separator)
}
public static func plainString(_ htmlString: String) -> String {
return htmlString.withBRsAsNewLines().convertingHTMLToPlainText()
}
public static func localize(_ string: String) -> String {
return string.localized()
}
public func localized() -> String {
return NSLocalizedString(self, comment: "")
}
public static func wholeRange(_ string: String) -> Range<Index> {
return string.characters.startIndex..<string.characters.endIndex
}
public static func words(_ string: String) -> [String] {
var results : [String] = []
string.enumerateLinguisticTags(in: self.wholeRange(string), scheme: NSLinguisticTagScheme.lemma.rawValue, options: [], orthography: nil) {
// string.enumerateLinguisticTagsInRange(self.wholeRange(string), scheme: NSLinguisticTagWord, options: [], orthography: nil) {
(tag, tokenRange, sentenceRange,_) in
results.append(String(string[tokenRange]))
// results.append(string.substring(with: tokenRange))
// results.append(string.substringWithRange(tokenRange))
}
return results
}
}
|
c5728492cdbce5f41aaab720c768a0b4
| 26.855072 | 140 | 0.708117 | false | false | false | false |
futureinapps/FIADatePickerDialog
|
refs/heads/master
|
FIADatePickerDialog/UIButton+FIADatePickerDialog.swift
|
mit
|
1
|
//
// UIButton+FIAButton.swift
// FIADatePickerDialog
//
// Created by Айрат Галиуллин on 14.12.16.
// Copyright © 2016 Fucher in Apps OOO. All rights reserved.
//
import UIKit
fileprivate var rawPointer: UInt8 = 0
fileprivate var rawPointer_Bool: UInt8 = 1
protocol FIADatePickerDialogActionDelegate {
func submit()
func cancel()
}
extension UIButton {
var delegate:FIADatePickerDialogActionDelegate?{
set{
objc_setAssociatedObject(self, &rawPointer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
get{
return objc_getAssociatedObject(self, &rawPointer) as? FIADatePickerDialogActionDelegate
}
}
var isDatePickerAction:Bool?{
set{
objc_setAssociatedObject(self, &rawPointer_Bool, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
get{
return objc_getAssociatedObject(self, &rawPointer_Bool) as? Bool
}
}
private var defaultBGRColor:UIColor?{
set{
objc_setAssociatedObject(self, &rawPointer_Bool, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
get{
return objc_getAssociatedObject(self, &rawPointer_Bool) as? UIColor
}
}
func submit(_ sender:UIButton!){
guard delegate != nil else {
fatalError("DatePickerDialogActions delegate should not be nil")
}
delegate?.submit()
}
func cancel(_ sender:UIButton!){
guard delegate != nil else {
fatalError("DatePickerDialogActions delegate should not be nil")
}
delegate?.cancel()
}
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if isDatePickerAction != nil && isDatePickerAction! {
backgroundColor = UIColor.hexStringToUIColor(hex: "222222",alpha:0.3)
}
return true
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
if isDatePickerAction != nil && isDatePickerAction! {
backgroundColor = UIColor.clear
}
}
}
|
306c1797bfb3b404e915129a21dbea53
| 28.479452 | 118 | 0.6329 | false | false | false | false |
900116/GodEyeClear
|
refs/heads/master
|
Classes/Extension/UI/UIScreen+GodEye.swift
|
mit
|
3
|
//
// UIScreen+GodEye.swift
// Pods
//
// Created by zixun on 16/12/27.
//
//
import Foundation
extension UIScreen {
class func onscreenFrame() -> CGRect {
return self.main.applicationFrame
}
class func offscreenFrame() -> CGRect {
var frame = self.onscreenFrame()
switch UIApplication.shared.statusBarOrientation {
case .portraitUpsideDown:
frame.origin.y = -frame.size.height
case .landscapeLeft:
frame.origin.x = frame.size.width
case .landscapeRight:
frame.origin.x = -frame.size.width;
default:
frame.origin.y = frame.size.height
}
return frame
}
}
|
3e1f0bdc7947573bb37c8a830a91dd0c
| 22.333333 | 58 | 0.594286 | false | false | false | false |
Parallaxer/PhotoBook
|
refs/heads/master
|
Sources/Views/InfinitePageView/InfinitePageView.swift
|
mit
|
1
|
import Parallaxer
import RxCocoa
import RxSwift
import UIKit
//------------------------------------------------------------------------------------------------------------
// Number of pages: 1
// Number of waypoints: 1 (min/max)
// 0
//(a)
// a
// X <- Left edge interval: [nil]
// X <- Wrapping interval: [nil]
// X <- Right edge interval: [nil]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 2
// Number of waypoints: 1
// 0 1
//(a)
// (a)
// [ ] <- Left edge interval: [0,1]
// X <- Wrapping interval: [nil]
// X <- Right edge interval: [nil]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 2
// Number of waypoints: 2 (min/max)
// 0 1
//(a)b
// a(b)
// [ ] <- Left edge interval: [0,1]
// X <- Wrapping interval: [nil]
// X <- Right edge interval: [nil]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 3
// Number of waypoints: 3 (min/max)
// 0 1 2
//(a)b c
// a(b)c
// a b(c)
// [ ] <- Left edge interval: [0,1]
// X <- Wrapping interval: [nil]
// [ ] <- Right edge interval: [1,2]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 4
// Number of waypoints: 3 (min)
// 0 1 2 3
//(a)b c
// a(b)c
// b(c)a
// [ ] <- Left edge interval: [0,1]
// [ ] <- Wrapping interval: [1,2]
// [ ] <- Right edge interval: [2,3]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 5
// Number of waypoints: 3 (min)
// 0 1 2 3 4
//(a)b c
// a(b)c
// . b(c)a
// . . c(a)b
// c a(b)
// [ ] <- Left edge interval: [0,1]
// [ ] <- Wrapping interval: [1,3]
// [ ] <- Right edge interval: [3,4]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 5
// Number of waypoints: 4
// 0 1 2 3 4
//(a)b c d
// a(b)c d
// a b(c)d
// . b c(d)a
// b c d(a)
// [ ] <- Left edge interval: [0,2]
// [ ] <- Wrapping interval: [2,3]
// [ ] <- Right edge interval: [3,4]
//------------------------------------------------------------------------------------------------------------
// Number of pages: 5
// Number of waypoints: 5 (max)
// 0 1 2 3 4
//(a)b c d e
// a(b)c d e
// a b(c)d e
// a b c(d)e
// a b c d(e)
// [ ] <- Left edge interval: [0,2]
// X <- Wrapping interval: [nil]
// [ ] <- Right edge interval: [2,4]
/// Used for the "cursor" and "waypoint" views in an `InfinitePageView`.
final class CircleView: UIView {
/// The circle's scale transform.
var scaleTransform: CGAffineTransform = .identity {
didSet { updateTransform() }
}
/// The circle's translation transform.
var translationTransform: CGAffineTransform = .identity {
didSet { updateTransform() }
}
private func updateTransform() {
transform = scaleTransform.concatenating(translationTransform)
}
}
@IBDesignable
public final class InfinitePageView: UIView {
// The total number of pages the view can represent. Set this equal to the number of pages in your table
// view or collection view.
@IBInspectable
public var numberOfPages: Int {
get { numberOfPagesRelay.value }
set {
numberOfPagesRelay.accept(newValue)
buildUI()
}
}
/// The maximum number of waypoints shown in the view at one time. For best results, use an odd number
/// so that the middle waypoint is rendered at the center of the view.
@IBInspectable
public var maxNumberOfWaypoints: Int {
get { maxNumberOfWaypointsRelay.value }
set {
maxNumberOfWaypointsRelay.accept(newValue)
buildUI()
}
}
private(set) var waypointViews: [CircleView] = []
private(set) weak var cursorView: CircleView?
/// The current cursor position.
var cursorPosition: CGFloat = 0 {
didSet {
let translation = CGAffineTransform(translationX: cursorPosition, y: 0)
cursorView?.translationTransform = translation
}
}
/// The current cursor size.
var cursorScale: CGFloat = 1 {
didSet {
let scale = CGAffineTransform(scaleX: cursorScale, y: cursorScale)
cursorView?.scaleTransform = scale
}
}
private let numberOfPagesRelay = BehaviorRelay<Int>(value: 0)
private let maxNumberOfWaypointsRelay = BehaviorRelay<Int>(value: 5)
private lazy var numberOfWaypoints: Observable<Int> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
maxNumberOfWaypointsRelay.asObservable())
.map { numberOfPages, maxNumberOfWaypoints in
return InfinitePageView.numberOfWaypoints(
numberOfPages: numberOfPages,
maxNumberOfWaypoints: maxNumberOfWaypoints)
}
private lazy var fullPageInterval: Observable<ParallaxInterval<CGFloat>?> = numberOfPagesRelay
.asObservable()
.map { numberOfPages in
let lastPageIndex = CGFloat(numberOfPages - 1)
return try ParallaxInterval<CGFloat>(from: 0, to: lastPageIndex)
}
.share(replay: 1)
/// The left edge interval starts at the first page index and extends to the center waypoint index.
///
/// The left edge interval may be `nil` in the following cases:
/// - The number of pages is 1 or less. (The center page index and the first page index are equal.)
private lazy var leftEdgeInterval: Observable<ParallaxInterval<CGFloat>?> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
numberOfWaypoints)
.map { numberOfPages, numberOfWaypoints -> ParallaxInterval<CGFloat>? in
let firstPageIndex = CGFloat(0)
let centerPageIndex =
CGFloat(InfinitePageView.indexOfCenterWaypoint(numberOfWaypoints: numberOfWaypoints))
return try ParallaxInterval<CGFloat>(from: firstPageIndex, to: centerPageIndex)
}
.share(replay: 1)
/// The wrapping interval starts where the left edge interval stopped and extends over the number of
/// wrapped indices (the difference between the number of pages and the number of waypoints.)
///
/// The wrapping interval may be `nil` in the following cases:
/// - The left edge interval is `nil`.
/// - The number of wrapped indices is 0. (The number of pages and the number of waypoints are equal.)
private lazy var wrappingInterval: Observable<ParallaxInterval<CGFloat>?> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
numberOfWaypoints,
leftEdgeInterval)
.map { numberOfPages, numberOfWaypoints, leftEdgeInterval -> ParallaxInterval<CGFloat>? in
guard let leftEdgeInterval = leftEdgeInterval else {
return nil
}
let numberOfWrappedIndices = CGFloat(numberOfPages - numberOfWaypoints)
return try ParallaxInterval<CGFloat>(
from: leftEdgeInterval.to,
to: leftEdgeInterval.to + numberOfWrappedIndices)
}
.share(replay: 1)
/// The right edge interval starts where either the wrapping interval or the left edge interval stopped
/// and extends to the last page index.
///
/// The right edge interval may be `nil` in the following cases:
/// - The left edge interval is `nil`.
/// - The left edge interval extends to the last page index.
private lazy var rightEdgeInterval: Observable<ParallaxInterval<CGFloat>?> = Observable
.combineLatest(
numberOfPagesRelay.asObservable(),
leftEdgeInterval,
wrappingInterval)
.map { numberOfPages, leftEdgeInterval, wrappingInterval -> ParallaxInterval<CGFloat>? in
guard let leftEdgeInterval = leftEdgeInterval else {
return nil
}
let lastPageIndex = CGFloat(numberOfPages - 1)
return try ParallaxInterval<CGFloat>(
from: wrappingInterval?.to ?? leftEdgeInterval.to,
to: lastPageIndex)
}
.share(replay: 1)
public override func awakeFromNib() {
super.awakeFromNib()
buildUI()
}
public override func layoutSubviews() {
super.layoutSubviews()
let circleRadius = waypointRadius
guard circleRadius.isFinite else {
return
}
let circleDiameter = 2 * circleRadius
let circleSize = CGSize(width: circleDiameter, height: circleDiameter)
let midY = bounds.midY
waypointViews.enumerated().forEach { i, circleView in
let waypointPosition = InfinitePageView.positionForWaypoint(at: i, radius: circleRadius)
circleView.center = CGPoint(x: waypointPosition, y: midY)
circleView.bounds.size = circleSize
circleView.bounds = circleView.bounds.integral
circleView.layer.cornerRadius = circleRadius
}
let cursorPosition = InfinitePageView.positionForWaypoint(at: 0, radius: circleRadius)
cursorView?.center = CGPoint(x: cursorPosition, y: midY)
cursorView?.bounds.size = circleSize
if let bounds = cursorView?.bounds.integral {
cursorView?.bounds = bounds
}
cursorView?.layer.cornerRadius = circleRadius
}
private func buildUI() {
cursorView?.removeFromSuperview()
waypointViews.forEach { $0.removeFromSuperview() }
waypointViews = (0 ..< numberOfWaypointsValue).map { _ in
InfinitePageView.createCircleView(isWaypoint: true)
}
waypointViews.forEach(addSubview)
let cursorView = InfinitePageView.createCircleView(isWaypoint: false)
addSubview(cursorView)
bringSubviewToFront(cursorView)
self.cursorView = cursorView
// Force immediate layout.
setNeedsLayout()
layoutIfNeeded()
}
private static func createCircleView(isWaypoint: Bool) -> CircleView {
let circleView = CircleView()
circleView.backgroundColor = isWaypoint ? UIColor.init(white: 1, alpha: 0.5) : UIColor.white
return circleView
}
}
extension InfinitePageView {
/// Bind the scrolling transform to the page view, allowing changes to the scrolling transform to drive
/// changes to state in the page view.
/// - Parameter scrollingTransform: The scrolling transform which should drive state changes in the page
/// view.
func bindScrollingTransform(_ scrollingTransform: Observable<ParallaxTransform<CGFloat>>) -> Disposable {
let leftEdgeTransform = self.leftEdgeTransform(from: scrollingTransform)
let rightEdgeTransform = self.rightEdgeTransform(from: scrollingTransform)
let wrappingTransform = self.wrappingTransform(from: scrollingTransform)
return Disposables.create([
bindCursorEffect(
with: scrollingTransform,
leftEdgeTransform: leftEdgeTransform,
rightEdgeTransform: rightEdgeTransform),
bindWrappingEffect(
with: scrollingTransform,
wrappingInterval: wrappingInterval,
wrappingTransform: wrappingTransform),
bindWaypointEffect(with: scrollingTransform)
])
}
private func leftEdgeTransform(
from scrollingTransform: Observable<ParallaxTransform<CGFloat>>)
-> Observable<ParallaxTransform<CGFloat>>
{
return scrollingTransform
.parallaxRelate(to: fullPageInterval.skipNil())
.parallaxFocus(on: leftEdgeInterval.skipNil())
.parallaxMorph(with: .just(.clampToUnitInterval))
}
private func wrappingTransform(
from scrollingTransform: Observable<ParallaxTransform<CGFloat>>)
-> Observable<ParallaxTransform<CGFloat>>
{
return scrollingTransform
.parallaxRelate(to: fullPageInterval.skipNil())
.parallaxFocus(on: wrappingInterval.skipNil())
.parallaxMorph(with: .just(.clampToUnitInterval))
}
private func rightEdgeTransform(
from scrollingTransform: Observable<ParallaxTransform<CGFloat>>)
-> Observable<ParallaxTransform<CGFloat>>
{
return scrollingTransform
.parallaxRelate(to: fullPageInterval.skipNil())
.parallaxFocus(on: rightEdgeInterval.skipNil())
.parallaxMorph(with: .just(.clampToUnitInterval))
}
}
extension InfinitePageView {
var waypointRadius: CGFloat {
let diameter = floor(bounds.width / CGFloat(numberOfWaypointsValue))
return floor(diameter / 2)
}
var numberOfWaypointsValue: Int {
return InfinitePageView.numberOfWaypoints(
numberOfPages: numberOfPagesRelay.value,
maxNumberOfWaypoints: maxNumberOfWaypointsRelay.value)
}
}
extension InfinitePageView {
var firstWaypointPosition: CGFloat {
let firstIndex = 0
return InfinitePageView.positionForWaypoint(at: firstIndex, radius: waypointRadius)
}
var centerWaypointPosition: CGFloat {
let centerIndex = InfinitePageView.indexOfCenterWaypoint(numberOfWaypoints: numberOfWaypointsValue)
return InfinitePageView.positionForWaypoint(at: centerIndex, radius: waypointRadius)
}
var lastWaypointPosition: CGFloat {
let lastIndex = numberOfWaypointsValue - 1
return InfinitePageView.positionForWaypoint(at: lastIndex, radius: waypointRadius)
}
static func numberOfWaypoints(numberOfPages: Int, maxNumberOfWaypoints: Int) -> Int {
return min(numberOfPages, maxNumberOfWaypoints)
}
private static func indexOfCenterWaypoint(numberOfWaypoints: Int) -> Int {
return numberOfWaypoints / 2
}
static func positionForWaypoint(at index: Int, radius: CGFloat) -> CGFloat {
let diameter = 2 * radius
return radius + (CGFloat(index) * (diameter))
}
}
|
715c2b9e89cb8cffe86c8b5735405304
| 35.952381 | 110 | 0.586679 | false | false | false | false |
IBM-Swift/Kitura
|
refs/heads/master
|
Sources/Kitura/staticFileServer/FileServer.swift
|
apache-2.0
|
1
|
/*
* Copyright IBM Corporation 2016
*
* 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 LoggerAPI
import Foundation
extension StaticFileServer {
// MARK: FileServer
class FileServer {
/// Serve "index.html" files in response to a request on a directory.
private let serveIndexForDirectory: Bool
/// Redirect to trailing "/" when the pathname is a dir.
private let redirect: Bool
/// the path from where the files are served
private let servingFilesPath: String
/// If a file is not found, the given extensions will be added to the file name and searched for.
/// The first that exists will be served.
private let possibleExtensions: [String]
/// A setter for response headers.
private let responseHeadersSetter: ResponseHeadersSetter?
/// Whether accepts range requests or not
let acceptRanges: Bool
/// A default index to be served if the requested path is not found.
/// This is intended to be used by single page applications.
let defaultIndex: String?
init(servingFilesPath: String, options: StaticFileServer.Options,
responseHeadersSetter: ResponseHeadersSetter?) {
self.possibleExtensions = options.possibleExtensions
self.serveIndexForDirectory = options.serveIndexForDirectory
self.redirect = options.redirect
self.acceptRanges = options.acceptRanges
self.servingFilesPath = servingFilesPath
self.responseHeadersSetter = responseHeadersSetter
self.defaultIndex = options.defaultIndex
}
func getFilePath(from request: RouterRequest) -> String? {
var filePath = servingFilesPath
guard let requestPath = request.parsedURLPath.path else {
return nil
}
var matchedPath = request.matchedPath
if matchedPath.hasSuffix("*") {
matchedPath = String(matchedPath.dropLast())
}
if !matchedPath.hasSuffix("/") {
matchedPath += "/"
}
if requestPath.hasPrefix(matchedPath) {
filePath += "/"
let url = String(requestPath.dropFirst(matchedPath.count))
if let decodedURL = url.removingPercentEncoding {
filePath += decodedURL
} else {
Log.warning("unable to decode url \(url)")
filePath += url
}
}
if filePath.hasSuffix("/") {
if serveIndexForDirectory {
filePath += "index.html"
} else {
return nil
}
}
return filePath
}
func serveFile(_ filePath: String, requestPath: String, queryString: String, response: RouterResponse) {
let fileManager = FileManager()
var isDirectory = ObjCBool(false)
if fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory) {
#if !os(Linux) || swift(>=4.1)
let isDirectoryBool = isDirectory.boolValue
#else
let isDirectoryBool = isDirectory
#endif
serveExistingFile(filePath, requestPath: requestPath, queryString: queryString,
isDirectory: isDirectoryBool, response: response)
return
}
if tryToServeWithExtensions(filePath, response: response) {
return
}
// We haven't been able to find the requested path. For single page applications,
// a default fallback index may be configured. Before we serve the default index
// we make sure that this is a not a direct file request. The best check we could
// run for that is if the requested file contains a '.'. This is inspired by:
// https://github.com/bripkens/connect-history-api-fallback
let isDirectFileAccess = filePath.split(separator: "/").last?.contains(".") ?? false
if isDirectFileAccess == false, let defaultIndex = self.defaultIndex {
serveDefaultIndex(defaultIndex: defaultIndex, response: response)
}
}
fileprivate func serveDefaultIndex(defaultIndex: String, response: RouterResponse) {
do {
try response.send(fileName: servingFilesPath + defaultIndex)
} catch {
response.error = Error.failedToRedirectRequest(path: servingFilesPath + "/", chainedError: error)
}
}
private func tryToServeWithExtensions(_ filePath: String, response: RouterResponse) -> Bool {
var served = false
let filePathWithPossibleExtensions = possibleExtensions.map { filePath + "." + $0 }
for filePathWithExtension in filePathWithPossibleExtensions {
served = served || serveIfNonDirectoryFile(atPath: filePathWithExtension, response: response)
}
return served
}
private func serveExistingFile(_ filePath: String, requestPath: String, queryString: String,
isDirectory: Bool, response: RouterResponse) {
if isDirectory {
if redirect {
do {
try response.redirect(requestPath + "/" + queryString)
} catch {
response.error = Error.failedToRedirectRequest(path: requestPath + "/", chainedError: error)
}
}
} else {
serveNonDirectoryFile(filePath, response: response)
}
}
@discardableResult
private func serveIfNonDirectoryFile(atPath path: String, response: RouterResponse) -> Bool {
var isDirectory = ObjCBool(false)
if FileManager().fileExists(atPath: path, isDirectory: &isDirectory) {
#if !os(Linux) || swift(>=4.1)
let isDirectoryBool = isDirectory.boolValue
#else
let isDirectoryBool = isDirectory
#endif
if !isDirectoryBool {
serveNonDirectoryFile(path, response: response)
return true
}
}
return false
}
private func serveNonDirectoryFile(_ filePath: String, response: RouterResponse) {
if !isValidFilePath(filePath) {
return
}
do {
let fileAttributes = try FileManager().attributesOfItem(atPath: filePath)
// At this point only GET or HEAD are expected
let request = response.request
let method = request.serverRequest.method
response.headers["Accept-Ranges"] = acceptRanges ? "bytes" : "none"
responseHeadersSetter?.setCustomResponseHeaders(response: response,
filePath: filePath,
fileAttributes: fileAttributes)
// Check headers to see if it is a Range request
if acceptRanges,
method == "GET", // As per RFC, Only GET request can be Range Request
let rangeHeader = request.headers["Range"],
RangeHeader.isBytesRangeHeader(rangeHeader),
let fileSize = (fileAttributes[FileAttributeKey.size] as? NSNumber)?.uint64Value {
// At this point it looks like the client requested a Range Request
if let rangeHeaderValue = try? RangeHeader.parse(size: fileSize, headerValue: rangeHeader),
rangeHeaderValue.type == "bytes",
!rangeHeaderValue.ranges.isEmpty {
// At this point range is valid and server is able to serve it
if ifRangeHeaderShouldPreventPartialReponse(requestHeaders: request.headers, fileAttributes: fileAttributes) {
// If-Range header prevented a partial response. Send the entire file
try response.send(fileName: filePath)
response.statusCode = .OK
} else {
// Send a partial response
serveNonDirectoryPartialFile(filePath, fileSize: fileSize, ranges: rangeHeaderValue.ranges, response: response)
}
} else {
// Send not satisfiable response
serveNotSatisfiable(filePath, fileSize: fileSize, response: response)
}
} else {
// Regular request OR Syntactically invalid range request OR fileSize was not available
if method == "HEAD" {
// Send only headers
_ = response.send(status: .OK)
} else {
if let etag = request.headers["If-None-Match"],
etag == CacheRelatedHeadersSetter.calculateETag(from: fileAttributes) {
response.statusCode = .notModified
} else {
// Send the entire file
try response.send(fileName: filePath)
response.statusCode = .OK
}
}
}
} catch {
Log.error("serving file at path \(filePath), error: \(error)")
}
}
private func isValidFilePath(_ filePath: String) -> Bool {
guard let absoluteBasePath = NSURL(fileURLWithPath: servingFilesPath).standardizingPath?.absoluteString,
let standardisedPath = NSURL(fileURLWithPath: filePath).standardizingPath?.absoluteString else {
return false
}
return standardisedPath.hasPrefix(absoluteBasePath)
}
private func serveNotSatisfiable(_ filePath: String, fileSize: UInt64, response: RouterResponse) {
response.headers["Content-Range"] = "bytes */\(fileSize)"
_ = response.send(status: .requestedRangeNotSatisfiable)
}
private func serveNonDirectoryPartialFile(_ filePath: String, fileSize: UInt64, ranges: [Range<UInt64>], response: RouterResponse) {
let contentType = ContentType.sharedInstance.getContentType(forFileName: filePath)
if ranges.count == 1 {
let data = FileServer.read(contentsOfFile: filePath, inRange: ranges[0])
// Send a single part response
response.headers["Content-Type"] = contentType
response.headers["Content-Range"] = "bytes \(ranges[0].lowerBound)-\(ranges[0].upperBound)/\(fileSize)"
response.send(data: data ?? Data())
response.statusCode = .partialContent
} else {
// Send multi part response
let boundary = "KituraBoundary\(UUID().uuidString)" // Maybe a better boundary can be calculated in the future
response.headers["Content-Type"] = "multipart/byteranges; boundary=\(boundary)"
var data = Data()
ranges.forEach { range in
let fileData = FileServer.read(contentsOfFile: filePath, inRange: range) ?? Data()
var partHeader = "--\(boundary)\r\n"
partHeader += "Content-Range: bytes \(range.lowerBound)-\(range.upperBound)/\(fileSize)\r\n"
partHeader += (contentType == nil ? "" : "Content-Type: \(contentType!)\r\n")
partHeader += "\r\n"
data.append(Data(partHeader.utf8))
data.append(fileData)
data.append(Data("\r\n".utf8))
}
data.append(Data("--\(boundary)--".utf8))
response.send(data: data)
response.statusCode = .partialContent
}
}
private func ifRangeHeaderShouldPreventPartialReponse(requestHeaders headers: Headers, fileAttributes: [FileAttributeKey : Any]) -> Bool {
// If-Range is optional
guard let ifRange = headers["If-Range"], !ifRange.isEmpty else {
return false
}
// If-Range can be one of two values: ETag or Last-Modified but not both.
// If-Range as ETag
if (ifRange.contains("\"")) {
if let etag = CacheRelatedHeadersSetter.calculateETag(from: fileAttributes),
!etag.isEmpty,
ifRange.contains(etag) {
return false
}
return true
}
// If-Range as Last-Modified
if let ifRangeLastModified = FileServer.date(from: ifRange),
let lastModified = fileAttributes[FileAttributeKey.modificationDate] as? Date,
floor(lastModified.timeIntervalSince1970) > floor(ifRangeLastModified.timeIntervalSince1970) {
return true
}
return false
}
/// Helper function to convert http date Strings into Date
static func date(from httpDate: String) -> Date? {
let df = DateFormatter()
df.dateFormat = "EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz"
return df.date(from:httpDate)
}
/// Helper function to read bytes (of a given range) of a file into data
static func read(contentsOfFile filePath: String, inRange range: Range<UInt64>) -> Data? {
let file = FileHandle(forReadingAtPath: filePath)
file?.seek(toFileOffset: range.lowerBound)
// range is inclusive to make sure to increate upper bound by 1
let data = file?.readData(ofLength: range.count + 1)
file?.closeFile()
return data
}
}
}
|
73a0d59d8a5611ac0adfee37102c20e6
| 45.591195 | 146 | 0.560813 | false | false | false | false |
chenchangqing/CQTextField
|
refs/heads/master
|
Pod/Classes/CQPasswordTextField.swift
|
mit
|
1
|
//
// CQPasswordTextField.swift
// Pods
//
// Created by green on 15/12/17.
//
//
import UIKit
@IBDesignable public class CQPasswordTextField: CQCutLineTextField {
// 密码可见按钮
private let eyeButton = UIButton()
// 密码可见按钮选中颜色
@IBInspectable dynamic var eyeImageColor:UIColor = UIColor.magenta {
didSet {
updateOpenEyeImage()
}
}
// 闭眼图片
@IBInspectable dynamic var closeEyeImage:UIImage? {
didSet {
updateCloseEyeImage()
}
}
// 睁眼图片
@IBInspectable dynamic var eyeImage:UIImage? {
didSet {
updateOpenEyeImage()
}
}
override public func draw(_ rect: CGRect) {
super.draw(rect)
eyeButton.frame = rightView.bounds
rightView.addSubview(eyeButton)
eyeButton.addTarget(self, action: #selector(CQPasswordTextField.eyeButtonClicked(_:)), for: .touchUpInside)
// 文本框
textField.isSecureTextEntry = true
}
func eyeButtonClicked(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
textField.isSecureTextEntry = false
} else {
textField.isSecureTextEntry = true
}
}
func updateOpenEyeImage() {
if let eyeImage = eyeImage {
eyeButton.tintColor = eyeImageColor
let tempImage = scaleImage(eyeImage, toScale: 0.5).withRenderingMode(.alwaysTemplate)
eyeButton.setImage(tempImage, for: .selected)
}
}
func updateCloseEyeImage() {
if let closeEyeImage = closeEyeImage {
let tempImage = scaleImage(closeEyeImage, toScale: 0.5)
eyeButton.setImage(tempImage, for: UIControlState())
}
}
}
|
681738248b0d1e91da1c8b4bf6654de7
| 23.487179 | 115 | 0.563351 | false | false | false | false |
jpsim/Yams
|
refs/heads/main
|
Sources/Yams/Tag.swift
|
mit
|
1
|
//
// Tag.swift
// Yams
//
// Created by Norio Nomura on 12/15/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
/// Tags describe the the _type_ of a Node.
public final class Tag {
/// Tag name.
public struct Name: RawRepresentable, Hashable {
/// This `Tag.Name`'s raw string value.
public let rawValue: String
/// Create a `Tag.Name` with a raw string value.
public init(rawValue: String) {
self.rawValue = rawValue
}
}
/// Shorthand accessor for `Tag(.implicit)`.
public static var implicit: Tag {
return Tag(.implicit)
}
/// Create a `Tag` with the specified name, resolver and constructor.
///
/// - parameter name: Tag name.
/// - parameter resolver: `Resolver` this tag should use, `.default` if omitted.
/// - parameter constructor: `Constructor` this tag should use, `.default` if omitted.
public init(_ name: Name,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default) {
self.resolver = resolver
self.constructor = constructor
self.name = name
}
/// Lens returning a copy of the current `Tag` with the specified overridden changes.
///
/// - note: Omitting or passing nil for a parameter will preserve the current `Tag`'s value in the copy.
///
/// - parameter name: Overridden tag name.
/// - parameter resolver: Overridden resolver.
/// - parameter constructor: Overridden constructor.
///
/// - returns: A copy of the current `Tag` with the specified overridden changes.
public func copy(with name: Name? = nil, resolver: Resolver? = nil, constructor: Constructor? = nil) -> Tag {
return .init(name ?? self.name, resolver ?? self.resolver, constructor ?? self.constructor)
}
// internal
let constructor: Constructor
var name: Name
fileprivate func resolved<T>(with value: T) -> Tag where T: TagResolvable {
if name == .implicit {
name = resolver.resolveTag(of: value)
} else if name == .nonSpecific {
name = T.defaultTagName
}
return self
}
// private
private let resolver: Resolver
}
extension Tag: CustomStringConvertible {
/// A textual representation of this tag.
public var description: String {
return name.rawValue
}
}
extension Tag: Hashable {
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
/// :nodoc:
public static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.name == rhs.name
}
}
extension Tag.Name: ExpressibleByStringLiteral {
/// :nodoc:
public init(stringLiteral value: String) {
self.rawValue = value
}
}
// http://www.yaml.org/spec/1.2/spec.html#Schema
extension Tag.Name {
// Special
/// Tag should be resolved by value.
public static let implicit: Tag.Name = ""
/// Tag should not be resolved by value, and be resolved as .str, .seq or .map.
public static let nonSpecific: Tag.Name = "!"
// Failsafe Schema
/// "tag:yaml.org,2002:str" <http://yaml.org/type/str.html>
public static let str: Tag.Name = "tag:yaml.org,2002:str"
/// "tag:yaml.org,2002:seq" <http://yaml.org/type/seq.html>
public static let seq: Tag.Name = "tag:yaml.org,2002:seq"
/// "tag:yaml.org,2002:map" <http://yaml.org/type/map.html>
public static let map: Tag.Name = "tag:yaml.org,2002:map"
// JSON Schema
/// "tag:yaml.org,2002:bool" <http://yaml.org/type/bool.html>
public static let bool: Tag.Name = "tag:yaml.org,2002:bool"
/// "tag:yaml.org,2002:float" <http://yaml.org/type/float.html>
public static let float: Tag.Name = "tag:yaml.org,2002:float"
/// "tag:yaml.org,2002:null" <http://yaml.org/type/null.html>
public static let null: Tag.Name = "tag:yaml.org,2002:null"
/// "tag:yaml.org,2002:int" <http://yaml.org/type/int.html>
public static let int: Tag.Name = "tag:yaml.org,2002:int"
// http://yaml.org/type/index.html
/// "tag:yaml.org,2002:binary" <http://yaml.org/type/binary.html>
public static let binary: Tag.Name = "tag:yaml.org,2002:binary"
/// "tag:yaml.org,2002:merge" <http://yaml.org/type/merge.html>
public static let merge: Tag.Name = "tag:yaml.org,2002:merge"
/// "tag:yaml.org,2002:omap" <http://yaml.org/type/omap.html>
public static let omap: Tag.Name = "tag:yaml.org,2002:omap"
/// "tag:yaml.org,2002:pairs" <http://yaml.org/type/pairs.html>
public static let pairs: Tag.Name = "tag:yaml.org,2002:pairs"
/// "tag:yaml.org,2002:set". <http://yaml.org/type/set.html>
public static let set: Tag.Name = "tag:yaml.org,2002:set"
/// "tag:yaml.org,2002:timestamp" <http://yaml.org/type/timestamp.html>
public static let timestamp: Tag.Name = "tag:yaml.org,2002:timestamp"
/// "tag:yaml.org,2002:value" <http://yaml.org/type/value.html>
public static let value: Tag.Name = "tag:yaml.org,2002:value"
/// "tag:yaml.org,2002:yaml" <http://yaml.org/type/yaml.html> We don't support this.
public static let yaml: Tag.Name = "tag:yaml.org,2002:yaml"
}
protocol TagResolvable {
var tag: Tag { get }
static var defaultTagName: Tag.Name { get }
func resolveTag(using resolver: Resolver) -> Tag.Name
}
extension TagResolvable {
var resolvedTag: Tag {
return tag.resolved(with: self)
}
func resolveTag(using resolver: Resolver) -> Tag.Name {
return tag.name == .implicit ? Self.defaultTagName : tag.name
}
}
|
d96ce62f5ec368a11cf4accef08d0c47
| 35.967105 | 113 | 0.629293 | false | false | false | false |
zenghaojim33/BeautifulShop
|
refs/heads/master
|
BeautifulShop/BeautifulShop/Charts/Charts/BarLineChartViewBase.swift
|
apache-2.0
|
1
|
//
// BarLineChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation;
import UIKit;
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate
{
/// the maximum number of entried to which values will be drawn
internal var _maxVisibleValueCount = 100
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
public var borderColor = UIColor.blackColor()
public var borderLineWidth: CGFloat = 1.0
/// if set to true, the highlight indicator (lines for linechart, dark bar for barchart) will be drawn upon selecting values.
public var highlightIndicatorEnabled = true
/// flag indicating if the grid background should be drawn or not
public var drawGridBackgroundEnabled = true
/// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
public var drawBordersEnabled = false
/// the object representing the labels on the y-axis, this object is prepared
/// in the pepareYLabels() method
internal var _leftAxis: ChartYAxis!
internal var _rightAxis: ChartYAxis!
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
internal var _leftYAxisRenderer: ChartYAxisRenderer!
internal var _rightYAxisRenderer: ChartYAxisRenderer!
internal var _leftAxisTransformer: ChartTransformer!
internal var _rightAxisTransformer: ChartTransformer!
internal var _xAxisRenderer: ChartXAxisRenderer!
private var _tapGestureRecognizer: UITapGestureRecognizer!
private var _doubleTapGestureRecognizer: UITapGestureRecognizer!
private var _pinchGestureRecognizer: UIPinchGestureRecognizer!
private var _panGestureRecognizer: UIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame);
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
internal override func initialize()
{
super.initialize();
_leftAxis = ChartYAxis(position: .Left);
_rightAxis = ChartYAxis(position: .Right);
_xAxis = ChartXAxis();
_leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler);
_leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer);
_rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer);
_xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer);
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"));
_doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:"));
_doubleTapGestureRecognizer.numberOfTapsRequired = 2;
_pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:"));
_panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"));
_pinchGestureRecognizer.delegate = self;
_panGestureRecognizer.delegate = self;
self.addGestureRecognizer(_tapGestureRecognizer);
if (_doubleTapToZoomEnabled)
{
self.addGestureRecognizer(_doubleTapGestureRecognizer);
}
updateScaleGestureRecognizers();
if (_dragEnabled)
{
self.addGestureRecognizer(_panGestureRecognizer);
}
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect);
if (_dataNotSet)
{
return;
}
let context = UIGraphicsGetCurrentContext();
if (xAxis.isAdjustXLabelsEnabled)
{
calcModulus();
}
// execute all drawing commands
drawGridBackground(context: context);
if (_leftAxis.isEnabled)
{
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
}
if (_rightAxis.isEnabled)
{
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
}
_xAxisRenderer?.calcXBounds(_xAxisRenderer.transformer);
_leftYAxisRenderer?.calcXBounds(_xAxisRenderer.transformer);
_rightYAxisRenderer?.calcXBounds(_xAxisRenderer.transformer);
_xAxisRenderer?.renderAxisLine(context: context);
_leftYAxisRenderer?.renderAxisLine(context: context);
_rightYAxisRenderer?.renderAxisLine(context: context);
// make sure the graph values and grid cannot be drawn outside the content-rect
CGContextSaveGState(context);
CGContextClipToRect(context, _viewPortHandler.contentRect);
if (_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
_xAxisRenderer?.renderGridLines(context: context);
_leftYAxisRenderer?.renderGridLines(context: context);
_rightYAxisRenderer?.renderGridLines(context: context);
renderer?.drawData(context: context);
if (!_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context);
}
if (!_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context);
}
if (!_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context);
}
// if highlighting is enabled
if (highlightEnabled && highlightIndicatorEnabled && valuesToHighlight())
{
renderer?.drawHighlighted(context: context, indices: _indicesToHightlight);
}
// Removes clipping rectangle
CGContextRestoreGState(context);
renderer!.drawExtras(context: context);
_xAxisRenderer.renderAxisLabels(context: context);
_leftYAxisRenderer.renderAxisLabels(context: context);
_rightYAxisRenderer.renderAxisLabels(context: context);
renderer!.drawValues(context: context);
_legendRenderer.renderLegend(context: context);
// drawLegend();
drawMarkers(context: context);
drawDescription(context: context);
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum);
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum);
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted);
_leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted);
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return;
}
calcMinMax();
_leftAxis?._defaultValueFormatter = _defaultValueFormatter;
_rightAxis?._defaultValueFormatter = _defaultValueFormatter;
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum);
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum);
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals);
_legendRenderer?.computeLegend(_data);
calculateOffsets();
setNeedsDisplay();
}
internal override func calcMinMax()
{
var minLeft = _data.getYMin(.Left);
var maxLeft = _data.getYMax(.Left);
var minRight = _data.getYMin(.Right);
var maxRight = _data.getYMax(.Right);
var leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft));
var rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight));
// in case all values are equal
if (leftRange == 0.0)
{
maxLeft = maxLeft + 1.0;
if (!_leftAxis.isStartAtZeroEnabled)
{
minLeft = minLeft - 1.0;
}
}
if (rightRange == 0.0)
{
maxRight = maxRight + 1.0;
if (!_rightAxis.isStartAtZeroEnabled)
{
minRight = minRight - 1.0;
}
}
var topSpaceLeft = leftRange * Float(_leftAxis.spaceTop);
var topSpaceRight = rightRange * Float(_rightAxis.spaceTop);
var bottomSpaceLeft = leftRange * Float(_leftAxis.spaceBottom);
var bottomSpaceRight = rightRange * Float(_rightAxis.spaceBottom);
_chartXMax = Float(_data.xVals.count - 1);
_deltaX = CGFloat(abs(_chartXMax - _chartXMin));
_leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft);
_rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight);
_leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft);
_rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight);
// consider starting at zero (0)
if (_leftAxis.isStartAtZeroEnabled)
{
_leftAxis.axisMinimum = 0.0;
}
if (_rightAxis.isStartAtZeroEnabled)
{
_rightAxis.axisMinimum = 0.0;
}
_leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum);
_rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum);
}
internal override func calculateOffsets()
{
if (!_customViewPortEnabled)
{
var offsetLeft = CGFloat(0.0);
var offsetRight = CGFloat(0.0);
var offsetTop = CGFloat(0.0);
var offsetBottom = CGFloat(0.0);
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += _legend.textWidthMax + _legend.xOffset * 2.0;
}
if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += _legend.textWidthMax + _legend.xOffset * 2.0;
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
offsetBottom += _legend.textHeightMax * 3.0;
}
}
// offsets for y-labels
if (leftAxis.needsOffset)
{
offsetLeft += leftAxis.requiredSize().width;
}
if (rightAxis.needsOffset)
{
offsetRight += rightAxis.requiredSize().width;
}
var xlabelheight = xAxis.labelHeight * 2.0;
if (xAxis.isEnabled)
{
// offsets for x-labels
if (xAxis.labelPosition == .Bottom)
{
offsetBottom += xlabelheight;
}
else if (xAxis.labelPosition == .Top)
{
offsetTop += xlabelheight;
}
else if (xAxis.labelPosition == .BothSided)
{
offsetBottom += xlabelheight;
offsetTop += xlabelheight;
}
}
var min = CGFloat(10.0);
_viewPortHandler.restrainViewPort(
offsetLeft: max(min, offsetLeft),
offsetTop: max(min, offsetTop),
offsetRight: max(min*2, offsetRight),
offsetBottom: max(min, offsetBottom));
}
prepareOffsetMatrix();
prepareValuePxMatrix();
}
/// calculates the modulus for x-labels and grid
internal func calcModulus()
{
if (_xAxis === nil)
{
return;
}
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a)));
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1;
}
}
public override func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint
{
var xPos = CGFloat(entry.xIndex);
if (self.isKindOfClass(BarChartView))
{
var bd = _data as! BarChartData;
var space = bd.groupSpace;
var j = _data.getDataSetByIndex(dataSetIndex)!.entryIndex(entry: entry, isEqual: true);
var x = CGFloat(j * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(j) + space / 2.0;
xPos += x;
}
// position of the marker depends on selected value index and value
var pt = CGPoint(x: xPos, y: CGFloat(entry.value) * _animator.phaseY);
getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt);
return pt;
}
/// draws the grid background
internal func drawGridBackground(#context: CGContext)
{
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextSaveGState(context);
}
if (drawGridBackgroundEnabled)
{
// draw the grid background
CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor);
CGContextFillRect(context, _viewPortHandler.contentRect);
}
if (drawBordersEnabled)
{
CGContextSetLineWidth(context, borderLineWidth);
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextStrokeRect(context, _viewPortHandler.contentRect);
}
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextRestoreGState(context);
}
}
/// Returns the Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer
{
if (which == .Left)
{
return _leftAxisTransformer;
}
else
{
return _rightAxisTransformer;
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case Both
case X
case Y
}
private var _isDragging = false;
private var _isScaling = false;
private var _gestureScaleAxis = GestureScaleAxis.Both;
private var _closestDataSetToTouch: ChartDataSet!;
/// the last highlighted object
private var _lastHighlighted: ChartHighlight!;
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self));
if (h === nil || h!.isEqual(_lastHighlighted))
{
self.highlightValue(highlight: nil, callDelegate: true);
_lastHighlighted = nil;
}
else
{
_lastHighlighted = h;
self.highlightValue(highlight: h, callDelegate: true);
}
}
}
@objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return;
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if (!_dataNotSet && _doubleTapToZoomEnabled)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom);
}
self.zoom(1.4, scaleY: 1.4, x: location.x, y: location.y);
}
}
}
@objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled))
{
_isScaling = true;
if (_pinchZoomEnabled)
{
_gestureScaleAxis = .Both;
}
else
{
var x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x);
var y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y);
if (x > y)
{
_gestureScaleAxis = .X;
}
else
{
_gestureScaleAxis = .Y;
}
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isScaling)
{
_isScaling = false;
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isScaling)
{
var location = recognizer.locationInView(self);
location.x = location.x - _viewPortHandler.offsetLeft;
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop);
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom);
}
var scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0;
var scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0;
var matrix = CGAffineTransformMakeTranslation(location.x, location.y);
matrix = CGAffineTransformScale(matrix, scaleX, scaleY);
matrix = CGAffineTransformTranslate(matrix,
-location.x, -location.y);
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
recognizer.scale = 1.0;
}
}
}
@objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
if (!_dataNotSet && _dragEnabled && !self.hasNoDragOffset || !self.isFullyZoomedOut)
{
_isDragging = true;
_closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self));
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isDragging)
{
_isDragging = false;
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isDragging)
{
var translation = recognizer.translationInView(self);
if (isAnyAxisInverted && _closestDataSetToTouch !== nil
&& getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
if (self is HorizontalBarChartView)
{
translation.x = -translation.x;
}
else
{
translation.y = -translation.y;
}
}
var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y);
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
recognizer.setTranslation(CGPoint(x: 0.0, y: 0.0), inView: self);
}
}
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)))
{
return true;
}
return false;
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4f, into the charts center. center.
public func zoomIn()
{
var matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms out by 0.7f, from the charts center. center.
public func zoomOut()
{
var matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0));
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// :param: scaleX if < 1f --> zoom out, if > 1f --> zoom in
/// :param: scaleY if < 1f --> zoom out, if > 1f --> zoom in
/// :param: x
/// :param: y
public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat)
{
var matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y);
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen()
{
var matrix = _viewPortHandler.fitScreen();
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true);
}
/// Sets the minimum scale value to which can be zoomed out. 1f = fitScreen
public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX);
_viewPortHandler.setMinimumScaleY(scaleY);
}
/// Sets the size of the area (range on the x-axis) that should be maximum
/// visible at once. If this is e.g. set to 10, no more than 10 values on the
/// x-axis can be viewed at once without scrolling.
public func setVisibleXRange(xRange: CGFloat)
{
var xScale = _deltaX / (xRange);
_viewPortHandler.setMinimumScaleX(xScale);
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// :param: yRange
/// :param: axis - the axis for which this limit should apply
public func setVisibleYRange(yRange: CGFloat, axis: ChartYAxis.AxisDependency)
{
var yScale = getDeltaY(axis) / yRange;
_viewPortHandler.setMinimumScaleY(yScale);
}
/// Moves the left side of the current viewport to the specified x-index.
public func moveViewToX(xIndex: Int)
{
if (_viewPortHandler.hasChartDimens)
{
var pt = CGPoint(x: CGFloat(xIndex), y: 0.0);
getTransformer(.Left).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); });
}
}
/// Centers the viewport to the specified y-value on the y-axis.
///
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); });
}
}
/// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// This will move the center of the current viewport to the specified x-index and y-value.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func centerViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY;
var xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX;
var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0);
getTransformer(axis).pointValueToPixel(&pt);
_viewPortHandler.centerViewPort(pt: pt, chart: self);
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); });
}
}
/// Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this.
public func setViewPortOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true;
if (NSThread.isMainThread())
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom);
prepareOffsetMatrix();
prepareValuePxMatrix();
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom);
});
}
}
/// Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically.
public func resetViewPortOffsets()
{
_customViewPortEnabled = false;
calculateOffsets();
}
// MARK: - Accessors
/// Returns the delta-y value (y-value range) of the specified axis.
public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat
{
if (axis == .Left)
{
return CGFloat(leftAxis.axisRange);
}
else
{
return CGFloat(rightAxis.axisRange);
}
}
/// Returns the position (in pixels) the provided Entry has inside the chart view
public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value));
getTransformer(axis).pointValueToPixel(&vals);
return vals;
}
/// the number of maximum visible drawn values on the chart
/// only active when setDrawValues() is enabled
public var maxVisibleValueCount: Int
{
get
{
return _maxVisibleValueCount;
}
set
{
_maxVisibleValueCount = newValue;
}
}
/// If set to true, the highlight indicators (cross of two lines for
/// LineChart and ScatterChart, dark bar overlay for BarChart) that give
/// visual indication that an Entry has been selected will be drawn upon
/// selecting values. This does not depend on the MarkerView.
/// :default: true
public var isHighlightIndicatorEnabled: Bool
{
return highlightIndicatorEnabled;
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var dragEnabled: Bool
{
get
{
return _dragEnabled;
}
set
{
if (_dragEnabled != newValue)
{
_dragEnabled = newValue;
if (_dragEnabled)
{
self.addGestureRecognizer(_panGestureRecognizer);
}
else
{
if (self.gestureRecognizers != nil)
{
for (var i = 0; i < self.gestureRecognizers!.count; i++)
{
if (self.gestureRecognizers?[i] === _panGestureRecognizer)
{
self.gestureRecognizers!.removeAtIndex(i);
break;
}
}
}
}
}
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var isDragEnabled: Bool
{
return dragEnabled;
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
public func setScaleEnabled(enabled: Bool)
{
if (_scaleXEnabled != enabled || _scaleYEnabled != enabled)
{
_scaleXEnabled = enabled;
_scaleYEnabled = enabled;
updateScaleGestureRecognizers();
}
}
public var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if (_scaleXEnabled != newValue)
{
_scaleXEnabled = newValue;
updateScaleGestureRecognizers();
}
}
}
public var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if (_scaleYEnabled != newValue)
{
_scaleYEnabled = newValue;
updateScaleGestureRecognizers();
}
}
}
public var isScaleXEnabled: Bool { return scaleXEnabled; }
public var isScaleYEnabled: Bool { return scaleYEnabled; }
/// flag that indicates if double tap zoom is enabled or not
public var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled;
}
set
{
if (_doubleTapToZoomEnabled != newValue)
{
_doubleTapToZoomEnabled = newValue;
if (_doubleTapToZoomEnabled)
{
self.addGestureRecognizer(_doubleTapGestureRecognizer);
}
else
{
if (self.gestureRecognizers != nil)
{
for (var i = 0; i < self.gestureRecognizers!.count; i++)
{
if (self.gestureRecognizers?[i] === _doubleTapGestureRecognizer)
{
self.gestureRecognizers!.removeAtIndex(i);
break;
}
}
}
}
}
}
}
/// :returns: true if zooming via double-tap is enabled false if not.
/// :default: true
public var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled;
}
/// :returns: true if drawing the grid background is enabled, false if not.
/// :default: true
public var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled;
}
/// :returns: true if drawing the borders rectangle is enabled, false if not.
/// :default: false
public var isDrawBordersEnabled: Bool
{
return drawBordersEnabled;
}
/// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart.
public func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight!
{
if (_dataNotSet || _data === nil)
{
println("Can't select by touch. No data set.");
return nil;
}
var valPt = CGPoint();
valPt.x = pt.x;
valPt.y = 0.0;
// take any transformer to determine the x-axis value
_leftAxisTransformer.pixelToValue(&valPt);
var xTouchVal = valPt.x;
var base = floor(xTouchVal);
var touchOffset = _deltaX * 0.025;
// touch out of chart
if (xTouchVal < -touchOffset || xTouchVal > _deltaX + touchOffset)
{
return nil;
}
if (base < 0.0)
{
base = 0.0;
}
if (base >= _deltaX)
{
base = _deltaX - 1.0;
}
var xIndex = Int(base);
// check if we are more than half of a x-value or not
if (xTouchVal - base > 0.5)
{
xIndex = Int(base + 1.0);
}
var valsAtIndex = getYValsAtIndex(xIndex);
var leftdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Left);
var rightdist = ChartUtils.getMinimumDistance(valsAtIndex, val: Float(pt.y), axis: .Right);
if (_data!.getFirstRight() === nil)
{
rightdist = FLT_MAX;
}
if (_data!.getFirstLeft() === nil)
{
leftdist = FLT_MAX;
}
var axis: ChartYAxis.AxisDependency = leftdist < rightdist ? .Left : .Right;
var dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Float(pt.y), axis: axis);
if (dataSetIndex == -1)
{
return nil;
}
return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex);
}
/// Returns an array of SelInfo objects for the given x-index. The SelInfo
/// objects give information about the value at the selected index and the
/// DataSet it belongs to.
public func getYValsAtIndex(xIndex: Int) -> [ChartSelInfo]
{
var vals = [ChartSelInfo]();
var pt = CGPoint();
for (var i = 0, count = _data.dataSetCount; i < count; i++)
{
var dataSet = _data.getDataSetByIndex(i);
if (dataSet === nil)
{
continue;
}
// extract all y-values from all DataSets at the given x-index
var yVal = dataSet!.yValForXIndex(xIndex);
pt.y = CGFloat(yVal);
getTransformer(dataSet!.axisDependency).pointValueToPixel(&pt);
if (!isnan(pt.y))
{
vals.append(ChartSelInfo(value: Float(pt.y), dataSetIndex: i, dataSet: dataSet!));
}
}
return vals;
}
/// Returns the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// getPixelsForValues(...).
public func getValueByTouchPoint(var #pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint
{
getTransformer(axis).pixelToValue(&pt);
return pt;
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to getValueByTouchPoint(...).
public func getPixelForValue(x: Float, y: Float, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var pt = CGPoint(x: CGFloat(x), y: CGFloat(y));
getTransformer(axis).pointValueToPixel(&pt);
return pt;
}
/// returns the y-value at the given touch position (must not necessarily be
/// a value contained in one of the datasets)
public func getYValueByTouchPoint(#pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat
{
return getValueByTouchPoint(pt: pt, axis: axis).y;
}
/// returns the Entry object displayed at the touched position of the chart
public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data!.getEntryForHighlight(h!);
}
return nil;
}
///returns the DataSet object displayed at the touched position of the chart
public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet!
{
var h = getHighlightByTouchPoint(pt);
if (h !== nil)
{
return _data.getDataSetByIndex(h.dataSetIndex) as! BarLineScatterCandleChartDataSet!;
}
return nil;
}
/// Returns the lowest x-index (value on the x-axis) that is still visible on he chart.
public var lowestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0);
}
/// Returns the highest x-index (value on the x-axis) that is still visible on the chart.
public var highestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom);
getTransformer(.Left).pixelToValue(&pt);
return (Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x);
}
/// returns the current x-scale factor
public var scaleX: CGFloat { return _viewPortHandler.scaleX; }
/// returns the current y-scale factor
public var scaleY: CGFloat { return _viewPortHandler.scaleY; }
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; }
/// Returns the left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
public var leftAxis: ChartYAxis
{
return _leftAxis;
}
/// Returns the right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
public var rightAxis: ChartYAxis { return _rightAxis; }
/// Returns the y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis
{
if (axis == .Left)
{
return _leftAxis;
}
else
{
return _rightAxis;
}
}
/// Returns the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis;
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately
public var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled;
}
set
{
if (_pinchZoomEnabled != newValue)
{
_pinchZoomEnabled = newValue;
updateScaleGestureRecognizers();
}
}
}
private func updateScaleGestureRecognizers()
{
if (self.gestureRecognizers != nil)
{
for (var i = 0; i < self.gestureRecognizers!.count; i++)
{
if (self.gestureRecognizers![i] === _pinchGestureRecognizer)
{
self.gestureRecognizers!.removeAtIndex(i);
break;
}
}
}
if (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)
{
self.addGestureRecognizer(_pinchGestureRecognizer);
}
}
/// returns true if pinch-zoom is enabled, false if not
/// :default: false
public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset);
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset);
}
/// :returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; }
public var xAxisRenderer: ChartXAxisRenderer { return _xAxisRenderer; }
public var leftYAxisRenderer: ChartYAxisRenderer { return _leftYAxisRenderer; }
public var rightYAxisRenderer: ChartYAxisRenderer { return _rightYAxisRenderer; }
public override var chartYMax: Float
{
return max(leftAxis.axisMaximum, rightAxis.axisMaximum);
}
public override var chartYMin: Float
{
return min(leftAxis.axisMinimum, rightAxis.axisMinimum);
}
/// Returns true if either the left or the right or both axes are inverted.
public var isAnyAxisInverted: Bool
{
return _leftAxis.isInverted || _rightAxis.isInverted;
}
}
/// Default formatter that calculates the position of the filled line.
internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter
{
private weak var _chart: BarLineChartViewBase!;
internal init(chart: BarLineChartViewBase)
{
_chart = chart;
}
internal func getFillLinePosition(#dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Float, chartMinY: Float) -> CGFloat
{
var fillMin = CGFloat(0.0);
if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
{
fillMin = 0.0;
}
else
{
if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled)
{
var max: Float, min: Float;
if (data.yMax > 0.0)
{
max = 0.0;
}
else
{
max = chartMaxY;
}
if (data.yMin < 0.0)
{
min = 0.0;
}
else
{
min = chartMinY;
}
fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max);
}
else
{
fillMin = 0.0;
}
}
return fillMin;
}
}
|
d199cbedb9c8a5734e6c1a10457be0d6
| 33.386813 | 263 | 0.573215 | false | false | false | false |
collegboi/iOS-Sprite-Game
|
refs/heads/master
|
Minnion Maze/Minnion Maze/Player.swift
|
mit
|
1
|
//
// Player.swift
// Minnion Maze
//
// Created by Timothy Barnard on 13/12/2014.
// Copyright (c) 2014 Timothy Barnard. All rights reserved.
//
import SpriteKit
class Player : SKNode {
let sprite: SKSpriteNode
var velocity: CGVector!
let textureBk: SKTexture!
let textureFd: SKTexture!
let textureLt: SKTexture!
let textureRt: SKTexture!
let textureMad: SKTexture!
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override init() {
//character directions with own SKTexture variables
let atlas = SKTextureAtlas(named: "characters")
textureBk = atlas.textureNamed("minnion_back")
textureFd = atlas.textureNamed("minnion_front")
textureLt = atlas.textureNamed("minnion_left")
textureRt = atlas.textureNamed("minnion_right")
textureMad = atlas.textureNamed("madMinnion")
textureFd.filteringMode = .Nearest
textureBk.filteringMode = .Nearest
textureRt.filteringMode = .Nearest
textureLt.filteringMode = .Nearest
textureMad.filteringMode = .Nearest
sprite = SKSpriteNode(texture: textureBk)
//self.velocity = CGVector(angle: 0)
super.init()
addChild(sprite)
name = "player"
// min diameter for the physics body around the sprite
var minDiam = min(sprite.size.width, sprite.size.height)
minDiam = max(minDiam - 4.0, 1.0)
let physicsBody = SKPhysicsBody(circleOfRadius: minDiam / 8.0 )
//let physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
//
physicsBody.usesPreciseCollisionDetection = true
//
physicsBody.allowsRotation = false
physicsBody.restitution = 0
physicsBody.friction = 0
physicsBody.linearDamping = 0
physicsBody.categoryBitMask = PhysicsCategory.Player
physicsBody.contactTestBitMask = PhysicsCategory.All
physicsBody.collisionBitMask = PhysicsCategory.Boundary | PhysicsCategory.Wall
self.physicsBody = physicsBody
}
//taking in velocity form acceleromter to move the sprite
func moveSprite(velocity: CGVector) {
physicsBody?.applyImpulse(velocity)
self.velocity = velocity
playerDirection()
}
//detects which direction sprite is moving to change sprites direciton
func playerDirection() {
let direction = physicsBody!.velocity
if abs(direction.dy) > abs(direction.dx) {
if direction.dy < 0 {
sprite.texture = textureFd
} else {
sprite.texture = textureBk
}
} else {
if direction.dx > 0 {
sprite.texture = textureRt
} else {
sprite.texture = textureLt
}
}//if statement to see if sprite is moving direciton
}
//method to turn minnion mad due to loosing game
func playerLoose(score: Bool) {
sprite.texture = textureMad
let actionJump1 = SKAction.scaleTo(1.2, duration: 0.2)
let actionJump2 = SKAction.scaleTo(1, duration: 0.2)
let wait = SKAction.waitForDuration(0.25)
let sequence = SKAction.sequence([actionJump1, actionJump2])
sprite.runAction(sequence)
}
}
|
5b97d5a1d64001dd029754eba3fb8eda
| 30.906542 | 86 | 0.621558 | false | false | false | false |
CaiMiao/CGSSGuide
|
refs/heads/master
|
DereGuide/Toolbox/MusicInfo/Model/CGSSSongFilter.swift
|
mit
|
1
|
//
// CGSSSongFilter.swift
// DereGuide
//
// Created by zzk on 11/09/2017.
// Copyright © 2017 zzk. All rights reserved.
//
import Foundation
struct CGSSSongFilter: CGSSFilter {
var liveTypes: CGSSLiveTypes
var eventTypes: CGSSLiveEventTypes
var centerTypes: CGSSCardTypes
var positionNumTypes: CGSSPositionNumberTypes
var favoriteTypes: CGSSFavoriteTypes
var searchText: String = ""
init(liveMask: UInt, eventMask: UInt, centerMask: UInt, positionNumMask: UInt, favoriteMask: UInt) {
liveTypes = CGSSLiveTypes.init(rawValue: liveMask)
eventTypes = CGSSLiveEventTypes.init(rawValue: eventMask)
centerTypes = CGSSCardTypes.init(rawValue: centerMask)
positionNumTypes = CGSSPositionNumberTypes.init(rawValue: positionNumMask)
favoriteTypes = CGSSFavoriteTypes.init(rawValue: favoriteMask)
}
func filter(_ list: [CGSSSong]) -> [CGSSSong] {
// let date1 = Date()
let result = list.filter { (v: CGSSSong) -> Bool in
let r1: Bool = searchText == "" ? true : {
let comps = searchText.components(separatedBy: " ")
for comp in comps {
if comp == "" { continue }
let b1 = { v.name.lowercased().contains(comp.lowercased()) }
let b2 = { v.detail.lowercased().contains(comp.lowercased())}
if b1() || b2() {
continue
} else {
return false
}
}
return true
}()
let r2: Bool = {
var b1 = false
if liveTypes == .all {
b1 = true
} else {
if liveTypes.contains(v.filterType) {
b1 = true
}
}
var b2 = false
if eventTypes == .all {
b2 = true
} else {
if eventTypes.contains(v.eventFilterType) {
b2 = true
}
}
var b3 = false
if centerTypes == .all {
b3 = true
} else {
if centerTypes.contains(v.centerType) {
b3 = true
}
}
var b4 = false
if positionNumTypes == .all {
b4 = true
} else {
if positionNumTypes.contains(v.positionNumType) {
b4 = true
}
}
var b7 = false
if favoriteTypes == .all {
b7 = true
} else {
if favoriteTypes.contains(v.favoriteType) {
b7 = true
}
}
if b1 && b2 && b3 && b4 && b7 {
return true
}
return false
}()
return r1 && r2
}
return result
}
func toDictionary() -> NSDictionary {
let dict = ["liveMask": liveTypes.rawValue, "eventMask": eventTypes.rawValue, "centerMask": centerTypes.rawValue, "favoriteMask": favoriteTypes.rawValue, "positionNumMask": positionNumTypes.rawValue] as NSDictionary
return dict
}
func save(to path: String) {
toDictionary().write(toFile: path, atomically: true)
}
init?(fromFile path: String) {
if let dict = NSDictionary.init(contentsOfFile: path) {
if let liveMask = dict.object(forKey: "liveMask") as? UInt, let eventMask = dict.object(forKey: "eventMask") as? UInt, let centerMask = dict.object(forKey: "centerMask") as? UInt, let favoriteMask = dict.object(forKey: "favoriteMask") as? UInt, let positionNumMask = dict.object(forKey: "positionNumMask") as? UInt {
self.init(liveMask: liveMask, eventMask: eventMask, centerMask: centerMask, positionNumMask: positionNumMask, favoriteMask: favoriteMask)
return
}
}
return nil
}
}
|
e26b22019c5139c5178f8b03961207f8
| 34.04 | 328 | 0.477169 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
refs/heads/master
|
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/OutputNodes/GroupOutputNode.swift
|
mit
|
1
|
//
// TransformNodeOutput.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/30/19.
//
import Foundation
import CoreGraphics
import QuartzCore
class GroupOutputNode: NodeOutput {
init(parent: NodeOutput?, rootNode: NodeOutput?) {
self.parent = parent
self.rootNode = rootNode
}
let parent: NodeOutput?
let rootNode: NodeOutput?
var isEnabled: Bool = true
private(set) var outputPath: CGPath? = nil
private(set) var transform: CATransform3D = CATransform3DIdentity
func setTransform(_ xform: CATransform3D, forFrame: CGFloat) {
transform = xform
outputPath = nil
}
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
guard isEnabled else {
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
outputPath = parent?.outputPath
return upstreamUpdates
}
let upstreamUpdates = parent?.hasOutputUpdates(forFrame) ?? false
if upstreamUpdates {
outputPath = nil
}
let rootUpdates = rootNode?.hasOutputUpdates(forFrame) ?? false
if rootUpdates {
outputPath = nil
}
var localUpdates: Bool = false
if outputPath == nil {
localUpdates = true
let newPath = CGMutablePath()
if let parentNode = parent, let parentPath = parentNode.outputPath {
/// First add parent path.
newPath.addPath(parentPath)
}
var xform = CATransform3DGetAffineTransform(transform)
if let rootNode = rootNode,
let rootPath = rootNode.outputPath,
let xformedPath = rootPath.copy(using: &xform) {
/// Now add root path. Note root path is transformed.
newPath.addPath(xformedPath)
}
outputPath = newPath
}
return upstreamUpdates || localUpdates
}
}
|
ba7a8fdba9df085f8900bdf94d4613f5
| 24.557143 | 74 | 0.660704 | false | false | false | false |
pietro82/TransitApp
|
refs/heads/master
|
TransitApp/DirectionsDataManager.swift
|
mit
|
1
|
//
// DirectionsDataManager.swift
// TransitApp
//
// Created by Pietro Santececca on 24/01/17.
// Copyright © 2017 Tecnojam. All rights reserved.
//
import MapKit
class DirectionsDataManager {
static func retreiveDirectionsOptions(originLocation: CLLocationCoordinate2D,
arrivalLocation: CLLocationCoordinate2D,
timeType: TimeType,
time: Date) -> [DirectionsOption] {
guard let result = parseJsonData() else {
print("Error during JSON parsing: file is badly formatted")
return []
}
return result
}
static fileprivate func parseJsonData() -> [DirectionsOption]? {
var options = [DirectionsOption]()
guard let url = Bundle.main.url(forResource: "door2door", withExtension: "json") else {
return nil
}
do {
let data = try Data(contentsOf: url)
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let optionsJson = json["routes"] as? [[String: Any]] {
for optionJson in optionsJson {
// Directions mode
guard let mode = optionJson["type"] as? String else { return nil }
// Directions provider
guard let provider = optionJson["provider"] as? String else { return nil }
// Directions list
guard let directionsJson = optionJson["segments"] as? [[String: Any]] else { return nil }
// Directions price
var price: Price?
if let priceJson = optionJson["price"] as? [String: Any] {
guard let currency = priceJson["currency"] as? String else { return nil }
guard let amount = priceJson["amount"] as? Double else { return nil }
price = Price(currency: currency, amount: amount)
}
var directions = [Direction]()
for directionJson in directionsJson {
// Direction name
var name: String?
if let nameJson = directionJson["name"] as? String { name = nameJson }
// Direction num stops
guard let numStops = directionJson["num_stops"] as? Int else { return nil }
// Direction travel mode
guard let travelMode = directionJson["travel_mode"] as? String else { return nil }
// Direction description
var description: String?
if let descriptionJson = directionJson["description"] as? String { description = descriptionJson }
// Direction color
guard let color = directionJson["color"] as? String else { return nil }
// Direction icon url
guard let iconUrl = directionJson["icon_url"] as? String else { return nil }
// Direction polyline
var polyline: String?
if let polylineJson = directionJson["polyline"] as? String { polyline = polylineJson }
// Stops
guard let stopsJson = directionJson["stops"] as? [[String: Any]] else { return nil }
var stops = [Stop]()
for stopJson in stopsJson {
// Stop latitude
guard let latitude = stopJson["lat"] as? Double else { return nil }
// Stop longitude
guard let longitude = stopJson["lng"] as? Double else { return nil }
// Stop time
guard let timeString = stopJson["datetime"] as? String,
let timeDate = Utils.convertToDate(string: timeString) else { return nil }
// Stop name
var name: String?
if let nameJson = stopJson["name"] as? String { name = nameJson }
// Create a new stop
let stop = Stop(name: name, latitude: latitude, longitude: longitude, time: timeDate, color: color)
// Add stop to the stop list
stops.append(stop)
}
// Create a new direction
let direction = Direction(name: name, numStops: numStops, stops: stops, travelMode: travelMode, description: description, color: color, iconUrl: iconUrl, polyline: polyline)
// Add direction to the directions list
directions.append(direction)
}
// Create a new option
let option = DirectionsOption(mode: mode, provider: provider, price: price, directions: directions)
// Add option to the result list
options.append(option)
}
}
}
catch {
print("Error deserializing JSON: \(error)")
}
return options
}
}
|
aa75737280ab5bcf8cf4cef2e14cd798
| 43.807407 | 197 | 0.440734 | false | false | false | false |
mark2b/l10n
|
refs/heads/master
|
Classes/l10n.swift
|
mit
|
1
|
//
// l10n.swift
//
// Created by Mark Berner on 19/01/2017.
// Copyright © 2017 Mark Berner. All rights reserved.
//
import Foundation
extension String {
public func l10n(_ resource: l10NResources.RawValue = l10NResources.default, locale:Locale? = nil, args:CVarArg...) -> String {
var bundle = Bundle.main
if let locale = locale {
let language = locale.languageCode
if let path = Bundle.main.path(forResource: language, ofType: "lproj"), let localizedBundle = Bundle(path: path) {
bundle = localizedBundle
}
}
var format:String
if resource == l10NResources.default {
format = bundle.localizedString(forKey: self, value: self, table: nil)
}
else {
format = bundle.localizedString(forKey: self, value: self, table: resource)
}
if args.count == 0 {
return format
}
else {
return NSString(format: format, arguments:getVaList(args)) as String
}
}
}
public struct l10NResources : RawRepresentable {
public typealias RawValue = String
public static let `default` = "default"
public init?(rawValue: l10NResources.RawValue) {
return nil
}
public var rawValue: String
}
|
2701f18ff4397eedede84a502968a93e
| 26.291667 | 131 | 0.603817 | false | false | false | false |
wireapp/wire-ios-sync-engine
|
refs/heads/develop
|
Source/Registration/UnregisteredUser+Payload.swift
|
gpl-3.0
|
1
|
//
// 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 Foundation
import WireDataModel
extension UnregisteredUser {
/**
* The dictionary payload that contains the resources to transmit to the backend
* when registering the user.
*/
var payload: ZMTransportData {
guard self.isComplete else {
fatalError("Attempt to register an incomplete user.")
}
var payload: [String: Any] = [:]
switch credentials! {
case .phone(let number):
payload["phone"] = number
payload["phone_code"] = verificationCode!
case .email(let address):
payload["email"] = address
payload["email_code"] = verificationCode!
}
payload["accent_id"] = accentColorValue!.rawValue
payload["name"] = name!
payload["locale"] = NSLocale.formattedLocaleIdentifier()
payload["label"] = CookieLabel.current.value
payload["password"] = password
return payload as ZMTransportData
}
}
|
ea961882ee3a876dd6b13d8933d8c628
| 29.690909 | 84 | 0.662322 | false | false | false | false |
sharkspeed/dororis
|
refs/heads/dev
|
languages/swift/guide/8-enumerations.swift
|
bsd-2-clause
|
1
|
// 8 Enumerations
// 定义一种常见类型 由一组相关联的值组成 允许你以一种类型安全的方式操作它们。
// C 的枚举要赋值一组 整数值 Swift 要更灵活
// 提供给枚举的 raw value 可以是 string cahracter integer floating-point
// 枚举可以存储任何类型 类似 unions 或 variants
// 可以有计算属性 定义初始化函数 可以被 extended 可以实现 protocols
// 8.1 Enumeration Syntax
enum CompassPoint {
case north
case south
case east
case west
}
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// Unlike C and Objective-C, Swift enumeration cases are not assigned a default integer value when they are created.
// Each enumeration definition defines a brand new type 每个枚举定义都生成一个新类型
// var directToEast = .east
var directToWest = CompassPoint.west
print(directToWest)
// 一旦 directToWest 被声明为 CompassPoint 就可以使用
directToWest = .east
print(directToWest)
// 8.2 Matching Enumeration Values with a Switch Statement
// 可以在 swich 中使用 枚举值
var directToWhere = CompassPoint.south
switch directToWhere {
case .north:
print("Go to north")
case .south:
print("Go to south")
case .west:
print("Go west")
case .east:
print("Go east")
}
// 如果不在 case 中列出全部枚举值的话就需要提供一个 default 语句
// 8.3 关联数值 Associated Values
// store UPC barcodes as a tuple of four integers, and QR code barcodes as a string of any length.
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("JDSKFSJDLFJ")
// 一个时刻只能保存一个枚举值
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let productCode, let checkCode):
print("UPC: \(numberSystem) - \(manufacturer) - \(productCode) - \(checkCode)")
case .qrCode(let productCode):
print("QR code: \(productCode)")
}
// 类似上边都是 let 声明的常量的情况 可以将 let 提前
switch productBarcode {
case let .upc(numberSystem, manufacturer, productCode, checkCode):
print("UPC: \(numberSystem) - \(manufacturer) - \(productCode) - \(checkCode)")
case let .qrCode(productCode):
print("QR code: \(productCode)")
}
// 8.4 Raw Values
// As an alternative to associated values 预设值的枚举需要类型一致
enum ASCIIControl: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
// raw value define enumeration 时就赋值
// associated value 在基于枚举值创建变量/常量时
// 8.4.1 Implicitly Assigned Raw Values
// 在使用 raw values 时, 如果类型为 integer 或者 string 你可以不用为每个 case 赋值,Swift 会自动为你赋值。
enum PlanetEasy: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// Planet.venus has an implicit raw value of 2, and so on.
enum CompassPointEasy: String {
case north, south, east, west
}
// int 的 raw values 从 0 开始 用户设置初始值可以修改这个默认值
// string 为 case 名的字面量
let earthsOrder = PlanetEasy.earth.rawValue
print(earthsOrder)
let sunsetDirection = CompassPointEasy.west.rawValue
print(sunsetDirection)
// 8.4.2 Initializing from a Raw Value
// 可以使用 枚举初始化 枚举实例
let aNewPlanet = PlanetEasy(rawValue: 7)
// aNewPlanet 类型为 Planet? 因为不是所有的 值都有对应的 case 找不到值就会返回 nil
let positionToFind = 11
if let somePlanet = PlanetEasy(rawValue: positionToFind) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
// 8.4.3 Recursive Enumerations
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// 或者
indirect enum ArithmeticExpressionNew {
case number(Int)
case addition(ArithmeticExpressionNew, ArithmeticExpressionNew)
case multiplication(ArithmeticExpressionNew, ArithmeticExpressionNew)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
// 可以用于递归计算中 类似 模式匹配
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}
print(evaluate(product))
// Prints "18"
|
7fafc237590fd6a35f2160ccfc64ab0e
| 24.255814 | 116 | 0.722312 | false | false | false | false |
lumenlunae/BusyNavigationBar
|
refs/heads/master
|
BusyNavigationBar/BusyNavigationBar/UINavigationBar+Animation.swift
|
mit
|
1
|
//
// UINavigationBar+Animation.swift
// BusyNavigationBar
//
// Created by Gunay Mert Karadogan on 22/7/15.
// Copyright (c) 2015 Gunay Mert Karadogan. All rights reserved.
//
import UIKit
private var BusyNavigationBarLoadingViewAssociationKey: UInt8 = 0
private var BusyNavigationBarOptionsAssociationKey: UInt8 = 1
private var alphaAnimationDurationOfLoadingView = 0.3
extension UINavigationBar {
private var busy_loadingView: UIView? {
get {
return objc_getAssociatedObject(self, &BusyNavigationBarLoadingViewAssociationKey) as? UIView
}
set(newValue) {
objc_setAssociatedObject(self, &BusyNavigationBarLoadingViewAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
private var busy_options: BusyNavigationBarOptions {
get {
return objc_getAssociatedObject(self, &BusyNavigationBarOptionsAssociationKey) as! BusyNavigationBarOptions
}
set(newValue) {
objc_setAssociatedObject(self, &BusyNavigationBarOptionsAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
public override var bounds: CGRect {
didSet {
if oldValue != bounds {
// If busy_loadingView is in the view hierarchy
if let _ = busy_loadingView?.superview {
// Remove loadingView
busy_loadingView?.removeFromSuperview()
self.busy_loadingView = nil
// Restart
start(self.busy_options)
}
}
}
}
public func start(options: BusyNavigationBarOptions? = nil) {
if let loadingView = self.busy_loadingView {
loadingView.removeFromSuperview()
}
busy_options = options ?? BusyNavigationBarOptions()
insertLoadingView()
UIView.animateWithDuration(alphaAnimationDurationOfLoadingView, animations: { () -> Void in
self.busy_loadingView!.alpha = self.busy_options.alpha
})
let animationLayer = pickAnimationLayer()
animationLayer.masksToBounds = true
animationLayer.position = busy_loadingView!.center
if busy_options.transparentMaskEnabled {
animationLayer.mask = maskLayer()
}
busy_loadingView!.layer.addSublayer(animationLayer)
}
public func stop(){
if let loadingView = self.busy_loadingView {
UIView.animateWithDuration(alphaAnimationDurationOfLoadingView, animations: { () -> Void in
loadingView.alpha = 0.0
}) { (Completed) -> Void in
loadingView.removeFromSuperview()
}
}
}
func insertLoadingView() {
busy_loadingView = UIView(frame: bounds)
busy_loadingView!.center.x = bounds.size.width / 2
busy_loadingView!.alpha = 0.0
busy_loadingView!.layer.masksToBounds = true
busy_loadingView!.userInteractionEnabled = false
insertSubview(busy_loadingView!, atIndex: 1)
}
func pickAnimationLayer() -> CALayer {
var animationLayer: CALayer
switch busy_options.animationType {
case .Stripes:
animationLayer = AnimationLayerCreator.stripeAnimationLayer(bounds, options: busy_options)
case .Bars:
animationLayer = AnimationLayerCreator.barAnimation(bounds, options: busy_options)
case .CustomLayer(let layerCreator):
animationLayer = layerCreator()
}
return animationLayer
}
func maskLayer() -> CALayer {
let alphaLayer = CAGradientLayer()
alphaLayer.frame = bounds
alphaLayer.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 0).CGColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.2).CGColor]
return alphaLayer
}
}
|
d07406a5b1b49af804b80e0d9c0f1b0d
| 32.181034 | 138 | 0.634191 | false | false | false | false |
22377832/swiftdemo
|
refs/heads/master
|
ImageButton/ImageButton/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ImageButton
//
// Created by adults on 2017/3/22.
// Copyright © 2017年 adults. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var featureView: UIView!
@IBOutlet weak var featureViewHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createFeatureView(8)
}
func createFeatureView(_ count: Int){
let images = [UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!,
UIImage(named: "touxiang.gif")!]
let tiltes = ["title",
"title",
"title",
"title",
"title",
"title",
"title",
"title"]
let selectors = [#selector(pushToSomewhereOne),
#selector(pushToSomewhereTwo),
#selector(pushToSomewhereThree),
#selector(pushToSomewhereFour),
#selector(pushToSomewhereOne),
#selector(pushToSomewhereTwo),
#selector(pushToSomewhereThree),
#selector(pushToSomewhereFour)]
let space: CGFloat = 0
let numberOfLine = 4
// switch count {
// case 1, 2, 3, 5, 6:
// numberOfLine = 3
// case 4, 7, 8:
// numberOfLine = 4
//
// default:
// numberOfLine = 4
//
// }
let imageButtonWidth = (view.bounds.width - space * CGFloat(numberOfLine - 1)) / CGFloat(numberOfLine)
let imageButtonHeight = imageButtonWidth * 1.2
let imageSize = CGSize(width: imageButtonWidth * 0.6, height: imageButtonWidth * 0.6)
let number1 = count / numberOfLine
let number2 = count % numberOfLine == 0 ? 0 : 1
featureViewHeight.constant = (imageButtonHeight + space) * CGFloat(number1 + number2)
for index in 0..<count {
let imageButton = CYCImageButtonView(frame: CGRect(x: CGFloat(index % numberOfLine) * (imageButtonWidth + space), y: CGFloat(index / numberOfLine) * (imageButtonHeight + space) , width: imageButtonWidth, height: imageButtonHeight), image: images[index], imageSize: imageSize, title: tiltes[index], target: self, action: selectors[index])
self.featureView.addSubview(imageButton)
}
}
func pushToSomewhereOne(){
print("push 1")
}
func pushToSomewhereTwo(){
print("push 2")
}
func pushToSomewhereThree(){
print("push 3")
}
func pushToSomewhereFour(){
print("push 4")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
c3b84e65f5024be4ba1a33cb17940f54
| 32.606061 | 349 | 0.536519 | false | false | false | false |
gmilos/swift
|
refs/heads/master
|
test/SILGen/multi_file.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
func markUsed<T>(_ t: T) {}
// CHECK-LABEL: sil hidden @_TF10multi_file12rdar16016713
func rdar16016713(_ r: Range) {
// CHECK: [[LIMIT:%[0-9]+]] = function_ref @_TFV10multi_file5Rangeg5limitSi : $@convention(method) (Range) -> Int
// CHECK: {{%[0-9]+}} = apply [[LIMIT]]({{%[0-9]+}}) : $@convention(method) (Range) -> Int
markUsed(r.limit)
}
// CHECK-LABEL: sil hidden @_TF10multi_file26lazyPropertiesAreNotStored
func lazyPropertiesAreNotStored(_ container: LazyContainer) {
var container = container
// CHECK: {{%[0-9]+}} = function_ref @_TFV10multi_file13LazyContainerg7lazyVarSi : $@convention(method) (@inout LazyContainer) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @_TF10multi_file29lazyRefPropertiesAreNotStored
func lazyRefPropertiesAreNotStored(_ container: LazyContainerClass) {
// CHECK: {{%[0-9]+}} = class_method %0 : $LazyContainerClass, #LazyContainerClass.lazyVar!getter.1 : (LazyContainerClass) -> () -> Int , $@convention(method) (@guaranteed LazyContainerClass) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @_TF10multi_file25finalVarsAreDevirtualizedFCS_18FinalPropertyClassT_
func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) {
// CHECK: ref_element_addr %0 : $FinalPropertyClass, #FinalPropertyClass.foo
markUsed(obj.foo)
// CHECK: class_method %0 : $FinalPropertyClass, #FinalPropertyClass.bar!getter.1
markUsed(obj.bar)
}
// rdar://18448869
// CHECK-LABEL: sil hidden @_TF10multi_file34finalVarsDontNeedMaterializeForSetFCS_27ObservingPropertyFinalClassT_
func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) {
obj.foo += 1
// CHECK: function_ref @_TFC10multi_file27ObservingPropertyFinalClassg3fooSi
// CHECK: function_ref @_TFC10multi_file27ObservingPropertyFinalClasss3fooSi
}
// rdar://18503960
// Ensure that we type-check the materializeForSet accessor from the protocol.
class HasComputedProperty: ProtocolWithProperty {
var foo: Int {
get { return 1 }
set {}
}
}
// CHECK-LABEL: sil hidden @_TFC10multi_file19HasComputedPropertym3fooSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC10multi_file19HasComputedPropertyS_20ProtocolWithPropertyS_FS1_m3fooSi : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
|
9b44f77a66cdb7e9e9ba6ce4a6cce4a6
| 52.26 | 295 | 0.755539 | false | false | false | false |
terietor/GTForms
|
refs/heads/master
|
Example/TestKeyboardTableViewController.swift
|
mit
|
1
|
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <giorgos.tsiapaliokas@mykolab.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 UIKit
import GTForms
class TestKeyboardTableViewController: FormTableViewController {
fileprivate lazy var hideKeyboardButton: UIBarButtonItem = {
let button = UIBarButtonItem(
title: "Hide Keyboard",
style: .done,
target: self,
action: #selector(didTapHideKeyboardButton)
)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.hideKeyboardButton
let selectionItems = [
SelectionFormItem(text: "Apple"),
SelectionFormItem(text: "Orange")
]
let selectionForm = SelectionForm(
items: selectionItems,
text: "Choose a fruit"
)
selectionForm.textColor = UIColor.red
selectionForm.textFont = UIFont
.preferredFont(forTextStyle: UIFontTextStyle.headline)
selectionForm.allowsMultipleSelection = true
let section = FormSection()
section.addRow(selectionForm)
section.addRow(FormDatePicker(text: "Date Picker"))
section.addRow(FormDoubleTextField(
text: "Double Form",
placeHolder: "Type a double")
)
self.formSections.append(section)
}
@objc fileprivate func didTapHideKeyboardButton() {
hideKeyboard()
}
}
|
c18918e32f8a72b1ac0dccf1826562a0
| 33.945205 | 82 | 0.687574 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.