repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
danielmartin/swift | stdlib/private/SwiftPrivate/IO.swift | 2 | 3406 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
import SwiftShims
public struct _FDInputStream {
public let fd: CInt
public var isClosed: Bool = false
public var isEOF: Bool = false
internal var _buffer = [UInt8](repeating: 0, count: 256)
internal var _bufferUsed: Int = 0
public init(fd: CInt) {
self.fd = fd
}
public mutating func getline() -> String? {
if let newlineIndex =
_buffer[0..<_bufferUsed].firstIndex(of: UInt8(Unicode.Scalar("\n").value)) {
let result = String(decoding: _buffer[0..<newlineIndex], as: UTF8.self)
_buffer.removeSubrange(0...newlineIndex)
_bufferUsed -= newlineIndex + 1
return result
}
if isEOF && _bufferUsed > 0 {
let result = String(decoding: _buffer[0..<_bufferUsed], as: UTF8.self)
_buffer.removeAll()
_bufferUsed = 0
return result
}
return nil
}
public mutating func read() {
let minFree = 128
var bufferFree = _buffer.count - _bufferUsed
if bufferFree < minFree {
_buffer.reserveCapacity(minFree - bufferFree)
while bufferFree < minFree {
_buffer.append(0)
bufferFree += 1
}
}
let fd = self.fd
let readResult: __swift_ssize_t = _buffer.withUnsafeMutableBufferPointer {
(_buffer) in
let addr = _buffer.baseAddress! + self._bufferUsed
let size = bufferFree
return _swift_stdlib_read(fd, addr, size)
}
if readResult == 0 {
isEOF = true
return
}
if readResult < 0 {
fatalError("read() returned error")
}
_bufferUsed += readResult
}
public mutating func close() {
if isClosed {
return
}
let result = _swift_stdlib_close(fd)
if result < 0 {
fatalError("close() returned an error")
}
isClosed = true
}
}
public struct _Stderr : TextOutputStream {
public init() {}
public mutating func write(_ string: String) {
for c in string.utf8 {
_swift_stdlib_putc_stderr(CInt(c))
}
}
}
public struct _FDOutputStream : TextOutputStream {
public let fd: CInt
public var isClosed: Bool = false
public init(fd: CInt) {
self.fd = fd
}
public mutating func write(_ string: String) {
let utf8CStr = string.utf8CString
utf8CStr.withUnsafeBufferPointer {
(utf8CStr) -> Void in
var writtenBytes = 0
let bufferSize = utf8CStr.count - 1
while writtenBytes != bufferSize {
let result = _swift_stdlib_write(
self.fd, UnsafeRawPointer(utf8CStr.baseAddress! + Int(writtenBytes)),
bufferSize - writtenBytes)
if result < 0 {
fatalError("write() returned an error")
}
writtenBytes += result
}
}
}
public mutating func close() {
if isClosed {
return
}
let result = _swift_stdlib_close(fd)
if result < 0 {
fatalError("close() returned an error")
}
isClosed = true
}
}
| apache-2.0 | 0338201794ea110ca44cb5b3a3691b7e | 25.403101 | 82 | 0.596594 | 4.2575 | false | false | false | false |
ask-fm/AFMActionSheet | Pod/Classes/AFMPresentationAnimator.swift | 1 | 2219 | //
// AFMPresentationAnimator.swift
// Pods
//
// Created by Ilya Alesker on 26/08/15.
// Copyright (c) 2015 Ask.fm Europe, Ltd. All rights reserved.
//
import UIKit
open class AFMPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning {
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! as UIViewController
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! as UIViewController
let finalFrame = transitionContext.initialFrame(for: fromViewController)
toViewController.view.frame = finalFrame
transitionContext.containerView.addSubview(toViewController.view)
let views = toViewController.view.subviews
let viewCount = Double(views.count)
var index = 0
let step: Double = self.transitionDuration(using: transitionContext) * 0.5 / viewCount
for view in views {
view.transform = CGAffineTransform(translationX: 0, y: finalFrame.height)
let delay = step * Double(index)
UIView.animate(withDuration: self.transitionDuration(using: transitionContext) - delay,
delay: delay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.3,
options: [],
animations: {
view.transform = CGAffineTransform.identity;
}, completion: nil)
index += 1
}
let backgroundColor = toViewController.view.backgroundColor!
toViewController.view.backgroundColor = backgroundColor.withAlphaComponent(0)
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
animations: {
toViewController.view.backgroundColor = backgroundColor
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
}
| mit | 395950fecee798ca7feb7bf7ae771057 | 37.929825 | 137 | 0.680937 | 5.933155 | false | false | false | false |
jsslai/Action | Demo/DemoTests/BarButtonTests.swift | 2 | 2671 | import Quick
import Nimble
import RxSwift
import RxBlocking
import Action
class BarButtonTests: QuickSpec {
override func spec() {
it("is nil by default") {
let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil)
expect(subject.rx_action).to( beNil() )
}
it("respects setter") {
let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil)
let action = emptyAction()
subject.rx_action = action
expect(subject.rx_action) === action
}
it("disables the button while executing") {
let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil)
var observer: AnyObserver<Void>!
let action = CocoaAction(workFactory: { _ in
return Observable.create { (obsv) -> Disposable in
observer = obsv
return NopDisposable.instance
}
})
subject.rx_action = action
action.execute()
expect(subject.enabled).toEventually( beFalse() )
observer.onCompleted()
expect(subject.enabled).toEventually( beTrue() )
}
it("disables the button if the Action is disabled") {
let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil)
subject.rx_action = emptyAction(.just(false))
expect(subject.enabled) == false
}
it("doesn't execute a disabled action when tapped") {
let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil)
var executed = false
subject.rx_action = CocoaAction(enabledIf: .just(false), workFactory: { _ in
executed = true
return .empty()
})
subject.target?.performSelector(subject.action, withObject: subject)
expect(executed) == false
}
it("executes the action when tapped") {
let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil)
var executed = false
let action = CocoaAction(workFactory: { _ in
executed = true
return .empty()
})
subject.rx_action = action
subject.target?.performSelector(subject.action, withObject: subject)
expect(executed) == true
}
it("disposes of old action subscriptions when re-set") {
let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil)
var disposed = false
autoreleasepool {
let disposeBag = DisposeBag()
let action = emptyAction()
subject.rx_action = action
action
.elements
.subscribe(onNext: nil, onError: nil, onCompleted: nil, onDisposed: {
disposed = true
})
.addDisposableTo(disposeBag)
}
subject.rx_action = nil
expect(disposed) == true
}
}
} | mit | a9373c3696ff04e82dac746c50cae0dd | 24.447619 | 86 | 0.668289 | 3.957037 | false | false | false | false |
broccolii/NipponColors | ColorPicker/ViewController/ColorListViewController.swift | 1 | 14378 | //
// ColorListViewController.swift
// ColorPicker
//
// Created by Broccoli on 15/11/2.
// Copyright © 2015年 Broccoli. All rights reserved.
//
import UIKit
class ColorListViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var lblColorName: UILabel!
@IBOutlet weak var lblBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var lblWidthConstraint: NSLayoutConstraint!
var dataArr = [ColorInfo]()
// 隐藏 状态栏
override func prefersStatusBarHidden() -> Bool {
return true
}
// MARK: - Life cycle
override func loadView() {
super.loadView()
// 在 viewdidload 之前 调用 prepareForSegue 所以 需要 提前 读取到 数据
readColorInfoData()
}
override func viewDidLoad() {
super.viewDidLoad()
// 添加 页面数据
view.backgroundColor = UIColor(red: CGFloat(dataArr[0].RValue) / 255.0, green: CGFloat(dataArr[0].GValue) / 255.0, blue: CGFloat(dataArr[0].BValue) / 255.0, alpha: 1.0)
lblColorName.text = dataArr[0].colorName
addOverLayer()
screenAdaptation()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ColorPropertyTableViewController" {
let VC = segue.destinationViewController as! ColorPropertyTableViewController
VC.colorInfo = dataArr[0]
}
}
// MARK: - private method
/// 读取 颜色数据
func readColorInfoData() {
let path = NSBundle.mainBundle().pathForResource("ColorInfoData", ofType: nil)
let data = NSData(contentsOfFile: path!)
do {
let jsonArr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! Array<[String: String]>
for (index, value) in jsonArr.enumerate() {
dataArr.append(ColorInfo.dicToModel(value, index: index))
}
} catch let error as NSError {
print(error)
}
}
/// 愚蠢的版本适配
private func screenAdaptation() {
// TODO: - 考虑 用最小 约束 修改适配
if UIScreen.mainScreen().bounds.width == 320 {
lblWidthConstraint.constant = 60
lblColorName.font = UIFont(name: "HeiseiMinStd-W7", size: 35.0)
if UIScreen.mainScreen().bounds.height == 480 {
lblColorName.hidden = true
}
} else {
lblBottomConstraint.constant = 20
lblColorName.font = UIFont(name: "HeiseiMinStd-W7", size: 43.0)
}
}
// 添加 宣纸样式的遮罩
private func addOverLayer() {
let overLayer = UIImageView()
overLayer.frame = UIScreen.mainScreen().bounds
overLayer.image = UIImage(named: "blurLayer")
overLayer.alpha = 0.4
view.insertSubview(overLayer, aboveSubview: lblColorName)
}
}
private let CellIdentifier = "ColorCollectionViewCell"
// MARK: - UICollectionViewDataSource
extension ColorListViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataArr.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! ColorCollectionViewCell
// 清空 cell 之前的 view 和 layer
// TODO: - 为了 VC 代码 简洁 这个可以写成 cell 的方法
for view in cell.subviews {
view.removeFromSuperview()
}
if let sublayer = cell.layer.sublayers {
for layer in sublayer {
layer.removeFromSuperlayer()
}
}
cell.colorInfo = dataArr[indexPath.row]
return cell
}
}
// MARK: - UICollectionViewDelegate
extension ColorListViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// 系统自带动画 修改 lblColorName 的 透明度 文本 并且通知 下方 属性栏 开始动画
UIView.animateWithDuration(1.2, animations: { () -> Void in
self.lblColorName.alpha = 0.0
}) { (finish) -> Void in
self.lblColorName.text = self.dataArr[indexPath.row].colorName
UIView.animateWithDuration(1.8, animations: { () -> Void in
self.lblColorName.alpha = 1.0
NSNotificationCenter.defaultCenter().postNotificationName("kChangeColorProperty", object: nil, userInfo: ["colorInfo" : self.dataArr[indexPath.row]])
})
}
// POP 动画修改颜色
let animation = POPBasicAnimation(propertyNamed: kPOPLayerBackgroundColor)
animation.toValue = UIColor(red: CGFloat(dataArr[indexPath.row].RValue) / 255.0, green: CGFloat(dataArr[indexPath.row].GValue) / 255.0, blue: CGFloat(dataArr[indexPath.row].BValue) / 255.0, alpha: 1.0)
animation.duration = 2.5
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
self.view.layer.pop_addAnimation(animation, forKey: nil)
collectionView.reloadItemsAtIndexPaths([indexPath])
}
}
/// MARK: - ColorCollectionViewCell
class ColorCollectionViewCell: UICollectionViewCell {
@IBOutlet var lblRGBValue: UILabel!
@IBOutlet var lblRGBName: UILabel!
var colorInfo: ColorInfo! {
didSet {
createRBGValue()
createColorName()
createColorCount()
createEnglishName()
drawMaskLayer()
beginAnimation()
}
}
/// 绘制 layer 的基础 data
private let moveToPointArr = [CGPoint(x: 22, y: 195), CGPoint(x: 27, y: 195), CGPoint(x: 32, y: 195)]
private let addLineToPointArr = [CGPoint(x: 22, y: 360), CGPoint(x: 27, y: 360), CGPoint(x: 32, y: 360)]
private let arcCenterArr = [CGPoint(x: 18, y: 39), CGPoint(x: 18, y: 81), CGPoint(x: 18, y: 123), CGPoint(x: 18, y: 165)]
/// RGB 线段
private lazy var lineLayerArr: [CAShapeLayer]! = {
var arr = [CAShapeLayer]()
for i in 0 ..< 3 {
let linePath = UIBezierPath()
linePath.moveToPoint(self.moveToPointArr[i])
linePath.addLineToPoint(self.addLineToPointArr[i])
linePath.closePath()
let lineLayer = CAShapeLayer()
lineLayer.strokeColor = UIColor(white: 1.0, alpha: 0.7).CGColor
lineLayer.lineWidth = 2.0
lineLayer.path = linePath.CGPath
arr.append(lineLayer)
}
return arr
}()
/// CMYK 圆弧
private lazy var shapeLayerArr: [CAShapeLayer]! = {
var arr = [CAShapeLayer]()
for i in 0 ..< 4 {
let path = UIBezierPath(arcCenter: self.arcCenterArr[i], radius: 12, startAngle: CGFloat(-M_PI / 2), endAngle: CGFloat(M_PI * 3 / 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.whiteColor().CGColor
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.path = path.CGPath
shapeLayer.lineWidth = 8.0
arr.append(shapeLayer)
}
return arr
}()
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let ctx = UIGraphicsGetCurrentContext()
// draw base white circle
CGContextSetLineWidth(ctx, 8)
CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 0.2)
CGContextAddArc(ctx, 18, 39, 12, 0, CGFloat(2 * M_PI), 0)
CGContextDrawPath(ctx, CGPathDrawingMode.Stroke)
CGContextAddArc(ctx, 18, 81, 12, 0, CGFloat(2 * M_PI), 0)
CGContextDrawPath(ctx, CGPathDrawingMode.Stroke)
CGContextAddArc(ctx, 18, 123, 12, 0, CGFloat(2 * M_PI), 0)
CGContextDrawPath(ctx, CGPathDrawingMode.Stroke)
CGContextAddArc(ctx, 18, 165, 12, 0, CGFloat(2 * M_PI), 0)
CGContextDrawPath(ctx, CGPathDrawingMode.Stroke)
// RGB 数值 线
CGContextSetLineWidth(ctx, 2)
CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 0.2)
let pointsValue1 = [CGPoint(x: 22, y: 195), CGPoint(x: 22, y: 360)]
CGContextAddLines(ctx, pointsValue1, 2)
let pointsValue2 = [CGPoint(x: 27, y: 195), CGPoint(x: 27, y: 360)]
CGContextAddLines(ctx, pointsValue2, 2)
let pointsValue3 = [CGPoint(x: 32, y: 195), CGPoint(x: 32, y: 360)]
CGContextAddLines(ctx, pointsValue3, 2)
CGContextStrokePath(ctx)
}
/// 绘制 底层视图
private func drawMaskLayer() {
for lineLayer in lineLayerArr {
layer.addSublayer(lineLayer)
}
for shapeLayer in shapeLayerArr {
layer.addSublayer(shapeLayer)
}
// draw color view
let colorView = CALayer()
colorView.frame = CGRect(x: 0, y: 0, width: 60, height: 8)
colorView.backgroundColor = UIColor(red: CGFloat(colorInfo.RValue) / 255.0, green: CGFloat(colorInfo.GValue) / 255.0, blue: CGFloat(colorInfo.BValue) / 255.0, alpha: 1.0).CGColor
self.layer.addSublayer(colorView)
}
}
// MARK: - create widget
extension ColorCollectionViewCell {
// 创建 颜色 英文名
private func createEnglishName() {
let lblEN = UILabel(frame: CGRect(x: 60 - 17, y: 195 + 17, width: 165, height: 17))
lblEN.font = UIFont(name: "DeepdeneBQ-Roman", size: 17.0)
lblEN.textColor = UIColor(white: 1.0, alpha: 0.9)
lblEN.text = colorInfo.colorEN
lblEN.layer.anchorPoint = CGPoint(x: 0, y: 1)
lblEN.layer.position = CGPoint(x: 60 - 17, y: 195)
lblEN.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2))
self.addSubview(lblEN)
}
// 创建 颜色 RGB 值
private func createRBGValue() {
let lblRGB = UILabel(frame: CGRect(x: 0, y: 195 + 9, width: 55, height: 11))
lblRGB.font = UIFont.systemFontOfSize(11.0)
lblRGB.textColor = UIColor(white: 1.0, alpha: 0.9)
lblRGB.text = colorInfo.RBGHexValue
lblRGB.layer.anchorPoint = CGPoint(x: 0, y: 1)
lblRGB.layer.position = CGPoint(x: 0, y: 195)
lblRGB.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2))
self.addSubview(lblRGB)
}
// 创建 颜色 编号
private func createColorCount() {
let lblCount = UILabel(frame: CGRect(x: 60, y: 23, width: 30, height: 13))
lblCount.font = UIFont.systemFontOfSize(13.0)
lblCount.textColor = UIColor(red: CGFloat(colorInfo.RValue) / 255.0, green: CGFloat(colorInfo.GValue) / 255.0, blue: CGFloat(colorInfo.BValue) / 255.0, alpha: 1.0)
lblCount.text = colorInfo.colorCount
lblCount.layer.anchorPoint = CGPoint(x: 0, y: 0)
lblCount.layer.position = CGPoint(x: 60, y: 23)
lblCount.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2))
self.addSubview(lblCount)
}
// 创建 颜色 中文名
private func createColorName() {
let lblName = UILabel(fontname: "HeiseiMinStd-W7", labelText: colorInfo.colorName, fontSize: 17.0)
lblName.textColor = UIColor(white: 1.0, alpha: 0.9)
lblName.frame = CGRect(x: 60 - CGRectGetWidth(lblName.bounds), y: 180 - CGRectGetHeight(lblName.bounds), width: CGRectGetWidth(lblName.bounds), height: CGRectGetHeight(lblName.bounds))
self.addSubview(lblName)
}
}
// MARK: - Add Animation
extension ColorCollectionViewCell {
private func beginAnimation() {
/// 添加 线段 的动画
let lineAnimationToValueArr = [CGFloat(colorInfo.RValue) / 255.0 / 2.0, CGFloat(colorInfo.GValue) / 255.0 / 2.0, CGFloat(colorInfo.BValue) / 255.0 / 2.0]
lineLayerAddAnimation(lineAnimationToValueArr)
/// 添加 圆弧 的动画
let shapeLayerToValueArr = [CGFloat(colorInfo.CValue) / 100.0, CGFloat(colorInfo.MValue) / 100.0, CGFloat(colorInfo.YValue) / 100.0, CGFloat(colorInfo.KValue) / 100.0]
shapeLayerAddAnimation(shapeLayerToValueArr)
}
private func lineLayerAddAnimation(toValueArr: [CGFloat]) {
for (i, lineLayer) in lineLayerArr.enumerate() {
let lineAnimation = POPBasicAnimation(propertyNamed: kPOPShapeLayerStrokeEnd)
lineAnimation.fromValue = 0.5
lineAnimation.toValue = toValueArr[i]
lineAnimation.duration = 1.0
lineAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
lineLayer.pop_addAnimation(lineAnimation, forKey: "strokeEnd")
}
}
private func shapeLayerAddAnimation(toValueArr: [CGFloat]) {
for (i, shapeLayer) in shapeLayerArr.enumerate() {
let animation = POPBasicAnimation(propertyNamed: kPOPShapeLayerStrokeEnd)
animation.fromValue = 1.0
animation.toValue = toValueArr[i]
animation.duration = 3.0
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.12, 1, 0.11, 0.94)
shapeLayer.pop_addAnimation(animation, forKey: "shapeLayer1Animation")
}
}
}
extension UILabel {
// 生成 竖向文本 水平居下对齐
convenience init(fontname: String ,labelText: String, fontSize :CGFloat) {
let font = UIFont(name: fontname, size: fontSize) as UIFont!
let textAttributes: [String : AnyObject] = [NSFontAttributeName: font]
let labelSize = labelText.boundingRectWithSize(CGSizeMake(fontSize, 480), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
self.init(frame: labelSize)
self.attributedText = NSAttributedString(string: labelText, attributes: textAttributes)
self.lineBreakMode = NSLineBreakMode.ByCharWrapping
self.numberOfLines = 0
}
} | mit | 76176b8e92f7bff6db4f23a95e089d6e | 38.688385 | 209 | 0.627882 | 4.475719 | false | false | false | false |
12207480/TYPagerController | TYPagerControllerDemo_swift/TabPagerControllerDemoController.swift | 1 | 1679 | //
// TabPagerControllerDemoController.swift
// TYPagerControllerDemo_swift
//
// Created by tany on 2017/7/19.
// Copyright © 2017年 tany. All rights reserved.
//
import UIKit
class TabPagerControllerDemoController: TYTabPagerController {
lazy var datas = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tabBar.layout.barStyle = TYPagerBarStyle.progressView
self.dataSource = self
self.delegate = self
self.loadData()
}
func loadData() {
var i = 0
while i < 20 {
self.datas.append(i%2==0 ?"Tab \(i)":"Tab Tab \(i)")
i += 1
}
self.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension TabPagerControllerDemoController: TYTabPagerControllerDataSource, TYTabPagerControllerDelegate {
func numberOfControllersInTabPagerController() -> Int {
return self.datas.count
}
func tabPagerController(_ tabPagerController: TYTabPagerController, controllerFor index: Int, prefetching: Bool) -> UIViewController {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(red: CGFloat(arc4random()%255)/255.0, green: CGFloat(arc4random()%255)/255.0, blue: CGFloat(arc4random()%255)/255.0, alpha: 1)
return vc
}
func tabPagerController(_ tabPagerController: TYTabPagerController, titleFor index: Int) -> String {
let title = self.datas[index]
return title
}
}
| mit | 30a015b8a449a481d440da63470886e7 | 28.403509 | 168 | 0.651551 | 4.591781 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Layers/Browse WFS layers/WFSLayersTableViewController.swift | 1 | 9179 | // Copyright 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class WFSLayersTableViewController: UITableViewController {
// Every layer info that could be used to create a WFSFeatureTable
var allLayerInfos: [AGSWFSLayerInfo] = []
// MapView to display the map with WFS features
var mapView: AGSMapView?
// Layer Info for the layer that is currently drawn on map view
var selectedLayerInfo: AGSWFSLayerInfo?
private var shouldSwapCoordinateOrder = false
private var lastQuery: AGSCancelable?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let selectedLayerInfo = selectedLayerInfo, let selectedRow = allLayerInfos.firstIndex(of: selectedLayerInfo) {
let selectedIndexPath = IndexPath(row: selectedRow, section: 0)
tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .middle)
tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .checkmark
}
}
// A convenience type for the table view sections.
private enum Section: Int {
case operational, swapCoordinateOrder
var label: String {
switch self {
case .operational:
return "Operational Layers"
case .swapCoordinateOrder:
return "Coordinate Order"
}
}
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return Section(rawValue: section)?.label
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .operational:
return allLayerInfos.count
case .swapCoordinateOrder:
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .operational:
let cell = tableView.dequeueReusableCell(withIdentifier: "LayerCell", for: indexPath)
let layerInfo = allLayerInfos[indexPath.row]
cell.textLabel?.text = layerInfo.title
cell.accessoryType = (tableView.indexPathForSelectedRow == indexPath) ? .checkmark : .none
return cell
case .swapCoordinateOrder:
let cell: SettingsTableViewCell = (tableView.dequeueReusableCell(withIdentifier: "SettingsCell", for: indexPath) as? SettingsTableViewCell)!
cell.swapCoordinateOrderSwitch.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged)
return cell
}
}
@objc
func switchChanged(_ swapSwitch: UISwitch) {
// Keep track of whether coordinate order should be swapped
self.shouldSwapCoordinateOrder = swapSwitch.isOn
// Check if there is a layer selected
if tableView.indexPathForSelectedRow != nil {
// Query for features taking into account the updated swap order, and display the layer
displaySelectedLayer()
}
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let selectedCell = tableView.cellForRow(at: indexPath), indexPath.section == 0 else {
return
}
// add a checkmark to the selected cell
selectedCell.accessoryType = .checkmark
if self.selectedLayerInfo != allLayerInfos[indexPath.row] {
// Get the selected layer info.
self.selectedLayerInfo = allLayerInfos[indexPath.row]
// Query for features and display the selected layer
displaySelectedLayer()
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
}
// MARK: - Helper Method
func displaySelectedLayer() {
// Check if selected layer info is non-nil
guard let selectedLayerInfo = self.selectedLayerInfo else {
return
}
// Create a WFS feature table with the layer info
let wfsFeatureTable = AGSWFSFeatureTable(layerInfo: selectedLayerInfo)
// Set the feature request mode to manual - only manual is supported at v100.5.
// In this mode, you must manually populate the table - panning and zooming won't request features automatically.
wfsFeatureTable.featureRequestMode = .manualCache
// Set the axis order based on the UI. It is by default false.
wfsFeatureTable.axisOrder = self.shouldSwapCoordinateOrder ? .swap : .noSwap
// If there is an existing query request, cancel it
if let lastQuery = self.lastQuery {
lastQuery.cancel()
}
// Create query parameters
let params = AGSQueryParameters()
params.whereClause = "1=1"
// Show progress
UIApplication.shared.showProgressHUD(message: "Querying")
// Populate features based on query
self.lastQuery = wfsFeatureTable.populateFromService(with: params, clearCache: true, outFields: ["*"]) { [weak self] (result: AGSFeatureQueryResult?, error: Error?) in
guard let self = self else { return }
// Check and get results
if let result = result, let mapView = self.mapView {
// The resulting features should be displayed on the map
// Print the count of features
print("Populated \(result.featureEnumerator().allObjects.count) features.")
// Create a feature layer from the WFS table.
let wfsFeatureLayer = AGSFeatureLayer(featureTable: wfsFeatureTable)
// Choose a renderer for the layer
wfsFeatureLayer.renderer = AGSSimpleRenderer.random(wfsFeatureTable)
// Replace map's operational layer
mapView.map?.operationalLayers.setArray([wfsFeatureLayer])
// Zoom to the extent of the layer
mapView.setViewpointGeometry(selectedLayerInfo.extent!, padding: 50.0)
}
// Check for error. If it's a user canceled error, do nothing.
// Otherwise, display an alert.
else if let error = error {
if (error as NSError).code != NSUserCancelledError {
self.presentAlert(error: error)
} else {
return
}
}
// Hide Progress
UIApplication.shared.hideProgressHUD()
}
}
}
private extension AGSSimpleRenderer {
/// Creates a renderer appropriate for the geometry type of the table,
/// and symbolizes the renderer with a random color
///
/// - Returns: A new `AGSSimpleRenderer` object.
static func random(_ table: AGSFeatureTable) -> AGSSimpleRenderer? {
switch table.geometryType {
case .point, .multipoint:
let simpleMarkerSymbol = AGSSimpleMarkerSymbol(style: .circle, color: .random(), size: 4.0)
return AGSSimpleRenderer(symbol: simpleMarkerSymbol)
case .polyline:
let simpleLineSymbol = AGSSimpleLineSymbol(style: .solid, color: .random(), width: 1.0)
return AGSSimpleRenderer(symbol: simpleLineSymbol)
case .polygon, .envelope:
let simpleFillSymbol = AGSSimpleFillSymbol(style: .solid, color: .random(), outline: nil)
return AGSSimpleRenderer(symbol: simpleFillSymbol)
default:
return nil
}
}
}
private extension UIColor {
/// Creates a random color whose red, green, and blue values are in the
/// range `0...1` and whose alpha value is `1`.
///
/// - Returns: A new `UIColor` object.
static func random() -> UIColor {
let range: ClosedRange<CGFloat> = 0...1
return UIColor(red: .random(in: range), green: .random(in: range), blue: .random(in: range), alpha: 1)
}
}
class SettingsTableViewCell: UITableViewCell {
@IBOutlet weak var swapCoordinateOrderSwitch: UISwitch!
}
| apache-2.0 | c48260ecbadee6881bfbf37064fe2c66 | 39.795556 | 175 | 0.630897 | 5.336628 | false | false | false | false |
hsavit1/LeetCode-Solutions-in-Swift | Solutions/Solutions/Medium/Medium_079_Word_Search.swift | 1 | 2032 | /*
https://leetcode.com/problems/word-search/
#79 Word Search
Level: medium
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
Inspired by @pavel-shlyk at https://leetcode.com/discuss/23165/accepted-very-short-java-solution-no-additional-space
*/
import Foundation
private extension String {
subscript (index: Int) -> Character {
return self[advance(self.startIndex, index)]
}
}
struct Medium_079_Word_Search {
static func exist(var board: [[Character]], word: String) -> Bool {
for var x = 0; x < board.count; x++ {
for var y = 0; y < board[x].count; y++ {
if exist_recursion_helper(board: &board, x: x, y: y, word: word, i: 0) {
return true
}
}
}
return false
}
static private func exist_recursion_helper(inout board board: [[Character]], x: Int, y: Int, word: String, i: Int) -> Bool {
if i == word.characters.count {
return true
}
if x < 0 || y < 0 || x == board.count || y == board[x].count {
return false
}
if board[x][y] != word[i] {
return false
}
let tmp: Character = board[x][y]
board[x][y] = "_"
let exist: Bool = exist_recursion_helper(board: &board, x: x, y: y+1, word: word, i: i+1)
|| exist_recursion_helper(board: &board, x: x, y: y-1, word: word, i: i+1)
|| exist_recursion_helper(board: &board, x: x-1, y: y, word: word, i: i+1)
|| exist_recursion_helper(board: &board, x: x+1, y: y, word: word, i: i+1)
board[x][y] = tmp
return exist
}
} | mit | 4ffa73c6b1fb55a8611bacd03cf49891 | 28.897059 | 197 | 0.572835 | 3.369818 | false | false | false | false |
ziogaschr/swift-sodium | Sodium/Bytes.swift | 2 | 462 | import Foundation
public typealias Bytes = Array<UInt8>
extension Array where Element == UInt8 {
init (count bytes: Int) {
self.init(repeating: 0, count: bytes)
}
public var utf8String: String? {
return String(data: Data(bytes: self), encoding: .utf8)
}
}
extension ArraySlice where Element == UInt8 {
var bytes: Bytes { return Bytes(self) }
}
public extension String {
var bytes: Bytes { return Bytes(self.utf8) }
}
| isc | 920f9dd7718c2d9c70aaaf00d08357af | 21 | 63 | 0.660173 | 3.637795 | false | false | false | false |
brentdax/swift | stdlib/public/core/HeapBuffer.swift | 3 | 2624 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
@usableFromInline // FIXME(sil-serialize-all)
internal typealias _HeapObject = SwiftShims.HeapObject
@usableFromInline
internal protocol _HeapBufferHeader_ {
associatedtype Value
init(_ value: Value)
var value: Value { get set }
}
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline
internal struct _HeapBufferHeader<T> : _HeapBufferHeader_ {
@usableFromInline // FIXME(sil-serialize-all)
internal typealias Value = T
@inlinable // FIXME(sil-serialize-all)
internal init(_ value: T) { self.value = value }
@usableFromInline // FIXME(sil-serialize-all)
internal var value: T
}
@usableFromInline
internal typealias _HeapBuffer<Value,Element>
= ManagedBufferPointer<_HeapBufferHeader<Value>, Element>
@usableFromInline
internal typealias _HeapBufferStorage<Value,Element>
= ManagedBuffer<_HeapBufferHeader<Value>, Element>
extension ManagedBufferPointer where Header : _HeapBufferHeader_ {
@usableFromInline // FIXME(sil-serialize-all)
internal typealias Value = Header.Value
@inlinable // FIXME(sil-serialize-all)
internal init(
_ storageClass: AnyClass,
_ initializer: Value, _ capacity: Int
) {
self.init(
_uncheckedBufferClass: storageClass,
minimumCapacity: capacity)
self.withUnsafeMutablePointerToHeader {
$0.initialize(to: Header(initializer))
}
}
@inlinable // FIXME(sil-serialize-all)
internal var value: Value {
@inline(__always)
get {
return header.value
}
@inline(__always)
set {
return header.value = newValue
}
}
@inlinable // FIXME(sil-serialize-all)
internal subscript(i: Int) -> Element {
@inline(__always)
get {
return withUnsafeMutablePointerToElements { $0[i] }
}
}
@inlinable // FIXME(sil-serialize-all)
internal var baseAddress: UnsafeMutablePointer<Element> {
@inline(__always)
get {
return withUnsafeMutablePointerToElements { $0 }
}
}
@inlinable // FIXME(sil-serialize-all)
internal var storage: AnyObject? {
@inline(__always)
get {
return buffer
}
}
}
| apache-2.0 | c62690df6f4a07f7f3b0874d1f28320c | 26.333333 | 80 | 0.660442 | 4.524138 | false | false | false | false |
alvesjtiago/hnr | HNR/Models/Job.swift | 1 | 756 | //
// Job.swift
// HNR
//
// Created by Tiago Alves on 17/09/2017.
// Copyright © 2017 Tiago Alves. All rights reserved.
//
import UIKit
class Job: NSObject {
var id: Int?
var title: String?
var text: String?
var score: Int?
var by: String?
var url: URL?
convenience init(json: NSDictionary) {
self.init()
id = json.value(forKey: "id") as? Int
title = json.value(forKey: "title") as? String
text = json.value(forKey: "text") as? String
score = json.value(forKey: "score") as? Int
by = json.value(forKey: "by") as? String
if let urlString = json.value(forKey: "url") as? String {
url = URL(string: urlString)
}
}
}
| mit | 780db12fe7cfd5a2a3d84dbf75218ef3 | 24.166667 | 65 | 0.553642 | 3.400901 | false | false | false | false |
jessesquires/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0120.xcplaygroundpage/Contents.swift | 2 | 6776 | /*:
# Revise `partition` Method Signature
* Proposal: [SE-0120](0120-revise-partition-method.md)
* Authors: [Lorenzo Racca](https://github.com/lorenzoracca), [Jeff Hajewski](https://github.com/j-haj), [Nate Cook](https://github.com/natecook1000)
* Review Manager: [Chris Lattner](http://github.com/lattner)
* Status: **Implemented (Swift 3)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000242.html)
* Bug: [SR-1965](https://bugs.swift.org/browse/SR-1965)
* Previous Revision: [1](https://github.com/apple/swift-evolution/blob/1dcfd35856a6f9c86af2cf7c94a9ab76411739e3/proposals/0120-revise-partition-method.md)
## Introduction
This proposal revises the signature for the collection partition algorithm. Partitioning is a foundational API for sorting and for searching through sorted collections.
- Swift-evolution thread: [Feedback from standard library team](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160502/016729.html)
- Swift Bug: [SR-1965](https://bugs.swift.org/browse/SR-1965)
## Motivation
Based on feedback during the review of proposal [SE-0074, Implementation of Binary Search Functions][se-74] and the [list of open issues affecting standard library API stability][list], this is a revised proposal focused only on the existing collection partition method.
The standard library's current `partition` methods, which partition a mutable collection using a binary predicate based on the value of the first element of a collection, are used by the standard library's sorting algorithm but don't offer more general partitioning functionality. A more general partition algorithm using a unary (single-argument) predicate would be more flexible and generally useful.
[se-74]: 0074-binary-search.md
[list]: https://gist.github.com/gribozavr/37e811f12b27c6365fc88e6f9645634d
## Proposed solution
The standard library should replace the two existing `partition` methods with a single method taking a unary predicate called `partition(by:)`. `partition(by:)` rearranges the elements of the collection according to the predicate, such that after partitioning there is a pivot index `p` where no element before `p` satisfies the predicate and every element at and after `p` *does* satisfy the predicate.
```swift
var n = [30, 40, 20, 30, 30, 60, 10]
let p = n.partition(by: { $0 > 30 })
// n == [30, 10, 20, 30, 30, 60, 40]
// p == 5
```
After partitioning is complete, the predicate returns `false` for every element in `n.prefix(upTo: p)` and `true` for every element in `n.suffix(from: p)`.
## Detailed design
`partition(by:)` should be added as a `MutableCollection` requirement with default implementations for mutable and bidirectional mutable collections. Any mutable collection can be partitioned, but the bidirectional algorithm generally performs far fewer assignments.
The proposed APIs are collected here:
```swift
protocol MutableCollection {
// existing requirements
/// Reorders the elements of the collection such that all the elements
/// that match the given predicate are after all the elements that do
/// not match the predicate.
///
/// After partitioning a collection, there is a pivot index `p` where
/// no element before `p` satisfies the `belongsInSecondPartition`
/// predicate and every element at or after `p` satisfies
/// `belongsInSecondPartition`.
///
/// In the following example, an array of numbers is partitioned by a
/// predicate that matches elements greater than 30.
///
/// var numbers = [30, 40, 20, 30, 30, 60, 10]
/// let p = numbers.partition(by: { $0 > 30 })
/// // p == 5
/// // numbers == [30, 10, 20, 30, 30, 60, 40]
///
/// The `numbers` array is now arranged in two partitions. The first
/// partition, `numbers.prefix(upTo: p)`, is made up of the elements that
/// are not greater than 30. The second partition, `numbers.suffix(from: p)`,
/// is made up of the elements that *are* greater than 30.
///
/// let first = numbers.prefix(upTo: p)
/// // first == [30, 10, 20, 30, 30]
/// let second = numbers.suffix(from: p)
/// // second == [60, 40]
///
/// - Parameter belongsInSecondPartition: A predicate used to partition
/// the collection. All elements satisfying this predicate are ordered
/// after all elements not satisfying it.
/// - Returns: The index of the first element in the reordered collection
/// that matches `belongsInSecondPartition`. If no elements in the
/// collection match `belongsInSecondPartition`, the returned index is
/// equal to the collection's `endIndex`.
///
/// - Complexity: O(n)
mutating func partition(
by belongsInSecondPartition: @noescape (Iterator.Element) throws-> Bool
) rethrows -> Index
}
extension MutableCollection {
mutating func partition(
by belongsInSecondPartition: @noescape (Iterator.Element) throws-> Bool
) rethrows -> Index
}
extension MutableCollection where Self: BidirectionalCollection {
mutating func partition(
by belongsInSecondPartition: @noescape (Iterator.Element) throws-> Bool
) rethrows -> Index
}
```
A full implementation of the two default implementations can be found [in this gist][gist].
[gist]: https://gist.github.com/natecook1000/70f36608ecd6236552ce0e9f79b98cff
## Impact on existing code
A thorough, though not exhaustive, search of GitHub for the existing `partition` method found no real evidence of its use. The evident uses of a `partition` method were mainly either tests from the Swift project or third-party implementations similar to the one proposed.
Any existing uses of the existing `partition` methods could be flagged or replaced programmatically. The replacement code, on a mutable collection `c`, finding the pivot `p`:
```swift
// old
let p = c.partition()
// new
let p = c.first.flatMap({ first in
c.partition(by: { $0 >= first })
}) ?? c.startIndex
```
## Alternatives considered
To more closely match the existing API, the `partition(by:)` method could be added only as a default implementation for mutable bidirectional collections. This would unnecessarily limit access to the algorithm for mutable forward collections.
The external parameter label could be `where` instead of `by`. However, using `where` implies that the method finds a pre-existing partition point within in the collection (as in `index(where:)`), rather than modifying the collection to be partitioned by the predicate (as in `sort(by:)`, assuming [SE-0118][] is accepted).
[SE-0118]: 0118-closure-parameter-names-and-labels.md
----------
[Previous](@previous) | [Next](@next)
*/
| mit | 4ec916eef25ad9cd2bfe73ced9fc3102 | 48.459854 | 403 | 0.722107 | 4.096735 | false | false | false | false |
lieonCX/Live | Live/Others/Lib/RITLImagePicker/Photofiles/Navigation/RITLPhotoNavigationViewModel.swift | 1 | 1463 | //
// RITLPhotoNavigationViewModel.swift
// RITLImagePicker-Swift
//
// Created by YueWen on 2017/1/10.
// Copyright © 2017年 YueWen. All rights reserved.
//
import UIKit
let RITLPhotoOriginSize:CGSize = CGSize(width: -100, height: -100)
/// 主导航控制器的viewModel
class RITLPhotoNavigationViewModel: RITLBaseViewModel {
/// 最大的选择数量,默认为9
var maxNumberOfSelectedPhoto = 9 {
willSet {
guard newValue > 0 else {
return
}
RITLPhotoCacheManager.sharedInstance.maxNumeberOfSelectedPhoto = newValue
}
}
/// 当前图片的规格,默认为RITLPhotoOriginSize,原始比例
var imageSize = RITLPhotoOriginSize {
willSet {
RITLPhotoCacheManager.sharedInstance.imageSize = newValue
}
}
/// 获取图片之后的闭包
var completeUsingImage:(([UIImage]) -> Void)? {
willSet {
RITLPhotoBridgeManager.sharedInstance.completeUsingImage = newValue
}
}
/// 获取图片数据之后的闭包
var completeUsingData:(([Data]) -> Void)? {
willSet {
RITLPhotoBridgeManager.sharedInstance.completeUsingData = newValue
}
}
deinit
{
print("\(self.self)deinit")
}
}
| mit | ce401b4a57c41932fbe0331bf422ddaa | 19.484848 | 85 | 0.551036 | 5.026022 | false | false | false | false |
NetFunctional/reddit4watch | Reddit4Watch WatchKit Extension/ThumbnailPostInterfaceController.swift | 1 | 1885 | //
// ThumbnailPostInterfaceController.swift
// Reddit4Watch
//
// Created by Gregory Hogue on 2015-01-30.
// Copyright (c) 2015 NetFunctional. All rights reserved.
//
import WatchKit
import Foundation
class ThumbnailPostInterfaceController: WKInterfaceController {
var redditURL: NSString = ""
@IBOutlet weak var postTitleLabel: WKInterfaceLabel!
@IBOutlet weak var postThumbnailImage: WKInterfaceImage!
@IBOutlet weak var postScoreLabel: WKInterfaceLabel!
@IBOutlet weak var postSubredditLabel: WKInterfaceLabel!
@IBOutlet weak var postAuthorLabel: WKInterfaceLabel!
@IBOutlet weak var postDateLabel: WKInterfaceLabel!
@IBAction func iPhoneButtonAction() {
println(redditURL)
WKInterfaceController.openParentApplication(["redditURL": redditURL],
reply: {(reply, error) -> Void in
println("Reply to openParentApplication received from iPhone app")
})
}
init(context: AnyObject?) {
super.init()
if let post = context as? NSDictionary {
redditURL = (post["permalink"] as? String)!
postTitleLabel.setText(post["title"] as? String)
postScoreLabel.setText(toString(post["score"] as! Int))
postSubredditLabel.setText(post["subreddit"] as? String)
postAuthorLabel.setText(post["author"] as? String)
let url = post["url"] as? String
postThumbnailImage.setImage(UIImage(data: NSData(contentsOfURL: NSURL(string: (post["thumbnail"] as? String)!)!)!))
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy, h:mm a"
postDateLabel.setText(dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: NSTimeInterval(post["created"] as! Int))))
}
}
} | bsd-2-clause | 08a778678409dddfda359cec94d8c391 | 35.980392 | 135 | 0.651459 | 5.013298 | false | false | false | false |
zqqf16/SYM | SYM/UI/MainWindowController.swift | 1 | 6958 | // The MIT License (MIT)
//
// Copyright (c) 2017 - present zqqf16
//
// 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 Cocoa
import Combine
extension NSImage {
static let alert: NSImage = #imageLiteral(resourceName: "alert")
static let symbol: NSImage = #imageLiteral(resourceName: "symbol")
}
class MainWindowController: NSWindowController {
// Toolbar items
@IBOutlet var symButton: NSButton!
@IBOutlet var downloadItem: DownloadToolbarItem!
@IBOutlet var deviceItem: NSToolbarItem!
@IBOutlet var indicator: NSProgressIndicator!
@IBOutlet var dsymPopUpButton: DsymToolBarButton!
var isSymbolicating: Bool = false {
didSet {
DispatchQueue.main.async {
if self.isSymbolicating {
self.indicator.startAnimation(nil)
self.indicator.isHidden = false
} else {
self.indicator.stopAnimation(nil)
self.indicator.isHidden = true
}
}
}
}
private var crashCancellable = Set<AnyCancellable>()
// Dsym
private var dsymManager = DsymManager()
private weak var dsymViewController: DsymViewController?
private var downloaderCancellable: AnyCancellable?
private var downloadTask: DsymDownloadTask?
private weak var downloadStatusViewController: DownloadStatusViewController?
// Crash
var crashContentViewController: ContentViewController! {
if let vc = contentViewController as? ContentViewController {
return vc
}
return nil
}
var crashDocument: CrashDocument? {
return self.document as? CrashDocument
}
override func windowDidLoad() {
super.windowDidLoad()
windowFrameAutosaveName = "MainWindow"
deviceItem.isEnabled = MDDeviceMonitor.shared().deviceConnected
dsymPopUpButton.dsymManager = dsymManager
NotificationCenter.default.addObserver(self, selector: #selector(updateDeviceButton(_:)), name: NSNotification.Name.MDDeviceMonitor, object: nil)
downloaderCancellable = DsymDownloader.shared.$tasks
.receive(on: DispatchQueue.main)
.map { [weak self] tasks -> DsymDownloadTask? in
if let uuid = self?.crashDocument?.crashInfo?.uuid {
return tasks[uuid]
}
return nil
}.sink { [weak self] task in
self?.bind(task: task)
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override var document: AnyObject? {
didSet {
crashCancellable.forEach { cancellable in
cancellable.cancel()
}
guard let document = document as? CrashDocument else {
crashContentViewController.document = nil
return
}
crashContentViewController.document = document
document.$crashInfo
.receive(on: DispatchQueue.main)
.sink { [weak self] crashInfo in
if let crash = crashInfo {
self?.dsymManager.update(crash)
}
}
.store(in: &crashCancellable)
document.$isSymbolicating
.receive(on: DispatchQueue.main)
.assign(to: \.isSymbolicating, on: self)
.store(in: &crashCancellable)
}
}
// MARK: Notifications
@objc func updateDeviceButton(_: Notification) {
deviceItem.isEnabled = MDDeviceMonitor.shared().deviceConnected
}
@objc func crashDidSymbolicated(_: Notification) {
isSymbolicating = false
}
// MARK: IBActions
@IBAction func symbolicate(_: AnyObject?) {
let content = crashDocument?.textStorage.string ?? ""
if content.strip().isEmpty {
return
}
isSymbolicating = true
let dsyms = dsymManager.dsymFiles.values.compactMap { $0.binaryPath }
crashDocument?.symbolicate(withDsymPaths: dsyms)
}
@IBAction func showDsymInfo(_: Any) {
guard dsymManager.crash != nil else {
return
}
let storyboard = NSStoryboard(name: NSStoryboard.Name("Dsym"), bundle: nil)
let vc = storyboard.instantiateController(withIdentifier: "DsymViewController") as! DsymViewController
vc.dsymManager = dsymManager
vc.bind(task: downloadTask)
dsymViewController = vc
contentViewController?.presentAsSheet(vc)
}
@IBAction func downloadDsym(_: AnyObject?) {
startDownloading()
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let vc = segue.destinationController as? DownloadStatusViewController {
vc.delegate = self
downloadStatusViewController = vc
}
}
}
extension MainWindowController: NSToolbarItemValidation {
func validateToolbarItem(_ item: NSToolbarItem) -> Bool {
return item.isEnabled
}
}
extension MainWindowController: DownloadStatusViewControllerDelegate {
func bind(task: DsymDownloadTask?) {
downloadTask = task
downloadStatusViewController?.bind(task: task)
downloadItem.bind(task: task)
dsymViewController?.bind(task: task)
if let files = task?.dsymFiles {
dsymManager.dsymFileDidUpdate(files)
}
}
func startDownloading() {
if let crash = dsymManager.crash {
DsymDownloader.shared.download(crashInfo: crash, fileURL: nil)
}
}
func cancelDownload() {
downloadTask?.cancel()
}
func currentDownloadTask() -> DsymDownloadTask? {
return downloadTask
}
}
| mit | 9858c02f9a8a962e6f9c0728fdc316b9 | 31.976303 | 153 | 0.640414 | 5.157895 | false | false | false | false |
RaviDesai/RSDRestServices | Pod/Classes/ResponseParsers/APIDataResponseParser.swift | 2 | 1285 | //
// NSDataResponseParser.swift
// CEVFoundation
//
// Created by Ravi Desai on 6/10/15.
// Copyright (c) 2015 CEV. All rights reserved.
//
import Foundation
public class APIDataResponseParser : APIResponseParserProtocol {
public typealias T = NSData
public init() {
self.acceptTypes = nil
}
public init(acceptTypes: [String]) {
self.acceptTypes = acceptTypes
}
public private(set) var acceptTypes: [String]?
public class func convertToSerializable(response: NetworkResponse) -> (NSData?, NSError?) {
let data: NSData? = response.getData()
let error: NSError? = response.getError()
return (data, error)
}
public class func convertToSerializableArray(response: NetworkResponse) -> ([NSData]?, NSError?) {
let data: NSData? = response.getData()
let error: NSError? = response.getError()
return (data != nil ? [data!] : nil, error)
}
public func Parse(response: NetworkResponse) -> (NSData?, NSError?) {
return APIDataResponseParser.convertToSerializable(response)
}
public func ParseToArray(response: NetworkResponse) -> ([NSData]?, NSError?) {
return APIDataResponseParser.convertToSerializableArray(response)
}
} | mit | 6f85aaaabc0181f4d45990a7185b8a1b | 29.619048 | 102 | 0.655253 | 4.556738 | false | false | false | false |
skutnii/4swivl | TestApp/TestApp/PersonCell.swift | 1 | 2381 | //
// PersonCell.swift
// TestApp
//
// Created by Serge Kutny on 9/17/15.
// Copyright © 2015 skutnii. All rights reserved.
//
import UIKit
protocol AvatarViewer : class {
func viewAvatar(forPerson person:Person?) -> ()
}
class PersonCell : UITableViewCell {
@IBOutlet var avatarView : UIImageView? = nil
@IBOutlet var nameLabel : UILabel? = nil
@IBOutlet var profileLabel : UILabel? = nil
@IBOutlet var infoView : UITextView? = nil
@IBOutlet var avatarOverlay : UIView? = nil {
didSet {
if nil != avatarOverlay {
avatarOverlay!.addGestureRecognizer(UITapGestureRecognizer(target:self, action:(NSSelectorFromString("viewAvatar"))))
}
}
}
weak var avatarViewDelegate : AvatarViewer? = nil
@IBAction func viewAvatar() {
avatarViewDelegate?.viewAvatar(forPerson: self.person)
}
private var _onAvatarChange : Callback<UIImage, Person>? = nil
var person : Person? = nil {
willSet {
person?.avatar.preview.removeObserver(_onAvatarChange)
}
didSet {
_onAvatarChange = person?.avatar.preview.addObserver({
[weak self]
(from: UIImage?, to: UIImage?, person: AnyObject) in
guard person === self?.person else {
return
}
self?.layoutSubviews()
})
}
}
override func layoutSubviews() {
super.layoutSubviews()
let name = NSMutableAttributedString(string: person?.login ?? "")
let link = NSMutableAttributedString(string:person?.profileLink ?? "")
name.setAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(20.0),
NSForegroundColorAttributeName: UIColor.whiteColor()], range: NSMakeRange(0, name.length))
link.setAttributes([NSFontAttributeName: UIFont.systemFontOfSize(16.0)], range: NSMakeRange(0, link.length))
let text = NSMutableAttributedString(string:"")
text.appendAttributedString(name)
text.appendAttributedString(NSAttributedString(string:"\n\n"))
text.appendAttributedString(link)
avatarView?.image = self.person?.avatar.preview[]
self.infoView?.attributedText = text
}
}
| mit | 66feb163b584b5df81f92f45113bf77f | 33 | 134 | 0.605462 | 5.140389 | false | false | false | false |
jad6/JadKit | JadKit/Protocols/DynamicList.swift | 1 | 13920 | //
// DynamicList.swift
// JadKit
//
// Created by Jad Osseiran on 7/13/15.
// Copyright © 2016 Jad Osseiran. All rights reserved.
//
// --------------------------------------------
//
// Implements the protocol and their extensions to get a Core Data backed fetched list going.
//
// --------------------------------------------
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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
import CoreData
/**
The basic beahviour that a fetched list needs to implement. The core
of a fetched list is a `NSFetchedResultsController` object that the
conforming object will need to create in order to properly calculate the
list data.
*/
public protocol DynamicList: List, NSFetchedResultsControllerDelegate {
/// A fetched object needs to conform to `NSFetchRequestResult`, restrict it to a `Object` in the
/// protocol extensions.
associatedtype FetchedObject: NSFetchRequestResult
/// The fetched results controller that will be used to populate the list
/// dynamically as the backing store is updated.
var fetchedResultsController: NSFetchedResultsController<FetchedObject>! { get set }
}
/**
Protocol extension to implement the basic fetched list methods.
*/
public extension DynamicList where Object == FetchedObject {
/// The number of sections fetched by the `fetchedResultsController`.
var sectionCount: Int {
return fetchedResultsController?.sections?.count ?? 0
}
/// The index titles for the fetched list.
var sectionIndexTitles: [String]? {
return fetchedResultsController?.sectionIndexTitles
}
/**
The number of rows in a section fetched by the `fetchedResultsController`.
- parameter section: The section in which the row count will be returned.
- returns: The number of rows in a given section. `0` if the section is
not found.
*/
func itemCount(at section: Int) -> Int {
if let sections = fetchedResultsController?.sections {
return sections[section].numberOfObjects
}
return 0
}
/**
Conveneient helper method to ensure that a given index path is valid.
- note: This method is implemented by a protocol extension if the object
conforms to either `DynamicList` or `StaticList`
- parameter indexPath: The index path to check for existance.
- returns: `true` iff the index path is valid for your data source.
*/
func isValid(indexPath: IndexPath) -> Bool {
guard indexPath.section < sectionCount && indexPath.section >= 0 else {
return false
}
return indexPath.row < itemCount(at: indexPath.section) && indexPath.row >= 0
}
/**
Convenient helper method to find the object at a given index path.
This method works well with `isValidIndexPath:`.
- note: This method is implemented by a protocol extension if the object
conforms to either `DynamicList` or `StaticList`
- parameter indexPath: The index path to retreive the object for.
- returns: An optional with the corresponding object at an index
path or nil if the index path is invalid.
*/
func object(at indexPath: IndexPath) -> Object? {
guard isValid(indexPath: indexPath) else {
return nil
}
return fetchedResultsController?.object(at: indexPath)
}
/**
Helper method to grab the title for a header for a given section.
- parameter section: The section for the header's title to grab.
- returns: The header title for the section or `nil` if none is found.
*/
func titleForHeader(at section: Int) -> String? {
guard isValid(indexPath: IndexPath(row: 0, section: section)) else {
return nil
}
return fetchedResultsController?.sections?[section].name
}
}
// MARK: Table
/**
Protocol to set up the conformance to the various protocols to allow
for a valid table view protocol extension implementation.
*/
public protocol DynamicTableList: DynamicList, UITableViewDataSource, UITableViewDelegate {
/// The table view that will be updated as the `fetchedResultsController`
/// is updated.
var tableView: UITableView! { get set }
}
/**
Protocol extension to implement the table view delegate & data source methods.
*/
public extension DynamicTableList where ListView == UITableView, Cell == UITableViewCell, Object == FetchedObject {
/**
Method to call in `tableView:cellForRowAtIndexPath:`.
- parameter indexPath: An index path locating a row in `tableView`
*/
func cell(at indexPath: IndexPath) -> UITableViewCell {
let identifier = cellIdentifier(at: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
if let object = object(at: indexPath) {
listView(tableView, configureCell: cell, withObject: object, atIndexPath: indexPath)
}
return cell
}
/**
Method to call in `tableView:didSelectRowAtIndexPath:`.
- parameter indexPath: An index path locating the new selected row in `tableView`.
*/
func didSelectItem(at indexPath: IndexPath) {
if let object = object(at: indexPath) {
listView(tableView, didSelectObject: object, atIndexPath: indexPath)
}
}
}
/**
Protocol extension to implement the fetched results controller
sdelegate methods.
*/
public extension DynamicTableList where ListView == UITableView, Cell == UITableViewCell, Object == FetchedObject {
/**
Method to call in `controllerWillChangeContent:`.
*/
func willChangeContent() {
tableView.beginUpdates()
}
/**
Method to call in `controller:didChangeSection:atIndex:forChangeType:`.
- parameter sectionIndex: The index of the changed section.
- parameter type: The type of change (insert or delete). Valid values are
`NSFetchedResultsChangeInsert` and `NSFetchedResultsChangeDelete`.
*/
func didChangeSection(_ sectionIndex: Int, withChangeType type: NSFetchedResultsChangeType) {
switch type {
case .insert:
tableView.insertSections(IndexSet(integer: sectionIndex), with: .automatic)
case .delete:
tableView.deleteSections(IndexSet(integer: sectionIndex), with: .automatic)
case .update:
tableView.reloadSections(IndexSet(integer: sectionIndex), with: .automatic)
default:
// FIXME: Figure out what to do with .Move
break
}
}
/**
Method to call in `controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:`.
- parameter indexPath: The index path of the changed object (this value is `nil`
for insertions).
- parameter type: The type of change. For valid values see `NSFetchedResultsChangeType`
- parameter newIndexPath: The destination path for the object for insertions or moves
(this value is `nil` for a deletion).
*/
func didChangeObject(at indexPath: IndexPath?, withChangeType type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .automatic)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .automatic)
case .update:
tableView.reloadRows(at: [indexPath!], with: .automatic)
case .move:
tableView.moveRow(at: indexPath!, to: newIndexPath!)
}
}
/**
Method to call in `controllerDidChangeContent:`
*/
func didChangeContent() {
tableView.endUpdates()
}
}
// MARK: Collection
/**
Protocol to set up the conformance to the various protocols to allow
for a valid collection view protocol extension implementation.
*/
public protocol DynamicCollectionList: DynamicList, UICollectionViewDataSource, UICollectionViewDelegate {
/// The collection view to update with the fetched changes.
var collectionView: UICollectionView? { get set }
/// Classes that conform to this protocol need only to initialise this
/// property. It is an array of block operations used to hold the section
/// and row changes so that the collection view can be animated in the same
/// way a table view controller handles section changes.
var changeOperations: [BlockOperation] { get set }
}
/**
Protocol extension to implement the custom source methods.
*/
public extension DynamicCollectionList where ListView == UICollectionView, Cell == UICollectionViewCell,
Object == FetchedObject {
/**
Cancel the queued up collection view row & section changes.
*/
func cancelChangeOperations() {
for operation: BlockOperation in changeOperations {
operation.cancel()
}
changeOperations.removeAll(keepingCapacity: false)
}
}
/**
Protocol extension to implement the collection view delegate &
data source methods.
*/
public extension DynamicCollectionList where ListView == UICollectionView, Cell == UICollectionViewCell,
Object == FetchedObject {
/**
Method to call in `collectionView:cellForItemAtIndexPath:`.
- parameter indexPath: The index path that specifies the location of the item.
*/
func cell(at indexPath: IndexPath) -> UICollectionViewCell {
let identifier = cellIdentifier(at: indexPath)
let cell = collectionView!.dequeueReusableCell(withReuseIdentifier: identifier,
for: indexPath)
if let object = object(at: indexPath) {
listView(collectionView!, configureCell: cell, withObject: object, atIndexPath: indexPath)
}
return cell
}
/**
Method to call in `collectionView:didSelectItemAtIndexPath:`.
- parameter indexPath: The index path of the cell that was selected.
*/
func didSelectItem(at indexPath: IndexPath) {
if let object = object(at: indexPath) {
listView(collectionView!, didSelectObject: object, atIndexPath: indexPath)
}
}
}
/**
Protocol extension to implement the fetched results controller
sdelegate methods.
*/
public extension DynamicCollectionList where ListView == UICollectionView, Cell == UICollectionViewCell,
Object == FetchedObject {
/**
Method to call in `controllerWillChangeContent:`.
*/
func willChangeContent() {
self.changeOperations.removeAll(keepingCapacity: false)
}
/**
Method to call in `controller:didChangeSection:atIndex:forChangeType:`.
- parameter sectionIndex: The index of the changed section.
- parameter type: The type of change (insert or delete). Valid values are
`NSFetchedResultsChangeInsert` and `NSFetchedResultsChangeDelete`.
*/
func didChangeSection(_ sectionIndex: Int, withChangeType type: NSFetchedResultsChangeType) {
let indexSet = IndexSet(integer: sectionIndex)
switch type {
case .insert:
changeOperations.append(
BlockOperation { [weak self] in
self?.collectionView!.insertSections(indexSet)
})
case .update:
changeOperations.append(
BlockOperation { [weak self] in
self?.collectionView!.reloadSections(indexSet)
})
case .delete:
changeOperations.append(
BlockOperation { [weak self] in
self?.collectionView!.deleteSections(indexSet)
})
default:
break
}
}
/**
Method to call in `controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:`.
- parameter indexPath: The index path of the changed object (this value is `nil`
for insertions).
- parameter type: The type of change. For valid values see `NSFetchedResultsChangeType`
- parameter newIndexPath: The destination path for the object for insertions or moves
(this value is `nil` for a deletion).
*/
func didChangeObject(at indexPath: IndexPath?, withChangeType type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
switch type {
case .insert:
changeOperations.append(
BlockOperation { [weak self] in
self?.collectionView!.insertItems(at: [newIndexPath!])
})
case .update:
changeOperations.append(
BlockOperation { [weak self] in
self?.collectionView!.reloadItems(at: [indexPath!])
})
case .move:
changeOperations.append(
BlockOperation { [weak self] in
self?.collectionView!.moveItem(at: indexPath!, to: newIndexPath!)
})
case .delete:
changeOperations.append(
BlockOperation { [weak self] in
self?.collectionView!.deleteItems(at: [indexPath!])
})
}
}
/**
Method to call in `controllerDidChangeContent:`
*/
func didChangeContent() {
for section in fetchedResultsController.sections! {
print(section.numberOfObjects)
}
collectionView!.performBatchUpdates({
for operation in self.changeOperations {
operation.start()
}
}, completion: { [weak self] finished in
self?.changeOperations.removeAll(keepingCapacity: false)
})
}
}
| bsd-2-clause | 751ceb2646231a98ca568a6d6736c0b4 | 34.689744 | 115 | 0.709606 | 4.949858 | false | false | false | false |
Mattmlm/codepathtwitter | Codepath Twitter/Codepath Twitter/ComposeTweetViewController.swift | 1 | 2200 | //
// ComposeTweetViewController.swift
// Codepath Twitter
//
// Created by admin on 10/4/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class ComposeTweetViewController: UIViewController {
@IBOutlet weak var tweetField: UITextField!
var replyToTweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#55ACEE");
self.navigationController?.navigationBar.translucent = false;
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor();
if replyToTweet != nil {
self.tweetField.text = "@\((replyToTweet!.user?.screenname)!) "
}
self.tweetField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onCancelButtonPressed(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil);
}
@IBAction func onTweetButtonPressed(sender: AnyObject) {
let dict = NSMutableDictionary()
dict["status"] = tweetField.text!
if replyToTweet != nil {
dict["in_reply_to_status_id"] = replyToTweet!.idString!
}
TwitterClient.sharedInstance.composeTweetWithCompletion(dict) { (tweet, error) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil);
})
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 60a868d261d40ffb975eba316bd7f693 | 31.338235 | 125 | 0.657572 | 5.174118 | false | false | false | false |
larrynatalicio/15DaysofAnimationsinSwift | Animation 08 - GradientAnimation/GradientAnimation/LoadingLabel.swift | 1 | 2860 | //
// LoadingLabel.swift
// GradientAnimation
//
// Created by Larry Natalicio on 4/23/16.
// Copyright © 2016 Larry Natalicio. All rights reserved.
//
import UIKit
@IBDesignable
class LoadingLabel: UIView {
// MARK: - Types
struct Constants {
struct Fonts {
static let loadingLabel = "HelveticaNeue-UltraLight"
}
}
// MARK: - Properties
let gradientLayer: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
// Configure gradient.
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
let colors = [UIColor.gray.cgColor, UIColor.white.cgColor, UIColor.gray.cgColor]
gradientLayer.colors = colors
let locations = [0.25, 0.5, 0.75]
gradientLayer.locations = locations as [NSNumber]?
return gradientLayer
}()
let textAttributes: [String: AnyObject] = {
let style = NSMutableParagraphStyle()
style.alignment = .center
return [NSFontAttributeName: UIFont(name: Constants.Fonts.loadingLabel, size: 70.0)!, NSParagraphStyleAttributeName: style]
}()
@IBInspectable var text: String! {
didSet {
setNeedsDisplay()
// Create a temporary graphic context in order to render the text as an image.
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
text.draw(in: bounds, withAttributes: textAttributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Use image to create a mask on the gradient layer.
let maskLayer = CALayer()
maskLayer.backgroundColor = UIColor.clear.cgColor
maskLayer.frame = bounds.offsetBy(dx: bounds.size.width, dy: 0)
maskLayer.contents = image?.cgImage
gradientLayer.mask = maskLayer
}
}
// MARK: - View Life Cycle
override func layoutSubviews() {
gradientLayer.frame = CGRect(x: -bounds.size.width, y: bounds.origin.y, width: 2 * bounds.size.width, height: bounds.size.height)
}
override func didMoveToWindow() {
super.didMoveToWindow()
layer.addSublayer(gradientLayer)
let gradientAnimation = CABasicAnimation(keyPath: "locations")
gradientAnimation.fromValue = [0.0, 0.0, 0.25]
gradientAnimation.toValue = [0.75, 1.0, 1.0]
gradientAnimation.duration = 1.7
gradientAnimation.repeatCount = Float.infinity
gradientAnimation.isRemovedOnCompletion = false
gradientAnimation.fillMode = kCAFillModeForwards
gradientLayer.add(gradientAnimation, forKey: nil)
}
}
| mit | cf608cc98b77bd7c2869a182f7c085e2 | 31.123596 | 137 | 0.616299 | 5.078153 | false | false | false | false |
esttorhe/MammutAPI | Sources/MammutAPI/Mappers/MentionMapper.swift | 1 | 877 | //
// Created by Esteban Torres on 21.04.17.
// Copyright (c) 2017 Esteban Torres. All rights reserved.
//
import Foundation
internal class MentionMapper: ModelMapping {
typealias Model = Mention
func map(json: ModelMapping.JSONDictionary) -> Result<Model, MammutAPIError.MappingError> {
guard
let id = json["id"] as? Int,
let urlString = json["url"] as? String,
let url = URL(string: urlString),
let username = json["username"] as? String,
let acct = json["acct"] as? String
else {
return .failure(MammutAPIError.MappingError.incompleteModel)
}
let mention = Mention(
id: id,
url: url,
username: username,
acct: acct
)
return .success(mention)
}
}
| mit | 61138d33eb9a33063a817a2139c10cbb | 28.233333 | 95 | 0.54504 | 4.520619 | false | false | false | false |
SmallPlanetSwift/PlanetSwift | Sources/PlanetSwift/PlanetViewController.swift | 1 | 5966 | //
// PlanetViewController.swift
// PlanetSwift
//
// Created by Brad Bambara on 1/21/15.
// Copyright (c) 2015 Small Planet. All rights reserved.
//
// swiftlint:disable line_length
// swiftlint:disable cyclomatic_complexity
import UIKit
public typealias AnchorageAction = ((String, UIView, UIView, UIView?, UIView?, [String: Object]) -> Void)
open class PlanetViewController: UIViewController {
open var planetViews = [PlanetView]()
var idMappings = [String: Object]()
@IBInspectable open var titleBundlePath: String?
open var mainBundlePath: String?
open var navigationBarHidden = false
open var persistentViews = false
open var statusBarStyle: UIStatusBarStyle = .default
open var titleXmlView: View?
open var mainXmlView: View?
private var anchorageAction: AnchorageAction?
open var safeAreaInsets: UIEdgeInsets {
if #available(iOS 11.0, *) {
if let navController = self.navigationController {
return navController.view.safeAreaInsets
}
if let window = UIApplication.shared.windows.first {
return window.safeAreaInsets
}
}
return UIEdgeInsets.zero
}
open func unloadViews() {
view.removeFromSuperview()
view = nil
titleXmlView = nil
mainXmlView = nil
idMappings.removeAll()
planetViews.removeAll()
}
open func loadPlanetViews(_ anchorage:@escaping AnchorageAction) {
navigationItem.title = self.title
if let titleBundlePath = titleBundlePath, let titleXmlView = PlanetUI.readFromFile(String(bundlePath: titleBundlePath)) as? View {
navigationItem.titleView = titleXmlView.view
titleXmlView.visit { $0.gaxbDidPrepare() }
searchXMLObject(titleXmlView)
self.titleXmlView = titleXmlView
}
if let mainBundlePath = mainBundlePath, let mainXmlView = PlanetUI.readFromFile(String(bundlePath: mainBundlePath)) as? View {
view.addSubview(mainXmlView.view)
mainXmlView.visit { $0.gaxbDidPrepare() }
searchXMLObject(mainXmlView)
self.mainXmlView = mainXmlView
}
if self.mainXmlView != nil || self.titleXmlView != nil {
// Overriding loadView because we need a function where the view exists
// but child view controllers have not been loaded yet
searchForPlanetView(view)
for planetView in planetViews {
if let xmlObj = planetView.xmlView {
searchXMLObject(xmlObj)
xmlObj.visit(decorate)
}
}
}
self.anchorageAction = anchorage
let mirror = Mirror(reflecting: self)
var validKeys: [String: Bool] = [:]
for case let (label?, _) in mirror.children {
validKeys[label] = true
}
// we cannot just iterate over the idMappings because the ordering is
// not garaunteed, therefor we walk over them in XML order
if let mainXmlView = mainXmlView {
mainXmlView.visit {
if let mmm = ($0 as? View) {
if let objectID = mmm.id {
let view = mmm.view
if let parent = view.superview {
if let idx = parent.subviews.firstIndex(of: view) {
let prev: UIView? = idx > 0 ? parent.subviews[idx-1] : nil
let next: UIView? = idx < parent.subviews.count-1 ? parent.subviews[idx+1] : nil
if validKeys[objectID] != nil {
setValue(view, forKey: objectID)
}
anchorage(objectID, view, parent, prev, next, idMappings)
} else {
if validKeys[objectID] != nil {
setValue(view, forKey: objectID)
}
anchorage(objectID, view, parent, nil, nil, idMappings)
}
}
}
}
}
}
}
func searchXMLObject(_ xmlObj: Object) {
xmlObj.visit { [unowned self] (element: GaxbElement) -> Void in
if let xmlController = element as? Controller {
xmlController.controllerObject = self
}
if let xmlObject = element as? Object, let objectId = xmlObject.id {
self.idMappings[objectId] = xmlObject
}
}
}
open func decorate(_ element: GaxbElement) {
// Override decorate in your controller class if you need a
// handle on the XML views from your PlanetView
}
func searchForPlanetView(_ searchedView: UIView) {
if let foundView = searchedView as? PlanetView {
planetViews.append(foundView)
}
for child in searchedView.subviews {
searchForPlanetView(child as UIView)
}
}
open func objectForId<T>(_ objID: String) -> T? {
guard let foundObj = idMappings[objID] as? T else { return nil }
return foundObj
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationController?.setNavigationBarHidden(navigationBarHidden, animated: true)
self.setNeedsStatusBarAppearanceUpdate()
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
open override func viewDidDisappear(_ animated: Bool) {
if persistentViews == false {
// Unload all exisiting views
unloadViews()
}
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
}
}
| mit | 01f5b18af26ca6a26fda98b5b91a48d3 | 34.094118 | 138 | 0.573584 | 5.192341 | false | false | false | false |
hayleyqinn/windWeather | 风生/Pods/Alamofire/Source/ServerTrustPolicy.swift | 303 | 12898 | //
// ServerTrustPolicy.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 Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
open class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
open let policies: [String: ServerTrustPolicy]
/// Initializes the `ServerTrustPolicyManager` instance with the given policies.
///
/// Since different servers and web services can have different leaf certificates, intermediate and even root
/// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
/// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
/// pinning for host3 and disabling evaluation for host4.
///
/// - parameter policies: A dictionary of all policies mapped to a particular host.
///
/// - returns: The new `ServerTrustPolicyManager` instance.
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/// Returns the `ServerTrustPolicy` for the given host if applicable.
///
/// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
/// this method and implement more complex mapping implementations such as wildcards.
///
/// - parameter host: The host to use when searching for a matching policy.
///
/// - returns: The server trust policy for the given host if found.
open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension URLSession {
private struct AssociatedKeys {
static var managerKey = "URLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
/// with a given set of criteria to determine whether the server trust is valid and the connection should be made.
///
/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
/// to route all communication over an HTTPS connection with pinning enabled.
///
/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
/// validate the host provided by the challenge. Applications are encouraged to always
/// validate the host in production environments to guarantee the validity of the server's
/// certificate chain.
///
/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
/// considered valid if one of the pinned certificates match one of the server certificates.
/// By validating both the certificate chain and host, certificate pinning provides a very
/// secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate
/// chain in production environments.
///
/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
/// valid if one of the pinned public keys match one of the server certificate public keys.
/// By validating both the certificate chain and host, public key pinning provides a very
/// secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate
/// chain in production environments.
///
/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
///
/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust.
public enum ServerTrustPolicy {
case performDefaultEvaluation(validateHost: Bool)
case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case disableEvaluation
case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool)
// MARK: - Bundle Location
/// Returns all certificates within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `.cer` files.
///
/// - returns: All certificates within the given bundle.
public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil)
}.joined())
for path in paths {
if
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/// Returns all public keys within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `*.cer` files.
///
/// - returns: All public keys within the given bundle.
public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificates(in: bundle) {
if let publicKey = publicKey(for: certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/// Evaluates whether the server trust is valid for the given host.
///
/// - parameter serverTrust: The server trust to evaluate.
/// - parameter host: The host of the challenge protection space.
///
/// - returns: Whether the server trust is valid.
public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .performDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
serverTrustIsValid = trustIsValid(serverTrust)
case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateData(for: serverTrust)
let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData == pinnedCertificateData {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .disableEvaluation:
serverTrustIsValid = true
case let .customEvaluation(closure):
serverTrustIsValid = closure(serverTrust, host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(_ trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType.unspecified
let proceed = SecTrustResultType.proceed
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateData(for trust: SecTrust) -> [Data] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateData(for: certificates)
}
private func certificateData(for certificates: [SecCertificate]) -> [Data] {
return certificates.map { SecCertificateCopyData($0) as Data }
}
// MARK: - Private - Public Key Extraction
private static func publicKeys(for trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if
let certificate = SecTrustGetCertificateAtIndex(trust, index),
let publicKey = publicKey(for: certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKey(for certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust, trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
| mit | 2f4dd75ba6fd0cf3e5d170412c90dc1f | 43.020478 | 120 | 0.653435 | 5.776086 | false | false | false | false |
Ellusioists/TimingRemind | TimingRemind/Views/TableViewCell.swift | 1 | 1512 | //
// TableViewCell.swift
// TimingRemind
//
// Created by Channing Kuo on 2017/10/9.
// Copyright © 2017年 Channing Kuo. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
var labelName, labelValue: UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = UITableViewCellSelectionStyle.none
accessoryType = UITableViewCellAccessoryType.disclosureIndicator
labelName = UILabel()
labelName.textColor = .white
labelName.textAlignment = .left
labelName.backgroundColor = .clear
contentView.addSubview(labelName)
labelValue = UILabel()
labelValue.textColor = .white
labelValue.textAlignment = .right
labelValue.backgroundColor = .clear
labelValue.lineBreakMode = .byTruncatingTail
contentView.addSubview(labelValue)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
labelName.frame = CGRect(x: 20, y: 0, width: 100, height: 50)
labelValue.frame = CGRect(x: 120, y: 0, width: contentView.bounds.width - 120, height: 50)
}
public func updateUIString(name: String, value: String) {
labelName.text = name
labelValue.text = value
}
}
| mit | 2089ea752bd0de141d8a65449cf65a08 | 29.795918 | 98 | 0.65275 | 5.03 | false | false | false | false |
xwu/swift | test/Compatibility/attr_override.swift | 10 | 17289 | // RUN: %target-typecheck-verify-swift -swift-version 4
@override // expected-error {{'override' can only be specified on class members}} {{1-11=}} expected-error {{'override' is a declaration modifier, not an attribute}} {{1-2=}}
func virtualAttributeCanNotBeUsedInSource() {}
class MixedKeywordsAndAttributes { // expected-note {{in declaration of 'MixedKeywordsAndAttributes'}}
// expected-error@+1 {{expected declaration}} expected-error@+1 {{consecutive declarations on a line must be separated by ';'}} {{11-11=;}}
override @inline(never) func f1() {}
}
class DuplicateOverrideBase {
func f1() {}
class func cf1() {}
class func cf2() {}
class func cf3() {}
class func cf4() {}
}
class DuplicateOverrideDerived : DuplicateOverrideBase {
override override func f1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override override class func cf1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf2() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
class override override func cf3() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf4() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
}
class A {
func f0() { }
func f1() { } // expected-note{{overridden declaration is here}}
var v1: Int { return 5 }
var v2: Int { return 5 } // expected-note{{overridden declaration is here}}
var v4: String { return "hello" }// expected-note{{attempt to override property here}}
var v5: A { return self }
var v6: A { return self }
var v7: A { // expected-note{{attempt to override property here}}
get { return self }
set { }
}
var v8: Int = 0 // expected-note {{attempt to override property here}}
var v9: Int { return 5 } // expected-note{{attempt to override property here}}
var v10: Int { return 5 } // expected-note{{attempt to override property here}}
subscript (i: Int) -> String { // expected-note{{potential overridden subscript 'subscript(_:)' here}}
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden subscript 'subscript(_:)' here}}
get {
return "hello"
}
set {
}
}
subscript (i: Int8) -> A { // expected-note{{potential overridden subscript 'subscript(_:)' here}}
get { return self }
}
subscript (i: Int16) -> A { // expected-note{{attempt to override subscript here}} expected-note{{potential overridden subscript 'subscript(_:)' here}}
get { return self }
set { }
}
func overriddenInExtension() {} // expected-note {{overri}}
}
class B : A {
override func f0() { }
func f1() { } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
override func f2() { } // expected-error{{method does not override any method from its superclass}}
override var v1: Int { return 5 }
var v2: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}
override var v3: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
override var v4: Int { return 5 } // expected-error{{property 'v4' with type 'Int' cannot override a property with type 'String'}}
// Covariance
override var v5: B { return self }
override var v6: B {
get { return self }
set { }
}
override var v7: B { // expected-error{{cannot override mutable property 'v7' of type 'A' with covariant type 'B'}}
get { return self }
set { }
}
// Stored properties
override var v8: Int { return 5 } // expected-error {{cannot override mutable property with read-only property 'v8'}}
override var v9: Int // expected-error{{cannot override with a stored property 'v9'}}
lazy override var v10: Int = 5 // expected-warning{{cannot override with a stored property 'v10'}}
override subscript (i: Int) -> String {
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{3-3=override }}
get {
return "hello"
}
set {
}
}
override subscript (f: Float) -> String { // expected-error{{subscript does not override any subscript from its superclass}}
get {
return "hello"
}
set {
}
}
// Covariant
override subscript (i: Int8) -> B {
get { return self }
}
override subscript (i: Int16) -> B { // expected-error{{cannot override mutable subscript of type '(Int16) -> B' with covariant type '(Int16) -> A'}}
get { return self }
set { }
}
override init() { }
override deinit { } // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
override typealias Inner = Int // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
}
extension B {
override func overriddenInExtension() {} // expected-error{{overri}}
}
struct S {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
extension S {
override func ef() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
enum E {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
protocol P {
override func f() // expected-error{{method does not override any method from its parent protocol}}
}
override func f() { } // expected-error{{'override' can only be specified on class members}} {{1-10=}}
// Invalid 'override' on declarations inside closures.
var rdar16654075a = {
override func foo() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
var rdar16654075b = {
class A {
override func foo() {} // expected-error{{method does not override any method from its superclass}}
}
}
var rdar16654075c = { () -> () in
override func foo() {} // expected-error {{'override' can only be specified on class members}} {{3-12=}}
()
}
var rdar16654075d = { () -> () in
class A {
override func foo() {} // expected-error {{method does not override any method from its superclass}}
}
A().foo()
}
var rdar16654075e = { () -> () in
class A {
func foo() {}
}
class B : A {
override func foo() {}
}
A().foo()
}
class C {
init(string: String) { } // expected-note{{overridden declaration is here}}
required init(double: Double) { } // expected-note 3{{overridden required initializer is here}}
convenience init() { self.init(string: "hello") } // expected-note{{attempt to override convenience initializer here}}
}
class D1 : C {
override init(string: String) { super.init(string: string) }
required init(double: Double) { }
convenience init() { self.init(string: "hello") }
}
class D2 : C {
init(string: String) { super.init(string: string) } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
// FIXME: Would like to remove the space after 'override' as well.
required override init(double: Double) { } // expected-warning{{'override' is implied when overriding a required initializer}} {{12-21=}}
override convenience init() { self.init(string: "hello") } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class D3 : C {
override init(string: String) { super.init(string: string) }
override init(double: Double) { } // expected-error{{use the 'required' modifier to override a required initializer}}{{3-11=required}}
}
class D4 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required override init(string: String) { super.init(string: string) }
required init(double: Double) { }
}
class D5 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required convenience override init(string: String) { self.init(double: 5.0) }
required init(double: Double) { }
}
class D6 : C {
init(double: Double) { } // expected-error{{'required' modifier must be present on all overrides of a required initializer}} {{3-3=required }}
}
// rdar://problem/18232867
class C_empty_tuple {
init() { }
}
class D_empty_tuple : C_empty_tuple {
override init(foo:()) { } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class C_with_let {
let x = 42 // expected-note {{attempt to override property here}}
}
class D_with_let : C_with_let {
override var x : Int { get { return 4 } set {} } // expected-error {{cannot override immutable 'let' property 'x' with the getter of a 'var'}}
}
// <rdar://problem/21311590> QoI: Inconsistent diagnostics when no constructor is available
class C21311590 {
override init() {} // expected-error {{initializer does not override a designated initializer from its superclass}}
}
class B21311590 : C21311590 {}
_ = C21311590()
_ = B21311590()
class MismatchOptionalBase {
func param(_: Int?) {}
func paramIUO(_: Int!) {}
func result() -> Int { return 0 }
func fixSeveralTypes(a: Int?, b: Int!) -> Int { return 0 }
func functionParam(x: ((Int) -> Int)?) {}
func tupleParam(x: (Int, Int)?) {}
func compositionParam(x: (P1 & P2)?) {}
func nameAndTypeMismatch(label: Int?) {}
func ambiguousOverride(a: Int, b: Int?) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
func ambiguousOverride(a: Int?, b: Int) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
var prop: Int = 0 // expected-note {{attempt to override property here}}
var optProp: Int? // expected-note {{attempt to override property here}}
var getProp: Int { return 0 } // expected-note {{attempt to override property here}}
var getOptProp: Int? { return nil }
init(param: Int?) {}
init() {} // expected-note {{non-failable initializer 'init()' overridden here}}
subscript(a: Int?) -> Void { // expected-note {{attempt to override subscript here}}
get { return () }
set {}
}
subscript(b: Void) -> Int { // expected-note {{attempt to override subscript here}}
get { return 0 }
set {}
}
subscript(get a: Int?) -> Void {
return ()
}
subscript(get b: Void) -> Int {
return 0
}
subscript(ambiguous a: Int, b: Int?) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
subscript(ambiguous a: Int?, b: Int) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
}
protocol P1 {}
protocol P2 {}
class MismatchOptional : MismatchOptionalBase {
override func param(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{29-29=?}}
override func paramIUO(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{32-32=?}}
override func result() -> Int? { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}}
override func fixSeveralTypes(a: Int, b: Int) -> Int! { return nil }
// expected-error@-1 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{39-39=?}}
// expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{47-47=?}}
// expected-error@-3 {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{55-56=}}
override func functionParam(x: @escaping (Int) -> Int) {} // expected-error {{cannot override instance method parameter of type '((Int) -> Int)?' with non-optional type '(Int) -> Int'}} {{34-34=(}} {{56-56=)?}}
override func tupleParam(x: (Int, Int)) {} // expected-error {{cannot override instance method parameter of type '(Int, Int)?' with non-optional type '(Int, Int)'}} {{41-41=?}}
override func compositionParam(x: P1 & P2) {} // expected-error {{cannot override instance method parameter of type '(P1 & P2)?' with non-optional type 'P1 & P2'}} {{37-37=(}} {{44-44=)?}}
override func nameAndTypeMismatch(_: Int) {}
// expected-error@-1 {{argument labels for method 'nameAndTypeMismatch' do not match those of overridden method 'nameAndTypeMismatch(label:)'}} {{37-37=label }}
// expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{43-43=?}}
override func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} {{none}}
override func ambiguousOverride(a: Int, b: Int) {} // expected-error {{method does not override any method from its superclass}} {{none}}
override var prop: Int? { // expected-error {{property 'prop' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
get { return nil }
set {}
}
override var optProp: Int { // expected-error {{cannot override mutable property 'optProp' of type 'Int?' with covariant type 'Int'}} {{none}}
get { return 0 }
set {}
}
override var getProp: Int? { return nil } // expected-error {{property 'getProp' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
override var getOptProp: Int { return 0 } // okay
override init(param: Int) {} // expected-error {{cannot override initializer parameter of type 'Int?' with non-optional type 'Int'}}
override init?() {} // expected-error {{failable initializer 'init()' cannot override a non-failable initializer}} {{none}}
override subscript(a: Int) -> Void { // expected-error {{cannot override mutable subscript of type '(Int) -> Void' with covariant type '(Int?) -> Void'}}
get { return () }
set {}
}
override subscript(b: Void) -> Int? { // expected-error {{cannot override mutable subscript of type '(Void) -> Int?' with covariant type '(Void) -> Int'}}
get { return nil }
set {}
}
override subscript(get a: Int) -> Void { // expected-error {{cannot override subscript index of type 'Int?' with non-optional type 'Int'}} {{32-32=?}}
return ()
}
override subscript(get b: Void) -> Int? { // expected-error {{cannot override subscript element type 'Int' with optional type 'Int?'}} {{41-42=}}
return nil
}
override subscript(ambiguous a: Int?, b: Int?) -> Void { // expected-error {{declaration 'subscript(ambiguous:_:)' cannot override more than one superclass declaration}}
return ()
}
override subscript(ambiguous a: Int, b: Int) -> Void { // expected-error {{subscript does not override any subscript from its superclass}}
return ()
}
}
class MismatchOptional2 : MismatchOptionalBase {
override func result() -> Int! { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}}
// None of these are overrides because we didn't say 'override'. Since they're
// not exact matches, they shouldn't result in errors.
func param(_: Int) {}
func ambiguousOverride(a: Int, b: Int) {}
// This is covariant, so we still assume it's meant to override.
func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}}
}
class MismatchOptional3 : MismatchOptionalBase {
override func result() -> Optional<Int> { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Optional<Int>'}} {{none}}
}
// Make sure we remap the method's innermost generic parameters
// to the correct depth
class GenericBase<T> {
func doStuff<U>(t: T, u: U) {}
init<U>(t: T, u: U) {}
}
class ConcreteSub : GenericBase<Int> {
override func doStuff<U>(t: Int, u: U) {}
override init<U>(t: Int, u: U) {}
}
class ConcreteBase {
init<U>(t: Int, u: U) {}
func doStuff<U>(t: Int, u: U) {}
}
class GenericSub<T> : ConcreteBase {
override init<U>(t: Int, u: U) {}
override func doStuff<U>(t: Int, u: U) {}
}
// Issue with generic parameter index
class MoreGenericSub1<T, TT> : GenericBase<T> {
override func doStuff<U>(t: T, u: U) {}
}
class MoreGenericSub2<TT, T> : GenericBase<T> {
override func doStuff<U>(t: T, u: U) {}
}
// Issue with insufficient canonicalization when
// comparing types
protocol SI {}
protocol CI {}
protocol Sequence {
associatedtype I : SI // expected-note{{declared here}}
}
protocol Collection : Sequence {
associatedtype I : CI // expected-warning{{redeclaration of associated type 'I'}}
}
class Index<F, T> {
func map(_ f: F) -> T {}
}
class CollectionIndex<C : Collection> : Index<C, C.I> {
override func map(_ f: C) -> C.I {}
}
| apache-2.0 | c69fd2b7394260ad044815aa0af6c656 | 38.204082 | 212 | 0.6706 | 3.888664 | false | false | false | false |
brentsimmons/Evergreen | Mac/AppDefaults.swift | 1 | 12010 | //
// AppDefaults.swift
// NetNewsWire
//
// Created by Brent Simmons on 9/22/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import AppKit
enum FontSize: Int {
case small = 0
case medium = 1
case large = 2
case veryLarge = 3
}
final class AppDefaults {
static let defaultThemeName = "Default"
static var shared = AppDefaults()
private init() {}
struct Key {
static let firstRunDate = "firstRunDate"
static let windowState = "windowState"
static let activeExtensionPointIDs = "activeExtensionPointIDs"
static let lastImageCacheFlushDate = "lastImageCacheFlushDate"
static let sidebarFontSize = "sidebarFontSize"
static let timelineFontSize = "timelineFontSize"
static let timelineSortDirection = "timelineSortDirection"
static let timelineGroupByFeed = "timelineGroupByFeed"
static let detailFontSize = "detailFontSize"
static let openInBrowserInBackground = "openInBrowserInBackground"
static let subscribeToFeedsInDefaultBrowser = "subscribeToFeedsInDefaultBrowser"
static let articleTextSize = "articleTextSize"
static let refreshInterval = "refreshInterval"
static let addWebFeedAccountID = "addWebFeedAccountID"
static let addWebFeedFolderName = "addWebFeedFolderName"
static let addFolderAccountID = "addFolderAccountID"
static let importOPMLAccountID = "importOPMLAccountID"
static let exportOPMLAccountID = "exportOPMLAccountID"
static let defaultBrowserID = "defaultBrowserID"
static let currentThemeName = "currentThemeName"
// Hidden prefs
static let showDebugMenu = "ShowDebugMenu"
static let timelineShowsSeparators = "CorreiaSeparators"
static let showTitleOnMainWindow = "KafasisTitleMode"
static let feedDoubleClickMarkAsRead = "GruberFeedDoubleClickMarkAsRead"
static let suppressSyncOnLaunch = "DevroeSuppressSyncOnLaunch"
#if !MAC_APP_STORE
static let webInspectorEnabled = "WebInspectorEnabled"
static let webInspectorStartsAttached = "__WebInspectorPageGroupLevel1__.WebKit2InspectorStartsAttached"
#endif
}
private static let smallestFontSizeRawValue = FontSize.small.rawValue
private static let largestFontSizeRawValue = FontSize.veryLarge.rawValue
let isDeveloperBuild: Bool = {
if let dev = Bundle.main.object(forInfoDictionaryKey: "DeveloperEntitlements") as? String, dev == "-dev" {
return true
}
return false
}()
var isFirstRun: Bool = {
if let _ = UserDefaults.standard.object(forKey: Key.firstRunDate) as? Date {
return false
}
firstRunDate = Date()
return true
}()
var windowState: [AnyHashable : Any]? {
get {
return UserDefaults.standard.object(forKey: Key.windowState) as? [AnyHashable : Any]
}
set {
UserDefaults.standard.set(newValue, forKey: Key.windowState)
}
}
var activeExtensionPointIDs: [[AnyHashable : AnyHashable]]? {
get {
return UserDefaults.standard.object(forKey: Key.activeExtensionPointIDs) as? [[AnyHashable : AnyHashable]]
}
set {
UserDefaults.standard.set(newValue, forKey: Key.activeExtensionPointIDs)
}
}
var lastImageCacheFlushDate: Date? {
get {
return AppDefaults.date(for: Key.lastImageCacheFlushDate)
}
set {
AppDefaults.setDate(for: Key.lastImageCacheFlushDate, newValue)
}
}
var openInBrowserInBackground: Bool {
get {
return AppDefaults.bool(for: Key.openInBrowserInBackground)
}
set {
AppDefaults.setBool(for: Key.openInBrowserInBackground, newValue)
}
}
// Special case for this default: store/retrieve it from the shared app group
// defaults, so that it can be resolved by the Safari App Extension.
var subscribeToFeedDefaults: UserDefaults {
if let appGroupID = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String,
let appGroupDefaults = UserDefaults(suiteName: appGroupID) {
return appGroupDefaults
}
else {
return UserDefaults.standard
}
}
var subscribeToFeedsInDefaultBrowser: Bool {
get {
return subscribeToFeedDefaults.bool(forKey: Key.subscribeToFeedsInDefaultBrowser)
}
set {
subscribeToFeedDefaults.set(newValue, forKey: Key.subscribeToFeedsInDefaultBrowser)
}
}
var sidebarFontSize: FontSize {
get {
return fontSize(for: Key.sidebarFontSize)
}
set {
AppDefaults.setFontSize(for: Key.sidebarFontSize, newValue)
}
}
var timelineFontSize: FontSize {
get {
return fontSize(for: Key.timelineFontSize)
}
set {
AppDefaults.setFontSize(for: Key.timelineFontSize, newValue)
}
}
var detailFontSize: FontSize {
get {
return fontSize(for: Key.detailFontSize)
}
set {
AppDefaults.setFontSize(for: Key.detailFontSize, newValue)
}
}
var addWebFeedAccountID: String? {
get {
return AppDefaults.string(for: Key.addWebFeedAccountID)
}
set {
AppDefaults.setString(for: Key.addWebFeedAccountID, newValue)
}
}
var addWebFeedFolderName: String? {
get {
return AppDefaults.string(for: Key.addWebFeedFolderName)
}
set {
AppDefaults.setString(for: Key.addWebFeedFolderName, newValue)
}
}
var addFolderAccountID: String? {
get {
return AppDefaults.string(for: Key.addFolderAccountID)
}
set {
AppDefaults.setString(for: Key.addFolderAccountID, newValue)
}
}
var importOPMLAccountID: String? {
get {
return AppDefaults.string(for: Key.importOPMLAccountID)
}
set {
AppDefaults.setString(for: Key.importOPMLAccountID, newValue)
}
}
var exportOPMLAccountID: String? {
get {
return AppDefaults.string(for: Key.exportOPMLAccountID)
}
set {
AppDefaults.setString(for: Key.exportOPMLAccountID, newValue)
}
}
var defaultBrowserID: String? {
get {
return AppDefaults.string(for: Key.defaultBrowserID)
}
set {
AppDefaults.setString(for: Key.defaultBrowserID, newValue)
}
}
var currentThemeName: String? {
get {
return AppDefaults.string(for: Key.currentThemeName)
}
set {
AppDefaults.setString(for: Key.currentThemeName, newValue)
}
}
var showTitleOnMainWindow: Bool {
return AppDefaults.bool(for: Key.showTitleOnMainWindow)
}
var showDebugMenu: Bool {
return AppDefaults.bool(for: Key.showDebugMenu)
}
var feedDoubleClickMarkAsRead: Bool {
get {
return AppDefaults.bool(for: Key.feedDoubleClickMarkAsRead)
}
set {
AppDefaults.setBool(for: Key.feedDoubleClickMarkAsRead, newValue)
}
}
var suppressSyncOnLaunch: Bool {
get {
return AppDefaults.bool(for: Key.suppressSyncOnLaunch)
}
set {
AppDefaults.setBool(for: Key.suppressSyncOnLaunch, newValue)
}
}
#if !MAC_APP_STORE
var webInspectorEnabled: Bool {
get {
return AppDefaults.bool(for: Key.webInspectorEnabled)
}
set {
AppDefaults.setBool(for: Key.webInspectorEnabled, newValue)
}
}
var webInspectorStartsAttached: Bool {
get {
return AppDefaults.bool(for: Key.webInspectorStartsAttached)
}
set {
AppDefaults.setBool(for: Key.webInspectorStartsAttached, newValue)
}
}
#endif
var timelineSortDirection: ComparisonResult {
get {
return AppDefaults.sortDirection(for: Key.timelineSortDirection)
}
set {
AppDefaults.setSortDirection(for: Key.timelineSortDirection, newValue)
}
}
var timelineGroupByFeed: Bool {
get {
return AppDefaults.bool(for: Key.timelineGroupByFeed)
}
set {
AppDefaults.setBool(for: Key.timelineGroupByFeed, newValue)
}
}
var timelineShowsSeparators: Bool {
return AppDefaults.bool(for: Key.timelineShowsSeparators)
}
var articleTextSize: ArticleTextSize {
get {
let rawValue = UserDefaults.standard.integer(forKey: Key.articleTextSize)
return ArticleTextSize(rawValue: rawValue) ?? ArticleTextSize.large
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: Key.articleTextSize)
}
}
var refreshInterval: RefreshInterval {
get {
let rawValue = UserDefaults.standard.integer(forKey: Key.refreshInterval)
return RefreshInterval(rawValue: rawValue) ?? RefreshInterval.everyHour
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: Key.refreshInterval)
}
}
func registerDefaults() {
#if DEBUG
let showDebugMenu = true
#else
let showDebugMenu = false
#endif
let defaults: [String : Any] = [Key.sidebarFontSize: FontSize.medium.rawValue,
Key.timelineFontSize: FontSize.medium.rawValue,
Key.detailFontSize: FontSize.medium.rawValue,
Key.timelineSortDirection: ComparisonResult.orderedDescending.rawValue,
Key.timelineGroupByFeed: false,
"NSScrollViewShouldScrollUnderTitlebar": false,
Key.refreshInterval: RefreshInterval.everyHour.rawValue,
Key.showDebugMenu: showDebugMenu,
Key.currentThemeName: Self.defaultThemeName]
UserDefaults.standard.register(defaults: defaults)
// It seems that registering a default for NSQuitAlwaysKeepsWindows to true
// is not good enough to get the system to respect it, so we have to literally
// set it as the default to get it to take effect. This overrides a system-wide
// setting in the System Preferences, which is ostensibly meant to "close windows"
// in an app, but has the side-effect of also not preserving or restoring any state
// for the window. Since we've switched to using the standard state preservation and
// restoration mechanisms, and because it seems highly unlikely any user would object
// to NetNewsWire preserving this state, we'll force the preference on. If this becomes
// an issue, this could be changed to proactively look for whether the default has been
// set _by the user_ to false, and respect that default if it is so-set.
// UserDefaults.standard.set(true, forKey: "NSQuitAlwaysKeepsWindows")
// TODO: revisit the above when coming back to state restoration issues.
}
func actualFontSize(for fontSize: FontSize) -> CGFloat {
switch fontSize {
case .small:
return NSFont.systemFontSize
case .medium:
return actualFontSize(for: .small) + 1.0
case .large:
return actualFontSize(for: .medium) + 4.0
case .veryLarge:
return actualFontSize(for: .large) + 8.0
}
}
}
private extension AppDefaults {
static var firstRunDate: Date? {
get {
return AppDefaults.date(for: Key.firstRunDate)
}
set {
AppDefaults.setDate(for: Key.firstRunDate, newValue)
}
}
func fontSize(for key: String) -> FontSize {
// Punted till after 1.0.
return .medium
// var rawFontSize = int(for: key)
// if rawFontSize < smallestFontSizeRawValue {
// rawFontSize = smallestFontSizeRawValue
// }
// if rawFontSize > largestFontSizeRawValue {
// rawFontSize = largestFontSizeRawValue
// }
// return FontSize(rawValue: rawFontSize)!
}
static func setFontSize(for key: String, _ fontSize: FontSize) {
setInt(for: key, fontSize.rawValue)
}
static func string(for key: String) -> String? {
return UserDefaults.standard.string(forKey: key)
}
static func setString(for key: String, _ value: String?) {
UserDefaults.standard.set(value, forKey: key)
}
static func bool(for key: String) -> Bool {
return UserDefaults.standard.bool(forKey: key)
}
static func setBool(for key: String, _ flag: Bool) {
UserDefaults.standard.set(flag, forKey: key)
}
static func int(for key: String) -> Int {
return UserDefaults.standard.integer(forKey: key)
}
static func setInt(for key: String, _ x: Int) {
UserDefaults.standard.set(x, forKey: key)
}
static func date(for key: String) -> Date? {
return UserDefaults.standard.object(forKey: key) as? Date
}
static func setDate(for key: String, _ date: Date?) {
UserDefaults.standard.set(date, forKey: key)
}
static func sortDirection(for key:String) -> ComparisonResult {
let rawInt = int(for: key)
if rawInt == ComparisonResult.orderedAscending.rawValue {
return .orderedAscending
}
return .orderedDescending
}
static func setSortDirection(for key: String, _ value: ComparisonResult) {
if value == .orderedAscending {
setInt(for: key, ComparisonResult.orderedAscending.rawValue)
}
else {
setInt(for: key, ComparisonResult.orderedDescending.rawValue)
}
}
}
| mit | bb1c2c85fc410fcbc9788a373440e3cd | 26.543578 | 109 | 0.735282 | 3.724876 | false | false | false | false |
jtaxen/FindShelter | Pods/FBAnnotationClusteringSwift/Pod/Classes/FBAnnotationClusterView.swift | 1 | 4238 | //
// FBAnnotationClusterView.swift
// FBAnnotationClusteringSwift
//
// Created by Robert Chen on 4/2/15.
// Copyright (c) 2015 Robert Chen. All rights reserved.
//
import Foundation
import MapKit
open class FBAnnotationClusterView : MKAnnotationView {
var count = 0
var fontSize:CGFloat = 12
var imageName = "clusterSmall"
var loadExternalImage : Bool = false
var borderWidth:CGFloat = 3
var countLabel:UILabel? = nil
//var option : FBAnnotationClusterViewOptions? = nil
public init(annotation: MKAnnotation?, reuseIdentifier: String?, options: FBAnnotationClusterViewOptions?){
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
let cluster:FBAnnotationCluster = annotation as! FBAnnotationCluster
count = cluster.annotations.count
// change the size of the cluster image based on number of stories
switch count {
case 0...5:
fontSize = 12
if (options != nil) {
loadExternalImage=true;
imageName = (options?.smallClusterImage)!
}
else {
imageName = "clusterSmall"
}
borderWidth = 3
case 6...15:
fontSize = 13
if (options != nil) {
loadExternalImage=true;
imageName = (options?.mediumClusterImage)!
}
else {
imageName = "clusterMedium"
}
borderWidth = 4
default:
fontSize = 14
if (options != nil) {
loadExternalImage=true;
imageName = (options?.largeClusterImage)!
}
else {
imageName = "clusterLarge"
}
borderWidth = 5
}
backgroundColor = UIColor.clear
setupLabel()
setTheCount(count)
}
// required override public init(frame: CGRect) {
// super.init(frame: frame)
//
// }
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupLabel(){
countLabel = UILabel(frame: bounds)
if let countLabel = countLabel {
countLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
countLabel.textAlignment = .center
countLabel.backgroundColor = UIColor.clear
countLabel.textColor = UIColor(red: 5/255, green: 56/255, blue: 126/255, alpha: 1.0)
countLabel.adjustsFontSizeToFitWidth = true
countLabel.minimumScaleFactor = 2
countLabel.numberOfLines = 1
countLabel.font = UIFont(name: "Futura", size: fontSize)
countLabel.baselineAdjustment = .alignCenters
addSubview(countLabel)
}
}
func setTheCount(_ localCount:Int){
count = localCount;
countLabel?.text = "\(localCount)"
setNeedsLayout()
}
override open func layoutSubviews() {
// Images are faster than using drawRect:
let imageAsset = UIImage(named: imageName, in: (!loadExternalImage) ? Bundle(for: FBAnnotationClusterView.self) : nil, compatibleWith: nil)
//UIImage(named: imageName)!
countLabel?.frame = self.bounds
image = imageAsset
centerOffset = CGPoint.zero
// adds a white border around the green circle
layer.borderColor = UIColor(red: 5/255, green: 56/255, blue: 126/255, alpha: 1.0).cgColor
layer.borderWidth = borderWidth
layer.cornerRadius = self.bounds.size.width / 2
}
}
open class FBAnnotationClusterViewOptions : NSObject {
var smallClusterImage : String
var mediumClusterImage : String
var largeClusterImage : String
public init (smallClusterImage : String, mediumClusterImage : String, largeClusterImage : String) {
self.smallClusterImage = smallClusterImage;
self.mediumClusterImage = mediumClusterImage;
self.largeClusterImage = largeClusterImage;
}
}
| mit | 4c75c354a080cda44ceaebbe9a7fdaab | 28.84507 | 147 | 0.579991 | 5.433333 | false | false | false | false |
ualch9/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/ShadowSelectionTableViewCell.swift | 3 | 1286 | //
// ShadowSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/25/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import SwiftEntryKit
class ShadowSelectionTableViewCell: SelectionTableViewCell {
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "Drop Shadow"
descriptionValue = "A drop shadow effect that can be applied to the entry"
insertSegments(by: ["Off", "On"])
selectSegment()
}
private func selectSegment() {
switch attributesWrapper.attributes.shadow {
case .none:
segmentedControl.selectedSegmentIndex = 0
case .active(with: _):
segmentedControl.selectedSegmentIndex = 1
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
attributesWrapper.attributes.shadow = .none
case 1:
let value = EKAttributes.Shadow.Value(color: .black, opacity: 0.5, radius: 10, offset: .zero)
attributesWrapper.attributes.shadow = .active(with: value)
default:
break
}
}
}
| apache-2.0 | 5b5f9e126161dfa84b7b857e6a22744a | 30.365854 | 105 | 0.650078 | 4.780669 | false | false | false | false |
Flinesoft/CSVImporter | UsageExamples.playground/Contents.swift | 1 | 6291 | import Foundation
import CSVImporter
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
//: Get the path to an example CSV file (see Resources folder of this Playground).
let path = Bundle.main.path(forResource: "Teams", ofType: "csv")!
//: ## CSVImporter
//: The CSVImporter class is the class which includes all the import logic.
//: ### init<T>(path:)
//: First create an instance of CSVImporter. Let's do this with the default type `[String]` like this:
let defaultImporter = CSVImporter<[String]>(path: path)
let stringImporter = CSVImporter<[String]>(contentString: try! String(contentsOfFile: path))
//: ### Basic import: .startImportingRecords & .onFinish
//: For a basic line-by-line import of your file start the import and use the `.onFinish` callback. The import is done asynchronously but all callbacks (like `.onFinish`) are called on the main thread.
defaultImporter.startImportingRecords { $0 }.onFinish { importedRecords in
type(of: importedRecords)
importedRecords.count // number of all records
importedRecords[100] // this is a single record
importedRecords // array with all records (in this case an array of arrays)
}
stringImporter.startImportingRecords { $0 }.onFinish { importedRecords in
type(of: importedRecords)
importedRecords.count // number of all records
importedRecords[100] // this is a single record
importedRecords // array with all records (in this case an array of arrays)
}
//: ### Synchronous import: .importRecords
//: Line-by-line import which results in the end result immediately. Works synchronously.
let results = defaultImporter.importRecords { $0 }
results
//: ### .onFail
//: In case your path was wrong the chainable `.onFail` callback will be called instead of the `.onFinish`.
let wrongPathImporter = CSVImporter<[String]>(path: "a/wrong/path")
wrongPathImporter.startImportingRecords { $0 }.onFail {
_ = ".onFail called because the path is wrong"
}.onFinish { importedRecords in
_ = ".onFinish is never called here because the path is wrong"
}
//: ### .onProgress
//: If you want to show progress to your users you can use the `.onProgress` callback. It will be called multiple times a second with the current number of lines already processed.
defaultImporter.startImportingRecords { $0 }.onProgress { importedDataLinesCount in
importedDataLinesCount
"Progress Update in main thread: \(importedDataLinesCount) lines were imported"
}
//: ### .startImportingRecords(structure:)
//: Some CSV files offer some structural information about the data on the first line (the header line). You can also tell CSVImporter to use this first line to return a dictionary where the structure information are used as keys. The default data type for structural imports therefore is a String dictionary (`[String: String]`).
let structureImporter = CSVImporter<[String: String]>(path: path)
structureImporter.startImportingRecords(structure: { headerValues in
_ = headerValues // the structural information from the first line as a [String]
}){ $0 }.onFinish { importedRecords in
type(of: importedRecords)
importedRecords.count // the number of all imported records
importedRecords[99] // this is a single record
}
//: ### .startImportingRecords(mapper:)
//: You don't need to use the default types `[String]` for the default importer. You can use your own type by proving your own mapper instead of `{ $0 }` from the examples above. The mapper gets a `[String]` and needs to return your own type.
// Let's define our own class:
class Team {
let year: String, league: String
init(year: String, league: String) {
self.year = year
self.league = league
}
}
// Now create an importer for our own type and start importing:
let teamsDefaultImporter = CSVImporter<Team>(path: path)
teamsDefaultImporter.startImportingRecords { recordValues -> Team in
return Team(year: recordValues[0], league: recordValues[1])
}.onFinish { importedRecords in
type(of: importedRecords) // the type is now [Team]
importedRecords.count // number of all imported records
let aTeam = importedRecords[100]
aTeam.year
aTeam.league
}
//: ### .startImportingRecords(structure:recordMapper:)
//: You can also use a record mapper and use structured data together. In this case the mapper gets a `[String: String]` and needs to return with your own type again.
let teamsStructuredImporter = CSVImporter<Team>(path: path)
teamsStructuredImporter.startImportingRecords(structure: { headerValues in
_ = headerValues // the structure form the first line of the CSV file
}) { recordValues -> Team in
return Team(year: recordValues["yearID"]!, league: recordValues["lgID"]!)
}.onFinish { (importedRecords) -> Void in
type(of: importedRecords) // the type is now [Team]
importedRecords.count // number of all imported records
let aTeam = importedRecords[99]
aTeam.year
aTeam.league
}
//: Note that the structural importer is slower than the default importer.
//: You can also build an importer with a file URL
//: Get the file URL to an example CSV file (see Resources folder of this Playground).
let fileURL = Bundle.main.url(forResource: "Teams.csv", withExtension: nil)!
//: ## CSVImporter
//: The CSVImporter class is the class that includes all the import logic.
//: ### init<T>(path:)
//: First create an instance of CSVImporter. Let's do this with the default type `[String]` like this:
let fileURLImporter = CSVImporter<[String]>(url: fileURL)
//: ### Basic import: .startImportingRecords & .onFinish
//: For a basic line-by-line import of your file start the import and use the `.onFinish` callback. The import is done asynchronously but all callbacks (like `.onFinish`) are called on the main thread.
fileURLImporter?.startImportingRecords { $0 }.onFinish { importedRecords in
type(of: importedRecords)
importedRecords.count // number of all records
importedRecords[100] // this is a single record
importedRecords // array with all records (in this case an array of arrays)
}
| mit | 31d499bc3d6e13d2605a835c2ad9f5fb | 38.566038 | 330 | 0.717215 | 4.591971 | false | false | false | false |
austinzheng/swift | test/Inputs/conditional_conformance_basic_conformances.swift | 2 | 16543 | public func takes_p1<T: P1>(_: T.Type) {}
public protocol P1 {
func normal()
func generic<T: P3>(_: T)
}
public protocol P2 {}
public protocol P3 {}
public struct IsP2: P2 {}
public struct IsP3: P3 {}
public struct Single<A> {}
extension Single: P1 where A: P2 {
public func normal() {}
public func generic<T: P3>(_: T) {}
}
// witness method for Single.normal
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE6normalyyF"(%swift.type* [[A]], i8** [[A_P2]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness method for Single.generic
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6SingleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[A_P2_i8star:%.*]] = load i8*, i8** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[A_P2:%.*]] = bitcast i8* [[A_P2_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[A_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[A:%.*]] = load %swift.type*, %swift.type** [[A_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6SingleVA2A2P2RzlE7genericyyqd__AA2P3Rd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[A]], %swift.type* %"\CF\84_1_0", i8** [[A_P2]], i8** %"\CF\84_1_0.P3")
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func single_generic<T: P2>(_: T.Type) {
takes_p1(Single<T>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances14single_genericyyxmAA2P2RzlF"(%swift.type*, %swift.type* %T, i8** %T.P2)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVMa"(i64 0, %swift.type* %T)
// CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[T_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %T.P2, i8*** [[T_P2_PTR]], align 8
// CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func single_concrete() {
takes_p1(Single<IsP2>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances15single_concreteyyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 0)
// CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[Single_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Single_TYPE]], %swift.type* [[Single_TYPE]], i8** [[Single_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// Lazy witness table accessor for the concrete Single<IsP2> : P1.
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [1 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGMa"(i64 0)
// CHECK-NEXT: [[Single_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [1 x i8**], [1 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[A_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[A_P2_PTR]], align 8
// CHECK-NEXT: [[Single_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Single_P1]], i8*** @"$s42conditional_conformance_basic_conformances6SingleVyAA4IsP2VGACyxGAA2P1A2A0G0RzlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Single_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
public struct Double<B, C> {}
extension Double: P1 where B: P2, C: P3 {
public func normal() {}
public func generic<T: P3>(_: T) {}
}
// witness method for Double.normal
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP6normalyyFTW"(%T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8**
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2
// CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3
// CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE6normalyyF"(%swift.type* [[B]], %swift.type* [[C]], i8** [[B_P2]], i8** [[C_P3]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// witness method for Double.generic
// CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVyxq_GAA2P1A2A2P2RzAA2P3R_rlAaEP7genericyyqd__AaGRd__lFTW"(%swift.opaque* noalias nocapture, %swift.type* %"\CF\84_1_0", i8** %"\CF\84_1_0.P3", %T42conditional_conformance_basic_conformances6DoubleV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -1
// CHECK-NEXT: [[B_P2_i8star:%.*]] = load i8*, i8** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[B_P2:%.*]] = bitcast i8* [[B_P2_i8star]] to i8**
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8*, i8** %SelfWitnessTable, i32 -2
// CHECK-NEXT: [[C_P3_i8star:%.*]] = load i8*, i8** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[C_P3:%.*]] = bitcast i8* [[C_P3_i8star]] to i8**
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[B_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY]], i64 2
// CHECK-NEXT: [[B:%.*]] = load %swift.type*, %swift.type** [[B_PTR]], align 8
// CHECK-NEXT: [[SELF_AS_TYPE_ARRAY_2:%.*]] = bitcast %swift.type* %Self to %swift.type**
// CHECK-NEXT: [[C_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[SELF_AS_TYPE_ARRAY_2]], i64 3
// CHECK-NEXT: [[C:%.*]] = load %swift.type*, %swift.type** [[C_PTR]], align 8
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances6DoubleVA2A2P2RzAA2P3R_rlE7genericyyqd__AaERd__lF"(%swift.opaque* noalias nocapture %0, %swift.type* [[B]], %swift.type* [[C]], %swift.type* %"\CF\84_1_0", i8** [[B_P2]], i8** [[C_P3]], i8** %"\CF\84_1_0.P3")
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func double_generic_generic<U: P2, V: P3>(_: U.Type, _: V.Type) {
takes_p1(Double<U, V>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances015double_generic_F0yyxm_q_mtAA2P2RzAA2P3R_r0_lF"(%swift.type*, %swift.type*, %swift.type* %U, %swift.type* %V, i8** %U.P2, i8** %V.P3)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %U, %swift.type* %V)
// CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %U.P2, i8*** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1
// CHECK-NEXT: store i8** %V.P3, i8*** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func double_generic_concrete<X: P2>(_: X.Type) {
takes_p1(Double<X, IsP3>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances23double_generic_concreteyyxmAA2P2RzlF"(%swift.type*, %swift.type* %X, i8** %X.P2)
// CHECK-NEXT: entry:
// CHECK: %conditional.requirement.buffer = alloca [2 x i8**], align 8
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVMa"(i64 0, %swift.type* %X, %swift.type* bitcast (i64* getelementptr inbounds (<{ i8**, i64, <{ {{.*}} }>* }>, <{ {{.*}} }>* @"$s42conditional_conformance_basic_conformances4IsP3VMf", i32 0, i32 1) to %swift.type*))
// CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** %X.P2, i8*** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
public func double_concrete_concrete() {
takes_p1(Double<IsP2, IsP3>.self)
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s42conditional_conformance_basic_conformances016double_concrete_F0yyF"()
// CHECK-NEXT: entry:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 0)
// CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"()
// CHECK-NEXT: call swiftcc void @"$s42conditional_conformance_basic_conformances8takes_p1yyxmAA2P1RzlF"(%swift.type* [[Double_TYPE]], %swift.type* [[Double_TYPE]], i8** [[Double_P1]])
// CHECK-NEXT: ret void
// CHECK-NEXT: }
// Lazy witness table accessor for the concrete Double<IsP2, IsP3> : P1.
// CHECK-LABEL: define linkonce_odr hidden i8** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWl"()
// CHECK-NEXT: entry:
// CHECK-NEXT: %conditional.requirement.buffer = alloca [2 x i8**], align 8
// CHECK-NEXT: [[CACHE:%.*]] = load i8**, i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL", align 8
// CHECK-NEXT: [[IS_NULL:%.*]] = icmp eq i8** [[CACHE]], null
// CHECK-NEXT: br i1 [[IS_NULL]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGMa"(i64 0)
// CHECK-NEXT: [[Double_TYPE:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[CONDITIONAL_REQUIREMENTS:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* %conditional.requirement.buffer, i32 0, i32 0
// CHECK-NEXT: [[B_P2_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 0
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP2VAA0F0AAWP", i32 0, i32 0), i8*** [[B_P2_PTR]], align 8
// CHECK-NEXT: [[C_P3_PTR:%.*]] = getelementptr inbounds i8**, i8*** [[CONDITIONAL_REQUIREMENTS]], i32 1
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s42conditional_conformance_basic_conformances4IsP3VAA0F0AAWP", i32 0, i32 0), i8*** [[C_P3_PTR]], align 8
// CHECK-NEXT: [[Double_P1:%.*]] = call i8** @swift_getWitnessTable
// CHECK-NEXT: store atomic i8** [[Double_P1]], i8*** @"$s42conditional_conformance_basic_conformances6DoubleVyAA4IsP2VAA0F2P3VGACyxq_GAA2P1A2A0G0RzAA0H0R_rlWL" release, align 8
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi i8** [ [[CACHE]], %entry ], [ [[Double_P1]], %cacheIsNull ]
// CHECK-NEXT: ret i8** [[T0]]
// CHECK-NEXT: }
func dynamicCastToP1(_ value: Any) -> P1? {
return value as? P1
}
protocol P4 {}
typealias P4Typealias = P4
protocol P5 {}
struct SR7101<T> {}
extension SR7101 : P5 where T == P4Typealias {}
| apache-2.0 | 606133037e36027c18b4ffda9bbcd6f8 | 65.172 | 383 | 0.658345 | 3.017694 | false | false | false | false |
austinzheng/swift | benchmark/single-source/Memset.swift | 34 | 931 | //===--- Memset.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let Memset = BenchmarkInfo(
name: "Memset",
runFunction: run_Memset,
tags: [.validation])
@inline(never)
func memset(_ a: inout [Int], _ c: Int) {
for i in 0..<a.count {
a[i] = c
}
}
@inline(never)
public func run_Memset(_ N: Int) {
var a = [Int](repeating: 0, count: 10_000)
for _ in 1...50*N {
memset(&a, 1)
memset(&a, 0)
}
CheckResults(a[87] == 0)
}
| apache-2.0 | 6ca2ad629bf5b5bb9115bb5695767c06 | 25.6 | 80 | 0.555317 | 3.8 | false | false | false | false |
ReiVerdugo/uikit-fundamentals | step4.8-roshamboWithHistory-solution/RockPaperScissors/HistoryViewController.swift | 1 | 1663 | //
// File.swift
// RockPaperScissors
//
// Created by Jason on 11/14/14.
// Copyright (c) 2014 Gabrielle Miller-Messner. All rights reserved.
//
import Foundation
import UIKit
// MARK: - HistoryViewController : UIViewController, UITableViewDelegate, UITableViewDataSource
class HistoryViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Properties
var history: [RPSMatch]!
// MARK: Outlets
@IBOutlet weak var tableView: UITableView!
// MARK: Table View Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return history.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellID = "HistoryCell"
let cell = tableView.dequeueReusableCellWithIdentifier(CellID, forIndexPath: indexPath)
let match = self.history[indexPath.row]
cell.textLabel!.text = victoryStatusDescription(match)
cell.detailTextLabel!.text = "\(match.p1) vs. \(match.p2)"
return cell
}
// MARK: Victory Status
func victoryStatusDescription(match: RPSMatch) -> String {
if (match.p1 == match.p2) {
return "Tie."
} else if (match.p1.defeats(match.p2)) {
return "Win!"
} else {
return "Loss."
}
}
// MARK: Actions
@IBAction func dismissHistory(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | edfdcc6c7d691981acf63b8c7879fe8d | 24.584615 | 109 | 0.617559 | 4.949405 | false | false | false | false |
Pandanx/PhotoPickerController | Classes/PhotoGridController.swift | 1 | 13543 | //
// PhotoGridController.swift
// Photos
//
// Created by 张晓鑫 on 2017/6/1.
// Copyright © 2017年 Wang. All rights reserved.
//
import UIKit
import Photos
let screenWidth:CGFloat = UIScreen.main.bounds.width
let screenHeigth:CGFloat = UIScreen.main.bounds.height
class PhotoGridController: UIViewController {
var completeItem: UIBarButtonItem! = UIBarButtonItem()
var collectionView: UICollectionView!
///后去到的结果 存放PHAsset
var assetsFetchResults: PHFetchResult<PHAsset>!
///带缓存的图片管理对象
var imageMannger: PHCachingImageManager!
///预览图大小
open var assetGridThumbnailSize: CGSize!
//原图大小
var realImageSize: CGSize!
///与缓存Rect
var previousPreheatRect: CGRect!
///最多可选择的个数
var maxSelected = 9
///点击完成时的回调
var completeHandler:((_ assets:[PHAsset]) ->())?
var shouldDeleteAfterExport: Bool = false
lazy var selectedLabel: ImageSelectedLabel = {
let tempLabel = ImageSelectedLabel(toolBar:self.navigationController!.toolbar)
return tempLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
//设置流对象layout
let collectionLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
collectionLayout.minimumLineSpacing = 1
collectionLayout.minimumInteritemSpacing = 1
collectionLayout.sectionInset = UIEdgeInsets.zero
collectionLayout.itemSize = CGSize(width:screenWidth/4.0-1, height:screenWidth/4.0-1)
collectionView = UICollectionView(frame:view.bounds, collectionViewLayout: collectionLayout)
collectionView.register(PhotoGridCell.self, forCellWithReuseIdentifier: "PhotoGridCollectionCell")
collectionView.backgroundColor = UIColor.white
//并设置允许多选
collectionView.allowsMultipleSelection = true
collectionView.delegate = self
collectionView.dataSource = self
self.view.addSubview(collectionView)
completeItem = UIBarButtonItem(title: "完成", style: UIBarButtonItemStyle.plain, target: self, action: #selector(finishSelected))
let flexibleItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
self.toolbarItems = [flexibleItem, completeItem]
if assetsFetchResults == nil {
//如果没有传入值 则获取所有资源
let allPhotoOption = PHFetchOptions()
allPhotoOption.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
assetsFetchResults = PHAsset.fetchAssets(with: allPhotoOption)
}
//初始化和重置缓存
imageMannger = PHCachingImageManager()
self.resetCachedAssets()
let rightBarItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancel))
navigationItem.rightBarButtonItem = rightBarItem
completeItem.action = #selector(finishSelected)
disableItems()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//计算出小图大小(为targetSize做准备)
let scale = UIScreen.main.scale
let cellSize = (self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
assetGridThumbnailSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale)
realImageSize = CGSize(width: screenWidth * scale, height: screenHeigth * scale)
self.navigationController!.isToolbarHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController!.isToolbarHidden = true
selectedLabel.selectedNumber = 0
}
// 是否页面加载完毕 , 加载完毕后再做缓存 否则数值可能有误
var didLoad = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
didLoad = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func enableItems() {
completeItem.isEnabled = true
}
fileprivate func disableItems() {
completeItem.isEnabled = false
}
/**
重置缓存
*/
func resetCachedAssets() {
imageMannger.stopCachingImagesForAllAssets()
previousPreheatRect = CGRect.zero
}
/**
取消
*/
func cancel() {
navigationController?.dismiss(animated: true, completion: nil)
}
/**
获取已选择个数
*/
func selectedCount() -> Int {
return self.collectionView.indexPathsForSelectedItems?.count ?? 0
}
/*
// 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.
}
*/
}
extension PhotoGridController {
/**
点击完成调出图片资源
*/
func finishSelected() {
var assets:[PHAsset] = []
// let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
option.resizeMode = .fast
if let indexPaths = collectionView.indexPathsForSelectedItems {
indexPaths.forEach({ (indexPath) in
assets.append(assetsFetchResults[indexPath.row])
})
}
self.dismiss(animated: true) {
self.completeHandler?(assets)
}
}
func assetToUIImage(asset: PHAsset, isThumbImage:Bool) -> UIImage? {
var image: UIImage?
// 新建一个默认类型的图像管理器imageManager
let imageManager = PHImageManager.default()
// 新建一个PHImageRequestOptions对象
let imageRequestOption = PHImageRequestOptions()
// PHImageRequestOptions是否有效
imageRequestOption.isSynchronous = true
// 缩略图的压缩模式设置为无
imageRequestOption.resizeMode = .none
// 缩略图的质量为高质量,不管加载时间花多少
imageRequestOption.deliveryMode = .highQualityFormat
// 按照PHImageRequestOptions指定的规则取出图片
imageManager.requestImage(for: asset, targetSize: isThumbImage ? assetGridThumbnailSize : PHImageManagerMaximumSize, contentMode: .aspectFill, options: imageRequestOption, resultHandler: {
(result, _ info) -> Void in
image = result
})
return image
}
}
// MARK: - UICollectionViewDelegate&&UICollectionViewDataSource
extension PhotoGridController:UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.assetsFetchResults.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoGridCollectionCell", for: indexPath) as! PhotoGridCell
let asset = self.assetsFetchResults[indexPath.row]
imageMannger.requestImage(for: asset, targetSize: assetGridThumbnailSize, contentMode: PHImageContentMode.aspectFill, options: nil) { (image, info) in
cell.imageView.image = image
switch asset.mediaType {
case .video:
cell.duration = asset.duration
default:
break
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? PhotoGridCell {
let selectedCount = self.selectedCount()
selectedLabel.selectedNumber = selectedCount
if selectedCount == 0 {
self.disableItems()
}
cell.showAnim()
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? PhotoGridCell {
let selectedCount = self.selectedCount()
if selectedCount > self.maxSelected {
//选择个数大于选择数 设置为不选中状态
collectionView.deselectItem(at: indexPath, animated: false)
selectedLabel.animateMaxSelected()
} else {
selectedLabel.selectedNumber = selectedCount
if selectedCount > 0 && !self.completeItem.isEnabled{
self.enableItems()
}
cell.showAnim()
}
}
}
/**
滚动中更新缓存
*/
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.updateChachedAssets()
}
func updateChachedAssets() {
let isViewVisible = self.isViewLoaded && didLoad
if !isViewVisible {
return
}
var preheatRect = self.collectionView.bounds
preheatRect = preheatRect.insetBy(dx: 0, dy: -0.5*preheatRect.height)
let delta = abs(preheatRect.midY - self.previousPreheatRect.midY)
if delta > collectionView.bounds.size.height / 3.0 {
var addIndexPaths = [IndexPath]()
var removedIndexPaths = [IndexPath]()
self.computeDifferenceBetweenRect(self.previousPreheatRect, andRect: preheatRect, removedHandler: { (removedRect) in
let indexPaths = self.collectionView.indexPathsForElementsInRect(removedRect)
removedIndexPaths = removedIndexPaths.filter({ (indexPath) -> Bool in
return !indexPaths.contains(indexPath)
})
}, addedHandler: { (addedRect) in
let indexPaths = self.collectionView.indexPathsForElementsInRect(addedRect)
indexPaths.forEach({ (indexPath) in
addIndexPaths.append(indexPath)
})
})
let assetsToStartCaching = self.assetsAtIndexPaths(addIndexPaths)
let assetsStopCaching = self.assetsAtIndexPaths(removedIndexPaths)
self.imageMannger.startCachingImages(for: assetsToStartCaching, targetSize: assetGridThumbnailSize, contentMode: PHImageContentMode.aspectFill, options: nil)
self.imageMannger.stopCachingImages(for: assetsStopCaching, targetSize: assetGridThumbnailSize, contentMode: PHImageContentMode.aspectFill, options: nil)
self.previousPreheatRect = preheatRect
}
}
func computeDifferenceBetweenRect(_ oldRect:CGRect, andRect newRect:CGRect, removedHandler:((_ removedRect:CGRect)->())?, addedHandler:((_ addedRect:CGRect)->())?) {
//判断两个矩形是否相交
if newRect.intersects(oldRect) {
let oldMaxY = oldRect.maxY
let newMaxY = newRect.maxY
let oldMinY = oldRect.minY
let newMinY = oldRect.minY
if newMaxY > oldMaxY {
let rectToAdd = CGRect(x: newRect.origin.x, y: oldMaxY, width: newRect.size.width, height: newMaxY - oldMaxY)
addedHandler?(rectToAdd)
}
if oldMinY > newMinY {
let rectToAdd = CGRect(x: newRect.origin.x, y: newMinY, width: newRect.size.width, height: oldMinY - newMinY)
addedHandler?(rectToAdd)
}
if newMaxY < oldMaxY {
let rectToRemove = CGRect(x: newRect.origin.x, y: newMaxY, width:newRect.size.width, height: oldMaxY - newMaxY)
removedHandler?(rectToRemove)
}
if oldMinY < newMinY {
let rectToRemove = CGRect(x: newRect.origin.x, y: oldMinY, width:newRect.size.width, height: newMinY - oldMinY)
removedHandler?(rectToRemove)
}
} else {
addedHandler?(newRect)
removedHandler?(oldRect)
}
}
func assetsAtIndexPaths(_ indexPaths:[IndexPath]) -> [PHAsset] {
var assets = [PHAsset]()
indexPaths.forEach { (indexPath) in
let asset = self.assetsFetchResults[indexPath.row]
assets.append(asset)
}
return assets
}
}
extension UICollectionView {
func indexPathsForElementsInRect(_ rect: CGRect) -> [IndexPath] {
let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect)
if let allLayoutAttributes = allLayoutAttributes , allLayoutAttributes.count == 0 {
var indexPaths = [IndexPath]()
allLayoutAttributes.forEach({ (attribute) in
let indexPath = attribute.indexPath
indexPaths.append(indexPath)
})
return indexPaths
}else {
return []
}
}
}
| mit | 0b57d5c673a98ce8dc598460048e6276 | 36.150997 | 196 | 0.635429 | 5.472094 | false | false | false | false |
february29/Learning | swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift | 71 | 5688 | //
// SerialDispatchQueueScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.TimeInterval
import struct Foundation.Date
import Dispatch
/**
Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure
that even if concurrent dispatch queue is passed, it's transformed into a serial one.
It is extremely important that this scheduler is serial, because
certain operator perform optimizations that rely on that property.
Because there is no way of detecting is passed dispatch queue serial or
concurrent, for every queue that is being passed, worst case (concurrent)
will be assumed, and internal serial proxy dispatch queue will be created.
This scheduler can also be used with internal serial queue alone.
In case some customization need to be made on it before usage,
internal serial queue can be customized using `serialQueueConfiguration`
callback.
*/
public class SerialDispatchQueueScheduler : SchedulerType {
public typealias TimeInterval = Foundation.TimeInterval
public typealias Time = Date
/// - returns: Current time.
public var now : Date {
return Date()
}
let configuration: DispatchQueueConfiguration
init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway)
}
/**
Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`.
Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`.
- parameter internalSerialQueueName: Name of internal serial dispatch queue.
- parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue.
*/
public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
let queue = DispatchQueue(label: internalSerialQueueName, attributes: [])
serialQueueConfiguration?(queue)
self.init(serialQueue: queue, leeway: leeway)
}
/**
Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`.
- parameter queue: Possibly concurrent dispatch queue used to perform work.
- parameter internalSerialQueueName: Name of internal serial dispatch queue proxy.
*/
public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
// Swift 3.0 IUO
let serialQueue = DispatchQueue(label: internalSerialQueueName,
attributes: [],
target: queue)
self.init(serialQueue: serialQueue, leeway: leeway)
}
/**
Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues.
- parameter qos: Identifier for global dispatch queue with specified quality of service class.
- parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy.
*/
@available(iOS 8, OSX 10.10, *)
public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway)
}
/**
Schedules an action to be executed immediatelly.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public final func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
return self.scheduleInternal(state, action: action)
}
func scheduleInternal<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
return self.configuration.schedule(state, action: action)
}
/**
Schedules an action to be executed.
- parameter state: State passed to the action to be executed.
- parameter dueTime: Relative time after which to execute the action.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public final func scheduleRelative<StateType>(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable {
return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action)
}
/**
Schedules a periodic piece of work.
- parameter state: State passed to the action to be executed.
- parameter startAfter: Period after which initial work should be run.
- parameter period: Period for running the work periodically.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action)
}
}
| mit | 66eecf9b6d8c68728374ceb38e424f12 | 45.235772 | 190 | 0.728679 | 5.426527 | false | true | false | false |
ls1intum/ArTEMiS | src/main/resources/templates/swift/solution/Sources/${packageNameFolder}Lib/Client.swift | 1 | 2302 | import Foundation
public class Client {
/**
Main method.
Add code to demonstrate your implementation here.
*/
public static func main() {
/// Init Context and Policy
let sortingContext = Context()
let policy = Policy(sortingContext)
/// Run 10 times to simulate different sorting strategies
for _ in 0 ..< 10 {
let dates: [Date] = createRandomDatesList()
sortingContext.setDates(dates)
policy.configure()
print("Unsorted Array of course dates = ")
printDateList(dates)
print()
sortingContext.sort()
print("Sorted Array of course dates = ")
printDateList(sortingContext.getDates())
print()
}
}
/// Generates an Array of random Date objects with random Array size between 5 and 15.
private static func createRandomDatesList() -> [Date] {
let listLength: Int = randomIntegerWithin(5, 15)
var list = [Date]()
let dateFormat = DateFormatter()
dateFormat.dateFormat = "dd.MM.yyyy"
dateFormat.timeZone = TimeZone(identifier: "UTC")
let lowestDate: Date! = dateFormat.date(from: "08.11.2016")
let highestDate: Date! = dateFormat.date(from: "15.04.2017")
for _ in 0 ..< listLength {
let randomDate: Date! = randomDateWithin(lowestDate, highestDate)
list.append(randomDate)
}
return list
}
/// Creates a random Date within given Range
private static func randomDateWithin(_ low: Date, _ high: Date) -> Date {
let randomSeconds: Double = randomDoubleWithin(low.timeIntervalSince1970, high.timeIntervalSince1970)
return Date(timeIntervalSince1970: randomSeconds)
}
/// Creates a random Double within given Range
private static func randomDoubleWithin(_ low: Double, _ high: Double) -> Double {
return Double.random(in: low...high)
}
/// Creates a random Integer within given Range
private static func randomIntegerWithin(_ low: Int, _ high: Int) -> Int {
return Int.random(in: low...high)
}
/// Prints out given Array of Date objects
private static func printDateList(_ list: [Date]) {
print(list)
}
}
| mit | b39ef73fe572eba67f8d64369fae9a6a | 35.507937 | 109 | 0.617391 | 4.627767 | false | false | false | false |
toashd/SwiftCenteredTabBar | SwiftCenteredTabBar/TSDCenterTabBarController.swift | 1 | 2172 | //
// TSDCenteredTabBarController.swift
// SwiftCenteredTabBar
//
// Created by Tobias Schmid on 03.06.14.
// Copyright (c) 2014 toashd. All rights reserved.
//
import UIKit
class TSDCenteredTabBarController: UITabBarController {
var centerButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var buttonImage = UIImage(named: "tabBarCameraCenter")
var buttonImageActive = UIImage(named: "tabBarCameraCenterActive")
self.addCenterButtonWithImage(
buttonImage,
highlightImage: buttonImageActive,
target: self,
action:Selector("buttonPressed:")
)
}
override func tabBar(tabBar: UITabBar!, didSelectItem item: UITabBarItem!) {
if item == self.tabBar.items[self.tabBar.items.count / 2] as NSObject {
centerButton.selected = true
} else {
centerButton.selected = false
}
}
func addCenterButtonWithImage(buttonImage: UIImage, highlightImage: UIImage, target: AnyObject, action: Selector) {
var button : UIButton! = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height)
button.setBackgroundImage(buttonImage, forState: UIControlState.Normal)
button.setBackgroundImage(highlightImage, forState: UIControlState.Selected)
button.setBackgroundImage(highlightImage, forState: UIControlState.Highlighted)
var heightDifference = buttonImage.size.height - self.tabBar.frame.size.height
if heightDifference < 0 {
button.center = self.tabBar.center
} else {
var center = self.tabBar.center
center.y = center.y - heightDifference / 2.0
button.center = center
}
button.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
self.centerButton = button
}
func buttonPressed(sender: AnyObject) {
self.selectedIndex = self.tabBar.items.count / 2
centerButton.selected = true
}
}
| mit | df2bb41c6f999001709a717bb7afe647 | 31.41791 | 119 | 0.668508 | 4.815965 | false | false | false | false |
xshfsky/WeiBo | WeiBo/WeiBo/Classes/Discover/Controller/DiscoverTableViewController.swift | 1 | 3576 | //
// DiscoverTableViewController.swift
// WeiBo
//
// Created by Miller on 15/9/26.
// Copyright © 2015年 Xie Yufeng. All rights reserved.
//
import UIKit
class DiscoverTableViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !isLogin == true {
if isLogin == false {
visiterView?.setVisterViewInfo(false, imageNamed: "visitordiscover_image_message", title: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过")
return
}
return
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 05ce80469c4d7b4971a44d2e902f7be3 | 33.821782 | 157 | 0.673585 | 5.46118 | false | false | false | false |
GagSquad/SwiftCommonUtil | CommonUtil/CommonUtil/CacheUtil.swift | 1 | 970 | //
// CacheUtil.swift
// CommonUtil
//
// Created by lijunjie on 15/12/4.
// Copyright © 2015年 lijunjie. All rights reserved.
//
import Foundation
public class CacheUtil {
var cache: NSCache = NSCache()
private static let share = CacheUtil()
private init () {}
public func shareCache() -> NSCache {
return cache
}
public func systemMemoryCacheSet(key: NSCoding, value: AnyObject) {
self.shareCache().setObject(value, forKey: key)
}
public func systemMemoryCacheRemove(key: AnyObject) {
self.shareCache().removeObjectForKey(key)
}
public func systemMemoryCacheGetValue(key:AnyObject) -> AnyObject? {
return self.shareCache().objectForKey(key)
}
public func systemMemoryCacheEmptyValue(key:AnyObject) -> Bool {
return (self.systemMemoryCacheGetValue(key) == nil)
}
}
public let SharedCacheUtil: CacheUtil = CacheUtil.share
| gpl-2.0 | a0e6d258f5f649ca430a7a45e47e0018 | 22.02381 | 72 | 0.649431 | 4.336323 | false | false | false | false |
badoo/Chatto | ChattoAdditions/sources/Input/ChatInputBar.swift | 1 | 12165 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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
public protocol ChatInputBarDelegate: AnyObject {
func inputBarShouldBeginTextEditing(_ inputBar: ChatInputBar) -> Bool
func inputBarDidBeginEditing(_ inputBar: ChatInputBar)
func inputBarDidEndEditing(_ inputBar: ChatInputBar)
func inputBarDidChangeText(_ inputBar: ChatInputBar)
func inputBarSendButtonPressed(_ inputBar: ChatInputBar)
func inputBar(_ inputBar: ChatInputBar, shouldFocusOnItem item: ChatInputItemProtocol) -> Bool
func inputBar(_ inputBar: ChatInputBar, didLoseFocusOnItem item: ChatInputItemProtocol)
func inputBar(_ inputBar: ChatInputBar, didReceiveFocusOnItem item: ChatInputItemProtocol)
func inputBarDidShowPlaceholder(_ inputBar: ChatInputBar)
func inputBarDidHidePlaceholder(_ inputBar: ChatInputBar)
}
@objc
open class ChatInputBar: ReusableXibView {
public var pasteActionInterceptor: PasteActionInterceptor? {
get { return self.textView.pasteActionInterceptor }
set { self.textView.pasteActionInterceptor = newValue }
}
public weak var delegate: ChatInputBarDelegate?
public weak var presenter: ChatInputBarPresenter?
public var shouldEnableSendButton = { (inputBar: ChatInputBar) -> Bool in
return !inputBar.textView.text.isEmpty
}
public var inputTextView: UITextView? {
return self.textView
}
@IBOutlet weak var scrollView: HorizontalStackScrollView!
@IBOutlet weak var textView: ExpandableTextView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var topBorderHeightConstraint: NSLayoutConstraint!
@IBOutlet var constraintsForHiddenTextView: [NSLayoutConstraint]!
@IBOutlet var constraintsForVisibleTextView: [NSLayoutConstraint]!
@IBOutlet var constraintsForVisibleSendButton: [NSLayoutConstraint]!
@IBOutlet var constraintsForHiddenSendButton: [NSLayoutConstraint]!
@IBOutlet var tabBarContainerHeightConstraint: NSLayoutConstraint!
class open func loadNib() -> ChatInputBar {
let view = Bundle.resources.loadNibNamed(self.nibName(), owner: nil, options: nil)!.first as! ChatInputBar
view.translatesAutoresizingMaskIntoConstraints = false
view.frame = CGRect.zero
return view
}
override class func nibName() -> String {
return "ChatInputBar"
}
open override func awakeFromNib() {
super.awakeFromNib()
self.topBorderHeightConstraint.constant = 1 / UIScreen.main.scale
self.textView.scrollsToTop = false
self.textView.delegate = self
self.textView.placeholderDelegate = self
self.scrollView.scrollsToTop = false
self.sendButton.isEnabled = false
}
open override func updateConstraints() {
if self.showsTextView {
NSLayoutConstraint.activate(self.constraintsForVisibleTextView)
NSLayoutConstraint.deactivate(self.constraintsForHiddenTextView)
} else {
NSLayoutConstraint.deactivate(self.constraintsForVisibleTextView)
NSLayoutConstraint.activate(self.constraintsForHiddenTextView)
}
if self.showsSendButton {
NSLayoutConstraint.deactivate(self.constraintsForHiddenSendButton)
NSLayoutConstraint.activate(self.constraintsForVisibleSendButton)
} else {
NSLayoutConstraint.deactivate(self.constraintsForVisibleSendButton)
NSLayoutConstraint.activate(self.constraintsForHiddenSendButton)
}
super.updateConstraints()
}
open var showsTextView: Bool = true {
didSet {
self.setNeedsUpdateConstraints()
self.setNeedsLayout()
self.updateIntrinsicContentSizeAnimated()
}
}
open var showsSendButton: Bool = true {
didSet {
self.setNeedsUpdateConstraints()
self.setNeedsLayout()
self.updateIntrinsicContentSizeAnimated()
}
}
public var maxCharactersCount: UInt? // nil -> unlimited
private func updateIntrinsicContentSizeAnimated() {
let options: UIView.AnimationOptions = [.beginFromCurrentState, .allowUserInteraction]
UIView.animate(withDuration: 0.25, delay: 0, options: options, animations: { () -> Void in
self.invalidateIntrinsicContentSize()
self.layoutIfNeeded()
}, completion: nil)
}
open override func layoutSubviews() {
self.updateConstraints() // Interface rotation or size class changes will reset constraints as defined in interface builder -> constraintsForVisibleTextView will be activated
super.layoutSubviews()
}
var inputItems = [ChatInputItemProtocol]() {
didSet {
let inputItemViews = self.inputItems.map { (item: ChatInputItemProtocol) -> ChatInputItemView in
let inputItemView = ChatInputItemView()
inputItemView.inputItem = item
inputItemView.delegate = self
return inputItemView
}
self.scrollView.addArrangedViews(inputItemViews)
}
}
open func becomeFirstResponderWithInputView(_ inputView: UIView?) {
self.textView.inputView = inputView
if self.textView.isFirstResponder {
self.textView.reloadInputViews()
} else {
self.textView.becomeFirstResponder()
}
}
public var inputText: String {
get {
return self.textView.text
}
set {
self.textView.text = newValue
self.updateSendButton()
}
}
public var inputSelectedRange: NSRange {
get {
return self.textView.selectedRange
}
set {
self.textView.selectedRange = newValue
}
}
public var placeholderText: String {
get {
return self.textView.placeholderText
}
set {
self.textView.placeholderText = newValue
}
}
fileprivate func updateSendButton() {
self.sendButton.isEnabled = self.shouldEnableSendButton(self)
}
@IBAction func buttonTapped(_ sender: AnyObject) {
self.presenter?.onSendButtonPressed()
self.delegate?.inputBarSendButtonPressed(self)
}
public func setTextViewPlaceholderAccessibilityIdentifer(_ accessibilityIdentifer: String) {
self.textView.setTextPlaceholderAccessibilityIdentifier(accessibilityIdentifer)
}
}
// MARK: - ChatInputItemViewDelegate
extension ChatInputBar: ChatInputItemViewDelegate {
func inputItemViewTapped(_ view: ChatInputItemView) {
self.focusOnInputItem(view.inputItem)
}
public func focusOnInputItem(_ inputItem: ChatInputItemProtocol) {
let shouldFocus = self.delegate?.inputBar(self, shouldFocusOnItem: inputItem) ?? true
guard shouldFocus else { return }
let previousFocusedItem = self.presenter?.focusedItem
self.presenter?.onDidReceiveFocusOnItem(inputItem)
if let previousFocusedItem = previousFocusedItem {
self.delegate?.inputBar(self, didLoseFocusOnItem: previousFocusedItem)
}
self.delegate?.inputBar(self, didReceiveFocusOnItem: inputItem)
}
}
// MARK: - ChatInputBarAppearance
extension ChatInputBar {
public func setAppearance(_ appearance: ChatInputBarAppearance) {
self.textView.font = appearance.textInputAppearance.font
self.textView.textColor = appearance.textInputAppearance.textColor
self.textView.tintColor = appearance.textInputAppearance.tintColor
self.textView.textContainerInset = appearance.textInputAppearance.textInsets
self.textView.setTextPlaceholderFont(appearance.textInputAppearance.placeholderFont)
self.textView.setTextPlaceholderColor(appearance.textInputAppearance.placeholderColor)
self.textView.placeholderText = appearance.textInputAppearance.placeholderText
self.textView.layer.borderColor = appearance.textInputAppearance.borderColor.cgColor
self.textView.layer.borderWidth = appearance.textInputAppearance.borderWidth
self.textView.accessibilityIdentifier = appearance.textInputAppearance.accessibilityIdentifier
self.tabBarInterItemSpacing = appearance.tabBarAppearance.interItemSpacing
self.tabBarContentInsets = appearance.tabBarAppearance.contentInsets
self.sendButton.contentEdgeInsets = appearance.sendButtonAppearance.insets
self.sendButton.setTitle(appearance.sendButtonAppearance.title, for: .normal)
appearance.sendButtonAppearance.titleColors.forEach { (state, color) in
self.sendButton.setTitleColor(color, for: state.controlState)
}
self.sendButton.titleLabel?.font = appearance.sendButtonAppearance.font
self.sendButton.accessibilityIdentifier = appearance.sendButtonAppearance.accessibilityIdentifier
self.tabBarContainerHeightConstraint.constant = appearance.tabBarAppearance.height
}
}
extension ChatInputBar { // Tabar
public var tabBarInterItemSpacing: CGFloat {
get {
return self.scrollView.interItemSpacing
}
set {
self.scrollView.interItemSpacing = newValue
}
}
public var tabBarContentInsets: UIEdgeInsets {
get {
return self.scrollView.contentInset
}
set {
self.scrollView.contentInset = newValue
}
}
}
// MARK: UITextViewDelegate
extension ChatInputBar: UITextViewDelegate {
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return self.delegate?.inputBarShouldBeginTextEditing(self) ?? true
}
public func textViewDidEndEditing(_ textView: UITextView) {
self.presenter?.onDidEndEditing()
self.delegate?.inputBarDidEndEditing(self)
}
public func textViewDidBeginEditing(_ textView: UITextView) {
self.presenter?.onDidBeginEditing()
self.delegate?.inputBarDidBeginEditing(self)
}
public func textViewDidChange(_ textView: UITextView) {
self.updateSendButton()
self.delegate?.inputBarDidChangeText(self)
}
open func textView(_ textView: UITextView, shouldChangeTextIn nsRange: NSRange, replacementText text: String) -> Bool {
guard let maxCharactersCount = self.maxCharactersCount else { return true }
let currentText: NSString = textView.text as NSString
let currentCount = currentText.length
let rangeLength = nsRange.length
let nextCount = currentCount - rangeLength + (text as NSString).length
return UInt(nextCount) <= maxCharactersCount
}
}
// MARK: ExpandableTextViewPlaceholderDelegate
extension ChatInputBar: ExpandableTextViewPlaceholderDelegate {
public func expandableTextViewDidShowPlaceholder(_ textView: ExpandableTextView) {
self.delegate?.inputBarDidShowPlaceholder(self)
}
public func expandableTextViewDidHidePlaceholder(_ textView: ExpandableTextView) {
self.delegate?.inputBarDidHidePlaceholder(self)
}
}
| mit | 2bfdc42cb5e34dabf6d4f43c3c6f2a9c | 37.990385 | 182 | 0.714427 | 5.631944 | false | false | false | false |
jeffreybergier/Hipstapaper | Hipstapaper/Packages/V3Errors/Sources/V3Errors/Errors/CPError+CodableError.swift | 1 | 2521 | //
// Created by Jeffrey Bergier on 2022/08/05.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Umbrella
extension CPError {
public var codableValue: CodableError {
let data: Data?
switch self {
case .accountStatus(let status):
data = try? PropertyListEncoder().encode(status.rawValue)
case .sync(let error):
// TODO: Enhance to save suberror kind
NSLog(String(describing: error))
data = nil
}
return CodableError(domain: type(of: self).errorDomain,
code: self.errorCode,
arbitraryData: data)
}
public init?(codableError: CodableError) {
guard type(of: self).errorDomain == codableError.errorDomain else { return nil }
switch codableError.errorCode {
case 1001:
let status: CPAccountStatus = {
guard
let data = codableError.arbitraryData,
let rawValue = try? PropertyListDecoder().decode(Int.self, from: data),
let status = CPAccountStatus(rawValue: rawValue)
else { return .couldNotDetermine }
return status
}()
self = .accountStatus(status)
case 1002:
self = .sync(nil)
default:
return nil
}
}
}
| mit | e0e74a68f1dadf39264124da35a40c7e | 37.784615 | 91 | 0.638239 | 4.738722 | false | false | false | false |
dvor/Antidote | Antidote/NotificationCoordinator.swift | 1 | 14199 | // 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
private enum NotificationType {
case newMessage(OCTMessageAbstract)
case friendRequest(OCTFriendRequest)
}
private struct Constants {
static let NotificationVisibleDuration = 3.0
}
protocol NotificationCoordinatorDelegate: class {
func notificationCoordinator(_ coordinator: NotificationCoordinator, showChat chat: OCTChat)
func notificationCoordinatorShowFriendRequest(_ coordinator: NotificationCoordinator, showRequest request: OCTFriendRequest)
func notificationCoordinatorAnswerIncomingCall(_ coordinator: NotificationCoordinator, userInfo: String)
func notificationCoordinator(_ coordinator: NotificationCoordinator, updateFriendsBadge badge: Int)
func notificationCoordinator(_ coordinator: NotificationCoordinator, updateChatsBadge badge: Int)
}
class NotificationCoordinator: NSObject {
weak var delegate: NotificationCoordinatorDelegate?
fileprivate let theme: Theme
fileprivate let userDefaults = UserDefaultsManager()
fileprivate let notificationWindow: NotificationWindow
fileprivate weak var submanagerObjects: OCTSubmanagerObjects!
fileprivate var messagesToken: RLMNotificationToken?
fileprivate var chats: Results<OCTChat>
fileprivate var chatsToken: RLMNotificationToken?
fileprivate var requests: Results<OCTFriendRequest>
fileprivate var requestsToken: RLMNotificationToken?
fileprivate let avatarManager: AvatarManager
fileprivate let audioPlayer = AlertAudioPlayer()
fileprivate var notificationQueue = [NotificationType]()
fileprivate var inAppNotificationAppIdsRegistered = [String: Bool]()
fileprivate var bannedChatIdentifiers = Set<String>()
init(theme: Theme, submanagerObjects: OCTSubmanagerObjects) {
self.theme = theme
self.notificationWindow = NotificationWindow(theme: theme)
self.submanagerObjects = submanagerObjects
self.avatarManager = AvatarManager(theme: theme)
let predicate = NSPredicate(format: "lastMessage.dateInterval > lastReadDateInterval")
self.chats = submanagerObjects.chats(predicate: predicate)
self.requests = submanagerObjects.friendRequests()
super.init()
addNotificationBlocks()
NotificationCenter.default.addObserver(self, selector: #selector(NotificationCoordinator.applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
messagesToken?.stop()
chatsToken?.stop()
requestsToken?.stop()
}
/**
Show or hide connnecting view.
*/
func toggleConnectingView(show: Bool, animated: Bool) {
notificationWindow.showConnectingView(show, animated: animated)
}
/**
Stops showing notifications for given chat.
Also removes all related to that chat notifications from queue.
*/
func banNotificationsForChat(_ chat: OCTChat) {
bannedChatIdentifiers.insert(chat.uniqueIdentifier)
notificationQueue = notificationQueue.filter {
switch $0 {
case .newMessage(let messageAbstract):
return messageAbstract.chatUniqueIdentifier != chat.uniqueIdentifier
case .friendRequest:
return true
}
}
LNNotificationCenter.default().clearPendingNotifications(forApplicationIdentifier: chat.uniqueIdentifier);
}
/**
Unban notifications for given chat (if they were banned before).
*/
func unbanNotificationsForChat(_ chat: OCTChat) {
bannedChatIdentifiers.remove(chat.uniqueIdentifier)
}
func handleLocalNotification(_ notification: UILocalNotification) {
guard let userInfo = notification.userInfo as? [String: String] else {
return
}
guard let action = NotificationAction(dictionary: userInfo) else {
return
}
performAction(action)
}
func showCallNotificationWithCaller(_ caller: String, userInfo: String) {
let object = NotificationObject(
title: caller,
body: String(localized: "notification_is_calling"),
action: .answerIncomingCall(userInfo: userInfo),
soundName: "isotoxin_Ringtone.aac")
showLocalNotificationObject(object)
}
func registerInAppNotificationAppId(_ appId: String) {
if inAppNotificationAppIdsRegistered[appId] == nil {
LNNotificationCenter.default().registerApplication(withIdentifier: appId, name: Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String, icon: UIImage(named: "notification-app-icon"), defaultSettings: LNNotificationAppSettings.default())
inAppNotificationAppIdsRegistered[appId] = true
}
}
}
extension NotificationCoordinator: CoordinatorProtocol {
func startWithOptions(_ options: CoordinatorOptions?) {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
let application = UIApplication.shared
application.registerUserNotificationSettings(settings)
application.cancelAllLocalNotifications()
updateBadges()
}
}
// MARK: Notifications
extension NotificationCoordinator {
func applicationDidBecomeActive() {
UIApplication.shared.cancelAllLocalNotifications()
}
}
private extension NotificationCoordinator {
func addNotificationBlocks() {
let messages = submanagerObjects.messages().sortedResultsUsingProperty("dateInterval", ascending: false)
messagesToken = messages.addNotificationBlock { [unowned self] change in
switch change {
case .initial:
break
case .update(let messages, _, let insertions, _):
guard let messages = messages else {
break
}
if insertions.contains(0) {
let message = messages[0]
self.playSoundForMessageIfNeeded(message)
if self.shouldEnqueueMessage(message) {
self.enqueueNotification(.newMessage(message))
}
}
case .error(let error):
fatalError("\(error)")
}
}
chatsToken = chats.addNotificationBlock { [unowned self] change in
switch change {
case .initial:
break
case .update:
self.updateBadges()
case .error(let error):
fatalError("\(error)")
}
}
requestsToken = requests.addNotificationBlock { [unowned self] change in
switch change {
case .initial:
break
case .update(let requests, _, let insertions, _):
guard let requests = requests else {
break
}
for index in insertions {
let request = requests[index]
self.audioPlayer.playSound(.NewMessage)
self.enqueueNotification(.friendRequest(request))
}
self.updateBadges()
case .error(let error):
fatalError("\(error)")
}
}
}
func playSoundForMessageIfNeeded(_ message: OCTMessageAbstract) {
if message.isOutgoing() {
return
}
if message.messageText != nil || message.messageFile != nil {
audioPlayer.playSound(.NewMessage)
}
}
func shouldEnqueueMessage(_ message: OCTMessageAbstract) -> Bool {
if message.isOutgoing() {
return false
}
if UIApplication.isActive && bannedChatIdentifiers.contains(message.chatUniqueIdentifier) {
return false
}
if message.messageText != nil || message.messageFile != nil {
return true
}
return false
}
func enqueueNotification(_ notification: NotificationType) {
notificationQueue.append(notification)
showNextNotification()
}
func showNextNotification() {
if notificationQueue.isEmpty {
return
}
let notification = notificationQueue.removeFirst()
let object = notificationObjectFromNotification(notification)
if UIApplication.isActive {
switch notification {
case .newMessage(let messageAbstract):
showInAppNotificationObject(object, chatUniqueIdentifier: messageAbstract.chatUniqueIdentifier)
default:
showInAppNotificationObject(object, chatUniqueIdentifier: nil)
}
}
else {
showLocalNotificationObject(object)
}
}
func showInAppNotificationObject(_ object: NotificationObject, chatUniqueIdentifier: String?) {
var appId:String
if chatUniqueIdentifier != nil {
appId = chatUniqueIdentifier!
} else {
appId = Bundle.main.bundleIdentifier!
}
registerInAppNotificationAppId(appId);
let notification = LNNotification.init(message: object.body, title: object.title)
notification?.defaultAction = LNNotificationAction.init(title: nil, handler: { [weak self] _ in
self?.performAction(object.action)
})
LNNotificationCenter.default().present(notification, forApplicationIdentifier: appId)
showNextNotification()
}
func showLocalNotificationObject(_ object: NotificationObject) {
let local = UILocalNotification()
local.alertBody = "\(object.title): \(object.body)"
local.userInfo = object.action.archive()
local.soundName = object.soundName
UIApplication.shared.presentLocalNotificationNow(local)
showNextNotification()
}
func notificationObjectFromNotification(_ notification: NotificationType) -> NotificationObject {
switch notification {
case .friendRequest(let request):
return notificationObjectFromRequest(request)
case .newMessage(let message):
return notificationObjectFromMessage(message)
}
}
func notificationObjectFromRequest(_ request: OCTFriendRequest) -> NotificationObject {
let title = String(localized: "notification_incoming_contact_request")
let body = request.message ?? ""
let action = NotificationAction.openRequest(requestUniqueIdentifier: request.uniqueIdentifier)
return NotificationObject(title: title, body: body, action: action, soundName: "isotoxin_NewMessage.aac")
}
func notificationObjectFromMessage(_ message: OCTMessageAbstract) -> NotificationObject {
let title: String
if let friend = submanagerObjects.object(withUniqueIdentifier: message.senderUniqueIdentifier, for: .friend) as? OCTFriend {
title = friend.nickname
}
else {
title = ""
}
var body: String = ""
let action = NotificationAction.openChat(chatUniqueIdentifier: message.chatUniqueIdentifier)
if let messageText = message.messageText {
let defaultString = String(localized: "notification_new_message")
if userDefaults.showNotificationPreview {
body = messageText.text ?? defaultString
}
else {
body = defaultString
}
}
else if let messageFile = message.messageFile {
let defaultString = String(localized: "notification_incoming_file")
if userDefaults.showNotificationPreview {
body = messageFile.fileName ?? defaultString
}
else {
body = defaultString
}
}
return NotificationObject(title: title, body: body, action: action, soundName: "isotoxin_NewMessage.aac")
}
func performAction(_ action: NotificationAction) {
switch action {
case .openChat(let identifier):
guard let chat = submanagerObjects.object(withUniqueIdentifier: identifier, for: .chat) as? OCTChat else {
return
}
delegate?.notificationCoordinator(self, showChat: chat)
banNotificationsForChat(chat)
case .openRequest(let identifier):
guard let request = submanagerObjects.object(withUniqueIdentifier: identifier, for: .friendRequest) as? OCTFriendRequest else {
return
}
delegate?.notificationCoordinatorShowFriendRequest(self, showRequest: request)
case .answerIncomingCall(let userInfo):
delegate?.notificationCoordinatorAnswerIncomingCall(self, userInfo: userInfo)
}
}
func updateBadges() {
let chatsCount = chats.count
let requestsCount = requests.count
delegate?.notificationCoordinator(self, updateChatsBadge: chatsCount)
delegate?.notificationCoordinator(self, updateFriendsBadge: requestsCount)
UIApplication.shared.applicationIconBadgeNumber = chatsCount + requestsCount
}
// func chatsBadge() -> Int {
// // TODO update to new Realm and filter unread chats with predicate "lastMessage.dateInterval > lastReadDateInterval"
// var badge = 0
// for index in 0..<chats.count {
// guard let chat = chats[index] as? OCTChat else {
// continue
// }
// if chat.hasUnreadMessages() {
// badge += 1
// }
// }
// return badge
// }
}
| mit | 6fca03eeb053de89cfb80df7d8c5eb99 | 34.675879 | 255 | 0.635115 | 5.874638 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCap/Beacon/BeaconsViewController.swift | 1 | 3850 | //
// BeaconsViewController.swift
// BlueCap
//
// Created by Troy Stribling on 9/13/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import UIKit
import BlueCapKit
class BeaconsViewController: UITableViewController {
var beaconRegion : BeaconRegion?
struct MainStoryBoard {
static let beaconCell = "BeaconCell"
}
required init(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let beaconRegion = self.beaconRegion {
self.navigationItem.title = beaconRegion.identifier
NSNotificationCenter.defaultCenter().addObserver(self, selector:"updateBeacons", name:BlueCapNotification.didUpdateBeacon, object:beaconRegion)
} else {
self.navigationItem.title = "Beacons"
}
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func prepareForSegue(segue:UIStoryboardSegue, sender: AnyObject!) {
}
func updateBeacons() {
Logger.debug("BeaconRegionsViewController#updateBeacons")
self.tableView.reloadData()
}
func sortBeacons(b1:Beacon, b2:Beacon) -> Bool {
if b1.major > b2.major {
return true
} else if b1.major == b2.major && b1.minor > b2.minor {
return true
} else {
return false
}
}
func didResignActive() {
Logger.debug("BeaconRegionsViewController#didResignActive")
self.navigationController?.popToRootViewControllerAnimated(false)
}
func didBecomeActive() {
Logger.debug("BeaconRegionsViewController#didBecomeActive")
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let beaconRegion = self.beaconRegion {
return beaconRegion.beacons.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryBoard.beaconCell, forIndexPath: indexPath) as BeaconCell
if let beaconRegion = self.beaconRegion {
let beacon = sorted(beaconRegion.beacons, self.sortBeacons)[indexPath.row]
if let uuid = beacon.proximityUUID {
cell.proximityUUIDLabel.text = uuid.UUIDString
} else {
cell.proximityUUIDLabel.text = "Unknown"
}
if let major = beacon.major {
cell.majorLabel.text = "\(major)"
} else {
cell.majorLabel.text = "Unknown"
}
if let minor = beacon.minor {
cell.minorLabel.text = "\(minor)"
} else {
cell.minorLabel.text = "Unknown"
}
cell.proximityLabel.text = beacon.proximity.stringValue
cell.rssiLabel.text = "\(beacon.rssi)"
let accuracy = NSString(format:"%.4f", beacon.accuracy)
cell.accuracyLabel.text = "\(accuracy)m"
}
return cell
}
}
| mit | ba5dffad3d6290b9dc6122f3b9d2bd4f | 32.77193 | 155 | 0.635584 | 5.181696 | false | false | false | false |
crazypoo/PTools | Pods/PermissionsKit/Sources/LocationAlwaysPermission/LocationAlwaysHandler.swift | 1 | 2565 | // The MIT License (MIT)
// Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, [email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if PERMISSIONSKIT_SPM
import PermissionsKit
import LocationExtension
#endif
#if os(iOS) && PERMISSIONSKIT_LOCATION_ALWAYS
import Foundation
import MapKit
class LocationAlwaysHandler: NSObject, CLLocationManagerDelegate {
// MARK: - Location Manager
lazy var locationManager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .notDetermined {
return
}
completionHandler()
}
// MARK: - Process
var completionHandler: () -> Void = {}
func requestPermission(_ completionHandler: @escaping () -> Void) {
self.completionHandler = completionHandler
let status = CLLocationManager.authorizationStatus()
switch status {
case .notDetermined:
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
case .authorizedWhenInUse:
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
default:
self.completionHandler()
}
}
// MARK: - Init
static var shared: LocationAlwaysHandler?
override init() {
super.init()
}
deinit {
locationManager.delegate = nil
}
}
#endif
| mit | 5da54080f33655f17212af85339db596 | 32.298701 | 110 | 0.691888 | 5.221996 | false | false | false | false |
wei18810109052/CWWeChat | CWWeChat/ChatModule/CWChatKit/Message/Layout/CWMessageViewLayout.swift | 2 | 9756 | //
// CWMessageViewLayout.swift
// CWWeChat
//
// Created by chenwei on 2017/7/14.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
import YYText
protocol CWMessageViewLayoutDelegate: NSObjectProtocol {
func collectionView(_ collectionView: UICollectionView, itemAt indexPath: IndexPath) -> CWMessageModel
}
/**
使用collectionView 不太熟悉 待完善
*/
class CWMessageViewLayout: UICollectionViewFlowLayout {
weak var delegate: CWMessageViewLayoutDelegate?
var setting = CWMessageLayoutSettings.share
var needLayout: Bool = true
var contentHeight = CGFloat()
var cache = [IndexPath: CWMessageLayoutAttributes]()
var visibleLayoutAttributes = [CWMessageLayoutAttributes]()
override public class var layoutAttributesClass: AnyClass {
return CWMessageLayoutAttributes.self
}
override public var collectionViewContentSize: CGSize {
return CGSize(width: collectionViewWidth, height: contentHeight)
}
fileprivate var collectionViewHeight: CGFloat {
return collectionView!.frame.height
}
fileprivate var collectionViewWidth: CGFloat {
return collectionView!.frame.width
}
private var contentOffset: CGPoint {
return collectionView!.contentOffset
}
}
extension CWMessageViewLayout {
func prepareCache() {
cache.removeAll(keepingCapacity: true)
}
override func prepare() {
guard let collectionView = collectionView,
let delegate = self.delegate,
needLayout == true else {
return
}
prepareCache()
needLayout = false
contentHeight = 0
// 计算布局
let section = 0
for item in 0 ..< collectionView.numberOfItems(inSection: section) {
let cellIndexPath = IndexPath(item: item, section: section)
let attributes = CWMessageLayoutAttributes(forCellWith: cellIndexPath)
configure(attributes: attributes)
// cell 高度
let heightOfCell = attributes.messageContainerFrame.height + kMessageCellBottomMargin + kMessageCellTopMargin
attributes.frame = CGRect(x: 0, y: contentHeight, width: kScreenWidth, height: heightOfCell)
contentHeight = attributes.frame.maxY
cache[cellIndexPath] = attributes
}
}
private func configure(attributes: CWMessageLayoutAttributes) {
guard let collectionView = collectionView,
let message = delegate?.collectionView(collectionView, itemAt: attributes.indexPath) else {
return
}
attributes.avaterFrame = avatarFrame(with: message)
setupUsernameFrame(with: attributes, message: message)
setupContainerFrame(with: attributes, message: message)
setupStateFrame(with: attributes, message: message)
}
// 头像
func avatarFrame(with message: CWMessageModel) -> CGRect {
let size: CGSize = setting.kAvaterSize
let origin: CGPoint
if message.isSend {
origin = CGPoint(x: collectionViewWidth - setting.kMessageToLeftPadding - size.width,
y: setting.kMessageToTopPadding)
} else {
origin = CGPoint(x: setting.kMessageToLeftPadding, y: setting.kMessageToTopPadding)
}
return CGRect(origin: origin, size: size)
}
// 昵称(如果有昵称,则昵称和头像y一样)
func setupUsernameFrame(with attributes: CWMessageLayoutAttributes, message: CWMessageModel) {
var size: CGSize = setting.kUsernameSize
let origin: CGPoint
if message.showUsername == false {
size = CGSize.zero
}
if message.isSend {
origin = CGPoint(x: attributes.avaterFrame.minX - setting.kUsernameLeftPadding - size.width,
y: attributes.avaterFrame.minY)
} else {
origin = CGPoint(x: attributes.avaterFrame.maxX + setting.kUsernameLeftPadding,
y: attributes.avaterFrame.minY)
}
attributes.usernameFrame = CGRect(origin: origin, size: size)
}
func setupContainerFrame(with attributes: CWMessageLayoutAttributes, message: CWMessageModel) {
// 如果是文字
var contentSize: CGSize = CGSize.zero
switch message.messageType {
case .text:
let content = (message.messageBody as! CWTextMessageBody).text
let size = CGSize(width: kChatTextMaxWidth, height: CGFloat.greatestFiniteMagnitude)
var edge: UIEdgeInsets
if message.isSend {
edge = ChatCellUI.right_edge_insets
} else {
edge = ChatCellUI.left_edge_insets
}
let modifier = CWTextLinePositionModifier(font: setting.contentTextFont)
// YYTextContainer
let textContainer = YYTextContainer(size: size)
textContainer.linePositionModifier = modifier
textContainer.maximumNumberOfRows = 0
let textFont = setting.contentTextFont
let textAttributes = [NSAttributedStringKey.font: textFont,
NSAttributedStringKey.foregroundColor: UIColor.black]
let textAttri = CWChatTextParser.parseText(content, attributes: textAttributes)!
let textLayout = YYTextLayout(container: textContainer, text: textAttri)!
contentSize = CGSize(width: textLayout.textBoundingSize.width+edge.left+edge.right,
height: textLayout.textBoundingSize.height+edge.top+edge.bottom)
message.textLayout = textLayout
case .image:
let imageSize = (message.messageBody as! CWImageMessageBody).size
//根据图片的比例大小计算图片的frame
if imageSize.width > imageSize.height {
var height = kChatImageMaxWidth * imageSize.height / imageSize.width
height = max(kChatImageMinWidth, height)
contentSize = CGSize(width: ceil(kChatImageMaxWidth), height: ceil(height))
} else {
var width = kChatImageMaxWidth * imageSize.width / imageSize.height
width = max(kChatImageMinWidth, width)
contentSize = CGSize(width: ceil(width), height: ceil(kChatImageMaxWidth))
}
let edge = UIEdgeInsets.zero
contentSize = CGSize(width: contentSize.width+edge.left+edge.right,
height: contentSize.height+edge.top+edge.bottom)
case .voice:
let voiceMessage = message.messageBody as! CWVoiceMessageBody
var scale: CGFloat = CGFloat(voiceMessage.voiceLength)/60.0
if scale > 1 {
scale = 1
}
contentSize = CGSize(width: ceil(scale*kChatVoiceMaxWidth)+70,
height: setting.kAvaterSize.height+13)
case .emoticon:
contentSize = CGSize(width: 120, height: 120)
case .location:
contentSize = CGSize(width: 250, height: 150)
default:
break
}
let origin: CGPoint
if message.isSend {
origin = CGPoint(x: attributes.avaterFrame.minX - setting.kUsernameLeftPadding - contentSize.width,
y: attributes.usernameFrame.minY)
} else {
origin = CGPoint(x: attributes.avaterFrame.maxX + setting.kUsernameLeftPadding,
y: attributes.usernameFrame.minY)
}
attributes.messageContainerFrame = CGRect(origin: origin, size: contentSize)
}
func setupStateFrame(with attributes: CWMessageLayoutAttributes, message: CWMessageModel) {
let containerFrame = attributes.messageContainerFrame
let origin: CGPoint
if message.isSend {
origin = CGPoint(x: containerFrame.minX - 2 - setting.errorSize.width,
y: containerFrame.midY - 10)
} else {
origin = CGPoint(x: containerFrame.minX + 2 + setting.errorSize.width,
y: containerFrame.midY - 10)
}
attributes.errorFrame = CGRect(origin: origin, size: setting.errorSize)
attributes.activityFrame = CGRect(origin: origin, size: setting.errorSize)
}
// 所有cell 布局
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath]
}
//3
override public func layoutAttributesForElements(
in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
visibleLayoutAttributes.removeAll(keepingCapacity: true)
for (_, attributes) in cache where attributes.frame.intersects(rect) {
visibleLayoutAttributes.append(attributes)
}
return visibleLayoutAttributes
}
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) {
super.invalidateLayout(with: context)
if context.invalidateDataSourceCounts {
needLayout = true
}
}
}
| mit | dbdb185d285db76b932b07afc1d1d9fa | 34.973881 | 121 | 0.609584 | 5.608493 | false | false | false | false |
warnerbros/cpe-manifest-ios-data | Source/TheTake/TheTakeAPIUtil.swift | 1 | 6278 | //
// TheTakeAPIUtil.swift
//
import Foundation
public class TheTakeAPIUtil: APIUtil, ProductAPIUtil {
public static var APIDomain = "https://thetake.p.mashape.com"
public static var APINamespace = "thetake.com"
private struct Headers {
static let APIKey = "X-Mashape-Key"
static let Accept = "Accept"
static let AcceptValue = "application/json"
}
public var featureAPIID: String?
public var productCategories: [ProductCategory]?
private var frameTimes = [Double: NSDictionary]()
private var _frameTimeKeys = [Double]()
open var frameTimeKeys: [Double] {
if _frameTimeKeys.count == 0 {
_frameTimeKeys = frameTimes.keys.sorted()
}
return _frameTimeKeys
}
public convenience init(apiKey: String, featureAPIID: String? = nil) {
self.init(apiDomain: TheTakeAPIUtil.APIDomain)
self.featureAPIID = featureAPIID
self.customHeaders[Headers.APIKey] = apiKey
self.customHeaders[Headers.Accept] = Headers.AcceptValue
}
open func closestFrameTime(_ timeInSeconds: Double) -> Double {
let timeInMilliseconds = timeInSeconds * 1000
var closestFrameTime = -1.0
if frameTimes.count > 0 && frameTimes[timeInMilliseconds] == nil {
if let frameIndex = frameTimeKeys.index(where: { $0 > timeInMilliseconds }) {
closestFrameTime = frameTimeKeys[max(frameIndex - 1, 0)]
}
} else {
closestFrameTime = timeInMilliseconds
}
return closestFrameTime
}
open func getProductFrameTimes(completion: @escaping (_ frameTimes: [Double]?) -> Void) -> URLSessionDataTask? {
if let apiID = featureAPIID {
return getJSONWithPath("/frames/listFrames", parameters: ["media": apiID, "start": "0", "limit": "10000"], successBlock: { (result) -> Void in
if let frames = result["result"] as? [NSDictionary] {
completion(frames.flatMap({ $0["frameTime"] as? Double }))
} else {
completion(nil)
}
}, errorBlock: { (error) in
print("Error fetching product frame times: \(error?.localizedDescription ?? "Unknown error")")
completion(nil)
})
}
return nil
}
open func getProductCategories(completion: ((_ productCategories: [ProductCategory]?) -> Void)?) -> URLSessionDataTask? {
if productCategories != nil {
completion?(productCategories)
return nil
}
if let apiID = featureAPIID {
productCategories = [TheTakeProductCategory]()
return getJSONWithPath("/categories/listProductCategories", parameters: ["media": apiID], successBlock: { [weak self] (result) in
if let categories = result["result"] as? [NSDictionary] {
self?.productCategories = categories.flatMap({ TheTakeProductCategory(data: $0) })
}
completion?(self?.productCategories)
}, errorBlock: { [weak self] (error) in
print("Error fetching product categories: \(error?.localizedDescription ?? "Unknown error")")
completion?(self?.productCategories)
})
}
return nil
}
open func getFrameProducts(_ frameTime: Double, completion: @escaping (_ products: [ProductItem]?) -> Void) -> URLSessionDataTask? {
if let apiID = featureAPIID, frameTime >= 0 && frameTimes[frameTime] != nil {
return getJSONWithPath("/frameProducts/listFrameProducts", parameters: ["media": apiID, "time": String(frameTime)], successBlock: { (result) -> Void in
if let productList = result["result"] as? NSArray {
var products = [TheTakeProduct]()
for productInfo in productList {
if let productData = productInfo as? NSDictionary, let product = TheTakeProduct(data: productData) {
products.append(product)
}
}
completion(products)
}
}) { (error) -> Void in
print("Error fetching products for frame \(frameTime): \(error?.localizedDescription ?? "Unknown error")")
completion(nil)
}
} else {
completion(nil)
}
return nil
}
open func getCategoryProducts(_ categoryID: String?, completion: @escaping (_ products: [ProductItem]?) -> Void) -> URLSessionDataTask? {
if let apiID = featureAPIID {
var parameters: [String: String] = ["media": apiID, "limit": "100"]
if let categoryID = categoryID {
parameters["category"] = categoryID
}
return getJSONWithPath("/products/listProducts", parameters: parameters, successBlock: { (result) -> Void in
if let productList = result["result"] as? NSArray {
var products = [TheTakeProduct]()
for productInfo in productList {
if let productData = productInfo as? NSDictionary, let product = TheTakeProduct(data: productData) {
products.append(product)
}
}
completion(products)
}
}) { (error) -> Void in
print("Error fetching products for category ID \(categoryID ?? "NONE"): \(error?.localizedDescription ?? "Unknown error")")
completion(nil)
}
} else {
completion(nil)
}
return nil
}
open func getProductDetails(_ productID: String, completion: @escaping (_ product: ProductItem?) -> Void) -> URLSessionDataTask {
return getJSONWithPath("/products/productDetails", parameters: ["product": productID], successBlock: { (result) -> Void in
completion(TheTakeProduct(data: result))
}) { (error) -> Void in
print("Error fetching product details for product ID \(productID): \(error?.localizedDescription ?? "Unknown error")")
completion(nil)
}
}
}
| apache-2.0 | 40729bf20b2c981d15da4375538b76be | 38.987261 | 163 | 0.57582 | 5.306847 | false | false | false | false |
ixonelaguardia/miDiccionario | DiccionarioAPP/DiccionarioAPP/ListadoIdiomasViewController.swift | 1 | 2965 | //
// ListadoIdiomasViewController.swift
// DiccionarioAPP
//
// Created by on 12/1/16.
// Copyright © 2016 Egibide. All rights reserved.
//
import UIKit
class ListadoIdiomasViewController: UIViewController {
var idiomas=["","","",""]
@IBOutlet weak var boton1: UIButton!
@IBOutlet weak var boton2: UIButton!
@IBOutlet weak var boton3: UIButton!
@IBOutlet weak var boton4: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func carcelar(segue:UIStoryboardSegue) {
}
@IBAction func hecho(segue:UIStoryboardSegue) {
let nuevoIdiomaVC = segue.sourceViewController as! NuevoIdiomaViewController
for i in 0...3{
if idiomas[i]==""{
idiomas[i] = nuevoIdiomaVC.nombreIdioma
break
}
}
if boton1.titleLabel!.text==nil{
boton1.setTitle(idiomas[0], forState: .Normal)
boton1.enabled=true
}else{
if boton2.titleLabel!.text==nil{
boton2.setTitle(idiomas[1], forState: .Normal)
boton2.enabled=true
}else{
if boton3.titleLabel!.text==nil{
boton3.setTitle(idiomas[2], forState: .Normal)
boton3.enabled=true
}else {
if boton4.titleLabel!.text==nil{
boton4.setTitle(idiomas[3], forState: .Normal)
boton4.enabled=true
}
}
}
}
}
var idioma=5;
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destino = segue.destinationViewController as? Listado {
if segue.identifier=="segueIdioma1"{
destino.indiceIdioma=0
destino.titulo=boton1.titleLabel!.text!
} else if segue.identifier=="segueIdioma2"{
destino.indiceIdioma=1
destino.titulo=boton2.titleLabel!.text!
} else if segue.identifier=="segueIdioma3"{
destino.indiceIdioma=2
destino.titulo=boton3.titleLabel!.text!
} else if segue.identifier=="segueIdioma4"{
destino.indiceIdioma=3
destino.titulo=boton4.titleLabel!.text!
}
}
}
} | apache-2.0 | f1dc5d26fdf2056faa8e42920c0c4761 | 29.255102 | 106 | 0.525304 | 4.956522 | false | false | false | false |
mykoma/NetworkingLib | Networking/Sources/HttpTransaction/HttpTransaction+Operation.swift | 1 | 2033 | //
// HttpTransaction+RequestOperation.swift
// Networking
//
// Created by Apple on 2016/11/4.
// Copyright © 2016年 goluk. All rights reserved.
//
import Foundation
// MARK: - Operations
extension HttpTransaction {
public func cancel() {
self.currentRequest?.request?.cancel()
self.currentRequest?.isCancelled = true
}
public func suspend() {
self.currentRequest?.request?.suspend()
}
public func resume() {
self.currentRequest?.request?.resume()
}
}
// MARK: - Download
var HttpTransaction_Download_ResumeData: UInt8 = 0
extension HttpTransaction {
var resumeData: Data? {
get {
return objc_getAssociatedObject(self,
&HttpTransaction_Download_ResumeData) as? Data
}
set {
objc_setAssociatedObject(self,
&HttpTransaction_Download_ResumeData,
newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public func suspendDownload() {
self.cancel()
}
public func resumeDownload() {
let _ = HttpNetworking.sharedInstance
.sendingDownloadResume(transaction: self)
.subscribe(onNext: { [weak self](resp) in
guard let strongSelf = self else {
return
}
strongSelf.rxObserver?.onNext(resp)
}, onError: { [weak self](error) in
guard let strongSelf = self else {
return
}
strongSelf.rxObserver?.onError(error)
}, onCompleted: { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.rxObserver?.onCompleted()
}) {
// Dispose
}
}
}
| mit | 6f7a9c7557ed331706bce6e93025e089 | 26.066667 | 94 | 0.502956 | 5.413333 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01294-getselftypeforcontainer.swift | 11 | 548 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
var m: Int -> Int = {
n $0
o: Int = { d, l f
}(k, m)
protocol j {
typealias l = d}
class g<q : l, m : l p q.g == m> : j {
class k {
protocol c : b { func b
| apache-2.0 | b55aba5c4b9f8f2190f937a89ba6db03 | 31.235294 | 78 | 0.678832 | 3.223529 | false | false | false | false |
kstaring/swift | test/Constraints/dictionary_literal.swift | 4 | 4154 | // RUN: %target-parse-verify-swift
final class DictStringInt : ExpressibleByDictionaryLiteral {
typealias Key = String
typealias Value = Int
init(dictionaryLiteral elements: (String, Int)...) { }
}
final class Dictionary<K, V> : ExpressibleByDictionaryLiteral {
typealias Key = K
typealias Value = V
init(dictionaryLiteral elements: (K, V)...) { }
}
func useDictStringInt(_ d: DictStringInt) {}
func useDict<K, V>(_ d: Dictionary<K,V>) {}
// Concrete dictionary literals.
useDictStringInt(["Hello" : 1])
useDictStringInt(["Hello" : 1, "World" : 2])
useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
useDictStringInt([4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}}
useDictStringInt([nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}}
useDictStringInt([7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
// Generic dictionary literals.
useDict(["Hello" : 1])
useDict(["Hello" : 1, "World" : 2])
useDict(["Hello" : 1.5, "World" : 2])
useDict([1 : 1.5, 3 : 2.5])
// Fall back to Dictionary<K, V> if no context is otherwise available.
var a = ["Hello" : 1, "World" : 2]
var a2 : Dictionary<String, Int> = a
var a3 = ["Hello" : 1]
var b = [1 : 2, 1.5 : 2.5]
var b2 : Dictionary<Double, Double> = b
var b3 = [1 : 2.5]
// <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error
// expected-note @+1 {{did you mean to use a dictionary literal instead?}}
var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' cannot be used with array literal}}
"closure_1" as String, {(Int) -> Int in 0},
"closure_2", {(Int) -> Int in 0}]
var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}}
var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}}
var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
// <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better
var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}}
class A { }
class B : A { }
class C : A { }
func testDefaultExistentials() {
let _ = ["a" : 1, "b" : 2.5, "c" : "hello"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}{{46-46= as Dictionary<String, Any>}}
let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"]
let d2 = [:]
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = d2 // expected-error{{value of type 'Dictionary<AnyHashable, Any>'}}
let _ = ["a": 1,
"b": ["a", 2, 3.14159],
"c": ["a": 2, "b": 3.5]]
// expected-error@-3{{heterogeneous collection literal could only be inferred to 'Dictionary<String, Any>'; add explicit type annotation if this is intentional}}
let d3 = ["b" : B(), "c" : C()]
let _: Int = d3 // expected-error{{value of type 'Dictionary<String, A>'}}
let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, Any>'}}
let _ = ["a" : "hello", 17 : "string"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to 'Dictionary<AnyHashable, String>'}}
}
| apache-2.0 | 7d1c6819d8783d5d3a8626239a6d0254 | 43.191489 | 200 | 0.655272 | 3.508446 | false | false | false | false |
maxbritto/cours-ios11-swift4 | Apprendre/Objectif 3/Objectif3_UIKit/Objectif3_UIKit/ViewController.swift | 1 | 2987 | //
// ViewController.swift
// Objectif3_UIKit
//
// Created by Maxime Britto on 28/07/2017.
// Copyright © 2017 Purple Giraffe. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var ui_tableView: UITableView!
var _70sShowList:[String] = []
var _friendsList:[String] = []
@IBOutlet weak var ui_demoTextField: UITextField!
@IBAction func dissmissKeyboard() {
ui_demoTextField.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ui_demoTextField.becomeFirstResponder()
ui_tableView.dataSource = self
_70sShowList.append("Donna")
_70sShowList.append("Eric")
_70sShowList.append("Kelso")
_70sShowList.append("Jackie")
_70sShowList.append("Fez")
_70sShowList.append("Hide")
_70sShowList.append("Bob")
_70sShowList.append("Midge")
_friendsList.append("Monica")
_friendsList.append("Rachel")
_friendsList.append("Phoebe")
_friendsList.append("Chandler")
_friendsList.append("Joey")
_friendsList.append("Ross")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let title:String
if section == 0 {
title = "That 70's Show"
} else {
title = "Friends"
}
return title
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rowCount:Int
if section == 0 {
rowCount = _70sShowList.count
} else {
rowCount = _friendsList.count
}
return rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "number-cell", for: indexPath)
if let titleLabel = cell.textLabel {
if indexPath.section == 0 {
titleLabel.text = _70sShowList[indexPath.row]
} else {
titleLabel.text = _friendsList[indexPath.row]
}
}
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
_70sShowList.remove(at: indexPath.row)
} else {
_friendsList.remove(at: indexPath.row)
}
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
| apache-2.0 | d4f3d260a132b4a5ee6f2a9024ff10a9 | 29.161616 | 127 | 0.602143 | 4.847403 | false | false | false | false |
AssistoLab/FloatingLabel | FloatingLabel/src/fields/EmailFloatingField.swift | 2 | 443 | //
// EmailFloatingField.swift
// FloatingLabel
//
// Created by Kevin Hirsch on 23/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
public class EmailFloatingField: FloatingTextField {
override public func setup() {
super.setup()
keyboardType = .EmailAddress
autocapitalizationType = .None
autocorrectionType = .No
spellCheckingType = .No
validation = Validation(.EmailAddress)
}
} | mit | f0c72a5fdbd731946495307375e4242a | 17.5 | 57 | 0.715576 | 3.885965 | false | false | false | false |
lukesutton/olpej | Olpej/Olpej/Properties-Label.swift | 1 | 1959 | extension Property {
public static func text<T: UILabel>(value: String) -> Property<T> {
return Property<T>("label.text", value.hashValue) { _, mode, view in
switch(mode) {
case .remove: view.text = nil
case .update: view.text = value
}
}
}
public static func attributedText<T: UILabel>(value: NSAttributedString) -> Property<T> {
return Property<T>("label.attributedText", value.hashValue) { _, mode, view in
switch(mode) {
case .remove: view.attributedText = nil
case .update: view.attributedText = value
}
}
}
public static func font<T: UILabel>(value: UIFont) -> Property<T> {
return Property<T>("label.font", value.hashValue) { _, mode, view in
switch(mode) {
case .remove: view.font = nil
case .update: view.font = value
}
}
}
public static func textColor<T: UILabel>(color: UIColor) -> Property<T> {
return Property<T>("label.font", color.hashValue) { _, mode, view in
switch(mode) {
case .remove: view.textColor = nil
case .update: view.textColor = color
}
}
}
public static func textAlignment<T: UILabel>(alignment: NSTextAlignment) -> Property<T> {
return Property<T>("label.font", alignment.hashValue) { _, mode, view in
switch(mode) {
case .remove: view.textAlignment = .Left
case .update: view.textAlignment = alignment
}
}
}
public static func lineBreakMode<T: UILabel>(breakMode: NSLineBreakMode) -> Property<T> {
return Property<T>("label.font", breakMode.hashValue) { _, mode, view in
switch(mode) {
case .remove: view.lineBreakMode = .ByTruncatingTail
case .update: view.lineBreakMode = breakMode
}
}
}
} | mit | b8362a985c8e89b4d2f00a5f6a125108 | 34.636364 | 93 | 0.558959 | 4.432127 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS | AztecTests/NSAttributedString/Conversions/AttributedStringSerializerTests.swift | 2 | 8686 | import XCTest
@testable import Aztec
class AttributedStringSerializerTests: XCTestCase {
/// Verifies that <span> Nodes are preserved into the NSAttributedString instance, by means of the UnsupportedHTML
/// attribute.
///
func testMultipleSpanNodesAreProperlyPreservedWithinUnsupportedHtmlAttribute() {
let textNode = TextNode(text: "Ehlo World!")
// <span class="aztec"></span>
let spanAttribute2 = Attribute(type: .class, value: .string("aztec"))
let spanNode2 = ElementNode(type: .span, attributes: [spanAttribute2], children: [textNode])
// <span class="first"><span class="aztec"></span>
let spanAttribute1 = Attribute(type: .class, value: .string("first"))
let spanNode1 = ElementNode(type: .span, attributes: [spanAttribute1], children: [spanNode2])
// <h1><span class="first"><span class="aztec"></span></span></h1>
let headerNode = ElementNode(type: .h1, attributes: [], children: [spanNode1])
let rootNode = RootNode(children: [headerNode])
// Convert
let output = attributedString(from: rootNode)
// Test
var range = NSRange()
guard let unsupportedHTML = output.attribute(.unsupportedHtml, at: 0, effectiveRange: &range) as? UnsupportedHTML else {
XCTFail()
return
}
let representations = unsupportedHTML.representations
XCTAssert(range.length == textNode.length())
XCTAssert(representations.count == 2)
let restoredSpanElement2 = representations.last
XCTAssertEqual(restoredSpanElement2?.name, "span")
let restoredSpanAttribute2 = restoredSpanElement2?.attributes.first
XCTAssertEqual(restoredSpanAttribute2?.name, "class")
XCTAssertEqual(restoredSpanAttribute2?.value.toString(), "aztec")
let restoredSpanElement1 = representations.first
XCTAssertEqual(restoredSpanElement1?.name, "span")
let restoredSpanAttribute1 = restoredSpanElement1?.attributes.first
XCTAssertEqual(restoredSpanAttribute1?.type, .class)
XCTAssertEqual(restoredSpanAttribute1?.value.toString(), "first")
}
/// Verifies that the DivFormatter effectively appends the DIV Element Representation, to the properties collection.
///
func testHtmlDivFormatterEffectivelyAppendsNewDivProperty() {
let textNode = TextNode(text: "Ehlo World!")
let divAttr3 = Attribute(type: .class, value: .string("third"))
let divNode3 = ElementNode(type: .div, attributes: [divAttr3], children: [textNode])
let divAttr2 = Attribute(type: .class, value: .string("second"))
let divNode2 = ElementNode(type: .div, attributes: [divAttr2], children: [divNode3])
let divAttr1 = Attribute(type: .class, value: .string("first"))
let divNode1 = ElementNode(type: .div, attributes: [divAttr1], children: [divNode2])
// Convert
let output = attributedString(from: divNode1)
// Test!
var range = NSRange()
guard let paragraphStyle = output.attribute(.paragraphStyle, at: 0, effectiveRange: &range) as? ParagraphStyle else {
XCTFail()
return
}
XCTAssert(range.length == textNode.length())
XCTAssert(paragraphStyle.htmlDiv.count == 3)
guard case let .element(restoredDiv1) = paragraphStyle.htmlDiv[0].representation!.kind,
case let .element(restoredDiv2) = paragraphStyle.htmlDiv[1].representation!.kind,
case let .element(restoredDiv3) = paragraphStyle.htmlDiv[2].representation!.kind
else {
XCTFail()
return
}
XCTAssert(restoredDiv1.name == divNode1.name)
XCTAssert(restoredDiv1.attributes == [divAttr1])
XCTAssert(restoredDiv2.name == divNode2.name)
XCTAssert(restoredDiv2.attributes == [divAttr2])
XCTAssert(restoredDiv3.name == divNode3.name)
XCTAssert(restoredDiv3.attributes == [divAttr3])
}
/// Verifies that BR elements contained within div tags do not cause any side effect.
/// Ref. #658
///
func testLineBreakTagWithinHTMLDivGetsProperlyEncodedAndDecoded() {
let inHtml = "<div><br>Aztec, don't forget me!</div>"
let inNode = HTMLParser().parse(inHtml)
let attrString = attributedString(from: inNode)
let outNode = AttributedStringParser().parse(attrString)
let outHtml = HTMLSerializer().serialize(outNode)
XCTAssertEqual(outHtml, inHtml)
}
/// Verifies that BR elements contained within span tags do not cause Data Loss.
/// Ref. #658
///
func testLineBreakTagWithinUnsupportedHTMLDoesNotCauseDataLoss() {
let inHtml = "<span><br>Aztec, don't forget me!</span>"
let expectedHtml = "<p><span><br>Aztec, don't forget me!</span></p>"
let inNode = HTMLParser().parse(inHtml)
let attrString = attributedString(from: inNode)
let outNode = AttributedStringParser().parse(attrString)
let outHtml = HTMLSerializer().serialize(outNode)
XCTAssertEqual(outHtml, expectedHtml)
}
/// Verifies that nested Unsupported HTML snippets get applied to *their own* UnsupportedHTML container.
/// Ref. #658
///
func testMultipleUnrelatedUnsupportedHTMLSnippetsDoNotGetAppliedToTheEntireStringRange() {
let inHtml = "<div>" +
"<p><span>One</span></p>" +
"<p><span><br></span></p>" +
"<p><span>Two</span></p>" +
"<p><br></p>" +
"<p><span>Three</span><span>Four</span><span>Five</span></p>" +
"</div>"
let inNode = HTMLParser().parse(inHtml)
let attrString = attributedString(from: inNode)
let outNode = AttributedStringParser().parse(attrString)
let outHtml = HTMLSerializer().serialize(outNode)
XCTAssertEqual(outHtml, inHtml)
}
/// Verifies that a linked image is properly converted from HTML to attributed string and back to HTML.
///
func testLinkedImageGetsProperlyEncodedAndDecoded() {
let inHtml = "<p><a href=\"https://wordpress.com\" class=\"alignnone\"><img src=\"https://s.w.org/about/images/wordpress-logo-notext-bg.png\" class=\"alignnone\"></a></p>"
let inNode = HTMLParser().parse(inHtml)
let attrString = attributedString(from: inNode)
let outNode = AttributedStringParser().parse(attrString)
let outHtml = HTMLSerializer().serialize(outNode)
XCTAssertEqual(outHtml, inHtml)
}
/// Verifies that Figure + Figcaption entities are properly mapped within an Image's caption field.
///
/// - Input: <figure><img src="."><figcaption><h1>I'm a caption!</h1></figcaption></figure>
///
/// - Output: Expected to he a single ImageAttachment, with it's `.caption` field properly set (and it's contents in h1 format).
///
func testFigcaptionElementGetsProperlySerializedIntoImageAttachmentCaptionField() {
// <figcaption><h1>I'm a caption!</h1></figcaption>
let figcaptionTextNode = TextNode(text: "I'm a caption!")
let figcaptionH1Node = ElementNode(type: .h1, attributes: [], children: [figcaptionTextNode])
let figcaptionMainNode = ElementNode(type: .figcaption, attributes: [], children: [figcaptionH1Node])
// <figure><img/><figcaption/></figure>
let imageNode = ElementNode(type: .img, attributes: [], children: [])
let figureNode = ElementNode(type: .figure, attributes: [], children: [imageNode, figcaptionMainNode])
// Convert
let rootNode = RootNode(children: [figureNode])
let output = attributedString(from: rootNode)
guard let imageAttachment = output.attribute(.attachment, at: 0, effectiveRange: nil) as? ImageAttachment else {
XCTFail()
return
}
guard let caption = output.caption(for: imageAttachment) else {
XCTFail()
return
}
let formatter = HeaderFormatter(headerLevel: .h1)
XCTAssertTrue(formatter.present(in: caption, at: 0))
}
}
// MARK: - Helpers
//
extension AttributedStringSerializerTests {
func attributedString(from node: Node) -> NSAttributedString {
let defaultAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 14),
.paragraphStyle: ParagraphStyle.default]
let serializer = AttributedStringSerializer()
return serializer.serialize(node, defaultAttributes: defaultAttributes)
}
}
| gpl-2.0 | 7e30f8004fd7988267a7713b084dde2e | 39.02765 | 179 | 0.649436 | 4.64492 | false | true | false | false |
rechsteiner/Parchment | Parchment/Classes/PagingOptions.swift | 1 | 6733 | import UIKit
public struct PagingOptions {
/// The size for each of the menu items. _Default:
/// .sizeToFit(minWidth: 150, height: 40)_
public var menuItemSize: PagingMenuItemSize
/// Determine the spacing between the menu items. _Default: 0_
public var menuItemSpacing: CGFloat
/// Determine the horizontal constraints of menu item label. _Default: 20_
public var menuItemLabelSpacing: CGFloat
/// Determine the insets at around all the menu items. _Default:
/// UIEdgeInsets.zero_
public var menuInsets: UIEdgeInsets
/// Determine whether the menu items should be centered when all the
/// items can fit within the bounds of the view. _Default: .left_
public var menuHorizontalAlignment: PagingMenuHorizontalAlignment
/// Determine the position of the menu relative to the content.
/// _Default: .top_
public var menuPosition: PagingMenuPosition
/// Determine the transition behaviour of menu items while scrolling
/// the content. _Default: .scrollAlongside_
public var menuTransition: PagingMenuTransition
/// Determine how users can interact with the menu items.
/// _Default: .scrolling_
public var menuInteraction: PagingMenuInteraction
/// Determine how users can interact with the contents
/// _Default: .scrolling_
public var contentInteraction: PagingContentInteraction
/// The class type for collection view layout. Override this if you
/// want to use your own subclass of the layout. Setting this
/// property will initialize the new layout type and update the
/// collection view.
/// _Default: PagingCollectionViewLayout.self_
public var menuLayoutClass: PagingCollectionViewLayout.Type
/// Determine how the selected menu item should be aligned when it
/// is selected. Effectivly the same as the
/// `UICollectionViewScrollPosition`. _Default: .preferCentered_
public var selectedScrollPosition: PagingSelectedScrollPosition
/// Add an indicator view to the selected menu item. The indicator
/// width will be equal to the selected menu items width. Insets
/// only apply horizontally. _Default: .visible_
public var indicatorOptions: PagingIndicatorOptions
/// The class type for the indicator view. Override this if you want
/// your use your own subclass of PagingIndicatorView. _Default:
/// PagingIndicatorView.self_
public var indicatorClass: PagingIndicatorView.Type
/// Determine the color of the indicator view.
public var indicatorColor: UIColor
/// Add a border at the bottom of the menu items. The border will be
/// as wide as all the menu items. Insets only apply horizontally.
/// _Default: .visible_
public var borderOptions: PagingBorderOptions
/// The class type for the border view. Override this if you want
/// your use your own subclass of PagingBorderView. _Default:
/// PagingBorderView.self_
public var borderClass: PagingBorderView.Type
/// Determine the color of the border view.
public var borderColor: UIColor
/// Updates the content inset for the menu items based on the
/// .safeAreaInsets property. _Default: true_
public var includeSafeAreaInsets: Bool
/// The font used for title label on the menu items.
public var font: UIFont
/// The font used for the currently selected menu item.
public var selectedFont: UIFont
/// The color of the title label on the menu items.
public var textColor: UIColor
/// The text color for the currently selected menu item.
public var selectedTextColor: UIColor
/// The background color for the menu items.
public var backgroundColor: UIColor
/// The background color for the selected menu item.
public var selectedBackgroundColor: UIColor
/// The background color for the view behind the menu items.
public var menuBackgroundColor: UIColor
/// The background color for the paging contents
/// _Default: .white
public var pagingContentBackgroundColor: UIColor
/// The scroll navigation orientation of the content in the page
/// view controller. _Default: .horizontal_
public var contentNavigationOrientation: PagingNavigationOrientation
public var scrollPosition: UICollectionView.ScrollPosition {
switch selectedScrollPosition {
case .left:
return UICollectionView.ScrollPosition.left
case .right:
return UICollectionView.ScrollPosition.right
case .preferCentered, .center:
return UICollectionView.ScrollPosition.centeredHorizontally
}
}
public var menuHeight: CGFloat {
return menuItemSize.height + menuInsets.top + menuInsets.bottom
}
public var estimatedItemWidth: CGFloat {
switch menuItemSize {
case let .fixed(width, _):
return width
case let .sizeToFit(minWidth, _):
return minWidth
case let .selfSizing(estimatedItemWidth, _):
return estimatedItemWidth
}
}
public init() {
selectedScrollPosition = .preferCentered
menuItemSize = .sizeToFit(minWidth: 150, height: 40)
menuPosition = .top
menuTransition = .scrollAlongside
menuInteraction = .scrolling
menuInsets = UIEdgeInsets.zero
menuItemSpacing = 0
menuItemLabelSpacing = 20
menuHorizontalAlignment = .left
includeSafeAreaInsets = true
indicatorClass = PagingIndicatorView.self
borderClass = PagingBorderView.self
menuLayoutClass = PagingCollectionViewLayout.self
indicatorOptions = .visible(
height: 4,
zIndex: Int.max,
spacing: UIEdgeInsets.zero,
insets: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
)
borderOptions = .visible(
height: 1,
zIndex: Int.max - 1,
insets: UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
)
font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
selectedFont = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
textColor = UIColor.black
selectedTextColor = UIColor(red: 3 / 255, green: 125 / 255, blue: 233 / 255, alpha: 1)
backgroundColor = .clear
selectedBackgroundColor = .clear
pagingContentBackgroundColor = .white
menuBackgroundColor = UIColor.white
borderColor = UIColor(white: 0.9, alpha: 1)
indicatorColor = UIColor(red: 3 / 255, green: 125 / 255, blue: 233 / 255, alpha: 1)
contentNavigationOrientation = .horizontal
contentInteraction = .scrolling
}
}
| mit | 5eb4afedd05ac6f731ccfe879817b86f | 37.039548 | 94 | 0.68647 | 5.179231 | false | false | false | false |
likojack/wedrive_event_management | weDrive/DatePickerDialog.swift | 2 | 12497 | import UIKit
import QuartzCore
class DatePickerDialog: UIView {
/* Consts */
private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50
private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1
private let kDatePickerDialogCornerRadius: CGFloat = 7
private let kDatePickerDialogCancelButtonTag: Int = 1
private let kDatePickerDialogDoneButtonTag: Int = 2
/* Views */
private var dialogView: UIView!
private var titleLabel: UILabel!
private var datePicker: UIDatePicker!
private var cancelButton: UIButton!
private var doneButton: UIButton!
/* Vars */
private var title: String!
private var doneButtonTitle: String!
private var cancelButtonTitle: String!
private var defaultDate: NSDate!
private var datePickerMode: UIDatePickerMode!
private var callback: ((date: NSDate) -> Void)!
/* Overrides */
init () {
super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientationDidChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/* Handle device orientation changes */
func deviceOrientationDidChange(notification: NSNotification) {
/* TODO */
}
/* Create the dialog view, and animate opening the dialog */
func show(#title: String, datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) {
show(title: title, doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: datePickerMode, callback: callback)
}
func show(#title: String, doneButtonTitle: String, cancelButtonTitle: String, defaultDate: NSDate = NSDate(), datePickerMode: UIDatePickerMode = .DateAndTime, callback: ((date: NSDate) -> Void)) {
self.title = title
self.doneButtonTitle = doneButtonTitle
self.cancelButtonTitle = cancelButtonTitle
self.datePickerMode = datePickerMode
self.callback = callback
self.defaultDate = defaultDate
self.dialogView = createContainerView()
self.dialogView!.layer.shouldRasterize = true
self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
self.dialogView!.layer.opacity = 0.5
self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addSubview(self.dialogView!)
/* Attached to the top most window (make sure we are using the right orientation) */
let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
switch(interfaceOrientation) {
case UIInterfaceOrientation.LandscapeLeft:
let t: Double = M_PI * 270 / 180
self.transform = CGAffineTransformMakeRotation(CGFloat(t))
break
case UIInterfaceOrientation.LandscapeRight:
let t: Double = M_PI * 90 / 180
self.transform = CGAffineTransformMakeRotation(CGFloat(t))
break
case UIInterfaceOrientation.PortraitUpsideDown:
let t: Double = M_PI * 180 / 180
self.transform = CGAffineTransformMakeRotation(CGFloat(t))
break
default:
break
}
self.frame = CGRectMake(0, 0, self.frame.width, self.frame.size.height)
UIApplication.sharedApplication().windows.first!.addSubview(self)
/* Anim */
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.dialogView!.layer.opacity = 1
self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
},
completion: nil
)
}
/* Dialog close animation then cleaning and removing the view from the parent */
private func close() {
let currentTransform = self.dialogView.layer.transform
let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0
let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0)
self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1))
self.dialogView.layer.opacity = 1
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.TransitionNone,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
self.dialogView.layer.opacity = 0
}) { (finished: Bool) -> Void in
for v in self.subviews {
v.removeFromSuperview()
}
self.removeFromSuperview()
}
}
/* Creates the container view here: create the dialog, then add the custom content and buttons */
private func createContainerView() -> UIView {
let screenSize = countScreenSize()
let dialogSize = CGSizeMake(
300,
230
+ kDatePickerDialogDefaultButtonHeight
+ kDatePickerDialogDefaultButtonSpacerHeight)
// For the black background
self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height)
// This is the dialog's container; we attach the custom content and the buttons to this one
let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height))
// First, we style the dialog to match the iOS8 UIAlertView >>>
let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer)
gradient.frame = dialogContainer.bounds
gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor,
UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor,
UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor]
let cornerRadius = kDatePickerDialogCornerRadius
gradient.cornerRadius = cornerRadius
dialogContainer.layer.insertSublayer(gradient, atIndex: 0)
dialogContainer.layer.cornerRadius = cornerRadius
dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor
dialogContainer.layer.borderWidth = 1
dialogContainer.layer.shadowRadius = cornerRadius + 5
dialogContainer.layer.shadowOpacity = 0.1
dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2)
dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor
dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath
// There is a line above the button
let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight))
lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1)
dialogContainer.addSubview(lineView)
// ˆˆˆ
//Title
self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30))
self.titleLabel.textAlignment = NSTextAlignment.Center
self.titleLabel.font = UIFont.boldSystemFontOfSize(17)
self.titleLabel.text = self.title
dialogContainer.addSubview(self.titleLabel)
self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0))
self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin
self.datePicker.frame.size.width = 300
self.datePicker.datePickerMode = self.datePickerMode
self.datePicker.date = self.defaultDate
dialogContainer.addSubview(self.datePicker)
// Add the buttons
addButtonsToView(dialogContainer)
return dialogContainer
}
/* Add buttons to container */
private func addButtonsToView(container: UIView) {
let buttonWidth = container.bounds.size.width / 2
self.cancelButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
self.cancelButton.frame = CGRectMake(
0,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.cancelButton.tag = kDatePickerDialogCancelButtonTag
self.cancelButton.setTitle(self.cancelButtonTitle, forState: UIControlState.Normal)
self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.cancelButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
container.addSubview(self.cancelButton)
self.doneButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
self.doneButton.frame = CGRectMake(
buttonWidth,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.doneButton.tag = kDatePickerDialogDoneButtonTag
self.doneButton.setTitle(self.doneButtonTitle, forState: UIControlState.Normal)
self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.doneButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
container.addSubview(self.doneButton)
}
func buttonTapped(sender: UIButton!) {
if sender.tag == kDatePickerDialogDoneButtonTag {
self.callback(date: self.datePicker.date)
} else if sender.tag == kDatePickerDialogCancelButtonTag {
//There's nothing do to here \o\
}
close()
}
/* Helper function: count and return the screen's size */
func countScreenSize() -> CGSize {
var screenWidth = UIScreen.mainScreen().bounds.size.width
var screenHeight = UIScreen.mainScreen().bounds.size.height
let interfaceOrientaion = UIApplication.sharedApplication().statusBarOrientation
if UIInterfaceOrientationIsLandscape(interfaceOrientaion) {
let tmp = screenWidth
screenWidth = screenHeight
screenHeight = tmp
}
return CGSizeMake(screenWidth, screenHeight)
}
} | apache-2.0 | 7f99ed3ffc80bf3a3512fda2fa648554 | 45.513308 | 250 | 0.640067 | 5.489455 | false | false | false | false |
firebase/quickstart-ios | authentication/AuthenticationExample/SceneDelegate.swift | 1 | 3193 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import FirebaseDynamicLinks
import FirebaseAuth
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
lazy var authNavController: UINavigationController = {
let navController = UINavigationController(rootViewController: AuthViewController())
navController.view.backgroundColor = .systemBackground
return navController
}()
lazy var userNavController: UINavigationController = {
let navController = UINavigationController(rootViewController: UserViewController())
navController.view.backgroundColor = .systemBackground
return navController
}()
lazy var tabBarController: UITabBarController = {
let tabBarController = UITabBarController()
tabBarController.delegate = tabBarController
tabBarController.view.backgroundColor = .systemBackground
return tabBarController
}()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
configureControllers()
window = UIWindow(windowScene: windowScene)
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
if let incomingURL = userActivity.webpageURL {
handleIncomingDynamicLink(incomingURL)
}
}
// MARK: - Firebase 🔥
private func handleIncomingDynamicLink(_ incomingURL: URL) {
DynamicLinks.dynamicLinks().handleUniversalLink(incomingURL) { dynamicLink, error in
guard error == nil else {
return print("ⓧ Error in \(#function): \(error!.localizedDescription)")
}
guard let link = dynamicLink?.url?.absoluteString else { return }
if Auth.auth().isSignIn(withEmailLink: link) {
// Save the link as it will be used in the next step to complete login
UserDefaults.standard.set(link, forKey: "Link")
// Post a notification to the PasswordlessViewController to resume authentication
NotificationCenter.default
.post(Notification(name: Notification.Name("PasswordlessEmailNotificationSuccess")))
}
}
}
// MARK: - Private Helpers
private func configureControllers() {
authNavController.configureTabBar(
title: "Authentication",
systemImageName: "person.crop.circle.fill.badge.plus"
)
userNavController.configureTabBar(title: "Current User", systemImageName: "person.fill")
tabBarController.viewControllers = [authNavController, userNavController]
}
}
| apache-2.0 | 2e5e98ba0fa97be6291d8b6a3316f352 | 34.820225 | 94 | 0.737453 | 5.22623 | false | false | false | false |
iHunterX/SocketIODemo | DemoSocketIO/Classes/RequiredViewController.swift | 1 | 3584 | //
// RequiredViewController.swift
// DemoSocketIO
//
// Created by Đinh Xuân Lộc on 10/28/16.
// Copyright © 2016 Loc Dinh Xuan. All rights reserved.
//
import UIKit
class RequiredViewController: PAPermissionsViewController,PAPermissionsViewControllerDelegate {
let cameraCheck = PACameraPermissionsCheck()
let locationCheck = PALocationPermissionsCheck()
let microphoneCheck = PAMicrophonePermissionsCheck()
let photoLibraryCheck = PAPhotoLibraryPermissionsCheck()
lazy var notificationsCheck : PAPermissionsCheck = {
if #available(iOS 10.0, *) {
return PAUNNotificationPermissionsCheck()
} else {
return PANotificationsPermissionsCheck()
}
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.delegate = self
let permissions = [
PAPermissionsItem.itemForType(.location, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.microphone, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.photoLibrary, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.notifications, reason: "Required to send you great updates")!,
PAPermissionsItem.itemForType(.camera, reason: PAPermissionDefaultReason)!]
let handlers = [
PAPermissionsType.location.rawValue: self.locationCheck,
PAPermissionsType.microphone.rawValue :self.microphoneCheck,
PAPermissionsType.photoLibrary.rawValue: self.photoLibraryCheck,
PAPermissionsType.camera.rawValue: self.cameraCheck,
PAPermissionsType.notifications.rawValue: self.notificationsCheck
]
self.setupData(permissions, handlers: handlers)
// Do any additional setup after loading the view.
self.tintColor = UIColor.white
self.backgroundImage = #imageLiteral(resourceName: "background")
self.useBlurBackground = false
self.titleText = "iSpam"
self.detailsText = "Please enable the following"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func permissionsViewControllerDidContinue(_ viewController: PAPermissionsViewController) {
if let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "MainController") as? UINavigationController {
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let presentingViewController: UIViewController! = self.presentingViewController
//
// self.dismiss(animated: false) {
// // go back to MainMenuView as the eyes of the user
// presentingViewController.dismiss(animated: false, completion: {
//// self.present(loginVC, animated: true, completion: nil)
// })
// }
loginVC.modalTransitionStyle = .crossDissolve
self.present(loginVC, animated: true, completion: nil)
}
}
/*
// 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.
}
*/
}
| gpl-3.0 | 632444195f8cc78aa8496f0ace580d4f | 39.213483 | 130 | 0.673931 | 5.497696 | false | false | false | false |
rtsbtx/IQKeyboardManager | IQKeybordManagerSwift/IQToolbar/IQToolbar.swift | 3 | 3368 | //
// IQToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/** @abstract IQToolbar for IQKeyboardManager. */
class IQToolbar: UIToolbar , UIInputViewAudioFeedback {
override class func initialize() {
superclass()?.initialize()
self.appearance().barTintColor = nil
self.appearance().backgroundColor = nil
}
var titleFont : UIFont? {
didSet {
if items != nil {
for item in items as! [UIBarButtonItem] {
if item is IQTitleBarButtonItem == true {
(item as! IQTitleBarButtonItem).font = titleFont
}
}
}
}
}
var title : String? {
didSet {
if items != nil {
for item in items as! [UIBarButtonItem] {
if item is IQTitleBarButtonItem == true {
(item as! IQTitleBarButtonItem).title = title
}
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
sizeToFit()
autoresizingMask = UIViewAutoresizing.FlexibleWidth
tintColor = UIColor .blackColor()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sizeToFit()
autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
tintColor = UIColor .blackColor()
}
override func sizeThatFits(size: CGSize) -> CGSize {
var sizeThatFit = super.sizeThatFits(size)
sizeThatFit.height = 44
return sizeThatFit
}
override var tintColor: UIColor! {
didSet {
if let unwrappedItems = items {
for item in unwrappedItems as! [UIBarButtonItem] {
if item is IQTitleBarButtonItem {
item.tintColor = tintColor
}
}
}
}
}
var enableInputClicksWhenVisible: Bool {
return true
}
}
| mit | 6104e77462887e8af62cbb168fa9cae7 | 30.476636 | 95 | 0.586995 | 5.512275 | false | false | false | false |
getsocial-im/getsocial-ios-sdk | example/GetSocialDemo/Views/Communities/Groups/Search/GroupsModel.swift | 1 | 5980 | //
// GenericModel.swift
// GetSocialDemo
//
// Copyright © 2020 GetSocial BV. All rights reserved.
//
import Foundation
class GroupsModel {
var onInitialDataLoaded: (() -> Void)?
var onDidOlderLoad: ((Bool) -> Void)?
var onError: ((String) -> Void)?
var groupFollowed: ((Int) -> Void)?
var groupUnfollowed: ((Int) -> Void)?
var onGroupDeleted: ((Int) -> Void)?
var onGroupJoined: ((GroupMember, Int) -> Void)?
var onGroupLeft: ((Int) -> Void)?
var onInviteAccepted: ((Int) -> Void)?
var pagingQuery: GroupsPagingQuery?
var query: GroupsQuery?
var groups: [Group] = []
var nextCursor: String = ""
func loadEntries(query: GroupsQuery) {
self.query = query
self.pagingQuery = GroupsPagingQuery.init(query)
self.groups.removeAll()
executeQuery(success: {
self.onInitialDataLoaded?()
}, failure: onError)
}
func loadNewer() {
self.pagingQuery?.nextCursor = ""
self.groups.removeAll()
executeQuery(success: {
self.onInitialDataLoaded?()
}, failure: onError)
}
func loadOlder() {
if self.nextCursor.count == 0 {
onDidOlderLoad?(false)
return
}
self.pagingQuery?.nextCursor = self.nextCursor
executeQuery(success: {
self.onDidOlderLoad?(true)
}, failure: onError)
}
func numberOfEntries() -> Int {
return self.groups.count
}
func entry(at: Int) -> Group {
return self.groups[at]
}
func findGroup(_ groupId: String) -> Group? {
return self.groups.filter {
return $0.id == groupId
}.first
}
func joinGroup(_ groupId: String) {
let query = JoinGroupQuery.init(groupId: groupId)
if let oldGroup = findGroup(groupId), let groupIndex = self.groups.firstIndex(of: oldGroup) {
Communities.joinGroup(query, success: { [weak self] member in
Communities.group(groupId, success: { group in
self?.groups[groupIndex] = group
self?.onGroupJoined?(member, groupIndex)
}, failure: { error in
self?.onError?(error.localizedDescription)
})
}, failure: { [weak self] error in
self?.onError?(error.localizedDescription)
})
}
}
func acceptInvite(_ groupId: String, membership: Membership) {
var groupIndex: Int?
for (index, group) in self.groups.enumerated() {
if group.id == groupId {
groupIndex = index
}
}
let query = JoinGroupQuery.init(groupId: groupId).withInvitationToken(membership.invitationToken!)
Communities.joinGroup(query, success: { [weak self] members in
Communities.group(groupId, success: { group in
self?.groups[groupIndex!] = group
self?.onInviteAccepted?(groupIndex!)
}, failure: { error in
self?.onError?(error.localizedDescription)
})
}, failure: { [weak self] error in
self?.onError?(error.localizedDescription)
})
}
func followGroup(_ groupId: String) {
if let group = findGroup(groupId), let groupIndex = self.groups.firstIndex(of: group) {
let query = FollowQuery.groups([groupId])
if group.isFollowedByMe {
Communities.unfollow(query, success: { _ in
PrivateGroupBuilder.updateGroup(group: group, isFollowed: false)
self.groupUnfollowed?(groupIndex)
}) { error in
self.onError?(error.localizedDescription)
}
} else {
Communities.follow(query, success: { _ in
PrivateGroupBuilder.updateGroup(group: group, isFollowed: true)
self.groupFollowed?(groupIndex)
}) { error in
self.onError?(error.localizedDescription)
}
}
}
}
func deleteGroup(_ groupId: String) {
var groupIndex: Int?
for (index, group) in self.groups.enumerated() {
if group.id == groupId {
groupIndex = index
}
}
Communities.removeGroups([groupId], success: { [weak self] in
self?.groups.remove(at: groupIndex!)
self?.onGroupDeleted?(groupIndex!)
}, failure: { [weak self] error in
self?.onError?(error.localizedDescription)
})
}
func leaveGroup(_ groupId: String) {
guard let currentUserId = GetSocial.currentUser()?.userId else {
self.onError?("Could not get current user")
return
}
var groupIndex: Int?
for (index, group) in self.groups.enumerated() {
if group.id == groupId {
groupIndex = index
}
}
let query = RemoveGroupMembersQuery.users(UserIdList.create([currentUserId]), from: groupId)
Communities.removeGroupMembers(query, success: { [weak self] in
Communities.group(groupId, success: { group in
self?.groups[groupIndex!] = group
self?.onGroupLeft?(groupIndex!)
}, failure: { error in
self?.onError?(error.localizedDescription)
})
}, failure: { [weak self] error in
self?.onError?(error.localizedDescription)
})
}
private func executeQuery(success: (() -> Void)?, failure: ((String) -> Void)?) {
Communities.groups(self.pagingQuery!, success: { result in
self.nextCursor = result.nextCursor
self.groups.append(contentsOf: result.groups)
success?()
}) { error in
failure?(error.localizedDescription)
}
}
}
| apache-2.0 | 0a4be5d3058cf1c66469992fd2a00bf2 | 32.779661 | 106 | 0.554441 | 4.794707 | false | false | false | false |
Kruks/FindViewControl | FindViewControl/FindViewControl/Constants.swift | 1 | 1070 | //
// Constants.swift
// MyCity311
//
// Created by Piyush on 6/2/16.
// Copyright © 2016 Kahuna Systems. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
enum TimeOutIntervals {
static let kSRRetryCount = 3
static let kMaxRetryCount = 3
static let kSRTimeoutInterval = 60
static let kMaxTimeoutInterval = 240
static let cacheImageTimeOut = 30.0
static let kMaxLocationWaitTime = 10
static let kMinHorizontalAccuracy = 100
static let horizontalLocationAccuracy = 70
static let maximumWaitTimeForLocation = 10
static let defaultImageCompressionValue = 0.7
static let queryPageSize = 10
}
enum UnidentifiedError: Error {
case emptyHTTPResponse
}
enum ServerResponseCodes
{
static let successCode: Int = 200
static let unknownErrorCode: Int = 1000
static let generalErrorCode = 201
static let sessionExpireErrorCode = 234
static let duplicateEntryCode = 203
}
}
| mit | 0bdb2b8bb9571498986bde333cad95e1 | 21.270833 | 57 | 0.661366 | 4.815315 | false | false | false | false |
universeiscool/MediaPickerController | MediaPickerController/MediaPickerController.swift | 1 | 11038 | //
// MediaPickerController.swift
// MediaPickerController
//
// Created by Malte Schonvogel on 22.11.15.
// Copyright © 2015 universeiscool UG (haftungsbeschränkt). All rights reserved.
//
import UIKit
import Photos
public enum MediaPickerOption
{
case ViewBackgroundColor(UIColor)
case NavigationBarTitleAttributes([String:AnyObject])
}
public enum MediaPickerAlbumType
{
case Moments
case Selected
case AllAssets
case UserAlbum
case Panorama
case Screenshots
case Favorites
case RecentlyAdded
case SelfPortraits
static func convertFromAssetTypes(assetCollectionSubtype: PHAssetCollectionSubtype) -> MediaPickerAlbumType?
{
var type:MediaPickerAlbumType? = nil
switch assetCollectionSubtype {
case .SmartAlbumPanoramas: type = .Panorama
case .SmartAlbumRecentlyAdded: type = .RecentlyAdded
case .SmartAlbumScreenshots: type = .Screenshots
case .SmartAlbumSelfPortraits: type = .SelfPortraits
case .SmartAlbumFavorites: type = .Favorites
case .SmartAlbumUserLibrary: type = .AllAssets
case .AlbumRegular: type = .UserAlbum
default: type = nil
}
return type
}
}
public class MediaPickerAlbum
{
var title: String?
var cover: UIImage?
var collection: PHAssetCollection?
var fetchResult: PHFetchResult? // For Moments
var assetCount: Int
var type: MediaPickerAlbumType
init(title:String?, collection:PHAssetCollection?, assetCount:Int, type: MediaPickerAlbumType)
{
self.title = title
self.collection = collection
self.assetCount = assetCount
self.type = type
}
}
public struct MediaPickerMoment
{
let title:String
let date:String
let assets:PHFetchResult
}
public class MediaPickerController: UINavigationController
{
public var selectedAssets = [PHAsset]() {
didSet {
doneButtonView.enabled = selectedAssets.count > 0
}
}
public var prevSelectedAssetIdentifiers:[String]?
lazy var doneButtonView:UIBarButtonItem = {
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(didClickDoneButton(_:)))
button.enabled = false
return button
}()
lazy var cancelButtonView:UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(didClickCancelButton(_:)))
}()
lazy var selectAlbumButtonView: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(didClickSelectAlbumButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
button.enabled = false
return button
}()
var selectAlbumButtonTitle:String {
set {
let attributedTitle = NSAttributedString(string: newValue.uppercaseString, attributes: navigationBarTitleAttributes)
selectAlbumButtonView.setAttributedTitle(attributedTitle, forState: .Normal)
selectAlbumButtonView.sizeToFit()
}
get {
return selectAlbumButtonView.titleLabel?.text ?? ""
}
}
lazy public var photosViewController: PhotosViewController = {
let vc = PhotosViewController()
return vc
}()
lazy public var momentsViewController: MomentsViewController = {
let vc = MomentsViewController()
return vc
}()
lazy public var albumsViewController: AlbumsViewController = {
let vc = AlbumsViewController(albums: self.albums)
vc.preferredContentSize = self.view.bounds.size
vc.delegate = self
return vc
}()
var albums: [[MediaPickerAlbum]]?
public var doneClosure:((assets: [PHAsset], momentTitle:String?, mediaPickerController:MediaPickerController) -> Void)?
public var cancelClosure:((mediaPickerController:MediaPickerController) -> Void)?
public var maximumSelect = Int(50) {
didSet {
allowsMultipleSelection = maximumSelect > 1
}
}
public var allowsMultipleSelection = true
public var viewBackgroundColor = UIColor.blackColor()
public var navigationBarTitleAttributes:[String:AnyObject] = [
NSForegroundColorAttributeName: UIColor.blackColor(),
NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 16.0)!,
NSKernAttributeName: 1.5
]
public var hintText:String?
public convenience init(mediaPickerOptions:[MediaPickerOption]?)
{
self.init(nibName: nil, bundle: nil)
if let options = mediaPickerOptions {
optionsToInstanceVariables(options)
}
}
override private init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override public func viewDidLoad()
{
super.viewDidLoad()
selectAlbumButtonTitle = "Loading ..."
let fetcher = AlbumFetcher.shared
fetcher.fetchAlbums{ (albums) in
self.selectAlbumButtonView.enabled = true
self.albums = albums
if let album = self.albums?.flatten().filter({ $0.type == .Moments }).first {
self.momentsViewController.album = album
} else if let album = self.albums?.flatten().first {
self.setViewControllers([self.photosViewController], animated: false)
self.photosViewController.album = album
}
}
}
public override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
// Make sure MomentsViewController won't be displayed, if allowsMultipleSelection is not allowed
if albums?.count > 0 && !allowsMultipleSelection {
if getActiveViewController() is MomentsViewController {
setViewControllers([photosViewController], animated: false)
if let album = self.albums?.flatten().filter({ $0.type == .AllAssets }).first where photosViewController.album == nil {
self.photosViewController.album = album
}
}
}
}
public override func viewDidDisappear(animated: Bool)
{
super.viewDidDisappear(animated)
PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self)
selectedAssets.removeAll()
}
override public func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public override func loadView()
{
super.loadView()
navigationBar.translucent = false
setViewControllers([momentsViewController], animated: false)
}
func didClickSelectAlbumButton(sender: UIButton)
{
guard let popover = albumsViewController.popoverPresentationController else {
return
}
popover.permittedArrowDirections = .Up
popover.sourceView = sender
let senderRect = sender.convertRect(sender.frame, fromView: sender.superview)
let sourceRect = CGRect(x: senderRect.origin.x, y: senderRect.origin.y + 4.0, width: senderRect.size.width, height: senderRect.size.height)
popover.sourceRect = sourceRect
popover.delegate = self
albumsViewController.hideMoments = !allowsMultipleSelection
presentViewController(albumsViewController, animated: true, completion: nil)
}
func didClickDoneButton(sender: UIBarButtonItem)
{
if let vc = viewControllers.first as? MomentsViewController {
if let moment = vc.selectedMoment {
var assets = [PHAsset]()
for i in 0..<moment.assets.count {
assets.append(moment.assets[i] as! PHAsset)
}
doneClosure?(assets:assets, momentTitle:moment.title, mediaPickerController:self)
}
} else if let _ = viewControllers.first as? PhotosViewController {
doneClosure?(assets:selectedAssets, momentTitle:nil, mediaPickerController:self)
}
}
func didClickCancelButton(sender: UIBarButtonItem)
{
cancelClosure?(mediaPickerController:self)
}
// MARK: Helper Functions
private func optionsToInstanceVariables(options:[MediaPickerOption])
{
for option in options {
switch option {
case let .ViewBackgroundColor(value): viewBackgroundColor = value
case let .NavigationBarTitleAttributes(value): navigationBarTitleAttributes = value
}
}
}
private func getActiveViewController() -> MediaPickerCollectionViewController?
{
if let vc = viewControllers.first as? MomentsViewController {
return vc
} else if let vc = viewControllers.first as? PhotosViewController {
return vc
}
return nil
}
}
extension MediaPickerController: PHPhotoLibraryChangeObserver
{
public func photoLibraryDidChange(changeInstance: PHChange)
{
}
}
// MARK: UIPopoverPresentationControllerDelegate
extension MediaPickerController: UIPopoverPresentationControllerDelegate
{
public func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle
{
return .None
}
public func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool
{
return true
}
}
// MARK: UINavigationControllerDelegate
//extension PhotosViewController: UINavigationControllerDelegate {
// public func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// if operation == .Push {
// return expandAnimator
// } else {
// return shrinkAnimator
// }
// }
//}
extension MediaPickerController: AlbumsViewControllerDelegate
{
func didSelectAlbum(album:MediaPickerAlbum)
{
self.albumsViewController.dismissViewControllerAnimated(true, completion: nil)
if album.type == .Moments {
self.setViewControllers([self.momentsViewController], animated: false)
self.momentsViewController.album = album
} else {
self.setViewControllers([self.photosViewController], animated: false)
self.photosViewController.album = album
}
}
} | mit | 917dcd555adf0004a75987f6fec97def | 32.344411 | 290 | 0.665912 | 5.70926 | false | false | false | false |
qlongming/shppingCat | shoppingCart-master/shoppingCart/Classes/ShopCart/Controller/MSShoppingCartViewController.swift | 1 | 9140 | //
// JFShoppingCartViewController.swift
// shoppingCart
//
// Created by jianfeng on 15/11/17.
// Copyright © 2015年 六阿哥. All rights reserved.
//
import UIKit
class MSShoppingCartViewController: UIViewController {
// MARK: - 属性
/// 已经添加进购物车的商品模型数组,初始化
var addGoodArray: [MSGoodModel]? {
didSet {
}
}
/// 总金额,默认0.00
var price: CFloat = 0.00
/// 商品列表cell的重用标识符
private let shoppingCarCellIdentifier = "shoppingCarCell"
// MARK: - view生命周期
override func viewDidLoad() {
super.viewDidLoad()
// 准备UI
prepareUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// 布局UI
layoutUI()
// 重新计算价格
reCalculateGoodCount()
}
/**
准备UI
*/
private func prepareUI() {
// 标题
navigationItem.title = "购物车列表"
// 导航栏左边返回
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "didTappedBackButton")
// view背景颜色
view.backgroundColor = UIColor.whiteColor()
// cell行高
tableView.rowHeight = 80
// 注册cell
tableView.registerClass(MSShoppingCartCell.self, forCellReuseIdentifier: shoppingCarCellIdentifier)
// 添加子控件
view.addSubview(tableView)
view.addSubview(bottomView)
bottomView.addSubview(selectButton)
bottomView.addSubview(totalPriceLabel)
bottomView.addSubview(buyButton)
// 判断是否需要全选
for model in addGoodArray! {
if model.selected != true {
// 只要有一个不等于就不全选
selectButton.selected = false
break
}
}
}
/**
布局UI
*/
private func layoutUI() {
// 约束子控件
tableView.snp_makeConstraints { (make) -> Void in
make.left.top.right.equalTo(0)
make.bottom.equalTo(-49)
}
bottomView.snp_makeConstraints { (make) -> Void in
make.left.bottom.right.equalTo(0)
make.height.equalTo(49)
}
selectButton.snp_makeConstraints { (make) -> Void in
make.left.equalTo(12)
make.centerY.equalTo(bottomView.snp_centerY)
}
totalPriceLabel.snp_makeConstraints { (make) -> Void in
make.center.equalTo(bottomView.snp_center)
}
buyButton.snp_makeConstraints { (make) -> Void in
make.right.equalTo(-12)
make.top.equalTo(9)
make.width.equalTo(88)
make.height.equalTo(30)
}
}
// MARK: - 懒加载
/// tableView
lazy var tableView: UITableView = {
let tableView = UITableView()
// 指定数据源和代理
tableView.dataSource = self
tableView.delegate = self
return tableView
}()
/// 底部视图
lazy var bottomView: UIView = {
let bottomView = UIView()
bottomView.backgroundColor = UIColor.whiteColor()
return bottomView
}()
/// 底部多选、反选按钮
lazy var selectButton: UIButton = {
let selectButton = UIButton(type: UIButtonType.Custom)
selectButton.setImage(UIImage(named: "check_n"), forState: UIControlState.Normal)
selectButton.setImage(UIImage(named: "check_y"), forState: UIControlState.Selected)
selectButton.setTitle("多选\\反选", forState: UIControlState.Normal)
selectButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
selectButton.titleLabel?.font = UIFont.systemFontOfSize(12)
selectButton.addTarget(self, action: "didTappedSelectButton:", forControlEvents: UIControlEvents.TouchUpInside)
selectButton.selected = true
selectButton.sizeToFit()
return selectButton
}()
/// 底部总价Label
lazy var totalPriceLabel: UILabel = {
let totalPriceLabel = UILabel()
let attributeText = NSMutableAttributedString(string: "总共价格:\(self.price)0")
attributeText.setAttributes([NSForegroundColorAttributeName : UIColor.redColor()], range: NSMakeRange(5, attributeText.length - 5))
totalPriceLabel.attributedText = attributeText
totalPriceLabel.sizeToFit()
return totalPriceLabel
}()
/// 底部付款按钮
lazy var buyButton: UIButton = {
let buyButton = UIButton(type: UIButtonType.Custom)
buyButton.setTitle("付款", forState: UIControlState.Normal)
buyButton.setBackgroundImage(UIImage(named: "button_cart_add"), forState: UIControlState.Normal)
buyButton.layer.cornerRadius = 15
buyButton.layer.masksToBounds = true
return buyButton
}()
}
// MARK: - UITableViewDataSource, UITableViewDelegate数据、代理
extension MSShoppingCartViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return addGoodArray?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 从缓存池创建cell,不成功就根据重用标识符和注册的cell新创建一个
let cell = tableView.dequeueReusableCellWithIdentifier(shoppingCarCellIdentifier, forIndexPath: indexPath) as! MSShoppingCartCell
// cell取消选中效果
cell.selectionStyle = UITableViewCellSelectionStyle.None
// 指定代理对象
cell.delegate = self
// 传递模型
cell.goodModel = addGoodArray?[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
reCalculateGoodCount()
}
}
// MARK: - view上的一些事件处理
extension MSShoppingCartViewController {
/**
返回按钮
*/
@objc private func didTappedBackButton() {
dismissViewControllerAnimated(true, completion: nil)
}
/**
重新计算商品数量
*/
private func reCalculateGoodCount() {
// 遍历模型
for model in addGoodArray! {
// 只计算选中的商品
if model.selected == true {
price += Float(model.count) * (model.newPrice! as NSString).floatValue
}
}
// 赋值价格
let attributeText = NSMutableAttributedString(string: "总共价格:\(self.price)0")
attributeText.setAttributes([NSForegroundColorAttributeName : UIColor.redColor()], range: NSMakeRange(5, attributeText.length - 5))
totalPriceLabel.attributedText = attributeText
// 清空price
price = 0
// 刷新表格
tableView.reloadData()
}
/**
点击了多选按钮后的事件处理
- parameter button: 多选按钮
*/
@objc private func didTappedSelectButton(button: UIButton) {
selectButton.selected = !selectButton.selected
for model in addGoodArray! {
model.selected = selectButton.selected
}
// 重新计算总价
reCalculateGoodCount()
// 刷新表格
tableView.reloadData()
}
}
// MARK: - JFShoppingCartCellDelegate代理方法
extension MSShoppingCartViewController: MSShoppingCartCellDelegate {
/**
当点击了cell中加、减按钮
- parameter cell: 被点击的cell
- parameter button: 被点击的按钮
- parameter countLabel: 显示数量的label
*/
func shoppingCartCell(cell: MSShoppingCartCell, button: UIButton, countLabel: UILabel) {
// 根据cell获取当前模型
guard let indexPath = tableView.indexPathForCell(cell) else {
return
}
// 获取当前模型,添加到购物车模型数组
let model = addGoodArray![indexPath.row]
if button.tag == 10 {
if model.count < 1 {
print("数量不能低于0")
return
}
// 减
model.count--
countLabel.text = "\(model.count)"
} else {
// 加
model.count++
countLabel.text = "\(model.count)"
}
// 重新计算商品数量
reCalculateGoodCount()
}
/**
重新计算总价
*/
func reCalculateTotalPrice() {
reCalculateGoodCount()
}
}
| apache-2.0 | 71e72abfe467a3345d7acaccfadde614 | 26.545752 | 151 | 0.582869 | 5.196671 | false | false | false | false |
aatalyk/swift-algorithm-club | Topological Sort/Topological Sort.playground/Contents.swift | 5 | 936 | //: Playground - noun: a place where people can play
import UIKit
let graph = Graph()
let node5 = graph.addNode("5")
let node7 = graph.addNode("7")
let node3 = graph.addNode("3")
let node11 = graph.addNode("11")
let node8 = graph.addNode("8")
let node2 = graph.addNode("2")
let node9 = graph.addNode("9")
let node10 = graph.addNode("10")
graph.addEdge(fromNode: node5, toNode: node11)
graph.addEdge(fromNode: node7, toNode: node11)
graph.addEdge(fromNode: node7, toNode: node8)
graph.addEdge(fromNode: node3, toNode: node8)
graph.addEdge(fromNode: node3, toNode: node10)
graph.addEdge(fromNode: node11, toNode: node2)
graph.addEdge(fromNode: node11, toNode: node9)
graph.addEdge(fromNode: node11, toNode: node10)
graph.addEdge(fromNode: node8, toNode: node9)
// using depth-first search
graph.topologicalSort()
// also using depth-first search
graph.topologicalSortAlternative()
// Kahn's algorithm
graph.topologicalSortKahn()
| mit | 04ba6457ffb5b2acb33e0cf2a0262e33 | 25.742857 | 52 | 0.747863 | 3.194539 | false | false | false | false |
audiokit/AudioKitArchive | Examples/OSX/Swift/AudioKitDemo/AudioKitDemo/AnalysisViewController.swift | 2 | 2807 | //
// AnalysisViewController.swift
// AudioKitDemo
//
// Created by Nicholas Arner on 3/1/15.
// Copyright (c) 2015 AudioKit. All rights reserved.
//
class AnalysisViewController: NSViewController {
@IBOutlet var frequencyLabel: NSTextField!
@IBOutlet var amplitudeLabel: NSTextField!
@IBOutlet var noteNameWithSharpsLabel: NSTextField!
@IBOutlet var noteNameWithFlatsLabel: NSTextField!
var analyzer: AKAudioAnalyzer!
let microphone = AKMicrophone()
let noteFrequencies = [16.35,17.32,18.35,19.45,20.6,21.83,23.12,24.5,25.96,27.5,29.14,30.87]
let noteNamesWithSharps = ["C", "C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"]
let noteNamesWithFlats = ["C", "D♭","D","E♭","E","F","G♭","G","A♭","A","B♭","B"]
let analysisSequence = AKSequence()
var updateAnalysis: AKEvent?
override func viewDidLoad() {
super.viewDidLoad()
AKSettings.shared().audioInputEnabled = true
analyzer = AKAudioAnalyzer(input: microphone.output)
AKOrchestra.addInstrument(microphone)
AKOrchestra.addInstrument(analyzer)
analyzer.play()
microphone.play()
let analysisSequence = AKSequence()
updateAnalysis = AKEvent {
self.updateUI()
analysisSequence.addEvent(self.updateAnalysis, afterDuration: 0.1)
}
analysisSequence.addEvent(updateAnalysis)
analysisSequence.play()
}
func updateUI() {
if (analyzer.trackedAmplitude.floatValue > 0.1) {
frequencyLabel.stringValue = String(format: "%0.1f", analyzer.trackedFrequency.floatValue)
var frequency = analyzer.trackedFrequency.floatValue
while (frequency > Float(noteFrequencies[noteFrequencies.count-1])) {
frequency = frequency / 2.0
}
while (frequency < Float(noteFrequencies[0])) {
frequency = frequency * 2.0
}
var minDistance: Float = 10000.0
var index = 0
for (var i = 0; i < noteFrequencies.count; i++) {
let distance = fabsf(Float(noteFrequencies[i]) - frequency)
if (distance < minDistance){
index = i
minDistance = distance
}
}
let octave = Int(log2f(analyzer.trackedFrequency.floatValue / frequency))
var noteName = String(format: "%@%d", noteNamesWithSharps[index], octave)
noteNameWithSharpsLabel.stringValue = noteName
noteName = String(format: "%@%d", noteNamesWithFlats[index], octave)
noteNameWithFlatsLabel.stringValue = noteName
}
amplitudeLabel.stringValue = String(format: "%0.2f", analyzer.trackedAmplitude.floatValue)
}
}
| mit | ae6c4e33a85095654648bee5cfe09d40 | 34.730769 | 102 | 0.613563 | 4.314241 | false | false | false | false |
socialbanks/ios-wallet | SocialWallet/BaseVC.swift | 1 | 3102 | //
// BaseVC.swift
// SocialWallet
//
// Created by Mauricio de Oliveira on 5/4/15.
// Copyright (c) 2015 SocialBanks. All rights reserved.
//
import UIKit
class BaseVC: UIViewController {
lazy var HUD:MBProgressHUD = {
let tmpHUD:MBProgressHUD = MBProgressHUD(view: self.view)
self.view.addSubview(tmpHUD)
//tmpHUD.delegate = self
tmpHUD.labelText = "Aguarde"
tmpHUD.detailsLabelText = "Carregando dados..."
//tmpHUD.square = true
return tmpHUD
}()
//MARK: UI Functions
func showLoading() {
self.showNetWorkActivity()
self.HUD.show(true)
}
func hideLoading() {
self.hideNetWorkActivity()
self.HUD.hide(true)
}
func showNetWorkActivity() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
func hideNetWorkActivity() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
override func viewDidLoad() {
super.viewDidLoad()
//self.removeLeftBarButtonTitle()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.backBarButtonItem?.tintColor = UIColor.whiteColor()
//self.removeLeftBarButtonTitle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Navigation bar functions
func setDefaultTitleLogo() {
let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
logo.contentMode = .ScaleAspectFit
logo.image = UIImage(named: "logo_socialbanks")
self.navigationItem.titleView = logo
}
func setupLeftMenuButton() {
let leftDrawerButton:MMDrawerBarButtonItem = MMDrawerBarButtonItem(target:self, action:"leftDrawerButtonPress")
leftDrawerButton.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = leftDrawerButton
}
func leftDrawerButtonPress() {
self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
}
func removeLeftBarButtonTitle() {
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
}
func removeLeftBarButton() {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
}
func instantiateViewControlerFromStoryboard(vcId: String, sbId: String) -> UIViewController {
let mainStoryboard:UIStoryboard = UIStoryboard(name: sbId, bundle: nil)
let vc:UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier(vcId) as! UIViewController
return vc
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
| mit | 756b01d8a5d171d79efacdb55edd678f | 29.411765 | 137 | 0.661186 | 5.085246 | false | false | false | false |
anlaital/Swan | Swan/Swan/CGSizeExtensions.swift | 1 | 1147 | //
// CGSizeExtensions.swift
// Swan
//
// Created by Antti Laitala on 19/11/15.
//
//
import Foundation
public func +(lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width + rhs.width, height: lhs.height + rhs.height)
}
public func +=(lhs: inout CGSize, rhs: CGSize) {
lhs.width += rhs.width
lhs.height += rhs.height
}
public func -(lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width - rhs.width, height: lhs.height - rhs.height)
}
public func -=(lhs: inout CGSize, rhs: CGSize) {
lhs.width -= rhs.width
lhs.height -= rhs.height
}
public func *(lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width * rhs.width, height: lhs.height * rhs.height)
}
public func *(lhs: CGSize, rhs: Double) -> CGSize {
return CGSize(width: Double(lhs.width) * rhs, height: Double(lhs.height) * rhs)
}
public func /(lhs: CGSize, rhs: CGSize) -> CGSize {
return CGSize(width: lhs.width / rhs.width, height: lhs.height / rhs.height)
}
public func /(lhs: CGSize, rhs: Double) -> CGSize {
return CGSize(width: Double(lhs.width) / rhs, height: Double(lhs.height) / rhs)
}
| mit | a7c0b06ae6ea6a03376de6acaa376e3a | 25.674419 | 83 | 0.655623 | 3.168508 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | RedBus/RedBus/Controller/FilterViewController.swift | 1 | 6983 | //
// FilterViewController.swift
// RedBus
//
// Created by Anirudh Das on 8/22/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import UIKit
class FilterViewController: BaseViewController {
@IBOutlet weak var bgView: UIView!
@IBOutlet weak var ratingImg: UIImageView!
@IBOutlet weak var ratingArrow: UIImageView!
@IBOutlet weak var departureImg: UIImageView!
@IBOutlet weak var departureArrowIng: UIImageView!
@IBOutlet weak var fareImg: UIImageView!
@IBOutlet weak var fareArrowImg: UIImageView!
@IBOutlet weak var acImg: UIImageView!
@IBOutlet weak var nonAcImg: UIImageView!
@IBOutlet weak var seaterImg: UIImageView!
@IBOutlet weak var sleeperImg: UIImageView!
@IBOutlet weak var resetBtn: UIButton!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var ratingBtn: UIButton!
@IBOutlet weak var departureTimeBtn: UIButton!
@IBOutlet weak var fareBtn: UIButton!
@IBOutlet weak var acBtn: UIButton!
@IBOutlet weak var nonAcBtn: UIButton!
@IBOutlet weak var seaterBtn: UIButton!
@IBOutlet weak var sleeperBtn: UIButton!
@IBOutlet weak var applyBtn: UIButton!
var sortBy: SortBusesBy = .none
var busFilterType = BusType(isAc: false, isNonAc: false, isSeater: false, isSleeper: false)
var applyCompletionHandler: ((SortBusesBy, BusType) -> ())?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
configureSortRadioButtonImage(isReset: false)
configureFilterCheckBoxImage(isReset: false)
}
func setupView() {
bgView.addShadow()
resetBtn.addShadow()
cancelBtn.addShadow()
ratingBtn.addShadow()
departureTimeBtn.addShadow()
fareBtn.addShadow()
acBtn.addShadow()
nonAcBtn.addShadow()
seaterBtn.addShadow()
sleeperBtn.addShadow()
applyBtn.addShadow()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.7)
}
@IBAction func resetBtnClicked(_ sender: UIButton) {
sortBy = .none
busFilterType = BusType(isAc: false, isNonAc: false, isSeater: false, isSleeper: false)
configureSortRadioButtonImage(isReset: true)
configureFilterCheckBoxImage(isReset: true)
}
@IBAction func applyBtnClicked(_ sender: UIButton) {
self.dismiss(animated: true, completion: {
self.applyCompletionHandler?(self.sortBy, self.busFilterType)
})
}
@IBAction func cancelBtnClicked(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func ratingBtnClicked(_ sender: UIButton) {
if sortBy == .ratingDescending {
sortBy = .ratingAscending
} else if sortBy == .ratingAscending {
sortBy = .none
} else {
sortBy = .ratingDescending
}
configureSortRadioButtonImage(isReset: false)
}
@IBAction func departureTimeBtnClicked(_ sender: UIButton) {
if sortBy == .departureTimeAscending {
sortBy = .departureTimeDescending
} else if sortBy == .departureTimeDescending {
sortBy = .none
} else {
sortBy = .departureTimeAscending
}
configureSortRadioButtonImage(isReset: false)
}
@IBAction func fareBtnClicked(_ sender: UIButton) {
if sortBy == .fareAscending {
sortBy = .fareDescending
} else if sortBy == .fareDescending {
sortBy = .none
} else {
sortBy = .fareAscending
}
configureSortRadioButtonImage(isReset: false)
}
@IBAction func acBtnClicked(_ sender: UIButton) {
busFilterType.isAc = busFilterType.isAc ? false : true
configureFilterCheckBoxImage(isReset: false)
}
@IBAction func nonAcBtnClicked(_ sender: UIButton) {
busFilterType.isNonAc = busFilterType.isNonAc ? false : true
configureFilterCheckBoxImage(isReset: false)
}
@IBAction func seaterBtnClicked(_ sender: UIButton) {
busFilterType.isSeater = busFilterType.isSeater ? false : true
configureFilterCheckBoxImage(isReset: false)
}
@IBAction func sleeperBtnClicked(_ sender: UIButton) {
busFilterType.isSleeper = busFilterType.isSleeper ? false : true
configureFilterCheckBoxImage(isReset: false)
}
func configureSortRadioButtonImage(isReset: Bool) {
func resetSortRadioButtonImage() {
ratingImg.image = Constants.ratingDeselected
ratingArrow.isHidden = true
departureImg.image = Constants.depatureDeselected
departureArrowIng.isHidden = true
fareImg.image = Constants.fareDeselected
fareArrowImg.isHidden = true
}
resetSortRadioButtonImage()
if !isReset {
switch sortBy {
case .ratingAscending:
ratingImg.image = Constants.ratingSelected
ratingArrow.image = Constants.arrowUp
ratingArrow.isHidden = false
case .ratingDescending:
ratingImg.image = Constants.ratingSelected
ratingArrow.image = Constants.arrowDown
ratingArrow.isHidden = false
case .departureTimeAscending:
departureImg.image = Constants.depatureSelected
departureArrowIng.image = Constants.arrowUp
departureArrowIng.isHidden = false
case .departureTimeDescending:
departureImg.image = Constants.depatureSelected
departureArrowIng.image = Constants.arrowDown
departureArrowIng.isHidden = false
case .fareAscending:
fareImg.image = Constants.fareSelected
fareArrowImg.image = Constants.arrowUp
fareArrowImg.isHidden = false
case .fareDescending:
fareImg.image = Constants.fareSelected
fareArrowImg.image = Constants.arrowDown
fareArrowImg.isHidden = false
case .none:
break
}
}
}
func configureFilterCheckBoxImage(isReset: Bool) {
if isReset {
acImg.image = Constants.acDeselected
nonAcImg.image = Constants.nonACDeselected
seaterImg.image = Constants.seaterDeselected
sleeperImg.image = Constants.sleeperDeselected
} else {
acImg.image = busFilterType.isAc ? Constants.acSelected : Constants.acDeselected
nonAcImg.image = busFilterType.isNonAc ? Constants.nonACSelected : Constants.nonACDeselected
seaterImg.image = busFilterType.isSeater ? Constants.seaterSelected : Constants.seaterDeselected
sleeperImg.image = busFilterType.isSleeper ? Constants.sleeperSelected : Constants.sleeperDeselected
}
}
}
| apache-2.0 | 697dcdf77530e919c41f4854a8001b4d | 36.336898 | 112 | 0.641077 | 5.301443 | false | true | false | false |
lady12/firefox-ios | Client/Frontend/Browser/BrowserViewController.swift | 7 | 91722 | /* 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 Photos
import UIKit
import WebKit
import Shared
import Storage
import SnapKit
import XCGLogger
import Alamofire
import Account
private let log = Logger.browserLogger
private let OKString = NSLocalizedString("OK", comment: "OK button")
private let CancelString = NSLocalizedString("Cancel", comment: "Cancel button")
private let KVOLoading = "loading"
private let KVOEstimatedProgress = "estimatedProgress"
private let KVOURL = "URL"
private let KVOCanGoBack = "canGoBack"
private let KVOCanGoForward = "canGoForward"
private let KVOContentSize = "contentSize"
private let ActionSheetTitleMaxLength = 120
private struct BrowserViewControllerUX {
private static let BackgroundColor = UIConstants.AppBackgroundColor
private static let ShowHeaderTapAreaHeight: CGFloat = 32
private static let BookmarkStarAnimationDuration: Double = 0.5
private static let BookmarkStarAnimationOffset: CGFloat = 80
}
class BrowserViewController: UIViewController {
var homePanelController: HomePanelViewController?
var webViewContainer: UIView!
var urlBar: URLBarView!
var readerModeBar: ReaderModeBarView?
private var statusBarOverlay: UIView!
private var toolbar: BrowserToolbar?
private var searchController: SearchViewController?
private let uriFixup = URIFixup()
private var screenshotHelper: ScreenshotHelper!
private var homePanelIsInline = false
private var searchLoader: SearchLoader!
private let snackBars = UIView()
private let auralProgress = AuralProgressBar()
// location label actions
private var pasteGoAction: AccessibleAction!
private var pasteAction: AccessibleAction!
private var copyAddressAction: AccessibleAction!
private weak var tabTrayController: TabTrayController!
private let profile: Profile
let tabManager: TabManager
// These views wrap the urlbar and toolbar to provide background effects on them
var header: UIView!
var headerBackdrop: UIView!
var footer: UIView!
var footerBackdrop: UIView!
private var footerBackground: UIView!
private var topTouchArea: UIButton!
private var scrollController = BrowserScrollingController()
private var keyboardState: KeyboardState?
let WhiteListedUrls = ["\\/\\/itunes\\.apple\\.com\\/"]
// Tracking navigation items to record history types.
// TODO: weak references?
var ignoredNavigation = Set<WKNavigation>()
var typedNavigation = [WKNavigation: VisitType]()
var navigationToolbar: BrowserToolbarProtocol {
return toolbar ?? urlBar
}
init(profile: Profile, tabManager: TabManager) {
self.profile = profile
self.tabManager = tabManager
super.init(nibName: nil, bundle: nil)
didInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.AllButUpsideDown
} else {
return UIInterfaceOrientationMask.All
}
}
override func didReceiveMemoryWarning() {
print("THIS IS BROWSERVIEWCONTROLLER.DIDRECEIVEMEMORYWARNING - WE ARE GOING TO TABMANAGER.RESETPROCESSPOOL()")
log.debug("THIS IS BROWSERVIEWCONTROLLER.DIDRECEIVEMEMORYWARNING - WE ARE GOING TO TABMANAGER.RESETPROCESSPOOL()")
NSLog("THIS IS BROWSERVIEWCONTROLLER.DIDRECEIVEMEMORYWARNING - WE ARE GOING TO TABMANAGER.RESETPROCESSPOOL()")
super.didReceiveMemoryWarning()
tabManager.resetProcessPool()
}
private func didInit() {
screenshotHelper = BrowserScreenshotHelper(controller: self)
tabManager.addDelegate(self)
tabManager.addNavigationDelegate(self)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
func shouldShowFooterForTraitCollection(previousTraitCollection: UITraitCollection) -> Bool {
return previousTraitCollection.verticalSizeClass != .Compact &&
previousTraitCollection.horizontalSizeClass != .Regular
}
func toggleSnackBarVisibility(show show: Bool) {
if show {
UIView.animateWithDuration(0.1, animations: { self.snackBars.hidden = false })
} else {
snackBars.hidden = true
}
}
private func updateToolbarStateForTraitCollection(newCollection: UITraitCollection) {
let showToolbar = shouldShowFooterForTraitCollection(newCollection)
urlBar.setShowToolbar(!showToolbar)
toolbar?.removeFromSuperview()
toolbar?.browserToolbarDelegate = nil
footerBackground?.removeFromSuperview()
footerBackground = nil
toolbar = nil
if showToolbar {
toolbar = BrowserToolbar()
toolbar?.browserToolbarDelegate = self
footerBackground = wrapInEffect(toolbar!, parent: footer)
}
view.setNeedsUpdateConstraints()
if let home = homePanelController {
home.view.setNeedsUpdateConstraints()
}
if let tab = tabManager.selectedTab,
webView = tab.webView {
updateURLBarDisplayURL(tab)
navigationToolbar.updateBackStatus(webView.canGoBack)
navigationToolbar.updateForwardStatus(webView.canGoForward)
navigationToolbar.updateReloadStatus(tab.loading ?? false)
}
}
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
updateToolbarStateForTraitCollection(newCollection)
// WKWebView looks like it has a bug where it doesn't invalidate it's visible area when the user
// performs a device rotation. Since scrolling calls
// _updateVisibleContentRects (https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebView.mm#L1430)
// this method nudges the web view's scroll view by a single pixel to force it to invalidate.
if let scrollView = self.tabManager.selectedTab?.webView?.scrollView {
let contentOffset = scrollView.contentOffset
coordinator.animateAlongsideTransition({ context in
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y + 1), animated: true)
self.scrollController.showToolbars(animated: false)
// Update overlay that sits behind the status bar to reflect the new topLayoutGuide length. It seems that
// when updateViewConstraints is invoked during rotation, the UILayoutSupport instance hasn't updated
// to reflect the new orientation which is why we do it here instead of in updateViewConstraints.
self.statusBarOverlay.snp_remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(self.topLayoutGuide.length)
}
}, completion: { context in
scrollView.setContentOffset(CGPoint(x: contentOffset.x, y: contentOffset.y), animated: false)
})
}
}
func SELtappedTopArea() {
scrollController.showToolbars(animated: true)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: BookmarkStatusChangedNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELBookmarkStatusDidChange:", name: BookmarkStatusChangedNotification, object: nil)
KeyboardHelper.defaultHelper.addDelegate(self)
footerBackdrop = UIView()
footerBackdrop.backgroundColor = UIColor.whiteColor()
view.addSubview(footerBackdrop)
headerBackdrop = UIView()
headerBackdrop.backgroundColor = UIColor.whiteColor()
view.addSubview(headerBackdrop)
webViewContainer = UIView()
view.addSubview(webViewContainer)
// Temporary work around for covering the non-clipped web view content
statusBarOverlay = UIView()
statusBarOverlay.backgroundColor = BrowserViewControllerUX.BackgroundColor
view.addSubview(statusBarOverlay)
topTouchArea = UIButton()
topTouchArea.isAccessibilityElement = false
topTouchArea.addTarget(self, action: "SELtappedTopArea", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(topTouchArea)
// Setup the URL bar, wrapped in a view to get transparency effect
urlBar = URLBarView()
urlBar.translatesAutoresizingMaskIntoConstraints = false
urlBar.delegate = self
urlBar.browserToolbarDelegate = self
header = wrapInEffect(urlBar, parent: view, backgroundColor: nil)
// UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC
pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.generalPasteboard().string {
self.urlBar(self.urlBar, didSubmitText: pasteboardContents)
return true
}
return false
})
pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in
if let pasteboardContents = UIPasteboard.generalPasteboard().string {
// Enter overlay mode and fire the text entered callback to make the search controller appear.
self.urlBar.enterOverlayMode(pasteboardContents, pasted: true)
self.urlBar(self.urlBar, didEnterText: pasteboardContents)
return true
}
return false
})
copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in
if let urlString = self.urlBar.currentURL?.absoluteString {
UIPasteboard.generalPasteboard().string = urlString
}
return true
})
searchLoader = SearchLoader(history: profile.history, urlBar: urlBar)
footer = UIView()
self.view.addSubview(footer)
self.view.addSubview(snackBars)
snackBars.backgroundColor = UIColor.clearColor()
scrollController.urlBar = urlBar
scrollController.header = header
scrollController.footer = footer
scrollController.snackBars = snackBars
self.updateToolbarStateForTraitCollection(self.traitCollection)
setupConstraints()
}
private func setupConstraints() {
urlBar.snp_makeConstraints { make in
make.edges.equalTo(self.header)
}
let viewBindings: [String: AnyObject] = [
"header": header,
"topLayoutGuide": topLayoutGuide
]
let topConstraint = NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide][header]", options: [], metrics: nil, views: viewBindings)
view.addConstraints(topConstraint)
scrollController.headerTopConstraint = topConstraint.first
header.snp_makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
headerBackdrop.snp_makeConstraints { make in
make.edges.equalTo(self.header)
}
}
func loadQueuedTabs() {
log.debug("Loading queued tabs in the background.")
// Chain off of a trivial deferred in order to run on the background queue.
succeed().upon() { res in
self.dequeueQueuedTabs()
}
}
private func dequeueQueuedTabs() {
assert(!NSThread.currentThread().isMainThread, "This must be called in the background.")
self.profile.queue.getQueuedTabs() >>== { cursor in
// This assumes that the DB returns rows in some kind of sane order.
// It does in practice, so WFM.
log.debug("Queue. Count: \(cursor.count).")
if cursor.count > 0 {
var urls = [NSURL]()
for row in cursor {
if let url = row?.url.asURL {
log.debug("Queuing \(url).")
urls.append(url)
}
}
if !urls.isEmpty {
dispatch_async(dispatch_get_main_queue()) {
self.tabManager.addTabsForURLs(urls, zombie: false)
}
}
}
// Clear *after* making an attempt to open. We're making a bet that
// it's better to run the risk of perhaps opening twice on a crash,
// rather than losing data.
self.profile.queue.clearQueuedTabs()
}
}
func startTrackingAccessibilityStatus() {
NSNotificationCenter.defaultCenter().addObserverForName(UIAccessibilityVoiceOverStatusChanged, object: nil, queue: nil) { (notification) -> Void in
self.auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning()
}
auralProgress.hidden = !UIAccessibilityIsVoiceOverRunning()
}
func stopTrackingAccessibilityStatus() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIAccessibilityVoiceOverStatusChanged, object: nil)
auralProgress.hidden = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// On iPhone, if we are about to show the On-Boarding, blank out the browser so that it does
// not flash before we present. This change of alpha also participates in the animation when
// the intro view is dismissed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
self.view.alpha = (profile.prefs.intForKey(IntroViewControllerSeenProfileKey) != nil) ? 1.0 : 0.0
}
if tabManager.count == 0 && !AppConstants.IsRunningTest {
tabManager.restoreTabs()
}
if tabManager.count == 0 {
let tab = tabManager.addTab()
tabManager.selectTab(tab)
}
}
override func viewDidAppear(animated: Bool) {
startTrackingAccessibilityStatus()
// We want to load queued tabs here in case we need to execute any commands that were received while using a share extension,
// but no point even trying if this is the first time.
if !presentIntroViewController() {
loadQueuedTabs()
}
super.viewDidAppear(animated)
}
override func viewDidDisappear(animated: Bool) {
stopTrackingAccessibilityStatus()
}
override func updateViewConstraints() {
super.updateViewConstraints()
topTouchArea.snp_remakeConstraints { make in
make.top.left.right.equalTo(self.view)
make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight)
}
readerModeBar?.snp_remakeConstraints { make in
make.top.equalTo(self.header.snp_bottom).constraint
make.height.equalTo(UIConstants.ToolbarHeight)
make.leading.trailing.equalTo(self.view)
}
webViewContainer.snp_remakeConstraints { make in
make.left.right.equalTo(self.view)
if let readerModeBarBottom = readerModeBar?.snp_bottom {
make.top.equalTo(readerModeBarBottom)
} else {
make.top.equalTo(self.header.snp_bottom)
}
if let toolbar = self.toolbar {
make.bottom.equalTo(toolbar.snp_top)
} else {
make.bottom.equalTo(self.view)
}
}
// Setup the bottom toolbar
toolbar?.snp_remakeConstraints { make in
make.edges.equalTo(self.footerBackground!)
make.height.equalTo(UIConstants.ToolbarHeight)
}
footer.snp_remakeConstraints { make in
scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp_bottom).constraint
make.top.equalTo(self.snackBars.snp_top)
make.leading.trailing.equalTo(self.view)
}
footerBackdrop.snp_remakeConstraints { make in
make.edges.equalTo(self.footer)
}
adjustFooterSize(nil)
footerBackground?.snp_remakeConstraints { make in
make.bottom.left.right.equalTo(self.footer)
make.height.equalTo(UIConstants.ToolbarHeight)
}
urlBar.setNeedsUpdateConstraints()
// Remake constraints even if we're already showing the home controller.
// The home controller may change sizes if we tap the URL bar while on about:home.
homePanelController?.view.snp_remakeConstraints { make in
make.top.equalTo(self.urlBar.snp_bottom)
make.left.right.equalTo(self.view)
if self.homePanelIsInline {
make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom)
} else {
make.bottom.equalTo(self.view.snp_bottom)
}
}
}
private func wrapInEffect(view: UIView, parent: UIView) -> UIView {
return self.wrapInEffect(view, parent: parent, backgroundColor: UIColor.clearColor())
}
private func wrapInEffect(view: UIView, parent: UIView, backgroundColor: UIColor?) -> UIView {
let effect = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight))
effect.clipsToBounds = false
effect.translatesAutoresizingMaskIntoConstraints = false
if let _ = backgroundColor {
view.backgroundColor = backgroundColor
}
effect.addSubview(view)
parent.addSubview(effect)
return effect
}
private func showHomePanelController(inline inline: Bool) {
homePanelIsInline = inline
if homePanelController == nil {
homePanelController = HomePanelViewController()
homePanelController!.profile = profile
homePanelController!.delegate = self
homePanelController!.url = tabManager.selectedTab?.displayURL
homePanelController!.view.alpha = 0
addChildViewController(homePanelController!)
view.addSubview(homePanelController!.view)
homePanelController!.didMoveToParentViewController(self)
}
let panelNumber = tabManager.selectedTab?.url?.fragment
// splitting this out to see if we can get better crash reports when this has a problem
var newSelectedButtonIndex = 0
if let numberArray = panelNumber?.componentsSeparatedByString("=") {
if let last = numberArray.last, lastInt = Int(last) {
newSelectedButtonIndex = lastInt
}
}
homePanelController?.selectedButtonIndex = newSelectedButtonIndex
// We have to run this animation, even if the view is already showing because there may be a hide animation running
// and we want to be sure to override its results.
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.homePanelController!.view.alpha = 1
}, completion: { finished in
if finished {
self.webViewContainer.accessibilityElementsHidden = true
self.stopTrackingAccessibilityStatus()
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
}
})
view.setNeedsUpdateConstraints()
}
private func hideHomePanelController() {
if let controller = homePanelController {
UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in
controller.view.alpha = 0
}, completion: { finished in
if finished {
controller.willMoveToParentViewController(nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.homePanelController = nil
self.webViewContainer.accessibilityElementsHidden = false
self.startTrackingAccessibilityStatus()
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// Refresh the reading view toolbar since the article record may have changed
if let readerMode = self.tabManager.selectedTab?.getHelper(name: ReaderMode.name()) as? ReaderMode where readerMode.state == .Active {
self.showReaderModeBar(animated: false)
}
}
})
}
}
private func updateInContentHomePanel(url: NSURL?) {
if !urlBar.inOverlayMode {
if AboutUtils.isAboutHomeURL(url){
showHomePanelController(inline: (tabManager.selectedTab?.canGoForward ?? false || tabManager.selectedTab?.canGoBack ?? false))
} else {
hideHomePanelController()
}
}
}
private func showSearchController() {
if searchController != nil {
return
}
searchController = SearchViewController()
searchController!.searchEngines = profile.searchEngines
searchController!.searchDelegate = self
searchController!.profile = self.profile
searchLoader.addListener(searchController!)
addChildViewController(searchController!)
view.addSubview(searchController!.view)
searchController!.view.snp_makeConstraints { make in
make.top.equalTo(self.urlBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
return
}
homePanelController?.view?.hidden = true
searchController!.didMoveToParentViewController(self)
}
private func hideSearchController() {
if let searchController = searchController {
searchController.willMoveToParentViewController(nil)
searchController.view.removeFromSuperview()
searchController.removeFromParentViewController()
self.searchController = nil
homePanelController?.view?.hidden = false
}
}
private func finishEditingAndSubmit(url: NSURL, visitType: VisitType) {
urlBar.currentURL = url
urlBar.leaveOverlayMode()
if let tab = tabManager.selectedTab,
let nav = tab.loadRequest(NSURLRequest(URL: url)) {
self.recordNavigationInTab(tab, navigation: nav, visitType: visitType)
}
}
func addBookmark(url: String, title: String?) {
let shareItem = ShareItem(url: url, title: title, favicon: nil)
profile.bookmarks.shareItem(shareItem)
animateBookmarkStar()
// Dispatch to the main thread to update the UI
dispatch_async(dispatch_get_main_queue()) { _ in
self.toolbar?.updateBookmarkStatus(true)
self.urlBar.updateBookmarkStatus(true)
}
}
private func animateBookmarkStar() {
let offset: CGFloat
let button: UIButton!
if let toolbar: BrowserToolbar = self.toolbar {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset * -1
button = toolbar.bookmarkButton
} else {
offset = BrowserViewControllerUX.BookmarkStarAnimationOffset
button = self.urlBar.bookmarkButton
}
let offToolbar = CGAffineTransformMakeTranslation(0, offset)
UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 2.0, options: [], animations: { () -> Void in
button.transform = offToolbar
let rotation = CABasicAnimation(keyPath: "transform.rotation")
rotation.toValue = CGFloat(M_PI * 2.0)
rotation.cumulative = true
rotation.duration = BrowserViewControllerUX.BookmarkStarAnimationDuration + 0.075
rotation.repeatCount = 1.0
rotation.timingFunction = CAMediaTimingFunction(controlPoints: 0.32, 0.70 ,0.18 ,1.00)
button.imageView?.layer.addAnimation(rotation, forKey: "rotateStar")
}, completion: { finished in
UIView.animateWithDuration(BrowserViewControllerUX.BookmarkStarAnimationDuration, delay: 0.15, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { () -> Void in
button.transform = CGAffineTransformIdentity
}, completion: nil)
})
}
private func removeBookmark(url: String) {
profile.bookmarks.removeByURL(url).uponQueue(dispatch_get_main_queue()) { res in
if res.isSuccess {
self.toolbar?.updateBookmarkStatus(false)
self.urlBar.updateBookmarkStatus(false)
}
}
}
func SELBookmarkStatusDidChange(notification: NSNotification) {
if let bookmark = notification.object as? BookmarkItem {
if bookmark.url == urlBar.currentURL?.absoluteString {
if let userInfo = notification.userInfo as? Dictionary<String, Bool>{
if let added = userInfo["added"]{
self.toolbar?.updateBookmarkStatus(added)
self.urlBar.updateBookmarkStatus(added)
}
}
}
}
}
override func accessibilityPerformEscape() -> Bool {
if urlBar.inOverlayMode {
urlBar.SELdidClickCancel()
return true
} else if let selectedTab = tabManager.selectedTab where selectedTab.canGoBack {
selectedTab.goBack()
return true
}
return false
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
let webView = object as! WKWebView
if webView !== tabManager.selectedTab?.webView {
return
}
guard let path = keyPath else { assertionFailure("Unhandled KVO key: \(keyPath)"); return }
switch path {
case KVOEstimatedProgress:
guard let progress = change?[NSKeyValueChangeNewKey] as? Float else { break }
urlBar.updateProgressBar(progress)
// when loading is stopped, KVOLoading is fired first, and only then KVOEstimatedProgress with progress 1.0 which would leave the progress bar running
if progress != 1.0 || tabManager.selectedTab?.loading ?? false {
auralProgress.progress = Double(progress)
}
case KVOLoading:
guard let loading = change?[NSKeyValueChangeNewKey] as? Bool else { break }
toolbar?.updateReloadStatus(loading)
urlBar.updateReloadStatus(loading)
auralProgress.progress = loading ? 0 : nil
case KVOURL:
if let tab = tabManager.selectedTab where tab.webView?.URL == nil {
log.debug("URL IS NIL! WE ARE RESETTING PROCESS POOL")
NSLog("URL IS NIL! WE ARE RESETTING PROCESS POOL")
print("URL IS NIL! WE ARE RESETTING PROCESS POOL")
tabManager.resetProcessPool()
}
if let tab = tabManager.selectedTab where tab.webView === webView && !tab.restoring {
updateUIForReaderHomeStateForTab(tab)
}
case KVOCanGoBack:
guard let canGoBack = change?[NSKeyValueChangeNewKey] as? Bool else { break }
navigationToolbar.updateBackStatus(canGoBack)
case KVOCanGoForward:
guard let canGoForward = change?[NSKeyValueChangeNewKey] as? Bool else { break }
navigationToolbar.updateForwardStatus(canGoForward)
default:
assertionFailure("Unhandled KVO key: \(keyPath)")
}
}
private func updateUIForReaderHomeStateForTab(tab: Browser) {
updateURLBarDisplayURL(tab)
scrollController.showToolbars(animated: false)
if let url = tab.url {
if ReaderModeUtils.isReaderModeURL(url) {
showReaderModeBar(animated: false)
} else {
hideReaderModeBar(animated: false)
}
updateInContentHomePanel(url)
}
}
private func isWhitelistedUrl(url: NSURL) -> Bool {
for entry in WhiteListedUrls {
if let _ = url.absoluteString.rangeOfString(entry, options: .RegularExpressionSearch) {
return UIApplication.sharedApplication().canOpenURL(url)
}
}
return false
}
/// Updates the URL bar text and button states.
/// Call this whenever the page URL changes.
private func updateURLBarDisplayURL(tab: Browser) {
urlBar.currentURL = tab.displayURL
let isPage = (tab.displayURL != nil) ? isWebPage(tab.displayURL!) : false
navigationToolbar.updatePageStatus(isWebPage: isPage)
if let url = tab.displayURL?.absoluteString {
profile.bookmarks.isBookmarked(url, success: { bookmarked in
self.navigationToolbar.updateBookmarkStatus(bookmarked)
}, failure: { err in
log.error("Error getting bookmark status: \(err).")
})
}
}
func openURLInNewTab(url: NSURL) {
let tab = tabManager.addTab(NSURLRequest(URL: url))
tabManager.selectTab(tab)
}
}
/**
* History visit management.
* TODO: this should be expanded to track various visit types; see Bug 1166084.
*/
extension BrowserViewController {
func ignoreNavigationInTab(tab: Browser, navigation: WKNavigation) {
self.ignoredNavigation.insert(navigation)
}
func recordNavigationInTab(tab: Browser, navigation: WKNavigation, visitType: VisitType) {
self.typedNavigation[navigation] = visitType
}
/**
* Untrack and do the right thing.
*/
func getVisitTypeForTab(tab: Browser, navigation: WKNavigation?) -> VisitType? {
guard let navigation = navigation else {
// See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390
return VisitType.Link
}
if let _ = self.ignoredNavigation.remove(navigation) {
return nil
}
return self.typedNavigation.removeValueForKey(navigation) ?? VisitType.Link
}
}
extension BrowserViewController: URLBarDelegate {
func urlBarDidPressReload(urlBar: URLBarView) {
tabManager.selectedTab?.reload()
}
func urlBarDidPressStop(urlBar: URLBarView) {
tabManager.selectedTab?.stop()
}
func urlBarDidPressTabs(urlBar: URLBarView) {
let tabTrayController = TabTrayController()
tabTrayController.profile = profile
tabTrayController.tabManager = tabManager
if let tab = tabManager.selectedTab {
tab.setScreenshot(screenshotHelper.takeScreenshot(tab, aspectRatio: 0, quality: 1))
}
self.navigationController?.pushViewController(tabTrayController, animated: true)
self.tabTrayController = tabTrayController
}
func urlBarDidPressReaderMode(urlBar: URLBarView) {
if let tab = tabManager.selectedTab {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
switch readerMode.state {
case .Available:
enableReaderMode()
case .Active:
disableReaderMode()
case .Unavailable:
break
}
}
}
}
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool {
guard let tab = tabManager.selectedTab,
url = tab.displayURL,
result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name)
else {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed."))
return false
}
switch result {
case .Success:
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action."))
// TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback?
case .Failure(let error):
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it's already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures."))
log.error("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)")
}
return true
}
func locationActionsForURLBar(urlBar: URLBarView) -> [AccessibleAction] {
if UIPasteboard.generalPasteboard().string != nil {
return [pasteGoAction, pasteAction, copyAddressAction]
} else {
return [copyAddressAction]
}
}
func urlBarDidLongPressLocation(urlBar: URLBarView) {
let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
for action in locationActionsForURLBar(urlBar) {
longPressAlertController.addAction(action.alertAction(style: .Default))
}
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel alert view"), style: .Cancel, handler: { (alert: UIAlertAction) -> Void in
})
longPressAlertController.addAction(cancelAction)
if let popoverPresentationController = longPressAlertController.popoverPresentationController {
popoverPresentationController.sourceView = urlBar
popoverPresentationController.sourceRect = urlBar.frame
popoverPresentationController.permittedArrowDirections = .Any
}
self.presentViewController(longPressAlertController, animated: true, completion: nil)
}
func urlBarDidPressScrollToTop(urlBar: URLBarView) {
if let selectedTab = tabManager.selectedTab {
// Only scroll to top if we are not showing the home view controller
if homePanelController == nil {
selectedTab.webView?.scrollView.setContentOffset(CGPointZero, animated: true)
}
}
}
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]? {
return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction }
}
func urlBar(urlBar: URLBarView, didEnterText text: String) {
searchLoader.query = text
if text.isEmpty {
hideSearchController()
} else {
showSearchController()
searchController!.searchQuery = text
}
}
func urlBar(urlBar: URLBarView, didSubmitText text: String) {
var url = uriFixup.getURL(text)
// If we can't make a valid URL, do a search query.
if url == nil {
url = profile.searchEngines.defaultEngine.searchURLForQuery(text)
}
// If we still don't have a valid URL, something is broken. Give up.
if url == nil {
log.error("Error handling URL entry: \"\(text)\".")
return
}
finishEditingAndSubmit(url!, visitType: VisitType.Typed)
}
func urlBarDidEnterOverlayMode(urlBar: URLBarView) {
showHomePanelController(inline: false)
}
func urlBarDidLeaveOverlayMode(urlBar: URLBarView) {
hideSearchController()
updateInContentHomePanel(tabManager.selectedTab?.url)
}
}
extension BrowserViewController: BrowserToolbarDelegate {
func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goBack()
}
func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
// See 1159373 - Disable long press back/forward for backforward list
// let controller = BackForwardListViewController()
// controller.listData = tabManager.selectedTab?.backList
// controller.tabManager = tabManager
// presentViewController(controller, animated: true, completion: nil)
}
func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.reload()
}
func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.stop()
}
func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
tabManager.selectedTab?.goForward()
}
func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
// See 1159373 - Disable long press back/forward for backforward list
// let controller = BackForwardListViewController()
// controller.listData = tabManager.selectedTab?.forwardList
// controller.tabManager = tabManager
// presentViewController(controller, animated: true, completion: nil)
}
func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
if let tab = tabManager.selectedTab,
let url = tab.displayURL?.absoluteString {
profile.bookmarks.isBookmarked(url,
success: { isBookmarked in
if isBookmarked {
self.removeBookmark(url)
} else {
self.addBookmark(url, title: tab.title)
}
},
failure: { err in
log.error("Bookmark error: \(err).")
}
)
} else {
log.error("Bookmark error: No tab is selected, or no URL in tab.")
}
}
func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
}
func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) {
if let selected = tabManager.selectedTab {
if let url = selected.displayURL {
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.jobName = url.absoluteString
printInfo.outputType = .General
let renderer = BrowserPrintPageRenderer(browser: selected)
let activityItems = [printInfo, renderer, selected.title ?? url.absoluteString, url]
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
// Hide 'Add to Reading List' which currently uses Safari.
// Also hide our own View Later… after all, you're in the browser!
let viewLater = NSBundle.mainBundle().bundleIdentifier! + ".ViewLater"
activityViewController.excludedActivityTypes = [
UIActivityTypeAddToReadingList,
viewLater, // Doesn't work: rdar://19430419
]
activityViewController.completionWithItemsHandler = { activityType, completed, _, _ in
log.debug("Selected activity type: \(activityType).")
if completed {
if let selectedTab = self.tabManager.selectedTab {
// We don't know what share action the user has chosen so we simply always
// update the toolbar and reader mode bar to refelect the latest status.
self.updateURLBarDisplayURL(selectedTab)
self.updateReaderModeBar()
}
}
}
if let popoverPresentationController = activityViewController.popoverPresentationController {
// Using the button for the sourceView here results in this not showing on iPads.
popoverPresentationController.sourceView = toolbar ?? urlBar
popoverPresentationController.sourceRect = button.frame ?? button.frame
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Up
popoverPresentationController.delegate = self
}
presentViewController(activityViewController, animated: true, completion: nil)
}
}
}
}
extension BrowserViewController: WindowCloseHelperDelegate {
func windowCloseHelper(helper: WindowCloseHelper, didRequestToCloseBrowser browser: Browser) {
tabManager.removeTab(browser)
}
}
extension BrowserViewController: BrowserDelegate {
func browser(browser: Browser, didCreateWebView webView: WKWebView) {
webViewContainer.insertSubview(webView, atIndex: 0)
webView.snp_makeConstraints { make in
make.edges.equalTo(self.webViewContainer)
}
// Observers that live as long as the tab. Make sure these are all cleared
// in willDeleteWebView below!
webView.addObserver(self, forKeyPath: KVOEstimatedProgress, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOLoading, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoBack, options: .New, context: nil)
webView.addObserver(self, forKeyPath: KVOCanGoForward, options: .New, context: nil)
browser.webView?.addObserver(self, forKeyPath: KVOURL, options: .New, context: nil)
webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOContentSize, options: .New, context: nil)
webView.UIDelegate = self
let readerMode = ReaderMode(browser: browser)
readerMode.delegate = self
browser.addHelper(readerMode, name: ReaderMode.name())
let favicons = FaviconManager(browser: browser, profile: profile)
browser.addHelper(favicons, name: FaviconManager.name())
// Temporarily disable password support until the new code lands
let logins = LoginsHelper(browser: browser, profile: profile)
browser.addHelper(logins, name: LoginsHelper.name())
let contextMenuHelper = ContextMenuHelper(browser: browser)
contextMenuHelper.delegate = self
browser.addHelper(contextMenuHelper, name: ContextMenuHelper.name())
let errorHelper = ErrorPageHelper()
browser.addHelper(errorHelper, name: ErrorPageHelper.name())
let windowCloseHelper = WindowCloseHelper(browser: browser)
windowCloseHelper.delegate = self
browser.addHelper(windowCloseHelper, name: WindowCloseHelper.name())
let sessionRestoreHelper = SessionRestoreHelper(browser: browser)
sessionRestoreHelper.delegate = self
browser.addHelper(sessionRestoreHelper, name: SessionRestoreHelper.name())
}
func browser(browser: Browser, willDeleteWebView webView: WKWebView) {
webView.removeObserver(self, forKeyPath: KVOEstimatedProgress)
webView.removeObserver(self, forKeyPath: KVOLoading)
webView.removeObserver(self, forKeyPath: KVOCanGoBack)
webView.removeObserver(self, forKeyPath: KVOCanGoForward)
webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOContentSize)
webView.removeObserver(self, forKeyPath: KVOURL)
webView.UIDelegate = nil
webView.scrollView.delegate = nil
webView.removeFromSuperview()
}
private func findSnackbar(barToFind: SnackBar) -> Int? {
let bars = snackBars.subviews
for (index, bar) in bars.enumerate() {
if bar === barToFind {
return index
}
}
return nil
}
private func adjustFooterSize(top: UIView? = nil) {
snackBars.snp_remakeConstraints { make in
let bars = self.snackBars.subviews
// if the keyboard is showing then ensure that the snackbars are positioned above it, otherwise position them above the toolbar/view bottom
if bars.count > 0 {
let view = bars[bars.count-1]
make.top.equalTo(view.snp_top)
if let state = keyboardState {
make.bottom.equalTo(-(state.intersectionHeightForView(self.view)))
} else {
make.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom)
}
} else {
make.top.bottom.equalTo(self.toolbar?.snp_top ?? self.view.snp_bottom)
}
if traitCollection.horizontalSizeClass != .Regular {
make.leading.trailing.equalTo(self.footer)
self.snackBars.layer.borderWidth = 0
} else {
make.centerX.equalTo(self.footer)
make.width.equalTo(SnackBarUX.MaxWidth)
self.snackBars.layer.borderColor = UIConstants.BorderColor.CGColor
self.snackBars.layer.borderWidth = 1
}
}
}
// This removes the bar from its superview and updates constraints appropriately
private func finishRemovingBar(bar: SnackBar) {
// If there was a bar above this one, we need to remake its constraints.
if let index = findSnackbar(bar) {
// If the bar being removed isn't on the top of the list
let bars = snackBars.subviews
if index < bars.count-1 {
// Move the bar above this one
let nextbar = bars[index+1] as! SnackBar
nextbar.snp_updateConstraints { make in
// If this wasn't the bottom bar, attach to the bar below it
if index > 0 {
let bar = bars[index-1] as! SnackBar
nextbar.bottom = make.bottom.equalTo(bar.snp_top).constraint
} else {
// Otherwise, we attach it to the bottom of the snackbars
nextbar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).constraint
}
}
}
}
// Really remove the bar
bar.removeFromSuperview()
}
private func finishAddingBar(bar: SnackBar) {
snackBars.addSubview(bar)
bar.snp_remakeConstraints { make in
// If there are already bars showing, add this on top of them
let bars = self.snackBars.subviews
// Add the bar on top of the stack
// We're the new top bar in the stack, so make sure we ignore ourself
if bars.count > 1 {
let view = bars[bars.count - 2]
bar.bottom = make.bottom.equalTo(view.snp_top).offset(0).constraint
} else {
bar.bottom = make.bottom.equalTo(self.snackBars.snp_bottom).offset(0).constraint
}
make.leading.trailing.equalTo(self.snackBars)
}
}
func showBar(bar: SnackBar, animated: Bool) {
finishAddingBar(bar)
adjustFooterSize(bar)
bar.hide()
view.layoutIfNeeded()
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
bar.show()
self.view.layoutIfNeeded()
})
}
func removeBar(bar: SnackBar, animated: Bool) {
if let _ = findSnackbar(bar) {
UIView.animateWithDuration(animated ? 0.25 : 0, animations: { () -> Void in
bar.hide()
self.view.layoutIfNeeded()
}) { success in
// Really remove the bar
self.finishRemovingBar(bar)
// Adjust the footer size to only contain the bars
self.adjustFooterSize()
}
}
}
func removeAllBars() {
let bars = snackBars.subviews
for bar in bars {
if let bar = bar as? SnackBar {
bar.removeFromSuperview()
}
}
self.adjustFooterSize()
}
func browser(browser: Browser, didAddSnackbar bar: SnackBar) {
showBar(bar, animated: true)
}
func browser(browser: Browser, didRemoveSnackbar bar: SnackBar) {
removeBar(bar, animated: true)
}
}
extension BrowserViewController: HomePanelViewControllerDelegate {
func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectURL url: NSURL, visitType: VisitType) {
finishEditingAndSubmit(url, visitType: visitType)
}
func homePanelViewController(homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) {
if AboutUtils.isAboutHomeURL(tabManager.selectedTab?.url) {
tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil)
}
}
func homePanelViewControllerDidRequestToCreateAccount(homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
func homePanelViewControllerDidRequestToSignIn(homePanelViewController: HomePanelViewController) {
presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same
}
}
extension BrowserViewController: SearchViewControllerDelegate {
func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL) {
finishEditingAndSubmit(url, visitType: VisitType.Typed)
}
func presentSearchSettingsController() {
let settingsNavigationController = SearchSettingsTableViewController()
settingsNavigationController.model = self.profile.searchEngines
let navController = UINavigationController(rootViewController: settingsNavigationController)
self.presentViewController(navController, animated: true, completion: nil)
}
}
extension BrowserViewController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
// Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it
// and having multiple views with the same label confuses tests.
if let wv = previous?.webView {
wv.endEditing(true)
wv.accessibilityLabel = nil
wv.accessibilityElementsHidden = true
wv.accessibilityIdentifier = nil
// due to screwy handling within iOS, the scrollToTop handling does not work if there are
// more than one scroll view in the view hierarchy
// we therefore have to hide all the scrollViews that we are no actually interesting in interacting with
// to ensure that scrollsToTop actually works
wv.scrollView.hidden = true
}
if let tab = selected, webView = tab.webView {
// if we have previously hidden this scrollview in order to make scrollsToTop work then
// we should ensure that it is not hidden now that it is our foreground scrollView
if webView.scrollView.hidden {
webView.scrollView.hidden = false
}
updateURLBarDisplayURL(tab)
scrollController.browser = selected
webViewContainer.addSubview(webView)
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.accessibilityIdentifier = "contentView"
webView.accessibilityElementsHidden = false
if let url = webView.URL?.absoluteString {
profile.bookmarks.isBookmarked(url, success: { bookmarked in
self.toolbar?.updateBookmarkStatus(bookmarked)
self.urlBar.updateBookmarkStatus(bookmarked)
}, failure: { err in
log.error("Error getting bookmark status: \(err).")
})
} else {
// The web view can go gray if it was zombified due to memory pressure.
// When this happens, the URL is nil, so try restoring the page upon selection.
tab.reload()
}
}
removeAllBars()
if let bars = selected?.bars {
for bar in bars {
showBar(bar, animated: true)
}
}
navigationToolbar.updateReloadStatus(selected?.loading ?? false)
navigationToolbar.updateBackStatus(selected?.canGoBack ?? false)
navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false)
self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0))
if let readerMode = selected?.getHelper(name: ReaderMode.name()) as? ReaderMode {
urlBar.updateReaderModeState(readerMode.state)
if readerMode.state == .Active {
showReaderModeBar(animated: false)
} else {
hideReaderModeBar(animated: false)
}
} else {
urlBar.updateReaderModeState(ReaderModeState.Unavailable)
}
updateInContentHomePanel(selected?.url)
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int, restoring: Bool) {
// If we are restoring tabs then we update the count once at the end
if !restoring {
urlBar.updateTabCount(tabManager.count)
}
tab.browserDelegate = self
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex: Int) {
urlBar.updateTabCount(max(tabManager.count, 1))
// browserDelegate is a weak ref (and the tab's webView may not be destroyed yet)
// so we don't expcitly unset it.
}
func tabManagerDidAddTabs(tabManager: TabManager) {
urlBar.updateTabCount(tabManager.count)
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
urlBar.updateTabCount(tabManager.count)
}
private func isWebPage(url: NSURL) -> Bool {
let httpSchemes = ["http", "https"]
if let _ = httpSchemes.indexOf(url.scheme) {
return true
}
return false
}
}
extension BrowserViewController: WKNavigationDelegate {
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if tabManager.selectedTab?.webView !== webView {
return
}
// If we are going to navigate to a new page, hide the reader mode button. Unless we
// are going to a about:reader page. Then we keep it on screen: it will change status
// (orange color) as soon as the page has loaded.
if let url = webView.URL {
if !ReaderModeUtils.isReaderModeURL(url) {
urlBar.updateReaderModeState(ReaderModeState.Unavailable)
hideReaderModeBar(animated: false)
}
}
}
private func openExternal(url: NSURL, prompt: Bool = true) {
if prompt {
// Ask the user if it's okay to open the url with UIApplication.
let alert = UIAlertController(
title: String(format: NSLocalizedString("Opening %@", comment:"Opening an external URL"), url),
message: NSLocalizedString("This will open in another application", comment: "Opening an external app"),
preferredStyle: UIAlertControllerStyle.Alert
)
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction) in
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"Alert OK Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in
UIApplication.sharedApplication().openURL(url)
}))
presentViewController(alert, animated: true, completion: nil)
} else {
UIApplication.sharedApplication().openURL(url)
}
}
private func callExternal(url: NSURL) {
if let phoneNumber = url.resourceSpecifier.stringByRemovingPercentEncoding {
let alert = UIAlertController(title: phoneNumber, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment:"Alert Cancel Button"), style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: NSLocalizedString("Call", comment:"Alert Call Button"), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in
UIApplication.sharedApplication().openURL(url)
}))
presentViewController(alert, animated: true, completion: nil)
}
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.URL else {
decisionHandler(WKNavigationActionPolicy.Cancel)
return
}
switch url.scheme {
case "about", "http", "https":
if isWhitelistedUrl(url) {
// If the url is whitelisted, we open it without prompting…
// … unless the NavigationType is Other, which means it is JavaScript- or Redirect-initiated.
openExternal(url, prompt: navigationAction.navigationType == WKNavigationType.Other)
decisionHandler(WKNavigationActionPolicy.Cancel)
} else {
decisionHandler(WKNavigationActionPolicy.Allow)
}
case "tel":
callExternal(url)
decisionHandler(WKNavigationActionPolicy.Cancel)
default:
if UIApplication.sharedApplication().canOpenURL(url) {
openExternal(url)
}
decisionHandler(WKNavigationActionPolicy.Cancel)
}
}
func webView(webView: WKWebView,
didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic || challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest {
if let tab = tabManager[webView] {
let helper = tab.getHelper(name: LoginsHelper.name()) as! LoginsHelper
helper.handleAuthRequest(self, challenge: challenge).uponQueue(dispatch_get_main_queue()) { res in
if let credentials = res.successValue {
completionHandler(.UseCredential, credentials.credentials)
} else {
completionHandler(NSURLSessionAuthChallengeDisposition.RejectProtectionSpace, nil)
}
}
}
} else {
completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
let tab: Browser! = tabManager[webView]
tabManager.expireSnackbars()
if let url = webView.URL where !ErrorPageHelper.isErrorPageURL(url) && !AboutUtils.isAboutHomeURL(url) {
let notificationCenter = NSNotificationCenter.defaultCenter()
var info = [NSObject: AnyObject]()
info["url"] = tab.displayURL
info["title"] = tab.title
if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue {
info["visitType"] = visitType
}
tab.lastExecutedTime = NSDate.now()
notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info)
// Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore
// because that event wil not always fire due to unreliable page caching. This will either let us know that
// the currently loaded page can be turned into reading mode or if the page already is in reading mode. We
// ignore the result because we are being called back asynchronous when the readermode status changes.
webView.evaluateJavaScript("_firefox_ReaderMode.checkReadability()", completionHandler: nil)
}
if tab === tabManager.selectedTab {
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil)
// must be followed by LayoutChanged, as ScreenChanged will make VoiceOver
// cursor land on the correct initial element, but if not followed by LayoutChanged,
// VoiceOver will sometimes be stuck on the element, not allowing user to move
// forward/backward. Strange, but LayoutChanged fixes that.
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
}
}
extension BrowserViewController: WKUIDelegate {
func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if let currentTab = tabManager.selectedTab {
currentTab.setScreenshot(screenshotHelper.takeScreenshot(currentTab, aspectRatio: 0, quality: 1))
}
// If the page uses window.open() or target="_blank", open the page in a new tab.
// TODO: This doesn't work for window.open() without user action (bug 1124942).
let tab = tabManager.addTab(navigationAction.request, configuration: configuration)
tabManager.selectTab(tab)
return tab.webView
}
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
tabManager.selectTab(tabManager[webView])
// Show JavaScript alerts.
let title = frame.request.URL!.host
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in
completionHandler()
}))
presentViewController(alertController, animated: true, completion: nil)
}
func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {
tabManager.selectTab(tabManager[webView])
// Show JavaScript confirm dialogs.
let title = frame.request.URL!.host
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in
completionHandler(false)
}))
presentViewController(alertController, animated: true, completion: nil)
}
func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) {
tabManager.selectTab(tabManager[webView])
// Show JavaScript input dialogs.
let title = frame.request.URL!.host
let alertController = UIAlertController(title: title, message: prompt, preferredStyle: UIAlertControllerStyle.Alert)
var input: UITextField!
alertController.addTextFieldWithConfigurationHandler({ (textField: UITextField) in
textField.text = defaultText
input = textField
})
alertController.addAction(UIAlertAction(title: OKString, style: UIAlertActionStyle.Default, handler: { _ in
completionHandler(input.text)
}))
alertController.addAction(UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: { _ in
completionHandler(nil)
}))
presentViewController(alertController, animated: true, completion: nil)
}
/// Invoked when an error occurs during a committed main frame navigation.
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) {
return
}
// Ignore the "Plug-in handled load" error. Which is more like a notification than an error.
// Note that there are no constants in the SDK for the WebKit domain or error codes.
if error.domain == "WebKitErrorDomain" && error.code == 204 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error) {
return
}
if let url = error.userInfo["NSErrorFailingURLKey"] as? NSURL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
}
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
// Ignore the "Frame load interrupted" error that is triggered when we cancel a request
// to open an external application and hand it over to UIApplication.openURL(). The result
// will be that we switch to the external app, for example the app store, while keeping the
// original web page in the tab instead of replacing it with an error page.
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error) {
return
}
if error.code == Int(CFNetworkErrors.CFURLErrorCancelled.rawValue) {
if let browser = tabManager[webView] where browser === tabManager.selectedTab {
urlBar.currentURL = browser.displayURL
}
return
}
if let url = error.userInfo["NSErrorFailingURLKey"] as? NSURL {
ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView)
}
}
private func checkIfWebContentProcessHasCrashed(webView: WKWebView, error: NSError) -> Bool {
if error.code == WKErrorCode.WebContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
log.debug("WebContent process has crashed. Trying to reloadFromOrigin to restart it.")
webView.reloadFromOrigin()
return true
}
return false
}
func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {
if navigationResponse.canShowMIMEType {
decisionHandler(WKNavigationResponsePolicy.Allow)
return
}
let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: "Downloads aren't supported in Firefox yet (but we're working on it)."])
ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.URL!, inWebView: webView)
decisionHandler(WKNavigationResponsePolicy.Allow)
}
}
extension BrowserViewController: ReaderModeDelegate, UIPopoverPresentationControllerDelegate {
func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser) {
// If this reader mode availability state change is for the tab that we currently show, then update
// the button. Otherwise do nothing and the button will be updated when the tab is made active.
if tabManager.selectedTab === browser {
urlBar.updateReaderModeState(state)
}
}
func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser) {
self.showReaderModeBar(animated: true)
browser.showContent(true)
}
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
}
extension BrowserViewController: ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) {
// Persist the new style to the profile
let encodedStyle: [String:AnyObject] = style.encode()
profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle)
// Change the reader mode style on all tabs that have reader mode active
for tabIndex in 0..<tabManager.count {
if let tab = tabManager[tabIndex] {
if let readerMode = tab.getHelper(name: "ReaderMode") as? ReaderMode {
if readerMode.state == ReaderModeState.Active {
readerMode.style = style
}
}
}
}
}
}
extension BrowserViewController {
func updateReaderModeBar() {
if let readerModeBar = readerModeBar {
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
readerModeBar.unread = record.unread
readerModeBar.added = true
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
} else {
readerModeBar.unread = true
readerModeBar.added = false
}
}
}
func showReaderModeBar(animated animated: Bool) {
if self.readerModeBar == nil {
let readerModeBar = ReaderModeBarView(frame: CGRectZero)
readerModeBar.delegate = self
view.insertSubview(readerModeBar, belowSubview: header)
self.readerModeBar = readerModeBar
}
updateReaderModeBar()
self.updateViewConstraints()
}
func hideReaderModeBar(animated animated: Bool) {
if let readerModeBar = self.readerModeBar {
readerModeBar.removeFromSuperview()
self.readerModeBar = nil
self.updateViewConstraints()
}
}
/// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode
/// and be done with it. In the more complicated case, reader mode was already open for this page and we simply
/// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version
/// of the current page is there. And if so, we go there.
func enableReaderMode() {
guard let tab = tabManager.selectedTab, webView = tab.webView else { return }
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
guard let currentURL = webView.backForwardList.currentItem?.URL, let readerModeURL = ReaderModeUtils.encodeURL(currentURL) else { return }
if backList.count > 1 && backList.last?.URL == readerModeURL {
webView.goToBackForwardListItem(backList.last!)
} else if forwardList.count > 0 && forwardList.first?.URL == readerModeURL {
webView.goToBackForwardListItem(forwardList.first!)
} else {
// Store the readability result in the cache and load it. This will later move to the ReadabilityHelper.
webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in
if let readabilityResult = ReadabilityResult(object: object) {
do {
try ReaderModeCache.sharedInstance.put(currentURL, readabilityResult)
} catch _ {
}
if let nav = webView.loadRequest(NSURLRequest(URL: readerModeURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
})
}
}
/// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which
/// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that
/// case we simply open a new page with the original url. In the more complicated page, the non-readerized version
/// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there.
func disableReaderMode() {
if let tab = tabManager.selectedTab,
let webView = tab.webView {
let backList = webView.backForwardList.backList
let forwardList = webView.backForwardList.forwardList
if let currentURL = webView.backForwardList.currentItem?.URL {
if let originalURL = ReaderModeUtils.decodeURL(currentURL) {
if backList.count > 1 && backList.last?.URL == originalURL {
webView.goToBackForwardListItem(backList.last!)
} else if forwardList.count > 0 && forwardList.first?.URL == originalURL {
webView.goToBackForwardListItem(forwardList.first!)
} else {
if let nav = webView.loadRequest(NSURLRequest(URL: originalURL)) {
self.ignoreNavigationInTab(tab, navigation: nav)
}
}
}
}
}
}
}
extension BrowserViewController: ReaderModeBarViewDelegate {
func readerModeBar(readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) {
switch buttonType {
case .Settings:
if let readerMode = tabManager.selectedTab?.getHelper(name: "ReaderMode") as? ReaderMode where readerMode.state == ReaderModeState.Active {
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict) {
readerModeStyle = style
}
}
let readerModeStyleViewController = ReaderModeStyleViewController()
readerModeStyleViewController.delegate = self
readerModeStyleViewController.readerModeStyle = readerModeStyle
readerModeStyleViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
let popoverPresentationController = readerModeStyleViewController.popoverPresentationController
popoverPresentationController?.backgroundColor = UIColor.whiteColor()
popoverPresentationController?.delegate = self
popoverPresentationController?.sourceView = readerModeBar
popoverPresentationController?.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1)
popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.Up
self.presentViewController(readerModeStyleViewController, animated: true, completion: nil)
}
case .MarkAsRead:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail?
readerModeBar.unread = false
}
}
case .MarkAsUnread:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail?
readerModeBar.unread = true
}
}
case .AddToReadingList:
if let tab = tabManager.selectedTab,
let url = tab.url where ReaderModeUtils.isReaderModeURL(url) {
if let url = ReaderModeUtils.decodeURL(url) {
profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.currentDevice().name) // TODO Check result, can this fail?
readerModeBar.added = true
}
}
case .RemoveFromReadingList:
if let url = self.tabManager.selectedTab?.displayURL?.absoluteString, result = profile.readingList?.getRecordWithURL(url) {
if let successValue = result.successValue, record = successValue {
profile.readingList?.deleteRecord(record) // TODO Check result, can this fail?
readerModeBar.added = false
}
}
}
}
}
private class BrowserScreenshotHelper: ScreenshotHelper {
private weak var controller: BrowserViewController?
init(controller: BrowserViewController) {
self.controller = controller
}
func takeScreenshot(tab: Browser, aspectRatio: CGFloat, quality: CGFloat) -> UIImage? {
if let url = tab.url {
if url == UIConstants.AboutHomeURL {
if let homePanel = controller?.homePanelController {
return homePanel.view.screenshot(aspectRatio, quality: quality)
}
} else {
let offset = CGPointMake(0, -(tab.webView?.scrollView.contentInset.top ?? 0))
return tab.webView?.screenshot(aspectRatio, offset: offset, quality: quality)
}
}
return nil
}
}
extension BrowserViewController: IntroViewControllerDelegate {
func presentIntroViewController(force: Bool = false) -> Bool{
if force || profile.prefs.intForKey(IntroViewControllerSeenProfileKey) == nil {
let introViewController = IntroViewController()
introViewController.delegate = self
// On iPad we present it modally in a controller
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
introViewController.preferredContentSize = CGSize(width: IntroViewControllerUX.Width, height: IntroViewControllerUX.Height)
introViewController.modalPresentationStyle = UIModalPresentationStyle.FormSheet
}
presentViewController(introViewController, animated: true) {
self.profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey)
}
return true
}
return false
}
func introViewControllerDidFinish(introViewController: IntroViewController) {
introViewController.dismissViewControllerAnimated(true) { finished in
if self.navigationController?.viewControllers.count > 1 {
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
}
func presentSignInViewController() {
// Show the settings page if we have already signed in. If we haven't then show the signin page
let vcToPresent: UIViewController
if profile.hasAccount() {
let settingsTableViewController = SettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
vcToPresent = settingsTableViewController
} else {
let signInVC = FxAContentViewController()
signInVC.delegate = self
signInVC.url = profile.accountConfiguration.signInURL
signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "dismissSignInViewController")
vcToPresent = signInVC
}
let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent)
settingsNavigationController.modalPresentationStyle = .FormSheet
self.presentViewController(settingsNavigationController, animated: true, completion: nil)
}
func dismissSignInViewController() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func introViewControllerDidRequestToLogin(introViewController: IntroViewController) {
introViewController.dismissViewControllerAnimated(true, completion: { () -> Void in
self.presentSignInViewController()
})
}
}
extension BrowserViewController: FxAContentViewControllerDelegate {
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
log.debug("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
profile.setAccount(account)
if let account = self.profile.getAccount() {
account.advance()
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
log.info("Did cancel out of FxA signin")
self.dismissViewControllerAnimated(true, completion: nil)
}
}
extension BrowserViewController: ContextMenuHelperDelegate {
func contextMenuHelper(contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UILongPressGestureRecognizer) {
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
var dialogTitle: String?
if let url = elements.link {
dialogTitle = url.absoluteString
let newTabTitle = NSLocalizedString("Open In New Tab", comment: "Context menu item for opening a link in a new tab")
let openNewTabAction = UIAlertAction(title: newTabTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) in
self.scrollController.showToolbars(animated: !self.scrollController.toolbarsShowing, completion: { _ in
self.tabManager.addTab(NSURLRequest(URL: url))
})
}
actionSheetController.addAction(openNewTabAction)
let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard")
let copyAction = UIAlertAction(title: copyTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
let pasteBoard = UIPasteboard.generalPasteboard()
pasteBoard.string = url.absoluteString
}
actionSheetController.addAction(copyAction)
}
if let url = elements.image {
if dialogTitle == nil {
dialogTitle = url.absoluteString
}
let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus()
let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image")
let saveImageAction = UIAlertAction(title: saveImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
if photoAuthorizeStatus == PHAuthorizationStatus.Authorized || photoAuthorizeStatus == PHAuthorizationStatus.NotDetermined {
self.getImage(url) { UIImageWriteToSavedPhotosAlbum($0, nil, nil, nil) }
} else {
let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: UIAlertControllerStyle.Alert)
let dismissAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Default, handler: nil)
accessDenied.addAction(dismissAction)
let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: UIAlertActionStyle.Default ) { (action: UIAlertAction!) -> Void in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
accessDenied.addAction(settingsAction)
self.presentViewController(accessDenied, animated: true, completion: nil)
}
}
actionSheetController.addAction(saveImageAction)
let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard")
let copyAction = UIAlertAction(title: copyImageTitle, style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
let pasteBoard = UIPasteboard.generalPasteboard()
pasteBoard.string = url.absoluteString
// TODO: put the actual image on the clipboard
}
actionSheetController.addAction(copyAction)
}
// If we're showing an arrow popup, set the anchor to the long press location.
if let popoverPresentationController = actionSheetController.popoverPresentationController {
popoverPresentationController.sourceView = view
popoverPresentationController.sourceRect = CGRect(origin: gestureRecognizer.locationInView(view), size: CGSizeMake(0, 16))
popoverPresentationController.permittedArrowDirections = .Any
}
actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength)
let cancelAction = UIAlertAction(title: CancelString, style: UIAlertActionStyle.Cancel, handler: nil)
actionSheetController.addAction(cancelAction)
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
private func getImage(url: NSURL, success: UIImage -> ()) {
Alamofire.request(.GET, url)
.validate(statusCode: 200..<300)
.response { _, _, data, _ in
if let data = data,
let image = UIImage(data: data) {
success(image)
}
}
}
}
extension BrowserViewController: KeyboardHelperDelegate {
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
keyboardState = state
// if we are already showing snack bars, adjust them so they sit above the keyboard
if snackBars.subviews.count > 0 {
adjustFooterSize(nil)
}
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
keyboardState = nil
// if we are showing snack bars, adjust them so they are no longer sitting above the keyboard
if snackBars.subviews.count > 0 {
adjustFooterSize(nil)
}
}
}
extension BrowserViewController: SessionRestoreHelperDelegate {
func sessionRestoreHelper(helper: SessionRestoreHelper, didRestoreSessionForBrowser browser: Browser) {
browser.restoring = false
if let tab = tabManager.selectedTab where tab.webView === browser.webView {
updateUIForReaderHomeStateForTab(tab)
}
}
}
private struct CrashPromptMessaging {
static let CrashPromptTitle = NSLocalizedString("Well, this is embarrassing.", comment: "Restore Tabs Prompt Title")
static let CrashPromptDescription = NSLocalizedString("Looks like Firefox crashed previously. Would you like to restore your tabs?", comment: "Restore Tabs Prompt Description")
static let CrashPromptAffirmative = NSLocalizedString("Okay", comment: "Restore Tabs Affirmative Action")
static let CrashPromptNegative = NSLocalizedString("No", comment: "Restore Tabs Negative Action")
}
extension BrowserViewController: UIAlertViewDelegate {
private enum CrashPromptIndex: Int {
case Cancel = 0
case Restore = 1
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == CrashPromptIndex.Restore.rawValue {
tabManager.restoreTabs()
}
// In case restore fails, launch at least one tab
if tabManager.count == 0 {
let tab = tabManager.addTab()
tabManager.selectTab(tab)
}
}
}
| mpl-2.0 | 2e2f61360fd65c2387bc8669c2c73859 | 43.630657 | 406 | 0.655153 | 5.874335 | false | false | false | false |
wangjianquan/wjq-weibo | weibo_wjq/Tool/PhotoBrowse/PhotoBrowserAnimator.swift | 1 | 4454 | //
// PhotoBrowserAnimator.swift
// weibo_wjq
//
// Created by landixing on 2017/6/13.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
protocol AnimatorPresentDelegate: NSObjectProtocol {
//开始位置
func startAnimatorRect(indexpath: IndexPath) -> CGRect
//结束位置
func endAnimatorRect(indexpath: IndexPath) -> CGRect
//临时
func imageView(indexpath: IndexPath) -> UIImageView
}
protocol AnimatorDismissDelegate: NSObjectProtocol {
func imageViewForDismissView() -> UIImageView
func indexPathForDismissView() -> IndexPath
}
class PhotoBrowserAnimator: NSObject {
var isPresented : Bool = false
var presentDelegate : AnimatorPresentDelegate?
var dismissDelegate : AnimatorDismissDelegate?
var indexPath: IndexPath?
func setIndexPath(_ indexPath : IndexPath, presentedDelegate : AnimatorPresentDelegate, dismissDelegate : AnimatorDismissDelegate) {
self.indexPath = indexPath
self.presentDelegate = presentedDelegate
self.dismissDelegate = dismissDelegate
}
}
extension PhotoBrowserAnimator : UIViewControllerTransitioningDelegate{
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
return self
}
}
extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning{
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval
{
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning){
isPresented ? animationForPresentedView(transitionContext) : animationForDismissView(transitionContext)
}
}
extension PhotoBrowserAnimator {
//present动画
fileprivate func animationForPresentedView(_ transitionContext: UIViewControllerContextTransitioning?)
{
guard let presentDelegate = presentDelegate, let indexpath = indexPath else { return }
guard let presentView = transitionContext?.view(forKey: UITransitionContextViewKey.to) else {
return
}
transitionContext?.containerView.addSubview(presentView)
//临时iamgeview
let imageview = presentDelegate.imageView(indexpath: indexpath)
transitionContext?.containerView.addSubview(imageview)
//开始位置
imageview.frame = presentDelegate.startAnimatorRect(indexpath: indexpath)
presentView.alpha = 0.0
transitionContext?.containerView.backgroundColor = UIColor.black
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
//结束位置
imageview.frame = presentDelegate.endAnimatorRect(indexpath: indexpath)
}) { (_) in
transitionContext?.containerView.backgroundColor = UIColor.clear
imageview.removeFromSuperview()
presentView.alpha = 1.0
transitionContext?.completeTransition(true)
}
}
//dismiss动画
fileprivate func animationForDismissView(_ transitionContext: UIViewControllerContextTransitioning){
guard let dismissDele = dismissDelegate, let presentDele = presentDelegate else {
return
}
guard let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from) else {
return
}
dismissView.removeFromSuperview()
let imageview = dismissDele.imageViewForDismissView()
transitionContext.containerView.addSubview(imageview)
let indexpath = dismissDele.indexPathForDismissView()
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
imageview.frame = presentDele.startAnimatorRect(indexpath: indexpath)
}) { (_) in
imageview.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
}
| apache-2.0 | f201256b748c65f78440563b74385e4f | 27.406452 | 170 | 0.67772 | 6.522963 | false | false | false | false |
nsagora/validation-kit | ValidationToolkit.playground/Pages/BlockPredicate.xcplaygroundpage/Contents.swift | 1 | 441 |
import Foundation
import ValidationToolkit
/*:
## `BlockPredicate`
In the following example we use a `BlockPredicate` to evaluate if the length of the user input is equal to 5 characters.
*/
let input = "Hel!O"
let predicate = BlockPredicate<String> { $0.count == 5 }
let isValid = predicate.evaluate(with: input)
if isValid {
print("High ✋!")
}
else {
print("We're expecting exactlly 5 characters.")
}
//: [Next](@next)
| apache-2.0 | ba3fdec3e7a3f34704bd15aa8fd6a093 | 18.954545 | 121 | 0.690205 | 3.658333 | false | false | false | false |
daniel-barros/TV-Calendar | TV Calendar/ShowDetailDataSource.swift | 1 | 23788 | //
// ShowDetailDataSource.swift
// TV Calendar
//
// Created by Daniel Barros López on 1/18/17.
// Copyright © 2017 Daniel Barros. All rights reserved.
//
import ExtendedUIKit
/// Data source for table view that displays a show's detailed info.
/// It provides, at most, 4 table sections:
/// 0 - A DetailShowTableViewCell and a ShowActionsTableViewCell
/// 1 - Multiple ShowInfoTableViewCell
/// 2 - Multiple CalendarSettingTableViewCell and a CalendarActionTableViewCell (default-only settings)
/// 3 - Multiple CalendarSettingTableViewCell and CalendarActionTableViewCell (show-specific settings)
///
/// It also provides some `indexPaths(...)` funcs for retrieving index paths and sections. `indexPaths(forCellsAffectedBy:)` returns detailed info about rows and sections that need to be updated after a calendar settings change, which permits fine-grained table view updates with animations.
class ShowDetailDataSource: NSObject {
typealias AlteredIndexPaths = (added: [IndexPath], deleted: [IndexPath], updated: [IndexPath])
typealias AlteredSections = (added: IndexSet, deleted: IndexSet)
var show: Show? {
didSet { updateShowInfo() }
}
var calendarSettingsManager: CalendarSettingsManager?
/// The content displayed by the table view cells of type ShowInfoTableViewCell.
fileprivate var showInfo: [(title: String, body: String, maxNumberOfLines: Int)] = []
// MARK: IndexPaths and Sections Info
/// The index path for the DetailShowTableViewCell or nil if it doesn't exist.
func indexPathForDetailShowCell() -> IndexPath? {
return show == nil ? nil : IndexPath(row: 0, section: 0)
}
/// The index path for the ShowActionsTableViewCell or nil if it doesn't exist.
func indexPathForActionsCell() -> IndexPath? {
return hasActionsCell ? IndexPath(row: 1, section: 0) : nil
}
var showInfoSection: Int? {
return hasInfoSection ? 1 : nil
}
var calendarDefaultSettingsSection: Int? {
if !hasDefaultCalendarSettingsSection { return nil }
return hasInfoSection ? 2 : 1
}
var calendarShowSpecificSettingsSection: Int? {
if !hasShowSpecificCalendarSettingsSection { return nil }
return hasInfoSection ? 3 : 2
}
/// The index paths corresponding to cells which will be added/removed/updated and section numbers which will be added/removed as consequence of a calendar settings change.
/// The `updated` index paths correspond to the cells that need to be updated AFTER the table view inserts and removes the `added` and `deleted` index paths.
/// - warning: Call only after the calendar setting update has completed successfuly
func indexPaths(forCellsAffectedBy setting: CalendarSettings, in tableView: UITableView)
-> (AlteredIndexPaths, AlteredSections) {
switch setting {
case .createCalendarEvents: return indexPathsForCellsAffectedByCreateCalendarEvents()
case .eventsName: return indexPathsForCellsAffectedByEventsName()
case .createEventsForAllSeasons: return indexPathsForCellsAffectedByCreateEventsForAllSeasons(in: tableView)
case .createAllDayEvents: return indexPathsForCellsAffectedByCreateAllDayEvents(in: tableView)
case .useOriginalTimeZone: return indexPathsForCellsAffectedByUseOriginalTimeZone(in: tableView)
case .useNetworkAsLocation: return indexPathsForCellsAffectedByUseNetworkAsLocation(in: tableView)
case .setAlarms: return indexPathsForCellsAffectedBySetAlarms(in: tableView)
}
}
/// The index paths corresponding to cells which will be added/removed/updated as consequence of a calendar settings action.
/// The `updated` index paths correspond to the cells that need to be updated AFTER the table view inserts and removes the `added` and `deleted` index paths.
/// - warning: Call only after the calendar action has completed successfuly
func indexPaths(forCellsAffectedBy actionType: CalendarActionTableViewCell.ActionType, in tableView: UITableView)
-> AlteredIndexPaths {
switch actionType {
case .disableCalendarEventsForAll:
// Remove "disable events"
return ([], [indexPathCalendarActionCellWouldHave(withType: actionType)], [])
case .setDefaultSettings:
// Remove "set" and update "reset default settings"
return ([], [indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings)],
[indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings)])
case .resetToDefaultSettings:
let setDefaultsIndex = indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings)
// Remove "set" and update "reset default settings" and show-specific settings
if tableView.numberOfRows(inSection: calendarShowSpecificSettingsSection!) == CalendarSettings.numberOfShowSpecificSettings + 2 {
return ([], [indexPathCalendarActionCellWouldHave(withType: .setDefaultSettings)], [setDefaultsIndex] + indexPathsForSettingCellsInShowSpecificSection())
}
// Or update "set default settings" and show-specific settings
return ([], [], [setDefaultsIndex] + indexPathsForSettingCellsInShowSpecificSection())
case .enableCalendarEventsForAll:
// Update "enable events"
return ([],[],[indexPathCalendarActionCellWouldHave(withType: actionType)])
}
}
}
// MARK: - UITableViewDataSource
extension ShowDetailDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if show == nil { return 0 }
return 1 + (hasInfoSection ? 1 : 0) + (hasDefaultCalendarSettingsSection ? 1 : 0) + (hasShowSpecificCalendarSettingsSection ? 1 : 0)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard show != nil else {
return 0
}
switch section {
case 0:
return 1 + (hasActionsCell ? 1 : 0)
case 1:
if hasInfoSection { return showInfo.count }
else { return numberOfCellsInDefaultCalendarSettingsSection }
case 2:
if hasInfoSection { return numberOfCellsInDefaultCalendarSettingsSection }
else { return numberOfCellsInShowSpecificCalendarSettingsSection }
case 3:
return numberOfCellsInShowSpecificCalendarSettingsSection
default: assertionFailure(); return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let show = show else {
assertionFailure(); return UITableViewCell()
}
// Cell making
func detailShowCell() -> DetailShowTableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as DetailShowTableViewCell
cell.configure(with: show, animated: false)
return cell
}
func showActionsCell() -> ShowActionsTableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as ShowActionsTableViewCell
cell.configure(with: show)
return cell
}
func infoCell() -> ShowInfoTableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as ShowInfoTableViewCell
let info = showInfo[indexPath.row]
cell.configure(title: info.title, body: info.body,
maxNumberOfBodyLinesInCompactMode: info.maxNumberOfLines)
return cell
}
func calendarSettingCell(with setting: CalendarSettings) -> CalendarSettingTableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as CalendarSettingTableViewCell
cell.configure(with: show, setting: setting)
return cell
}
func calendarActionCell(with type: CalendarActionTableViewCell.ActionType, isLastOfSection: Bool = false, isLastOfTable: Bool = false) -> CalendarActionTableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath) as CalendarActionTableViewCell
cell.configure(with: show, type: type,
bottomMarginSize: isLastOfTable ? .medium : (isLastOfSection ? .large : .regular),
showsSeparator: (isLastOfSection || !isLastOfTable) ? true : false,
settingsManager: calendarSettingsManager)
return cell
}
// Cell selection
switch indexPath.section {
// SHOW DETAIL + ACTIONS SECTION
case 0:
if indexPath.row == 0 { return detailShowCell() }
else { return showActionsCell() }
// SHOW INFO SECTION
case 1 where hasInfoSection:
return infoCell()
// DEFAULT CALENDAR SETTINGS SECTION
case 1 where !hasInfoSection, 2:
switch indexPath.row {
// Calendar section title cell
case 0: return tableView.dequeueReusableCell(withIdentifier: "CalendarSettingsTitleCell", for: indexPath)
// "Creates calendar events" cell
case 1: return calendarSettingCell(with: .createCalendarEvents)
// "Disable calendar events for all" defaults cell
case 2 where numberOfCellsInDefaultCalendarSettingsSection == 3:
return calendarActionCell(with: .disableCalendarEventsForAll, isLastOfTable: true)
// "Events name" cell
case 2...CalendarSettings.numberOfDefaultOnlySettings:
return calendarSettingCell(with: CalendarSettings(rawValue: indexPath.row + defaultsOnlySettingsRawValueOffset)!)
// "Enable calendar for all shows" defaults cell
case CalendarSettings.numberOfDefaultOnlySettings + 1:
return calendarActionCell(with: .enableCalendarEventsForAll, isLastOfSection: true)
default: assertionFailure()
}
// SHOW-SPECIFIC CALENDAR SETTINGS SECTION
case 2 where !hasInfoSection, 3:
switch indexPath.row {
// Remaining calendar settings cells
case 0..<CalendarSettings.numberOfShowSpecificSettings:
return calendarSettingCell(with: CalendarSettings(rawValue: indexPath.row + showSpecificSettingsRawValueOffset)!)
// "Set default settings for all shows" cell
case CalendarSettings.numberOfShowSpecificSettings where numberOfCellsInShowSpecificCalendarSettingsSection > CalendarSettings.numberOfShowSpecificSettings + 1:
return calendarActionCell(with: .setDefaultSettings)
// "Reset to default settings" cell
case CalendarSettings.numberOfShowSpecificSettings where numberOfCellsInShowSpecificCalendarSettingsSection == CalendarSettings.numberOfShowSpecificSettings + 1, CalendarSettings.numberOfShowSpecificSettings + 1:
return calendarActionCell(with: .resetToDefaultSettings, isLastOfTable: true)
default: assertionFailure()
}
default: assertionFailure()
}
assertionFailure()
return UITableViewCell()
}
}
// MARK: - Number of cells and section existence
fileprivate extension ShowDetailDataSource {
var hasActionsCell: Bool {
return show?.trailerUrl != nil || show?.imdbUrl != nil || show?.isPersistent == true
}
var hasInfoSection: Bool {
return !showInfo.isEmpty
}
var hasDefaultCalendarSettingsSection: Bool {
return numberOfCellsInDefaultCalendarSettingsSection > 0
}
var hasShowSpecificCalendarSettingsSection: Bool {
return numberOfCellsInShowSpecificCalendarSettingsSection > 0
}
var numberOfCellsInDefaultCalendarSettingsSection: Int {
guard let show = show else { return 0 }
// No calendar settings for untracked shows
if !show.isPersistent {
return 0
}
// Calendar access not authorized: title + createCalendarEvents
if CalendarEventsManager.authorizationStatus != .authorized {
return 2
}
// Creates calendar events setting disabled
if !CalendarSettingsManager.boolValue(of: .createCalendarEvents, for: show) {
// If not disabled for all shows: title + createCalendarEvents + disableForAllShows
if CalendarSettingsManager.DefaultSettings.createsCalendarEvents {
return 3
}
// If already disabled for all shows: title + createCalendarEvents
else {
return 2
}
}
// Creates calendar events setting enabled
else {
return 2 + CalendarSettings.numberOfDefaultOnlySettings // title + createCalendarEvents + eventsName + enableForAllShows
}
}
var numberOfCellsInShowSpecificCalendarSettingsSection: Int {
guard let show = show else { return 0 }
// Not persistent, not creating events or not authorized to
if !hasDefaultCalendarSettingsSection
|| CalendarEventsManager.authorizationStatus != .authorized
|| !CalendarSettingsManager.boolValue(of: .createCalendarEvents, for: show) {
return 0
}
// Remaining settings + reset and set default settings if show's settings are different, or just reset default settings otherwise (even if it is using the default settings that cell shows a message)
return CalendarSettings.numberOfShowSpecificSettings + (CalendarSettingsManager.showHasSameSettingsAsDefault(show) ? 1 : 2)
}
/// The number you have to add to a row in the show-specific settings section to get the raw value of the corresponding CalendarSettings (or add to it to get the row from the raw value).
var showSpecificSettingsRawValueOffset: Int {
return CalendarSettings.numberOfDefaultOnlySettings
}
/// The number you have to add to a row in the defaults-only settings section to get the raw value of the corresponding CalendarSettings (or add to it to get the row from the raw value).
var defaultsOnlySettingsRawValueOffset: Int {
return -1
}
}
// MARK: - Data generation
fileprivate extension ShowDetailDataSource {
func updateShowInfo() {
showInfo = []
guard let show = show else {
return
}
let formatter = ShowFormatter(source: show)
if let summary = show.summary {
showInfo.append(("Summary", summary, 4))
}
if let genres = show.genres {
showInfo.append(("Genre", genres, 1))
}
if let runtimeString = formatter.string(for: .runtime) {
showInfo.append(("Duration", runtimeString, 1))
}
if Global.Other.showDatesInOriginalTimeZoneInDetailInfo {
if show.status == .airing,
show.timeZone != show.originalTimeZone,
let country = show.country,
let airDateString = formatter.string(for: .originalAirDayAndTime) {
showInfo.append(("Air Date in Original Time Zone", airDateString + " (\(country))", 1))
} else if show.status == .waitingForNewSeason,
let country = show.country,
let nextSeason = show.currentSeason.value,
let premiereDateString = formatter.string(for: .originalNextSeasonPremiereDate(appendingPremieresOnString: false)),
let localPremiereDateString = formatter.string(for: .nextSeasonPremiereDate(appendingPremieresOnString: false)),
premiereDateString != localPremiereDateString {
showInfo.append(("Season \(nextSeason) Premiere in Original Time Zone", premiereDateString + " (\(country))", 1))
}
}
if let actors = show.actors {
showInfo.append(("Actors", actors, 1))
}
}
}
// MARK: - Place for cells
fileprivate extension ShowDetailDataSource {
func indexPathsForSettingCellsInShowSpecificSection() -> [IndexPath] {
return (0..<CalendarSettings.numberOfShowSpecificSettings).map {
IndexPath(row: $0, section: calendarShowSpecificSettingsSection!)
}
}
/// The index path the CalendarActionTableViewCell would have if it existed.
/// - warning: Use carefully. This assumes the section where the cell would be exists.
func indexPathCalendarActionCellWouldHave(withType type: CalendarActionTableViewCell.ActionType) -> IndexPath {
switch type {
case .disableCalendarEventsForAll:
return IndexPath(row: 2, section: calendarDefaultSettingsSection!)
case .enableCalendarEventsForAll:
return IndexPath(row: CalendarSettings.numberOfDefaultOnlySettings + 1,
section: calendarDefaultSettingsSection!)
case .setDefaultSettings:
return IndexPath(row: CalendarSettings.numberOfShowSpecificSettings,
section: calendarShowSpecificSettingsSection!)
case .resetToDefaultSettings:
return IndexPath(row: CalendarSettings.numberOfShowSpecificSettings + 1,
section: calendarShowSpecificSettingsSection!)
}
}
func indexPathsForCellsAffectedByCreateCalendarEvents() -> (AlteredIndexPaths, AlteredSections) {
guard let show = show else { return (([],[],[]), ([],[])) }
let section = calendarDefaultSettingsSection!
// all default-only settings except "create events" plus one action button
let numberOfTemporaryCells = CalendarSettings.numberOfDefaultOnlySettings - 1 + 1
// They all go right after cell 1 (the "create events" cell)
let temporaryCellsIndexPaths = (2..<(2 + numberOfTemporaryCells)).map {
IndexPath(row: $0, section: section)
}
// The action button at the end of section when "create events" is off, if defaults is not off too.
let disableEventsActionCellIndexPathOrEmpty = CalendarSettingsManager.DefaultSettings.createsCalendarEvents ? [IndexPath(row: 2, section: section)] : []
// The "creates events" cell
let updatedCellIndexPath = [IndexPath(row: 1, section: section)]
let showSpecificSectionIndex = IndexSet(integer: section + 1)
// Turning on "creates events"
if CalendarSettingsManager.boolValue(of: .createCalendarEvents, for: show) {
return ((temporaryCellsIndexPaths, // add
disableEventsActionCellIndexPathOrEmpty, // delete
updatedCellIndexPath // update
),
(showSpecificSectionIndex, IndexSet())) // add, delete
}
// Turning off "creates events"
else {
return ((disableEventsActionCellIndexPathOrEmpty, // add
temporaryCellsIndexPaths, // delete
updatedCellIndexPath // update
),
(IndexSet(), showSpecificSectionIndex)) // add, delete
}
}
func indexPathsForCellsAffectedByEventsName() -> (AlteredIndexPaths, AlteredSections) {
return (([],[],[indexPathOfInitatingCell(for: .eventsName, section: .defaultsOnly)]),([],[]))
}
func indexPathsForCellsAffectedByCreateEventsForAllSeasons(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) {
var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView)
indexPaths.updated.append(indexPathOfInitatingCell(for: .createEventsForAllSeasons, section: .showSpecific))
return (indexPaths, ([],[]))
}
func indexPathsForCellsAffectedByCreateAllDayEvents(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) {
var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView)
indexPaths.updated.append(indexPathOfInitatingCell(for: .createAllDayEvents, section: .showSpecific))
// original time zone is disabled if all day events is true
indexPaths.updated.append(indexPathOfInitatingCell(for: .useOriginalTimeZone, section: .showSpecific))
return (indexPaths, ([],[]))
}
func indexPathsForCellsAffectedByUseOriginalTimeZone(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) {
var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView)
indexPaths.updated.append(indexPathOfInitatingCell(for: .useOriginalTimeZone, section: .showSpecific))
return (indexPaths, ([],[]))
}
func indexPathsForCellsAffectedByUseNetworkAsLocation(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) {
var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView)
indexPaths.updated.append(indexPathOfInitatingCell(for: .useNetworkAsLocation, section: .showSpecific))
return (indexPaths, ([],[]))
}
func indexPathsForCellsAffectedBySetAlarms(in tableView: UITableView) -> (AlteredIndexPaths, AlteredSections) {
var indexPaths = indexPathOfAffectedShowSpecificSectionActionCells(in: tableView)
indexPaths.updated.append(indexPathOfInitatingCell(for: .setAlarms, section: .showSpecific))
return (indexPaths, ([],[]))
}
enum SettingsSection {
case defaultsOnly, showSpecific
}
/// The index path of the cell corresponding to the specified setting.
private func indexPathOfInitatingCell(for setting: CalendarSettings, section: SettingsSection) -> IndexPath {
let row = setting.rawValue + (section == .defaultsOnly ? -defaultsOnlySettingsRawValueOffset : -showSpecificSettingsRawValueOffset)
let section = section == .defaultsOnly ? calendarDefaultSettingsSection! : calendarShowSpecificSettingsSection!
return IndexPath(row: row, section: section)
}
/// The `AlteredIndexPaths` for the "set default settings" and "reset to default settings" action cells in the show-specific calendar settings table section.
private func indexPathOfAffectedShowSpecificSectionActionCells(in tableView: UITableView) -> AlteredIndexPaths {
let numberOfRowsBefore = tableView.numberOfRows(inSection: calendarShowSpecificSettingsSection!)
let numberOfRowAfter = numberOfCellsInShowSpecificCalendarSettingsSection
let section = calendarShowSpecificSettingsSection!
let setDefaultsIndexPath = IndexPath(row: CalendarSettings.numberOfShowSpecificSettings,
section: section)
let resetDefaultsIndexPath = IndexPath(row: CalendarSettings.numberOfShowSpecificSettings + 1,
section: section)
// Need to delete the "set defaults" cell and update "reset defaults"
if numberOfRowsBefore > numberOfRowAfter {
return ([],
[setDefaultsIndexPath],
[resetDefaultsIndexPath])
}
// Need to add the "set defaults" cell and update "reset defaults"
else if numberOfRowsBefore < numberOfRowAfter {
return ([setDefaultsIndexPath],
[],
[resetDefaultsIndexPath])
}
// If same number of actions, no updates
else {
return ([],[],[])
}
}
}
| gpl-3.0 | ba64ebddc0fd6f2241d15189c6c6830d | 49.933619 | 291 | 0.669806 | 6.041656 | false | false | false | false |
emilstahl/swift | stdlib/public/SDK/Foundation/NSValue.swift | 10 | 1135 | //===--- NSValue.swift - Bridging things in NSValue -------------*-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
//
//===----------------------------------------------------------------------===//
extension NSRange : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSValue.self
}
public func _bridgeToObjectiveC() -> NSValue {
return NSValue(range: self)
}
public static func _forceBridgeFromObjectiveC(
x: NSValue,
inout result: NSRange?
) {
result = x.rangeValue
}
public static func _conditionallyBridgeFromObjectiveC(
x: NSValue,
inout result: NSRange?
) -> Bool {
self._forceBridgeFromObjectiveC(x, result: &result)
return true
}
}
| apache-2.0 | 28a49af6df0e7e7b6fa952a01213361d | 27.375 | 80 | 0.634361 | 4.768908 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01251-getcallerdefaultarg.swift | 1 | 580 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class func a() -> String {
re> d) {
}
protocol A {
}
init <A: A where A.B == D>(e: A.B) {
}
var e: Int -> Int = {
return $0
= { c, b in
}(f, e)
func a(b: Int = 0) {
}
let c = a
c()
| apache-2.0 | 78b2468d60f883b508ea629c6fa257bb | 24.217391 | 79 | 0.663793 | 3.052632 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/WMFAuthAccountCreationInfoFetcher.swift | 1 | 2376 |
public enum WMFAuthAccountCreationError: LocalizedError {
case cannotExtractInfo
case cannotCreateAccountsNow
public var errorDescription: String? {
switch self {
case .cannotExtractInfo:
return "Could not extract account creation info"
case .cannotCreateAccountsNow:
return "Unable to create accounts at this time"
}
}
}
public typealias WMFAuthAccountCreationInfoBlock = (WMFAuthAccountCreationInfo) -> Void
public struct WMFAuthAccountCreationInfo {
let canCreateAccounts:Bool
let captcha: WMFCaptcha?
init(canCreateAccounts:Bool, captcha:WMFCaptcha?) {
self.canCreateAccounts = canCreateAccounts
self.captcha = captcha
}
}
public class WMFAuthAccountCreationInfoFetcher {
private let manager = AFHTTPSessionManager.wmf_createDefault()
public func isFetching() -> Bool {
return manager.operationQueue.operationCount > 0
}
public func fetchAccountCreationInfoForSiteURL(_ siteURL: URL, success: @escaping WMFAuthAccountCreationInfoBlock, failure: @escaping WMFErrorHandler){
let manager = AFHTTPSessionManager(baseURL: siteURL)
manager.responseSerializer = WMFApiJsonResponseSerializer.init();
let parameters = [
"action": "query",
"meta": "authmanagerinfo",
"amirequestsfor": "create",
"format": "json"
]
_ = manager.wmf_apiPOSTWithParameters(parameters, success: { (_, response) in
guard
let response = response as? [String : AnyObject],
let query = response["query"] as? [String : AnyObject],
let authmanagerinfo = query["authmanagerinfo"] as? [String : AnyObject],
let requests = authmanagerinfo["requests"] as? [[String : AnyObject]]
else {
failure(WMFAuthAccountCreationError.cannotExtractInfo)
return
}
guard authmanagerinfo["cancreateaccounts"] != nil else {
failure(WMFAuthAccountCreationError.cannotCreateAccountsNow)
return
}
success(WMFAuthAccountCreationInfo.init(canCreateAccounts: true, captcha: WMFCaptcha.captcha(from: requests)))
}, failure: { (_, error) in
failure(error)
})
}
}
| mit | 79ee40e7c83bce7a8cd57206030515a2 | 39.271186 | 155 | 0.639731 | 5.670644 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/OnThisDayViewControllerHeader.swift | 2 | 2731 | import UIKit
class OnThisDayViewControllerHeader: UICollectionReusableView {
@IBOutlet weak var eventsLabel: UILabel!
@IBOutlet weak var onLabel: UILabel!
@IBOutlet weak var fromLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
updateFonts()
apply(theme: Theme.standard)
wmf_configureSubviewsForDynamicType()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
onLabel.font = UIFont.wmf_font(.heavyTitle1, compatibleWithTraitCollection: traitCollection)
}
func configureFor(eventCount: Int, firstEvent: WMFFeedOnThisDayEvent?, lastEvent: WMFFeedOnThisDayEvent?, midnightUTCDate: Date) {
let language = firstEvent?.language
let locale = NSLocale.wmf_locale(for: language)
semanticContentAttribute = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: language)
eventsLabel.semanticContentAttribute = semanticContentAttribute
onLabel.semanticContentAttribute = semanticContentAttribute
fromLabel.semanticContentAttribute = semanticContentAttribute
eventsLabel.text = String(format: WMFLocalizedString("on-this-day-detail-header-title", language: language, value:"{{PLURAL:%1$d|%1$d historical event|%1$d historical events}}", comment:"Title for 'On this day' detail view - %1$d is replaced with the number of historical events which occurred on the given day"), locale: locale, eventCount).uppercased(with: locale)
onLabel.text = DateFormatter.wmf_monthNameDayNumberGMTFormatter(for: language).string(from: midnightUTCDate)
if let firstEventEraString = firstEvent?.yearString, let lastEventEraString = lastEvent?.yearString {
fromLabel.text = String(format: WMFLocalizedString("on-this-day-detail-header-date-range", language: language, value:"from %1$@ - %2$@", comment:"Text for 'On this day' detail view events 'year range' label - %1$@ is replaced with string version of the oldest event year - i.e. '300 BC', %2$@ is replaced with string version of the most recent event year - i.e. '2006', "), locale: locale, lastEventEraString, firstEventEraString)
} else {
fromLabel.text = nil
}
}
}
extension OnThisDayViewControllerHeader: Themeable {
func apply(theme: Theme) {
backgroundColor = theme.colors.paperBackground
eventsLabel.textColor = theme.colors.secondaryText
onLabel.textColor = theme.colors.primaryText
fromLabel.textColor = theme.colors.secondaryText
}
}
| mit | e88fcbdab403025eded720e57a60e763 | 50.528302 | 442 | 0.71915 | 5.06679 | false | false | false | false |
julienbodet/wikipedia-ios | WMF Framework/EventLoggingService.swift | 1 | 20882 | import Foundation
enum EventLoggingError {
case generic
}
@objc(WMFEventLoggingService)
public class EventLoggingService : NSObject, URLSessionDelegate {
private struct Key {
static let isEnabled = "SendUsageReports"
static let appInstallID = "WMFAppInstallID"
static let lastLoggedSnapshot = "WMFLastLoggedSnapshot"
static let appInstallDate = "AppInstallDate"
static let loggedDaysInstalled = "DailyLoggingStatsDaysInstalled"
}
public var pruningAge: TimeInterval = 60*60*24*30 // 30 days
public var sendImmediatelyOnWWANThreshhold: TimeInterval = 30
public var postBatchSize = 10
public var postTimeout: TimeInterval = 60*2 // 2 minutes
public var postInterval: TimeInterval = 60*10 // 10 minutes
public var debugDisableImmediateSend = false
private static let scheme = "https" // testing is http
private static let host = "meta.wikimedia.org" // testing is deployment.wikimedia.beta.wmflabs.org
private static let path = "/beacon/event"
private let reachabilityManager: AFNetworkReachabilityManager
private let urlSessionConfiguration: URLSessionConfiguration
private var urlSession: URLSession?
private let postLock = NSLock()
private var posting = false
private var started = false
private var timer: Timer?
private var lastNetworkRequestTimestamp: TimeInterval?
private let persistentStoreCoordinator: NSPersistentStoreCoordinator
private let managedObjectContext: NSManagedObjectContext
@objc(sharedInstance) public static let shared: EventLoggingService = {
let fileManager = FileManager.default
var permanentStorageDirectory = fileManager.wmf_containerURL().appendingPathComponent("Event Logging", isDirectory: true)
var didGetDirectoryExistsError = false
do {
try fileManager.createDirectory(at: permanentStorageDirectory, withIntermediateDirectories: true, attributes: nil)
} catch let error {
DDLogError("EventLoggingService: Error creating permanent cache: \(error)")
}
do {
var values = URLResourceValues()
values.isExcludedFromBackup = true
try permanentStorageDirectory.setResourceValues(values)
} catch let error {
DDLogError("EventLoggingService: Error excluding from backup: \(error)")
}
let permanentStorageURL = permanentStorageDirectory.appendingPathComponent("Events.sqlite")
DDLogDebug("EventLoggingService: Events persistent store: \(permanentStorageURL)")
return EventLoggingService(permanentStorageURL: permanentStorageURL)
}()
@objc
public func log(event: Dictionary<String, Any>, schema: String, revision: Int, wiki: String) {
let event: NSDictionary = ["event": event, "schema": schema, "revision": revision, "wiki": wiki]
logEvent(event)
}
private var shouldSendImmediately: Bool {
if !started {
return false
}
if (debugDisableImmediateSend) {
return false
}
if self.reachabilityManager.isReachableViaWiFi {
return true
}
if self.reachabilityManager.isReachableViaWWAN,
let lastNetworkRequestTimestamp = self.lastNetworkRequestTimestamp,
Date.timeIntervalSinceReferenceDate < (lastNetworkRequestTimestamp + sendImmediatelyOnWWANThreshhold) {
return true
}
return false
}
public init(urlSesssionConfiguration: URLSessionConfiguration, reachabilityManager: AFNetworkReachabilityManager, permanentStorageURL: URL? = nil) {
self.reachabilityManager = reachabilityManager
self.urlSessionConfiguration = urlSesssionConfiguration
let bundle = Bundle.wmf
let modelURL = bundle.url(forResource: "EventLogging", withExtension: "momd")!
let model = NSManagedObjectModel(contentsOf: modelURL)!
let psc = NSPersistentStoreCoordinator(managedObjectModel: model)
let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(booleanLiteral: true), NSInferMappingModelAutomaticallyOption: NSNumber(booleanLiteral: true)]
if let storeURL = permanentStorageURL {
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
} catch {
do {
try FileManager.default.removeItem(at: storeURL)
} catch {
}
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
} catch {
abort()
}
}
} else {
do {
try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: options)
} catch {
abort()
}
}
self.persistentStoreCoordinator = psc
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = psc
}
public convenience init(permanentStorageURL: URL) {
let reachabilityManager = AFNetworkReachabilityManager.init(forDomain: EventLoggingService.host)
let urlSessionConfig = URLSessionConfiguration.default
urlSessionConfig.httpShouldUsePipelining = true
urlSessionConfig.allowsCellularAccess = true
urlSessionConfig.httpMaximumConnectionsPerHost = 2
urlSessionConfig.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
self.init(urlSesssionConfiguration: urlSessionConfig, reachabilityManager: reachabilityManager, permanentStorageURL: permanentStorageURL)
}
deinit {
stop()
}
@objc
public func start() {
assert(Thread.isMainThread, "must be started on main thread")
guard !self.started else {
return
}
self.started = true
self.urlSession = URLSession(configuration: self.urlSessionConfiguration, delegate: self, delegateQueue: nil)
NotificationCenter.default.addObserver(forName: NSNotification.Name.WMFNetworkRequestBegan, object: nil, queue: .main) { (note) in
self.lastNetworkRequestTimestamp = Date.timeIntervalSinceReferenceDate
//DDLogDebug("last network request: \(String(describing: self.lastNetworkRequestTimestamp))")
}
self.reachabilityManager.setReachabilityStatusChange { (status) in
switch status {
case .reachableViaWiFi:
self.tryPostEvents()
default:
break
}
}
self.reachabilityManager.startMonitoring()
self.timer = Timer.scheduledTimer(timeInterval: self.postInterval, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
prune()
#if DEBUG
self.managedObjectContext.perform {
do {
let countFetch: NSFetchRequest<EventRecord> = EventRecord.fetchRequest()
countFetch.includesSubentities = false
let count = try self.managedObjectContext.count(for: countFetch)
DDLogInfo("EventLoggingService: There are \(count) queued events")
} catch let error {
DDLogError(error.localizedDescription)
}
}
#endif
}
@objc
private func timerFired() {
tryPostEvents()
asyncSave()
}
@objc
public func stop() {
assert(Thread.isMainThread, "must be stopped on main thread")
guard self.started else {
return
}
self.started = false
self.reachabilityManager.stopMonitoring()
self.urlSession?.finishTasksAndInvalidate()
self.urlSession = nil
NotificationCenter.default.removeObserver(self)
self.timer?.invalidate()
self.timer = nil
self.managedObjectContext.performAndWait {
self.save()
}
}
@objc
public func reset() {
self.resetSession()
self.resetInstall()
}
private func prune() {
self.managedObjectContext.perform {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "WMFEventRecord")
fetch.returnsObjectsAsFaults = false
let pruneDate = Date().addingTimeInterval(-(self.pruningAge)) as NSDate
fetch.predicate = NSPredicate(format: "(recorded < %@) OR (posted != nil) OR (failed == TRUE)", pruneDate)
let delete = NSBatchDeleteRequest(fetchRequest: fetch)
delete.resultType = .resultTypeCount
do {
let result = try self.managedObjectContext.execute(delete)
guard let deleteResult = result as? NSBatchDeleteResult else {
DDLogError("EventLoggingService: Could not read NSBatchDeleteResult")
return
}
guard let count = deleteResult.result as? Int else {
DDLogError("EventLoggingService: Could not read NSBatchDeleteResult count")
return
}
DDLogInfo("EventLoggingService: Pruned \(count) events")
} catch let error {
DDLogError("EventLoggingService: Error pruning events: \(error.localizedDescription)")
}
}
}
@objc
public func logEvent(_ event: NSDictionary) {
let now = NSDate()
let moc = self.managedObjectContext
moc.perform {
let record = NSEntityDescription.insertNewObject(forEntityName: "WMFEventRecord", into: self.managedObjectContext) as! EventRecord
record.event = event
record.recorded = now
record.userAgent = WikipediaAppUtils.versionedUserAgent()
DDLogDebug("EventLoggingService: \(record.objectID) recorded!")
self.save()
if self.shouldSendImmediately {
self.tryPostEvents()
}
}
}
@objc
private func tryPostEvents() {
self.postLock.lock()
guard started, !posting else {
self.postLock.unlock()
return
}
posting = true
self.postLock.unlock()
let moc = self.managedObjectContext
moc.perform {
let fetch: NSFetchRequest<EventRecord> = EventRecord.fetchRequest()
fetch.sortDescriptors = [NSSortDescriptor(keyPath: \EventRecord.recorded, ascending: true)]
fetch.predicate = NSPredicate(format: "(posted == nil) AND (failed != TRUE)")
fetch.fetchLimit = self.postBatchSize
do {
var eventRecords: [EventRecord] = []
defer {
if eventRecords.count > 0 {
self.postEvents(eventRecords)
} else {
self.postLock.lock()
self.posting = false
self.postLock.unlock()
}
}
eventRecords = try moc.fetch(fetch)
} catch let error {
DDLogError(error.localizedDescription)
}
}
}
private func asyncSave() {
self.managedObjectContext.perform {
self.save()
}
}
private func postEvents(_ eventRecords: [EventRecord]) {
assert(posting, "method expects posting to be set when called")
DDLogDebug("EventLoggingService: Posting \(eventRecords.count) events!")
let taskGroup = WMFTaskGroup()
var completedRecordIDs = Set<NSManagedObjectID>()
var failedRecordIDs = Set<NSManagedObjectID>()
for record in eventRecords {
let moid = record.objectID
guard let payload = record.event else {
failedRecordIDs.insert(moid)
continue
}
taskGroup.enter()
let userAgent = record.userAgent ?? WikipediaAppUtils.versionedUserAgent()
submit(payload: payload, userAgent: userAgent) { (error) in
if error != nil {
failedRecordIDs.insert(moid)
} else {
completedRecordIDs.insert(moid)
}
taskGroup.leave()
}
}
taskGroup.waitInBackground {
self.managedObjectContext.perform {
let postDate = NSDate()
for moid in completedRecordIDs {
let mo = try? self.managedObjectContext.existingObject(with: moid)
guard let record = mo as? EventRecord else {
continue
}
record.posted = postDate
}
for moid in failedRecordIDs {
let mo = try? self.managedObjectContext.existingObject(with: moid)
guard let record = mo as? EventRecord else {
continue
}
record.failed = true
}
self.save()
self.postLock.lock()
self.posting = false
self.postLock.unlock()
if (completedRecordIDs.count == eventRecords.count) {
DDLogDebug("EventLoggingService: All records succeeded, attempting to post more")
self.tryPostEvents()
} else {
DDLogDebug("EventLoggingService: Some records failed, waiting to post more")
}
}
}
}
private func submit(payload: NSObject, userAgent: String, completion: @escaping (EventLoggingError?) -> Void) {
guard let urlSession = self.urlSession else {
assertionFailure("urlSession was nil")
completion(EventLoggingError.generic)
return
}
do {
let payloadJsonData = try JSONSerialization.data(withJSONObject:payload, options: [])
guard let payloadString = String(data: payloadJsonData, encoding: .utf8) else {
DDLogError("EventLoggingService: Could not convert JSON data to string")
completion(EventLoggingError.generic)
return
}
let encodedPayloadJsonString = payloadString.wmf_UTF8StringWithPercentEscapes()
var components = URLComponents()
components.scheme = EventLoggingService.scheme
components.host = EventLoggingService.host
components.path = EventLoggingService.path
components.percentEncodedQuery = encodedPayloadJsonString
guard let url = components.url else {
DDLogError("EventLoggingService: Could not creatre URL")
completion(EventLoggingError.generic)
return
}
var request = URLRequest(url: url)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
let task = urlSession.dataTask(with: request, completionHandler: { (_, response, error) in
guard error == nil,
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode / 100 == 2 else {
completion(EventLoggingError.generic)
return
}
completion(nil)
// DDLogDebug("EventLoggingService: event \(eventRecord.objectID) posted!")
})
task.resume()
} catch let error {
DDLogError(error.localizedDescription)
completion(EventLoggingError.generic)
return
}
}
// mark stored values
private func save() {
guard managedObjectContext.hasChanges else {
return
}
do {
try managedObjectContext.save()
} catch let error {
DDLogError("Error saving EventLoggingService managedObjectContext: \(error)")
}
}
private var semaphore = DispatchSemaphore(value: 1)
private var libraryValueCache: [String: NSCoding] = [:]
private func libraryValue(for key: String) -> NSCoding? {
semaphore.wait()
defer {
semaphore.signal()
}
var value = libraryValueCache[key]
if value != nil {
return value
}
managedObjectContext.performAndWait {
value = managedObjectContext.wmf_keyValue(forKey: key)?.value
if value != nil {
libraryValueCache[key] = value
return
}
if let legacyValue = UserDefaults.wmf_userDefaults().object(forKey: key) as? NSCoding {
value = legacyValue
libraryValueCache[key] = legacyValue
managedObjectContext.wmf_setValue(legacyValue, forKey: key)
UserDefaults.wmf_userDefaults().removeObject(forKey: key)
save()
}
}
return value
}
private func setLibraryValue(_ value: NSCoding?, for key: String) {
semaphore.wait()
defer {
semaphore.signal()
}
libraryValueCache[key] = value
managedObjectContext.perform {
self.managedObjectContext.wmf_setValue(value, forKey: key)
self.save()
}
}
@objc public var isEnabled: Bool {
get {
var isEnabled = false
if let enabledNumber = libraryValue(for: Key.isEnabled) as? NSNumber {
isEnabled = enabledNumber.boolValue
}
return isEnabled
}
set {
setLibraryValue(NSNumber(booleanLiteral: newValue), for: Key.isEnabled)
}
}
@objc public var appInstallID: String? {
get {
var installID = libraryValue(for: Key.appInstallID) as? String
if installID == nil || installID == "" {
installID = UUID().uuidString
setLibraryValue(installID as NSString?, for: Key.appInstallID)
}
return installID
}
set {
setLibraryValue(newValue as NSString?, for: Key.appInstallID)
}
}
@objc public var lastLoggedSnapshot: NSCoding? {
get {
return libraryValue(for: Key.lastLoggedSnapshot)
}
set {
setLibraryValue(newValue, for: Key.lastLoggedSnapshot)
}
}
@objc public var appInstallDate: Date? {
get {
var value = libraryValue(for: Key.appInstallDate) as? Date
if value == nil {
value = Date()
setLibraryValue(value as NSDate?, for: Key.appInstallDate)
}
return value
}
set {
setLibraryValue(newValue as NSDate?, for: Key.appInstallDate)
}
}
@objc public var loggedDaysInstalled: NSNumber? {
get {
return libraryValue(for: Key.loggedDaysInstalled) as? NSNumber
}
set {
setLibraryValue(newValue, for: Key.loggedDaysInstalled)
}
}
private var _sessionID: String?
@objc public var sessionID: String? {
semaphore.wait()
defer {
semaphore.signal()
}
if _sessionID == nil {
_sessionID = UUID().uuidString
}
return _sessionID
}
private var _sessionStartDate: Date?
@objc public var sessionStartDate: Date? {
semaphore.wait()
defer {
semaphore.signal()
}
if _sessionStartDate == nil {
_sessionStartDate = Date()
}
return _sessionStartDate
}
@objc public func resetSession() {
semaphore.wait()
defer {
semaphore.signal()
}
_sessionID = nil
_sessionStartDate = Date()
}
private func resetInstall() {
appInstallID = nil
lastLoggedSnapshot = nil
loggedDaysInstalled = nil
appInstallDate = nil
}
}
| mit | 953770e73b8c823ea98e3522f7206b81 | 34.453311 | 172 | 0.57959 | 5.985096 | false | false | false | false |
FXSolutions/FXDemoXCodeInjectionPlugin | testinjection/Stevia+Operators.swift | 2 | 3645 | //
// Stevia+Operators.swift
// Stevia
//
// Created by Sacha Durand Saint Omer on 10/02/16.
// Copyright © 2016 Sacha Durand Saint Omer. All rights reserved.
//
import UIKit
prefix operator | {}
public prefix func | (p:UIView) -> UIView {
return p.left(0)
}
postfix operator | {}
public postfix func | (p:UIView) -> UIView {
return p.right(0)
}
infix operator ~ {}
public func ~ (left: CGFloat, right: UIView) -> UIView {
return right.height(left)
}
public func ~ (left: UIView, right: CGFloat) -> UIView {
return left.height(right)
}
prefix operator |- {}
public prefix func |- (p: CGFloat) -> SideConstraint {
var s = SideConstraint()
s.constant = p
return s
}
public prefix func |- (v: UIView) -> UIView {
v.left(8)
return v
}
postfix operator -| {}
public postfix func -| (p: CGFloat) -> SideConstraint {
var s = SideConstraint()
s.constant = p
return s
}
public postfix func -| (v: UIView) -> UIView {
v.right(8)
return v
}
public struct SideConstraint {
var constant:CGFloat!
}
public struct PartialConstraint {
var view1:UIView!
var constant:CGFloat!
var views:[UIView]?
}
public func - (left: UIView, right: CGFloat) -> PartialConstraint {
var p = PartialConstraint()
p.view1 = left
p.constant = right
return p
}
// Side Constraints
public func - (left: SideConstraint, right: UIView) -> UIView {
if let spv = right.superview {
let c = constraint(item: right, attribute: .Left, toItem: spv, attribute: .Left, constant: left.constant)
spv.addConstraint(c)
}
return right
}
public func - (left: [UIView], right: SideConstraint) -> [UIView] {
let lastView = left[left.count-1]
if let spv = lastView.superview {
let c = constraint(item: lastView, attribute: .Right, toItem: spv, attribute: .Right, constant: -right.constant)
spv.addConstraint(c)
}
return left
}
public func - (left:UIView, right: SideConstraint) -> UIView {
if let spv = left.superview {
let c = constraint(item: left, attribute: .Right, toItem: spv, attribute: .Right, constant: -right.constant)
spv.addConstraint(c)
}
return left
}
public func - (left: PartialConstraint, right: UIView) -> [UIView] {
if let views = left.views {
if let spv = right.superview {
let lastView = views[views.count-1]
let c = constraint(item: lastView, attribute: .Right, toItem: right, attribute: .Left, constant: -left.constant)
spv.addConstraint(c)
}
return views + [right]
} else {
// were at the end?? nooope?/?
if let spv = right.superview {
let c = constraint(item: left.view1, attribute: .Right, toItem: right, attribute: .Left, constant: -left.constant)
spv.addConstraint(c)
}
return [left.view1, right]
}
}
public func - (left: UIView, right: UIView) -> [UIView] {
if let spv = left.superview {
let c = constraint(item: right, attribute: .Left, toItem: left, attribute: .Right, constant: 8)
spv.addConstraint(c)
}
return [left,right]
}
public func - (left: [UIView], right: CGFloat) -> PartialConstraint {
var p = PartialConstraint()
p.constant = right
p.views = left
return p
}
public func - (left: [UIView], right: UIView) -> [UIView] {
let lastView = left[left.count-1]
if let spv = lastView.superview {
let c = constraint(item: lastView, attribute: .Right, toItem: right, attribute: .Left, constant: -8)
spv.addConstraint(c)
}
return left + [right]
}
| mit | d0baf3bd7b1344e3d43410560ccb2269 | 23.789116 | 126 | 0.622393 | 3.677094 | false | false | false | false |
rockwotj/FirebaseMovieQuotesiOS | MovieQuotesCoreData/MovieQuoteDetailViewController.swift | 1 | 2162 | //
// MovieQuoteDetailViewController.swift
// MovieQuotesCoreData
//
// Created by CSSE Department on 3/24/15.
// Copyright (c) 2015 CSSE Department. All rights reserved.
//
import UIKit
class MovieQuoteDetailViewController: UIViewController {
@IBOutlet weak var quoteLabel: UILabel!
@IBOutlet weak var movieLabel: UILabel!
var quoteTextField: UITextField?
var movieTextField: UITextField?
var movieQuote : MovieQuote?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//TODO: Listen for changes to the quote
updateView()
}
func quoteChanged() {
//TODO: Push change to Firebase
}
func updateView() {
quoteLabel.text = movieQuote?.quote
movieLabel.text = movieQuote?.movie
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "showEditQuoteDialog")
}
func showEditQuoteDialog() {
let alertController = UIAlertController(title: "Edit new movie quote", message: "", preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler {
(textField) -> Void in
textField.placeholder = "Quote"
textField.text = self.movieQuote?.quote
self.quoteTextField = textField
textField.addTarget(self, action: "quoteChanged", forControlEvents: .EditingChanged)
}
alertController.addTextFieldWithConfigurationHandler {
(textField) -> Void in
textField.placeholder = "Movie Title"
textField.text = self.movieQuote?.movie
self.movieTextField = textField
textField.addTarget(self, action: "quoteChanged", forControlEvents: .EditingChanged)
}
let cancelAction = UIAlertAction(title: "Done", style: .Cancel) {
(_) -> Void in
println("Done")
}
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | 403cecc5c497065ed628976c1c0ef191 | 32.261538 | 132 | 0.651249 | 5.197115 | false | false | false | false |
KrishMunot/swift | test/SILGen/dynamic_self.swift | 5 | 8437 | // RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s
protocol P {
func f() -> Self
}
protocol CP : class {
func f() -> Self
}
class X : P, CP {
required init(int i: Int) { }
// CHECK-LABEL: sil hidden @_TFC12dynamic_self1X1f{{.*}} : $@convention(method) (@guaranteed X) -> @owned
func f() -> Self { return self }
// CHECK-LABEL: sil hidden @_TZFC12dynamic_self1X7factory{{.*}} : $@convention(method) (Int, @thick X.Type) -> @owned X
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : $@thick X.Type):
// CHECK: [[CTOR:%[0-9]+]] = class_method [[SELF]] : $@thick X.Type, #X.init!allocator.1 : X.Type -> (int: Int) -> X , $@convention(method) (Int, @thick X.Type) -> @owned X
// CHECK: apply [[CTOR]]([[I]], [[SELF]]) : $@convention(method) (Int, @thick X.Type) -> @owned X
class func factory(i: Int) -> Self { return self.init(int: i) }
}
class Y : X {
required init(int i: Int) { }
}
class GX<T> {
func f() -> Self { return self }
}
class GY<T> : GX<[T]> { }
// CHECK-LABEL: sil hidden @_TF12dynamic_self23testDynamicSelfDispatch{{.*}} : $@convention(thin) (@owned Y) -> ()
func testDynamicSelfDispatch(y: Y) {
// CHECK: bb0([[Y:%[0-9]+]] : $Y):
// CHECK: strong_retain [[Y]]
// CHECK: [[Y_AS_X:%[0-9]+]] = upcast [[Y]] : $Y to $X
// CHECK: [[X_F:%[0-9]+]] = class_method [[Y_AS_X]] : $X, #X.f!1 : X -> () -> Self , $@convention(method) (@guaranteed X) -> @owned X
// CHECK: [[X_RESULT:%[0-9]+]] = apply [[X_F]]([[Y_AS_X]]) : $@convention(method) (@guaranteed X) -> @owned X
// CHECK: strong_release [[Y_AS_X]]
// CHECK: [[Y_RESULT:%[0-9]+]] = unchecked_ref_cast [[X_RESULT]] : $X to $Y
// CHECK: strong_release [[Y_RESULT]] : $Y
// CHECK: strong_release [[Y]] : $Y
y.f()
}
// CHECK-LABEL: sil hidden @_TF12dynamic_self30testDynamicSelfDispatchGeneric{{.*}} : $@convention(thin) (@owned GY<Int>) -> ()
func testDynamicSelfDispatchGeneric(gy: GY<Int>) {
// CHECK: bb0([[GY:%[0-9]+]] : $GY<Int>):
// CHECK: strong_retain [[GY]]
// CHECK: [[GY_AS_GX:%[0-9]+]] = upcast [[GY]] : $GY<Int> to $GX<Array<Int>>
// CHECK: [[GX_F:%[0-9]+]] = class_method [[GY_AS_GX]] : $GX<Array<Int>>, #GX.f!1 : <T> GX<T> -> () -> Self , $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0>
// CHECK: [[GX_RESULT:%[0-9]+]] = apply [[GX_F]]<[Int]>([[GY_AS_GX]]) : $@convention(method) <τ_0_0> (@guaranteed GX<τ_0_0>) -> @owned GX<τ_0_0>
// CHECK: strong_release [[GY_AS_GX]]
// CHECK: [[GY_RESULT:%[0-9]+]] = unchecked_ref_cast [[GX_RESULT]] : $GX<Array<Int>> to $GY<Int>
// CHECK: strong_release [[GY_RESULT]] : $GY<Int>
// CHECK: strong_release [[GY]]
gy.f()
}
// CHECK-LABEL: sil hidden @_TF12dynamic_self21testArchetypeDispatch{{.*}} : $@convention(thin) <T where T : P> (@in T) -> ()
func testArchetypeDispatch<T: P>(t: T) {
// CHECK: bb0([[T:%[0-9]+]] : $*T):
// CHECK: [[ARCHETYPE_F:%[0-9]+]] = witness_method $T, #P.f!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T
// CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[ARCHETYPE_F]]<T>([[T_RESULT]], [[T]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
t.f()
}
// CHECK-LABEL: sil hidden @_TF12dynamic_self23testExistentialDispatch{{.*}}
func testExistentialDispatch(p: P) {
// CHECK: bb0([[P:%[0-9]+]] : $*P):
// CHECK: [[PCOPY_ADDR:%[0-9]+]] = open_existential_addr [[P]] : $*P to $*@opened([[N:".*"]]) P
// CHECK: [[P_RESULT:%[0-9]+]] = alloc_stack $P
// CHECK: [[P_RESULT_ADDR:%[0-9]+]] = init_existential_addr [[P_RESULT]] : $*P, $@opened([[N]]) P
// CHECK: [[P_F_METHOD:%[0-9]+]] = witness_method $@opened([[N]]) P, #P.f!1, [[PCOPY_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: apply [[P_F_METHOD]]<@opened([[N]]) P>([[P_RESULT_ADDR]], [[PCOPY_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : P> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK: destroy_addr [[P_RESULT]] : $*P
// CHECK: dealloc_stack [[P_RESULT]] : $*P
// CHECK: destroy_addr [[P]] : $*P
p.f()
}
// CHECK-LABEL: sil hidden @_TF12dynamic_self28testExistentialDispatchClass{{.*}} : $@convention(thin) (@owned CP) -> ()
func testExistentialDispatchClass(cp: CP) {
// CHECK: bb0([[CP:%[0-9]+]] : $CP):
// CHECK: [[CP_ADDR:%[0-9]+]] = open_existential_ref [[CP]] : $CP to $@opened([[N:".*"]]) CP
// CHECK: [[CP_F:%[0-9]+]] = witness_method $@opened([[N]]) CP, #CP.f!1, [[CP_ADDR]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0
// CHECK: [[CP_F_RESULT:%[0-9]+]] = apply [[CP_F]]<@opened([[N]]) CP>([[CP_ADDR]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : CP> (@guaranteed τ_0_0) -> @owned τ_0_0
// CHECK: [[RESULT_EXISTENTIAL:%[0-9]+]] = init_existential_ref [[CP_F_RESULT]] : $@opened([[N]]) CP : $@opened([[N]]) CP, $CP
// CHECK: strong_release [[CP_F_RESULT]] : $@opened([[N]]) CP
cp.f()
}
@objc class ObjC {
@objc func method() -> Self { return self }
}
// CHECK-LABEL: sil hidden @_TF12dynamic_self21testAnyObjectDispatch{{.*}} : $@convention(thin) (@owned AnyObject) -> ()
func testAnyObjectDispatch(o: AnyObject) {
// CHECK: dynamic_method_br [[O_OBJ:%[0-9]+]] : $@opened({{.*}}) AnyObject, #ObjC.method!1.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject):
// CHECK: [[VAR_9:%[0-9]+]] = partial_apply [[METHOD]]([[O_OBJ]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased AnyObject
var x = o.method
}
// <rdar://problem/16270889> Dispatch through ObjC metatypes.
class ObjCInit {
dynamic required init() { }
}
// CHECK: sil hidden @_TF12dynamic_self12testObjCInit{{.*}} : $@convention(thin) (@thick ObjCInit.Type) -> ()
func testObjCInit(meta: ObjCInit.Type) {
// CHECK: bb0([[THICK_META:%[0-9]+]] : $@thick ObjCInit.Type):
// CHECK: [[O:%[0-9]+]] = alloc_box $ObjCInit
// CHECK: [[PB:%.*]] = project_box [[O]]
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[THICK_META]] : $@thick ObjCInit.Type to $@objc_metatype ObjCInit.Type
// CHECK: [[OBJ:%[0-9]+]] = alloc_ref_dynamic [objc] [[OBJC_META]] : $@objc_metatype ObjCInit.Type, $ObjCInit
// CHECK: [[INIT:%[0-9]+]] = class_method [volatile] [[OBJ]] : $ObjCInit, #ObjCInit.init!initializer.1.foreign : ObjCInit.Type -> () -> ObjCInit , $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit
// CHECK: [[RESULT_OBJ:%[0-9]+]] = apply [[INIT]]([[OBJ]]) : $@convention(objc_method) (@owned ObjCInit) -> @owned ObjCInit
// CHECK: store [[RESULT_OBJ]] to [[PB]] : $*ObjCInit
// CHECK: strong_release [[O]] : $@box ObjCInit
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
var o = meta.init()
}
class OptionalResult {
func foo() -> Self? { return self }
}
// CHECK-LABEL: sil hidden @_TFC12dynamic_self14OptionalResult3foo
// CHECK: bb0(
// CHECK-NEXT: debug_value %0 : $OptionalResult
// CHECK-NEXT: strong_retain [[VALUE:%[0-9]+]]
// CHECK-NEXT: [[T0:%.*]] = enum $Optional<OptionalResult>, #Optional.some!enumelt.1, %0 : $OptionalResult
// CHECK-NEXT: return [[T0]] : $Optional<OptionalResult>
class OptionalResultInheritor : OptionalResult {
func bar() {}
}
func testOptionalResult(v : OptionalResultInheritor) {
v.foo()?.bar()
}
// CHECK-LABEL: sil hidden @_TF12dynamic_self18testOptionalResult{{.*}} : $@convention(thin) (@owned OptionalResultInheritor) -> ()
// CHECK: [[T0:%.*]] = class_method [[V:%.*]] : $OptionalResult, #OptionalResult.foo!1 : OptionalResult -> () -> Self? , $@convention(method) (@guaranteed OptionalResult) -> @owned Optional<OptionalResult>
// CHECK-NEXT: [[RES:%.*]] = apply [[T0]]([[V]])
// CHECK: select_enum [[RES]]
// CHECK: [[T1:%.*]] = unchecked_enum_data [[RES]]
// CHECK-NEXT: [[T4:%.*]] = unchecked_ref_cast [[T1]] : $OptionalResult to $OptionalResultInheritor
// CHECK-NEXT: enum $Optional<OptionalResultInheritor>, #Optional.some!enumelt.1, [[T4]]
// CHECK-LABEL: sil_witness_table hidden X: P module dynamic_self {
// CHECK: method #P.f!1: @_TTWC12dynamic_self1XS_1PS_FS1_1f
// CHECK-LABEL: sil_witness_table hidden X: CP module dynamic_self {
// CHECK: method #CP.f!1: @_TTWC12dynamic_self1XS_2CPS_FS1_1f
| apache-2.0 | b544d19b843ac2b200bce13fbcf6919f | 51.874214 | 211 | 0.591055 | 2.955009 | false | true | false | false |
texuf/outandabout | outandabout/outandabout/RSBarcodes/RSCodeGenerator.swift | 1 | 6048 | //
// RSCodeGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
import CoreImage
let DIGITS_STRING = "0123456789"
// Code generators are required to provide these two functions.
public protocol RSCodeGenerator {
func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage?
func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage?
}
// Check digit are not required for all code generators.
// UPC-E is using check digit to valid the contents to be encoded.
// Code39Mod43, Code93 and Code128 is using check digit to encode barcode.
public protocol RSCheckDigitGenerator {
func checkDigit(contents:String) -> String
}
// Abstract code generator, provides default functions for validations and generations.
public class RSAbstractCodeGenerator : RSCodeGenerator {
// Check whether the given contents are valid.
public func isValid(contents:String) -> Bool {
let length = contents.length()
if length > 0 {
for i in 0..<length {
let character = contents[i]
if !DIGITS_STRING.contains(character!) {
return false
}
}
return true
}
return false
}
// Barcode initiator, subclass should return its own value.
public func initiator() -> String {
return ""
}
// Barcode terminator, subclass should return its own value.
public func terminator() -> String {
return ""
}
// Barcode content, subclass should return its own value.
public func barcode(contents:String) -> String {
return ""
}
// Composer for combining barcode initiator, contents, terminator together.
func completeBarcode(barcode:String) -> String {
return self.initiator() + barcode + self.terminator()
}
// Drawer for completed barcode.
func drawCompleteBarcode(completeBarcode:String) -> UIImage? {
let length:Int = completeBarcode.length()
if length <= 0 {
return nil
}
// Values taken from CIImage generated AVMetadataObjectTypePDF417Code type image
// Top spacing = 1.5
// Bottom spacing = 2
// Left & right spacing = 2
// Height = 28
let width = length + 4
let size = CGSizeMake(CGFloat(width), 28)
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetShouldAntialias(context, false)
UIColor.whiteColor().setFill()
UIColor.blackColor().setStroke()
CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height))
CGContextSetLineWidth(context, 1)
for i in 0..<length {
let character = completeBarcode[i]
if character == "1" {
let x = i + (2 + 1)
CGContextMoveToPoint(context, CGFloat(x), 1.5)
CGContextAddLineToPoint(context, CGFloat(x), size.height - 2)
}
}
CGContextDrawPath(context, kCGPathFillStroke)
let barcode = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return barcode
}
// RSCodeGenerator
public func generateCode(machineReadableCodeObject:AVMetadataMachineReadableCodeObject) -> UIImage? {
return self.generateCode(machineReadableCodeObject.stringValue, machineReadableCodeObjectType: machineReadableCodeObject.type)
}
public func generateCode(contents:String, machineReadableCodeObjectType:String) -> UIImage? {
if self.isValid(contents) {
return self.drawCompleteBarcode(self.completeBarcode(self.barcode(contents)))
}
return nil
}
// Class funcs
// Get CIFilter name by machine readable code object type
public class func filterName(machineReadableCodeObjectType:String) -> String! {
if machineReadableCodeObjectType == AVMetadataObjectTypeQRCode {
return "CIQRCodeGenerator"
} else if machineReadableCodeObjectType == AVMetadataObjectTypePDF417Code {
return "CIPDF417BarcodeGenerator"
} else if machineReadableCodeObjectType == AVMetadataObjectTypeAztecCode {
return "CIAztecCodeGenerator"
} else if machineReadableCodeObjectType == AVMetadataObjectTypeCode128Code {
return "CICode128BarcodeGenerator"
} else {
return ""
}
}
// Generate CI related code image
public class func generateCode(contents:String, filterName:String) -> UIImage {
if filterName == "" {
return UIImage()
}
let filter = CIFilter(name: filterName)
filter.setDefaults()
let inputMessage = contents.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
filter.setValue(inputMessage, forKey: "inputMessage")
let outputImage = filter.outputImage
let context = CIContext(options: nil)
let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent())
return UIImage(CGImage: cgImage, scale: 1, orientation: UIImageOrientation.Up)!
}
// Resize image
public class func resizeImage(source:UIImage, scale:CGFloat) -> UIImage {
let width = source.size.width * scale
let height = source.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(width, height))
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, kCGInterpolationNone)
source.drawInRect(CGRectMake(0, 0, width, height))
let target = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return target
}
} | mit | cb5a8a9b17fab8022ec9da17b83ee0c2 | 35.439759 | 134 | 0.65129 | 5.498182 | false | false | false | false |
khizkhiz/swift | stdlib/public/core/Misc.swift | 2 | 5158 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Extern C functions
//===----------------------------------------------------------------------===//
// FIXME: Once we have an FFI interface, make these have proper function bodies
@_transparent
@warn_unused_result
public // @testable
func _countLeadingZeros(value: Int64) -> Int64 {
return Int64(Builtin.int_ctlz_Int64(value._value, false._value))
}
/// Returns if `x` is a power of 2.
@_transparent
@warn_unused_result
public // @testable
func _isPowerOf2(x: UInt) -> Bool {
if x == 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// zero.
return x & (x &- 1) == 0
}
/// Returns if `x` is a power of 2.
@_transparent
@warn_unused_result
public // @testable
func _isPowerOf2(x: Int) -> Bool {
if x <= 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// `Int.min`.
return x & (x &- 1) == 0
}
#if _runtime(_ObjC)
@_transparent
public func _autorelease(x: AnyObject) {
Builtin.retain(x)
Builtin.autorelease(x)
}
#endif
/// Invoke `body` with an allocated, but uninitialized memory suitable for a
/// `String` value.
///
/// This function is primarily useful to call various runtime functions
/// written in C++.
func _withUninitializedString<R>(
body: (UnsafeMutablePointer<String>) -> R
) -> (R, String) {
let stringPtr = UnsafeMutablePointer<String>(allocatingCapacity: 1)
let bodyResult = body(stringPtr)
let stringResult = stringPtr.move()
stringPtr.deallocateCapacity(1)
return (bodyResult, stringResult)
}
@_silgen_name("swift_getTypeName")
public func _getTypeName(type: Any.Type, qualified: Bool)
-> (UnsafePointer<UInt8>, Int)
/// Returns the demangled qualified name of a metatype.
@warn_unused_result
public // @testable
func _typeName(type: Any.Type, qualified: Bool = true) -> String {
let (stringPtr, count) = _getTypeName(type, qualified: qualified)
return ._fromWellFormedCodeUnitSequence(UTF8.self,
input: UnsafeBufferPointer(start: stringPtr, count: count))
}
@_silgen_name("swift_getTypeByMangledName")
func _getTypeByMangledName(
name: UnsafePointer<UInt8>,
_ nameLength: UInt)
-> Any.Type?
/// Lookup a class given a name. Until the demangled encoding of type
/// names is stabilized, this is limited to top-level class names (Foo.bar).
@warn_unused_result
public // SPI(Foundation)
func _typeByName(name: String) -> Any.Type? {
let components = name.characters.split{$0 == "."}.map(String.init)
guard components.count == 2 else {
return nil
}
// Note: explicitly build a class name to match on, rather than matching
// on the result of _typeName(), to ensure the type we are resolving is
// actually a class.
var name = "C"
if components[0] == "Swift" {
name += "s"
} else {
name += String(components[0].characters.count) + components[0]
}
name += String(components[1].characters.count) + components[1]
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { (nameUTF8) in
let type = _getTypeByMangledName(nameUTF8.baseAddress,
UInt(nameUTF8.endIndex))
return type
}
}
@warn_unused_result
@_silgen_name("swift_stdlib_demangleName")
func _stdlib_demangleNameImpl(
mangledName: UnsafePointer<UInt8>,
_ mangledNameLength: UInt,
_ demangledName: UnsafeMutablePointer<String>)
// NB: This function is not used directly in the Swift codebase, but is
// exported for Xcode support. Please coordinate before changing.
@warn_unused_result
public // @testable
func _stdlib_demangleName(mangledName: String) -> String {
let mangledNameUTF8 = Array(mangledName.utf8)
return mangledNameUTF8.withUnsafeBufferPointer {
(mangledNameUTF8) in
let (_, demangledName) = _withUninitializedString {
_stdlib_demangleNameImpl(
mangledNameUTF8.baseAddress, UInt(mangledNameUTF8.endIndex),
$0)
}
return demangledName
}
}
/// Returns `floor(log(x))`. This equals to the position of the most
/// significant non-zero bit, or 63 - number-of-zeros before it.
///
/// The function is only defined for positive values of `x`.
///
/// Examples:
///
/// floorLog2(1) == 0
/// floorLog2(2) == floorLog2(3) == 1
/// floorLog2(9) == floorLog2(15) == 3
///
/// TODO: Implement version working on Int instead of Int64.
@warn_unused_result
@_transparent
public // @testable
func _floorLog2(x: Int64) -> Int {
_sanityCheck(x > 0, "_floorLog2 operates only on non-negative integers")
// Note: use unchecked subtraction because we this expression cannot
// overflow.
return 63 &- Int(_countLeadingZeros(x))
}
| apache-2.0 | 93c39cfb8b7f9f7a49224fd3f4cc12a8 | 30.072289 | 80 | 0.663048 | 3.95249 | false | false | false | false |
alecananian/osx-coin-ticker | CoinTicker/Source/Exchanges/HuobiExchange.swift | 1 | 2999 | //
// HuobiExchange.swift
// CoinTicker
//
// Created by Alec Ananian on 1/10/18.
// Copyright © 2018 Alec Ananian.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import SwiftyJSON
import PromiseKit
class HuobiExchange: Exchange {
private struct Constants {
static let ProductListAPIPath = "https://api.huobi.pro/v1/common/symbols"
static let TickerAPIPathFormat = "https://api.huobi.pro/market/detail/merged?symbol=%@"
}
init(delegate: ExchangeDelegate? = nil) {
super.init(site: .huobi, delegate: delegate)
}
override func load() {
super.load(from: Constants.ProductListAPIPath) {
$0.json["data"].arrayValue.compactMap { result in
let baseCurrency = result["base-currency"].stringValue
let quoteCurrency = result["quote-currency"].stringValue
return CurrencyPair(
baseCurrency: baseCurrency,
quoteCurrency: quoteCurrency,
customCode: "\(baseCurrency)\(quoteCurrency)"
)
}
}
}
override internal func fetch() {
_ = when(resolved: selectedCurrencyPairs.map({ currencyPair -> Promise<ExchangeAPIResponse> in
let apiRequestPath = String(format: Constants.TickerAPIPathFormat, currencyPair.customCode)
return requestAPI(apiRequestPath, for: currencyPair)
})).map { [weak self] results in
results.forEach({ result in
switch result {
case .fulfilled(let value):
if let currencyPair = value.representedObject as? CurrencyPair {
let price = value.json["tick"]["close"].doubleValue
self?.setPrice(price, for: currencyPair)
}
default: break
}
})
self?.onFetchComplete()
}
}
}
| mit | a31bc7a0a0df6eb740de034d0dc2d6f0 | 38.447368 | 103 | 0.644096 | 4.72126 | false | false | false | false |
devandsev/theTVDB-iOS | tvShows/Source/Screens/WF.swift | 1 | 1260 | //
// BaseWireframe.swift
// tvShows
//
// Created by Andrey Sevrikov on 17/09/2017.
// Copyright © 2017 devandsev. All rights reserved.
//
import UIKit
class BaseWireframe: Wireframe {
let navigationController: UINavigationController
required init(with navigationController: UINavigationController) {
self.navigationController = navigationController
}
func show(viewController: UIViewController, modally: Bool = false) {
if modally {
self.navigationController.present(viewController, animated: true) {}
} else {
self.navigationController.pushViewController(viewController, animated: true)
}
}
func hide(viewController: UIViewController) {
guard let lastVC = self.navigationController.viewControllers.last,
lastVC == viewController else {
self.navigationController.dismiss(animated: true) {}
return
}
self.navigationController.popViewController(animated: true)
}
}
protocol Wireframe {
var navigationController: UINavigationController {get}
init(with navigationController: UINavigationController)
}
protocol ModuleConstructable {
func module() -> UIViewController
}
| mit | 7ff21a9d4a6e0e5684b4879f1206be2c | 26.369565 | 87 | 0.685465 | 5.312236 | false | false | false | false |
royratcliffe/Snippets | Sources/Bundle+Snippets.swift | 1 | 3750 | // Snippets NSBundle+Snippets.swift
//
// Copyright © 2008–2015, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//------------------------------------------------------------------------------
import Foundation
extension Bundle {
/// Loads an immutable property list from a named resource within a named
/// sub-directory. Fails by answering `nil` if the resource does not exist, or
/// it fails to load. Throws an error if the data loads but fails to decode as
/// a properly-formatted property list.
///
/// For some reason, `URLForResource` has an optional name parameter. Apple
/// documentation does not make it clear what happens if the name is
/// `nil`. This method does not follow the same pattern. The name string is
/// *not* optional.
public func propertyList(forResource name: String, subdirectory: String?) throws -> Any? {
guard let URL = url(forResource: name, withExtension: "plist", subdirectory: subdirectory) else {
return nil
}
guard let data = try? Data(contentsOf: URL) else {
return nil
}
return try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.MutabilityOptions(), format: nil)
}
/// - returns: Bundle's display name; returns the application's display name
/// if applied to the application's main bundle,
/// i.e. `NSBundle.mainBundle().displayName` gives you the application
/// display name.
///
/// See Technical Q&A QA1544 for more details.
///
/// Note that some users enable "Show all filename extensions" in Finder. With
/// that option enabled, the application display name becomes
/// AppDisplayName.app rather than just AppDisplayName. The displayName
/// implementation removes the `app` extension so that when creating an
/// Application Support folder by this name, for example, the new support
/// folder does not also carry the `app` extension.
public var displayName: String {
let manager = FileManager.default
let displayName = manager.displayName(atPath: bundlePath) as NSString
return displayName.deletingPathExtension
}
/// - parameter subpath: sub-folder within this bundle.
/// - returns: an array of storyboard names found in this bundle.
///
/// Compiled storyboards have the `storyboardc` extension; `c` standing for
/// compiled, presumably.
public func storyboardNames(inDirectory subpath: String?) -> [String] {
return paths(forResourcesOfType: "storyboardc", inDirectory: subpath).map { path in
let component = (path as NSString).lastPathComponent
return (component as NSString).deletingPathExtension
}
}
}
| mit | 772158f79be5711dd8a779f73e2f8827 | 46.329114 | 134 | 0.717304 | 4.763057 | false | false | false | false |
LarsStegman/helios-for-reddit | Sources/Model/Listing.swift | 1 | 1543 | //
// Listing.swift
// Helios
//
// Created by Lars Stegman on 30-12-16.
// Copyright © 2016 Stegman. All rights reserved.
//
import Foundation
public struct Listing: Kindable, Decodable {
let before: String?
let after: String?
let modhash: String?
var source: URL?
public let children: [KindWrapper]
public static let kind = Kind.listing
init(before: String?, after: String?, modhash: String?, source: URL?, children: [KindWrapper]) {
self.before = before
self.after = after
self.modhash = modhash
self.source = source
self.children = children
}
/// Whether there are pages before this one.
public var hasPrevious: Bool {
return before != nil
}
/// Whether there are more pages.
public var hasNext: Bool {
return after != nil
}
public init(from decoder: Decoder) throws {
let dataContainer = try decoder.container(keyedBy: CodingKeys.self)
source = try dataContainer.decodeIfPresent(URL.self, forKey: .source)
after = try dataContainer.decodeIfPresent(String.self, forKey: .after)
before = try dataContainer.decodeIfPresent(String.self, forKey: .before)
modhash = try dataContainer.decodeIfPresent(String.self, forKey: .modhash)
children = try dataContainer.decode([KindWrapper].self, forKey: .children)
}
enum CodingKeys: String, CodingKey {
case before
case after
case children
case modhash
case source
}
}
| mit | 4cba156387336ce412f61d34e2ad9851 | 27.555556 | 100 | 0.645266 | 4.456647 | false | false | false | false |
gbarcena/ImageCaptureSession | ImageCaptureSession/ViewController.swift | 1 | 2538 | //
// ViewController.swift
// ImageCaptureSession
//
// Created by Gustavo Barcena on 5/27/15.
// Copyright (c) 2015 Gustavo Barcena. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var previewView : PreviewView!
var captureSession : ImageCaptureSession?
override func viewDidLoad() {
super.viewDidLoad()
setupCameraView()
}
deinit {
captureSession?.stop()
}
func setupCameraView() {
let cameraPosition : AVCaptureDevicePosition
if (ImageCaptureSession.hasFrontCamera()) {
cameraPosition = .front
}
else if (ImageCaptureSession.hasBackCamera()) {
cameraPosition = .back
}
else {
cameraPosition = .unspecified
assertionFailure("Device needs to have a camera for this demo")
}
captureSession = ImageCaptureSession(position: cameraPosition, previewView: previewView)
captureSession?.start()
}
@IBAction func takePhotoPressed(_ sender:AnyObject) {
captureSession?.captureImage({ (image, error) -> Void in
if (error == nil) {
if let imageVC = self.storyboard?.instantiateViewController(withIdentifier: "ImageViewController") as? ImageViewController {
imageVC.image = image
self.present(imageVC, animated: true, completion: nil)
}
return
}
let alertController = UIAlertController(title: "Oh no!", message: "Failed to take a photo.", preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
})
}
@IBAction func switchCamerasPressed(_ sender:AnyObject) {
let stillFrame = previewView.snapshotView(afterScreenUpdates: false)
stillFrame?.frame = previewView.frame
view.insertSubview(stillFrame!, aboveSubview: previewView)
UIView.animate(withDuration: 0.05,
animations: {
self.captureSession?.previewLayer.opacity = 0
}, completion: { (finished) in
self.captureSession?.switchCameras()
UIView.animate(withDuration: 0.05,
animations: {
self.captureSession?.previewLayer.opacity = 1
}, completion: { (finished) in
stillFrame?.removeFromSuperview()
})
})
}
}
| mit | 80bb3adbc847e6acf52062e2fa9e1a42 | 33.297297 | 140 | 0.597715 | 5.469828 | false | false | false | false |
vi4m/Sideburns | Sources/Sideburns.swift | 1 | 1926 |
// Sideburns.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
@_exported import File
@_exported import HTTP
@_exported import Mustache
public typealias TemplateData = MustacheBoxable
public enum SideburnsError: ErrorProtocol {
case unsupportedTemplateEncoding
}
extension Response {
public init(status: Status = .ok, headers: Headers = [:], templateName: String, repository: TemplateRepository, templateData: TemplateData) throws {
let template = try repository.template(named: templateName)
let rendering = try template.render(box: Box(boxable: templateData))
self.init(status: status, headers: headers, body: rendering)
// if let fileExtension = templateFile.fileExtension, mediaType = mediaType(forFileExtension: fileExtension) {
// self.contentType = mediaType
// }
}
} | mit | 1b5729e6878107166387ab0b1d546fe1 | 41.822222 | 152 | 0.746106 | 4.585714 | false | false | false | false |
paleksandrs/APScheduledLocationManager | ScheduledLocationExample/ViewController.swift | 1 | 1944 | //
// Created by Aleksandrs Proskurins
//
// License
// Copyright © 2016 Aleksandrs Proskurins
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
import APScheduledLocationManager
import CoreLocation
class ViewController: UIViewController, APScheduledLocationManagerDelegate {
private var manager: APScheduledLocationManager!
@IBOutlet weak var startStopButton: UIButton!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
manager = APScheduledLocationManager(delegate: self)
}
@IBAction func startStop(_ sender: AnyObject) {
if manager.isRunning {
startStopButton.setTitle("start", for: .normal)
manager.stopUpdatingLocation()
}else{
if CLLocationManager.authorizationStatus() == .authorizedAlways {
startStopButton.setTitle("stop", for: .normal)
manager.startUpdatingLocation(interval: 60, acceptableLocationAccuracy: 100)
}else{
manager.requestAlwaysAuthorization()
}
}
}
func scheduledLocationManager(_ manager: APScheduledLocationManager, didUpdateLocations locations: [CLLocation]) {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
let l = locations.first!
textView.text = "\(textView.text!)\r \(formatter.string(from: Date())) loc: \(l.coordinate.latitude), \(l.coordinate.longitude)"
}
func scheduledLocationManager(_ manager: APScheduledLocationManager, didFailWithError error: Error) {
}
func scheduledLocationManager(_ manager: APScheduledLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
}
}
| mit | 47d6d1f113d601feb5ce7ff30d7f3300 | 30.33871 | 136 | 0.638703 | 6.090909 | false | false | false | false |
Kiandr/CrackingCodingInterview | Swift/Ch 2. Linked Lists/Ch 2. Linked Lists.playground/Pages/2.8 Loop Detection.xcplaygroundpage/Contents.swift | 1 | 1664 | import Foundation
/*:
2.8 Given a singly linked, circular list, return the node at the beginning of the loop.
A circular list is a (corrupt) linked list in which a node's next pointer points to
an earlier node in the list.
Input: `a -> b -> c -> d -> e -> c` (The same c as before) \
Output: `c`
*/
extension MutableList {
func nodeBeginningLoop() -> MutableList? {
return nodeBeginningLoop(advanceBy: 1)
}
private func nodeBeginningLoop(advanceBy: Int) -> MutableList? {
guard !isEmpty else { return nil }
guard self !== node(at: advanceBy) else { return self }
return tail?.nodeBeginningLoop(advanceBy: advanceBy + 1)
}
}
let list = MutableList(arrayLiteral: "a", "b", "c", "d", "e")
list.description
let listToAppend = MutableList(arrayLiteral: "a", "b", "c", "d", "e")
list.append(list: listToAppend)
list.description
assert(list.nodeBeginningLoop() == nil)
let circularList = MutableList(arrayLiteral: "a", "b", "c", "d", "e")
circularList.description
assert(circularList.nodeBeginningLoop() == nil)
let subList = circularList.tail?.tail
circularList.append(list: subList!)
assert(circularList.nodeBeginningLoop() === subList)
// customizing MutableList's debugDescription prevents the playground from recursing infintely
// when it prints a circular list
extension MutableList: CustomDebugStringConvertible {
public var debugDescription: String {
guard let head = head else { return "nil" }
let description = "\(head)"
if let tailHead = tail?.head {
return description + " -> \(tailHead) ..."
}
return description
}
}
| mit | 2d854aa4599c5c48d37369ee0a95a90a | 30.396226 | 94 | 0.670072 | 4.038835 | false | false | false | false |
Sethmr/FantasticView | FantasticView/FantasticView.swift | 1 | 839 | //
// FantasticView.swift
// FantasticView
//
// Created by Seth Rininger on 5/22/17.
// Copyright © 2017 Seth Rininger. All rights reserved.
//
import UIKit
class FantasticView: UIView {
let colors : [UIColor] = [.red, .orange, .yellow, .green, .blue, .purple]
var colorCounter = 0
override init(frame: CGRect) {
super.init(frame: frame)
let scheduledColorChanged = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { timer in
UIView.animate(withDuration: 2.0) {
self.layer.backgroundColor = self.colors[self.colorCounter % 6].cgColor
self.colorCounter += 1
}
}
scheduledColorChanged.fire()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 3ed7f3e66c6fbaca372fa00879cc607a | 23.647059 | 105 | 0.596659 | 4.067961 | false | false | false | false |
larryhou/swift | CoredataExample/CoredataExample/AppDelegate.swift | 1 | 6181 | //
// AppDelegate.swift
// CoredataExample
//
// Created by larryhou on 19/7/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let rootViewController = window!.rootViewController as! ViewController
rootViewController.managedObjectContext = managedObjectContext
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.larryhou.samples.CoredataExample" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count - 1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CoredataExample", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("data.sqlite")
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
var failureReason = "There was an error creating or loading the application's saved data."
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | a1823afbb5495733567ae49f73cc6a68 | 54.178571 | 291 | 0.722006 | 5.936599 | false | false | false | false |
duycao2506/SASCoffeeIOS | Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Presenter/NVActivityIndicatorPresenter.swift | 2 | 10575 | //
// NVActivityIndicatorPresenter.swift
// NVActivityIndicatorView
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
/// Class packages information used to display UI blocker.
public final class ActivityData {
/// Size of activity indicator view.
let size: CGSize
/// Message displayed under activity indicator view.
let message: String?
/// Font of message displayed under activity indicator view.
let messageFont: UIFont
/// Animation type.
let type: NVActivityIndicatorType
/// Color of activity indicator view.
let color: UIColor
/// Color of text.
let textColor: UIColor
/// Padding of activity indicator view.
let padding: CGFloat
/// Display time threshold to actually display UI blocker.
let displayTimeThreshold: Int
/// Minimum display time of UI blocker.
let minimumDisplayTime: Int
/// Background color of the UI blocker
let backgroundColor: UIColor
/**
Create information package used to display UI blocker.
Appropriate NVActivityIndicatorView.DEFAULT_* values are used for omitted params.
- parameter size: size of activity indicator view.
- parameter message: message displayed under activity indicator view.
- parameter messageFont: font of message displayed under activity indicator view.
- parameter type: animation type.
- parameter color: color of activity indicator view.
- parameter padding: padding of activity indicator view.
- parameter displayTimeThreshold: display time threshold to actually display UI blocker.
- parameter minimumDisplayTime: minimum display time of UI blocker.
- parameter textColor: color of the text below the activity indicator view. Will match color parameter if not set, otherwise DEFAULT_TEXT_COLOR if color is not set.
- returns: The information package used to display UI blocker.
*/
public init(size: CGSize? = nil,
message: String? = nil,
messageFont: UIFont? = nil,
type: NVActivityIndicatorType? = nil,
color: UIColor? = nil,
padding: CGFloat? = nil,
displayTimeThreshold: Int? = nil,
minimumDisplayTime: Int? = nil,
backgroundColor: UIColor? = nil,
textColor: UIColor? = nil) {
self.size = size ?? NVActivityIndicatorView.DEFAULT_BLOCKER_SIZE
self.message = message ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MESSAGE
self.messageFont = messageFont ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MESSAGE_FONT
self.type = type ?? NVActivityIndicatorView.DEFAULT_TYPE
self.color = color ?? NVActivityIndicatorView.DEFAULT_COLOR
self.padding = padding ?? NVActivityIndicatorView.DEFAULT_PADDING
self.displayTimeThreshold = displayTimeThreshold ?? NVActivityIndicatorView.DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD
self.minimumDisplayTime = minimumDisplayTime ?? NVActivityIndicatorView.DEFAULT_BLOCKER_MINIMUM_DISPLAY_TIME
self.backgroundColor = backgroundColor ?? NVActivityIndicatorView.DEFAULT_BLOCKER_BACKGROUND_COLOR
self.textColor = textColor ?? color ?? NVActivityIndicatorView.DEFAULT_TEXT_COLOR
}
}
/// Presenter that displays NVActivityIndicatorView as UI blocker.
public final class NVActivityIndicatorPresenter {
private enum State {
case waitingToShow
case showed
case waitingToHide
case hidden
}
private let restorationIdentifier = "NVActivityIndicatorViewContainer"
private let messageLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private var state: State = .hidden
private let startAnimatingGroup = DispatchGroup()
/// Shared instance of `NVActivityIndicatorPresenter`.
public static let sharedInstance = NVActivityIndicatorPresenter()
private init() {}
// MARK: - Public interface
/**
Display UI blocker.
- parameter data: Information package used to display UI blocker.
*/
public final func startAnimating(_ data: ActivityData) {
guard state == .hidden else { return }
state = .waitingToShow
startAnimatingGroup.enter()
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(data.displayTimeThreshold)) {
guard self.state == .waitingToShow else {
self.startAnimatingGroup.leave()
return
}
self.show(with: data)
self.startAnimatingGroup.leave()
}
}
/**
Remove UI blocker.
*/
public final func stopAnimating() {
_hide()
}
/// Set message displayed under activity indicator view.
///
/// - Parameter message: message displayed under activity indicator view.
public final func setMessage(_ message: String?) {
guard state == .showed else {
startAnimatingGroup.notify(queue: DispatchQueue.main) {
self.messageLabel.text = message
}
return
}
messageLabel.text = message
}
// MARK: - Helpers
private func show(with activityData: ActivityData) {
let containerView = UIView(frame: UIScreen.main.bounds)
containerView.backgroundColor = activityData.backgroundColor
containerView.restorationIdentifier = restorationIdentifier
containerView.translatesAutoresizingMaskIntoConstraints = false
let activityIndicatorView = NVActivityIndicatorView(
frame: CGRect(x: 0, y: 0, width: activityData.size.width, height: activityData.size.height),
type: activityData.type,
color: activityData.color,
padding: activityData.padding)
activityIndicatorView.startAnimating()
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(activityIndicatorView)
// Add constraints for `activityIndicatorView`.
({
let xConstraint = NSLayoutConstraint(item: containerView, attribute: .centerX, relatedBy: .equal, toItem: activityIndicatorView, attribute: .centerX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: containerView, attribute: .centerY, relatedBy: .equal, toItem: activityIndicatorView, attribute: .centerY, multiplier: 1, constant: 0)
containerView.addConstraints([xConstraint, yConstraint])
}())
messageLabel.font = activityData.messageFont
messageLabel.textColor = activityData.textColor
messageLabel.text = activityData.message
containerView.addSubview(messageLabel)
// Add constraints for `messageLabel`.
({
let leadingConstraint = NSLayoutConstraint(item: containerView, attribute: .leading, relatedBy: .equal, toItem: messageLabel, attribute: .leading, multiplier: 1, constant: -8)
let trailingConstraint = NSLayoutConstraint(item: containerView, attribute: .trailing, relatedBy: .equal, toItem: messageLabel, attribute: .trailing, multiplier: 1, constant: 8)
containerView.addConstraints([leadingConstraint, trailingConstraint])
}())
({
let spacingConstraint = NSLayoutConstraint(item: messageLabel, attribute: .top, relatedBy: .equal, toItem: activityIndicatorView, attribute: .bottom, multiplier: 1, constant: 8)
containerView.addConstraint(spacingConstraint)
}())
guard let keyWindow = UIApplication.shared.keyWindow else { return }
keyWindow.addSubview(containerView)
state = .showed
// Add constraints for `containerView`.
({
let leadingConstraint = NSLayoutConstraint(item: keyWindow, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: keyWindow, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: keyWindow, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: keyWindow, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: 0)
keyWindow.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])
}())
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(activityData.minimumDisplayTime)) {
self._hide()
}
}
private func _hide() {
if state == .waitingToHide {
hide()
} else if state == .waitingToShow {
state = .hidden
} else if state != .hidden {
state = .waitingToHide
}
}
private func hide() {
guard let keyWindow = UIApplication.shared.keyWindow else { return }
for item in keyWindow.subviews
where item.restorationIdentifier == restorationIdentifier {
item.removeFromSuperview()
}
state = .hidden
}
}
| gpl-3.0 | 1ff0dbe1072c44ef2a7c846ed96c3ee6 | 39.673077 | 189 | 0.679338 | 5.465116 | false | false | false | false |
akosma/Swift-Presentation | PresentationKit/Demos/MathDemo.swift | 1 | 2131 | import Cocoa
typealias ScalarFunction = Double -> Double
typealias Trapezoidal = (Double, Double) -> Double
prefix operator ∑ {}
prefix func ∑ (array: [Double]) -> Double {
var result = 0.0
for value in array {
result += value
}
return result
}
func ~= (left: Double, right: Double) -> Bool {
let ε : Double = 0.001
var δ = left - right
return abs(δ) <= ε
}
// Trapezoidal rule adapted from
// http://www.numericmethod.com/About-numerical-methods/numerical-integration/trapezoidal-rule
prefix operator ∫ {}
prefix func ∫ (𝑓: ScalarFunction) -> Trapezoidal {
return { (min : Double, max : Double) -> (Double) in
let steps = 100
let h = abs(min - max) / Double(steps)
var surfaces : [Double] = []
for position in 0..<steps {
let x1 = min + Double(position) * h
let x2 = x1 + h
let y1 = 𝑓(x1)
let y2 = 𝑓(x2)
let s = (y1 + y2) * h / 2
surfaces.append(s)
}
return ∑surfaces
}
}
public class MathDemo: BaseDemo {
override public var description : String {
return "This demo shows how to use custom operations to represent complex mathematical operations."
}
public override var URL : NSURL {
return NSURL(string: "https://github.com/mattt/Euler")
}
public override func show() {
let π = M_PI
let sum = ∑[1, 2, 3, 5, 8, 13]
// Function taken from the "fast numeric integral" example from
// http://www.codeproject.com/Articles/31550/Fast-Numerical-Integration
func 𝑓 (x: Double) -> Double {
return exp(-x / 5.0) * (2.0 + sin(2.0 * x))
}
let integral = (∫𝑓) (0, 100)
let sinIntegral = ∫sin
let curve1 = sinIntegral(0, π/2)
let curve2 = sinIntegral(0, π)
assert(curve1 ~= 1, "Almost 1")
assert(curve2 ~= 2, "Almost 2")
println("sum: \(sum) – integral: \(integral) – curve1: \(curve1) – curve2: \(curve2)")
}
}
| bsd-2-clause | 6262d6709ba187584b0f81c21ad9b9ab | 27.986111 | 107 | 0.552947 | 3.616984 | false | false | false | false |
jboullianne/EndlessTunes | EndlessSoundFeed/PlaylistSelectionController.swift | 1 | 5763 | //
// PlaylistSelectionController.swift
// EndlessSoundFeed
//
// Created by Jean-Marc Boullianne on 5/17/17.
// Copyright © 2017 Jean-Marc Boullianne. All rights reserved.
//
import UIKit
class PlaylistSelectionController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var manager:AccountManager!
var potentialTrack:Track!
@IBOutlet var albumView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var subtitleLabel: UILabel!
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.manager = AccountManager.sharedInstance
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.tableFooterView = UIView()
albumView.image = potentialTrack.thumbnailImage
albumView.layer.cornerRadius = 3
titleLabel.text = potentialTrack.title
subtitleLabel.text = potentialTrack.author
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return manager.playlists.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PlaylistSelectionCell", for: indexPath)
let index = indexPath.row
cell.textLabel?.text = manager.playlists[index].name
cell.textLabel?.textColor = UIColor.white
cell.detailTextLabel?.text = "\(manager.playlists[index].tracks.count)"
cell.detailTextLabel?.textColor = UIColor.white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let index = indexPath.row
//add track to playlist
self.manager.addTrack(toPlaylist: potentialTrack, index: index)
self.dismiss(animated: true, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func cancelPressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func createNewPressed(_ sender: Any) {
print("Create Playlist")
let ac = UIAlertController(title: "Create Playlist", message: "Enter a name for this new playlist", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Canceled Playlist Creation")
}
let confirmAction = UIAlertAction(title: "Create", style: .default) { (action) in
if let field = ac.textFields?[0]{
//print("NEW PLAYLIST NAME:", field.text)
let manager = AccountManager.sharedInstance
//manager.createNewPlaylist(name: field.text!)
manager.create(newPlaylist: field.text!, withTrack: self.potentialTrack)
self.dismiss(animated: true, completion: nil)
}
}
ac.addTextField { (textfield) in
textfield.placeholder = "Playlist Name"
}
ac.addAction(cancelAction)
ac.addAction(confirmAction)
self.present(ac, animated: true, completion: nil)
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | be2a24ef5460232b9a2d1e4912b06fb7 | 34.349693 | 136 | 0.653593 | 5.286239 | false | false | false | false |
mathewsheets/SwiftLearning | SwiftLearning.playground/Pages/Classes | Structures.xcplaygroundpage/Contents.swift | 1 | 16771 | /*:
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
- - -
# Classes & Structures
* callout(Session Overview): The Swift language features that we learned in the previous sessions dealt with simple data types. We learned about 'Int's, 'String's, 'Bool's that allowed us to store values with the correct data type. We can group a small number of data type values together as an atomic unit using tuples and we can store data type values in containers that will enabled us to collect data throughout our programs. Swift also provides us the ability to extend Swift itself by creating custom data types in the form of Classes and Structures. These custom data types in their simplest form are really composite data types, data types that contain other data types.
- - -
*/
import Foundation
/*:
## Creating
Creating a class or a structure is done with the keywords `class` and `struct`.
*/
class President {
}
struct Term {
}
/*:
Above we created a class `President` and a structure `Term`. Right now they don't store data or have behavior. Throughout this session we will build out what a `President` and `Term` can store the behavior it provides.
*/
/*:
## Types vs. Instances
`President` and `Term` are types. There is only 1 in existence throughout your program. We can create many instances of a `President` or `Term`. Remember the simple data types such as `Int` and `String`? There is only 1 `Int` and 1 `String` data type in Swift, but we can create as many instances as `Int` or `String` that we like.
*/
let president = President()
let term = Term()
/*:
Above we have created instances of type `President` and `Term` into constants. We create `President` and `Term` instance using an initializer `()`.
*/
/*:
## Value Types vs. Reference Types
Value types are data types like `Int` and `String`, their values are copied when either assigned to constancts or variables or passed to functions. Reference types are data type like closures, you are assigning or passing a location pointing to a memory space. Structures are *value types*. Classes are *reference types*. The difference is very important.
*/
/*:
## Properties
Properties enable you to store data within a class or structure. Properties are constants or variables tied to the class/structure (data type) or to an instance of the class/structure.
*/
class President1 {
static var address = "" // stored type property
let country = "United States of America" // stored instance constant property
var name = "" // stored instance variable propery
}
struct Term1 {
static let length = 4 // stored type property
var start: Date? // stored instance variable propery
var end: Date? // stored instance variable propery
}
/*:
Above we created a class `President1` and structure `Term1`, each with a type property and instance properties of a constant and variables. Some properties are initialized and some are optional.
*/
/*:
### Instance Stored Properties
`President1` and `Term1` both have instance stored properties. You can change instance stored properties through out your program for that particular instance.
*/
let president1 = President1()
president1.name = "George Washington"
var term1 = Term1()
term1.start = DateUtils.createDate(year: 1789, month: 4, day: 30)
term1.end = DateUtils.createDate(year: 1797, month: 3, day: 4)
/*:
Above we assign the `president1.name`, `term1.start` and `term1.end` instance stored property.
*/
/*:
### Type Stored Properties
Stored properties that only exist for the class/structure and *not* the instance of a class/structure are type stored properties. You create a type property with the keyword `static`.
*/
President1.address = "1600 Pennsylvania Ave NW, Washington, DC 20500"
let presidentAddress = President1.address
let presidentialLength = Term1.length
/*:
Above we assign the `President1.address` type store property. We are able to do this because it's a variable. The `Term.length` is a constant, therefore we can not assign a new value to it.
*/
//: > **Experiment**: Uncomment below to see what happens.
//president1.country = "South"
//Term1.length = 8
//let term2 = Term1();
//term2.start = nil
/*:
#### Computed Properties
Swift provides properties that look and act like stored properties, but they don't store anything; they derive values or accept values to be stored in a different way. These types of properties are called *computed properties*.
*/
class President3 {
var birthDate: Date?
var deathDate: Date?
var yearsAlive: Int { // computed property with "get", and "set" with custom parameter
get {
guard birthDate != nil && deathDate != nil else {
return 0
}
return DateUtils.yearSpan(from: birthDate!, to: deathDate!)
}
set(years) {
guard birthDate != nil else {
return
}
let dateComps = Calendar.current.dateComponents([.year, .month, .day], from: birthDate!)
deathDate = DateUtils.createDate(year: dateComps.year! + years, month: dateComps.month!, day: dateComps.day!)
}
}
var diedHowLongAgo: Int { // shorthand setter declaration, allowed to omit the (parenthesis and custom parameter name)
get {
guard deathDate != nil else {
return 0
}
return DateUtils.yearSpan(from: deathDate!, to: Date())
}
set { // no custom parameter, 'newValue' is the implicit constant storing the value
let nowComps = Calendar.current.dateComponents([.year, .month, .day], from: Date())
deathDate = DateUtils.createDate(year: nowComps.year! - newValue, month: nowComps.month!, day: nowComps.day! - 1) // subtract 1 so we don't end on same date
}
}
var age: Int { // read-only computed property, allowed to omit the "get"
guard birthDate != nil else {
return 0
}
return DateUtils.yearSpan(from: birthDate!, to: Date())
}
}
let ronald = President3()
ronald.birthDate = DateUtils.createDate(year: 1911, month: 2, day: 6)
ronald.diedHowLongAgo = 11
print("died \(ronald.diedHowLongAgo) years ago")
print("had \(ronald.yearsAlive) years on earth")
print("if alive he would be \(ronald.age) years old")
/*:
Above we created a `President3` class with stored properties of `birthDate` and `deathDate` and computed properties of `yearsAlive`, `diedHowLongAgo`, and `age`. Notice how the computed properteis act like proxies for the stored properties. Also notice how a computed property can be read-only as well as the shorhand version of the `set` for the `diedHowLongAgo` computed property.
*/
/*:
### Property Observers
Swift provides the abiliy to observe changes to properties when values change. The `willSet` method is called just before the property value is set and the `didSet` is called just after the property value is set.
*/
class ElectoralVote {
static let houseVotes = 435
static let senateVotes = 100
static let dictrictOfColumbiaVotes = 3
static let maxElectoralVotes = houseVotes + senateVotes + dictrictOfColumbiaVotes
static let electoralVotesNeedToWin = maxElectoralVotes / 2
var count: Int = 0 {
willSet {
print("About to set vote count to \(newValue)") // 'newValue' is the implicit constant storing the value
}
didSet {
print("You had \(oldValue) votes, now you have \(count)") // 'oldValue' is the implicit constant storing the value
if ElectoralVote.electoralVotesNeedToWin < count {
print("You just won the presidency")
}
}
}
}
print("There are a total of \(ElectoralVote.maxElectoralVotes) electoral votes.")
print("You need more than \(ElectoralVote.electoralVotesNeedToWin) electoral votes to win the presidency.")
let electoralVote = ElectoralVote()
electoralVote.count = 100
electoralVote.count = 270
/*:
Above we have a stored property `count` that is using the property observers of `willSet` and `didSet`. `willSet` provides the special `newValue` constant of *what* the property will change to. `didSet` provides the constant `oldValue` after the property as been changed.
*/
/*:
## Initializing
Initializers on classes and structures are specials methods that initialize the class or structure.
*/
class President4 {
var name = "James Madison"
var state = "Virginia"
var party = "Democratic-Republican"
}
struct Term4 {
var start: Date
var end: Date
}
/*:
### Default Initializer
Both classes and structures data types have default initializers. The default initializer is simply `()`, an empty pair of parentheses.
*/
let president4 = President4()
print(president4.name)
print(president4.state)
print(president4.party)
/*:
Above we create a new instance of class `President4` by using the default initializer of `()`.
*/
/*:
### Structures: Memberwise Initializer
Swift automatically provides structures an initializer with parameters for every variable stored property.
*/
let startTerm4 = DateUtils.createDate(year: 2004, month: 11, day: 2)
let endTerm4 = DateUtils.createDate(year: 2008, month: 11, day: 2)
let term4 = Term4(start: startTerm4!, end: endTerm4!)
/*:
Above we create a new instance of structure `Term4` by using the initializer memberwise initializer.
*/
/*:
## The `self` property and Custom Initializers
Custom initializers are initializers created by you for the purpose of supplying values to a class/structure. You use the argument values of the initializer to set properties. If the argument names are the same as the property names, you can use the implicit `self` property to distinguish between the class/structure and the argument. One important note on custom initializers is that all non-optional stored properties must be initialized.
*/
class President5 {
var name: String
var state: String
var party: String
init(name: String, state: String, party: String) { // initializer to set values using "self"
self.name = name
self.state = state
self.party = party
}
}
struct Term5 {
var start: Date
var end: Date
init(start: Date, end: Date) { // you can have multiple initializers
self.start = start
self.end = end
}
init(start: Date, years: Int) {
let startComps = Calendar.current.dateComponents([.year, .month, .day], from: start)
let end = DateUtils.createDate(year: startComps.year! + years, month: startComps.month!, day: startComps.day!)!
self.init(start: start, end: end) // allowed to call another initialize and need to initialize all non-optional stored properties
}
}
let president5 = President5(name: "James Monroe", state: "Virginia", party: "Democratic-Republican")
let term5_1 = Term5(start: DateUtils.createDate(year: 1817, month: 3, day: 4)!, end: DateUtils.createDate(year: 1825, month: 3, day: 4)!)
let term5_2 = Term5(start: DateUtils.createDate(year: 1817, month: 3, day: 4)!, years: 8)
print(term5_1.start)
print(term5_1.end)
print(term5_2.start)
print(term5_2.end)
/*:
Above we have class `President5` and structure `Term5`, both with custom initializer using `self` inside the initializer.
*/
/*:
## Methods
Methods give you the abiliy to provide behavior to your class/structure. Methods are just like functions, but are tied the class/structure and are able to access properties within the class/structure.
*/
class President6 {
var firstname: String!
var lastname: String!
var street: String!
var city: String!
var state: String!
var zip: String!
// custom initializer
init(firstname: String, lastname: String) {
self.firstname = firstname
self.lastname = lastname
}
// instance method
func getFullname() -> String {
return firstname + " " + lastname
}
// type method
static func buildFullname(firstname: String, lastname: String) -> String {
var fullname = ""
if(!firstname.isEmpty) {
fullname += firstname
}
if(!lastname.isEmpty) {
fullname += " "
fullname += lastname
}
return fullname
}
// type method that can be overridden by a subclass... inheritance not cover yet
class func buildAddress(street: String, city: String, state: String, zip: String) -> String {
var address = ""
if(!street.isEmpty) {
address += street
address += ","
}
if(!city.isEmpty) {
address += "\n"
address += city
address += ","
}
if(!state.isEmpty) {
address += " "
address += state
}
if(!zip.isEmpty) {
address += " "
address += zip
}
return address
}
}
/*:
### Instance Methods
`President6` has 1 instance method. It has access to instance properties.
*/
let president6 = President6(firstname: "John", lastname: "Adams")
print(president6.getFullname())
/*:
Above we assign an instance of `President6` to a constant and print the return of the instance method `getFullname()`.
*/
/*:
### Type Methods
`President6` has 2 type methods. Type methods do not have access to instance properties. You use the name of the class/structure then the method name to call a type method.
*/
president6.street = "1600 Pennsylvania Ave NW"
president6.city = "Washington"
president6.state = "DC"
president6.zip = "20500"
let address = President6.buildAddress(street: president6.street, city: president6.city, state: president6.state, zip: president6.zip)
print("The address of the president is\n\(address)")
let fullname = President6.buildFullname(firstname: president6.firstname, lastname: president6.lastname)
print("The name of the president is \(fullname)")
/*:
Above we call `buildAddress` and `buildFullname` type methods of class `President6` passing in arguments from instance properties.
*/
/*:
### Working with Parameters
Remember that methods are really functions but tied to either a class/structure or an instance of a class/structure and therefore have access to properties. One important note, type properties don't have access to instance properties, but instance properties can access type properties.
*/
class President7 {
var name: String!
var vpName: String!
func setFullname(first firstname: String, last lastname: String) { // shortened argument names
name = firstname + " " + lastname
}
func setVpName(_ firstname: String, _ lastname: String) { // no argument names
vpName = firstname + " " + lastname
}
}
let president7 = President7()
president7.setFullname(first: "Andrew", last: "Jackson")
president7.setVpName("Martin", "Van Buren")
/*:
Above are two methods, each mutating a name, either the president's name or vice president's name. All the rules we learned about functions in the [Functions](Functions) session apply to methods.
*/
/*:
## Deinitialization
Every class/structure has an `init`ializer and also an `deinit`ializer. The only purpose for the deinitializer is to do any cleanup tasks just before the memory of the class/structure becomes unreferencable.
*/
class President10 {
var name: String
init(name: String) {
print("initializing with \(name)")
self.name = name
}
deinit {
print("de-initializing president \(name)")
}
}
var president10: President10?
president10 = President10(name: "John Tyler")
president10 = nil
/*:
Above we have a print statement in the `init` and the `deinit` to show that the `deinit` will get called when the instance is no longer accessible.
*/
/*:
- - -
* callout(Checkpoint): At this point, you should be able to extend the Swift language by providing your own classes or structures and create instances of your class/structure using properties and methods.
- - -
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
*/
| mit | 76b5264afa24ce339a0d597024c90ac2 | 34.607219 | 679 | 0.667462 | 4.389165 | false | false | false | false |
Shashi717/ImmiGuide | ImmiGuide/ImmiGuide/TeamViewController.swift | 1 | 2908 | //
// TeamViewController.swift
// ImmiGuide
//
// Created by Annie Tung on 2/19/17.
// Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved.
//
import UIKit
class TeamViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var teamCollectionView: UICollectionView!
let teamArray = ["Annie Tung","Christopher Chavez", "Eashir Arafat", "Madushani Lekam Wasam Liyanage"]
let titleArray = ["Design Lead", "Project Manager", "Demo Lead", "Technical Lead"]
let teamDict = ["Annie Tung":"https://www.linkedin.com/in/tungannie/", "Christopher Chavez": "https://www.linkedin.com/in/cristopher-chavez-6693b965/", "Eashir Arafat":"https://www.linkedin.com/in/eashirarafat/", "Madushani Lekam Wasam Liyanage":"https://www.linkedin.com/in/madushani-lekam-wasam-liyanage-74319bb5/"]
var selectedTeamMember = ""
override func viewDidLoad() {
super.viewDidLoad()
teamCollectionView.delegate = self
teamCollectionView.dataSource = self
self.navigationItem.titleView = UIImageView(image: UIImage(named: "TeamIcon"))
teamCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "teamCellIdentifier")
let nib = UINib(nibName: "TeamDetailCollectionViewCell", bundle:nil)
teamCollectionView.register(nib, forCellWithReuseIdentifier: "teamCellIdentifier")
}
// MARK: - Collection View Data Source
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return teamArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "teamCellIdentifier", for: indexPath) as! TeamDetailCollectionViewCell
cell.nameLabel.text = teamArray[indexPath.row]
cell.titleLabel.text = titleArray[indexPath.row]
cell.imageView.image = UIImage(named: teamArray[indexPath.row])
cell.setNeedsLayout()
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedTeamMember = teamArray[indexPath.row]
performSegue(withIdentifier: "LinkedInSegue", sender: self)
}
// 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?) {
if segue.identifier == "LinkedInSegue" {
if let cuvc = segue.destination as? ContactUsViewController {
cuvc.url = teamDict[selectedTeamMember]
}
}
}
}
| mit | 747fc050b32c1b1ecd70c0a0e173f704 | 43.723077 | 321 | 0.703474 | 4.804959 | false | false | false | false |
wangyun-hero/sinaweibo-with-swift | sinaweibo/Classes/ViewModel/WYStatusViewModel.swift | 1 | 3216 | //
// WYStatusViewModel.swift
// sinaweibo
//
// Created by 王云 on 16/9/3.
// Copyright © 2016年 王云. All rights reserved.
//
import UIKit
class WYStatusViewModel: NSObject
{
// 当前微博作者的会员图标
var memberImage: UIImage?
// 认证的图标
var avatarImage: UIImage?
// 转发数
var reposts_count: String?
// 评论数量的字符串
var comments_count: String?
// 静态数量的字符串
var attitudes_count: String?
// 转发微博的内容
var retweetStautsText: String?
var status: WYStatus?
{
didSet
{
// 会员图标计算出来
if let mbrank = status?.user?.mbrank, mbrank > 0
{
// 会员图标名字
let imageName = "common_icon_membership_level\(mbrank)"
memberImage = UIImage(named: imageName)
}
// // 认证图标计算 认证类型 -1:没有认证,1:认证用户,2,3,5: 企业认证,220: 达人
if let type = status?.user?.verified_type
{
switch type
{
case 1: // 大v
avatarImage = #imageLiteral(resourceName: "avatar_vip")
case 2, 3, 5: // 企业
avatarImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
case 220: // 达人
avatarImage = #imageLiteral(resourceName: "avatar_grassroot")
default:
break
}
}
// 计算转发,评论,赞数
reposts_count = caclCount(count: status?.reposts_count ?? 0, defaultTitle: "转发")
comments_count = caclCount(count: status?.comments_count ?? 0, defaultTitle: "评论")
attitudes_count = caclCount(count: status?.attitudes_count ?? 0, defaultTitle: "赞")
// 计算转发微博的内容
if let text = status?.retweeted_status?.text, let name = status?.retweeted_status?.user?.name{
retweetStautsText = "@\(name):\(text)"
}
}
}
/// 计算转发评论赞的文字显示内容
///
/// - parameter count: 数量
/// - parameter defaultTitle: 如果数量为0,就返回默认的标题
///
/// - returns: <#return value description#>
private func caclCount(count: Int, defaultTitle: String) -> String
{
if count == 0 {
return defaultTitle
}else{
// 0 - 10000 --> 显示具体的数值
// 10000-11000 --> 1万
// 13000 --> 1.3万
// 20800 2万
if count < 10000 {
return "\(count)"
}else{
// 取到十位数
let result = count / 1000
// 取到小数点后的一位
let str = "\(Float(result) / 10)"
let string = "\(str)万"
// 如果有.0就替换成空字符串
return string.replacingOccurrences(of: ".0", with: "")
}
}
}
}
| mit | b5de13d2530dced4642f8f3211798307 | 27.45 | 106 | 0.475923 | 4.265367 | false | false | false | false |
shopgun/shopgun-ios-sdk | Sources/TjekPublicationViewer/IncitoPublication/IncitoLoaderViewController+v4APILoader.swift | 1 | 6571 | ///
/// Copyright (c) 2020 Tjek. All rights reserved.
///
import Foundation
import Future
@_exported import Incito
#if !COCOAPODS // Cocoapods merges these modules
import TjekAPI
import TjekEventsTracker
import enum TjekUtils.JSONValue
#endif
import UIKit
enum IncitoAPIQueryError: Error {
case invalidData
case notAnIncitoPublication
}
struct IncitoAPIQuery: Encodable {
enum DeviceCategory: String, Encodable {
case mobile
case tablet
case desktop
}
enum Orientation: String, Encodable {
case horizontal
case vertical
}
enum PointerType: String, Encodable {
case fine
case coarse
}
var id: PublicationId
var deviceCategory: DeviceCategory
var orientation: Orientation
var pointer: PointerType
var pixelRatio: Double
var maxWidth: Int
var versionsSupported: [String]
var localeCode: String?
var time: Date?
var featureLabels: [String: Double]
var apiRequest: APIRequest<IncitoDocument, API_v4> {
APIRequest<IncitoDocument, API_v4>(
endpoint: "generate_incito_from_publication",
body: .encodable(self),
decoder: APIRequestDecoder { data, _ in
guard let jsonDict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let jsonStr = String(data: data, encoding: .utf8) else {
throw IncitoAPIQueryError.invalidData
}
return try IncitoDocument(jsonDict: jsonDict, jsonStr: jsonStr)
}
)
}
enum CodingKeys: String, CodingKey {
case id,
deviceCategory = "device_category",
orientation,
pointer,
pixelRatio = "pixel_ratio",
maxWidth = "max_width",
versionsSupported = "versions_supported",
localeCode = "locale_code",
time,
featureLabels = "feature_labels"
}
func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(self.id, forKey: .id)
try c.encode(self.deviceCategory, forKey: .deviceCategory)
try c.encode(self.orientation, forKey: .orientation)
try c.encode(self.pointer, forKey: .pointer)
try c.encode(self.pixelRatio, forKey: .pixelRatio)
try c.encode(self.maxWidth, forKey: .maxWidth)
try c.encode(self.versionsSupported, forKey: .versionsSupported)
try c.encode(self.localeCode, forKey: .localeCode)
try c.encode(self.time, forKey: .time)
let features: [[String: JSONValue]] = self.featureLabels.map({ ["key": $0.jsonValue, "value": $1.jsonValue] })
try c.encode(features, forKey: .featureLabels)
}
}
extension IncitoAPIQuery.DeviceCategory {
init(device: UIDevice) {
switch device.userInterfaceIdiom {
case .pad:
self = .tablet
default:
self = .mobile
}
}
}
extension IncitoLoaderViewController {
public func load(
publicationId: PublicationId,
featureLabelWeights: [String: Double] = [:],
apiClient: TjekAPI = .shared,
publicationLoaded: ((Result<Publication_v2, Error>) -> Void)? = nil,
completion: ((Result<(viewController: IncitoViewController, firstSuccessfulLoad: Bool), Error>) -> Void)? = nil
) {
var hasLoadedIncito: Bool = false
if TjekEventsTracker.isInitialized {
TjekEventsTracker.shared.trackEvent(
.incitoPublicationOpened(publicationId)
)
}
if let publicationLoadedCallback = publicationLoaded {
apiClient.send(.getPublication(withId: publicationId))
.eraseToAnyError()
.run(publicationLoadedCallback)
}
let loader = IncitoLoader { [weak self] callback in
Future<IncitoAPIQuery>(work: { [weak self] in
let viewWidth = Int(self?.view.frame.size.width ?? 0)
let windowWidth = Int(self?.view.window?.frame.size.width ?? 0)
let screenWidth = Int(UIScreen.main.bounds.size.width)
let minWidth = 100
// build the query on the main queue.
return IncitoAPIQuery(
id: publicationId,
deviceCategory: .init(device: .current),
orientation: .vertical,
pointer: .coarse,
pixelRatio: Double(UIScreen.main.scale),
maxWidth: max(viewWidth >= minWidth ? viewWidth : windowWidth >= minWidth ? windowWidth : screenWidth, minWidth),
versionsSupported: IncitoEnvironment.supportedVersions,
localeCode: Locale.autoupdatingCurrent.identifier,
time: Date(),
featureLabels: featureLabelWeights
)
})
.performing(on: .main)
.flatMap({ query in apiClient.send(query.apiRequest) })
.eraseToAnyError()
// .measure(print: " 🌈 Incito Fully Loaded")
.run(callback)
}
self.load(loader) { vcResult in
switch vcResult {
case let .success(viewController):
let firstLoad = !hasLoadedIncito
hasLoadedIncito = true
completion?(.success((viewController, firstLoad)))
case let .failure(error):
completion?(.failure(error))
}
}
}
public func load(
publication: Publication_v2,
featureLabelWeights: [String: Double] = [:],
apiClient: TjekAPI = .shared,
completion: ((Result<(viewController: IncitoViewController, firstSuccessfulLoad: Bool), Error>) -> Void)? = nil
) {
// if the publication doesnt have a graphId, then just eject with an error
guard publication.hasIncitoPublication else {
self.load(IncitoLoader(load: { cb in cb(.failure(IncitoAPIQueryError.notAnIncitoPublication)) })) { vcResult in
completion?(vcResult.map({ ($0, false) }))
}
return
}
self.load(
publicationId: publication.id,
featureLabelWeights: featureLabelWeights,
apiClient: apiClient,
completion: completion
)
}
}
| mit | bd19e7432916f67ee7f66346ed7bc814 | 33.93617 | 133 | 0.580847 | 4.956981 | false | false | false | false |
marty-suzuki/QiitaWithFluxSample | QiitaWithFluxSample/Source/Search/Model/SearchTopViewModel.swift | 1 | 5727 | //
// SearchTopViewModel.swift
// QiitaWithFluxSample
//
// Created by marty-suzuki on 2017/04/16.
// Copyright © 2017年 marty-suzuki. All rights reserved.
//
import RxSwift
import RxCocoa
import Action
import QiitaSession
final class SearchTopViewModel {
private let session: QiitaSessionType
private let routeAction: RouteAction
private let applicationAction: ApplicationAction
let lastItemsRequest: Property<ItemsRequest?>
private let _lastItemsRequest = Variable<ItemsRequest?>(nil)
let items: Property<[Item]>
private let _items = Variable<[Item]>([])
let totalCount: Property<Int>
private let _totalCount = Variable<Int>(0)
let error: Property<Error?>
private let _error = Variable<Error?>(nil)
let hasNext: Property<Bool>
private let _hasNext = Variable<Bool>(true)
let searchAction: Action<ItemsRequest, ElementsResponse<Item>>
private let perPage: Int = 20
private let disposeBag = DisposeBag()
let noResult: Observable<Bool>
let reloadData: Observable<Void>
let isFirstLoading: Observable<Bool>
let keyboardWillShow: Observable<UIKeyboardInfo>
let keyboardWillHide: Observable<UIKeyboardInfo>
init(session: QiitaSessionType = QiitaSession.shared,
routeAction: RouteAction = .shared,
applicationAction: ApplicationAction = .shared,
selectedIndexPath: Observable<IndexPath>,
searchText: ControlProperty<String>,
deleteButtonTap: ControlEvent<Void>,
reachedBottom: Observable<Void>) {
self.session = session
self.routeAction = routeAction
self.applicationAction = applicationAction
self.lastItemsRequest = Property(_lastItemsRequest)
self.items = Property(_items)
self.error = Property(_error)
self.totalCount = Property(_totalCount)
self.hasNext = Property(_hasNext)
self.searchAction = Action { [weak session] request -> Observable<ElementsResponse<Item>> in
session.map { $0.send(request) } ?? .empty()
}
let itemsObservable = items.changed
self.noResult = Observable.combineLatest(itemsObservable,
searchAction.executing)
.map { !$0.isEmpty || $1 }
let hasNextObservable = hasNext.changed
self.reloadData = Observable.combineLatest(itemsObservable,
hasNextObservable)
.map { _ in }
self.isFirstLoading = Observable.combineLatest(itemsObservable,
hasNextObservable,
lastItemsRequest.changed)
.map { $0.0.isEmpty && $0.1 && $0.2 != nil }
self.keyboardWillShow = NotificationCenter.default.rx.notification(.UIKeyboardWillShow)
.map { $0.userInfo }
.filterNil()
.map { UIKeyboardInfo(info: $0) }
.filterNil()
self.keyboardWillHide = NotificationCenter.default.rx.notification(.UIKeyboardWillHide)
.map { $0.userInfo }
.filterNil()
.map { UIKeyboardInfo(info: $0) }
.filterNil()
selectedIndexPath
.withLatestFrom(_items.asObservable()) { $1[$0.row] }
.map { $0.url }
.subscribe(onNext: { [weak routeAction] in
routeAction?.show(searchDisplayType: .webView($0))
})
.disposed(by: disposeBag)
searchAction.elements
.subscribe(onNext: { [weak self] response in
guard let me = self else { return }
me._items.value.append(contentsOf: response.elements)
me._totalCount.value = response.totalCount
me._hasNext.value = (me._items.value.count < me._totalCount.value) && !response.elements.isEmpty
})
.disposed(by: disposeBag)
searchAction.errors
.map { Optional($0) }
.bind(to: _error)
.disposed(by: disposeBag)
deleteButtonTap
.subscribe(onNext: { [weak applicationAction] in
applicationAction?.removeAccessToken()
})
.disposed(by: disposeBag)
let firstLoad = searchText
.debounce(0.3, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.do(onNext: { [weak self] _ in
self?._lastItemsRequest.value = nil
self?._items.value.removeAll()
self?._hasNext.value = true
})
.filter { !$0.isEmpty }
.map { ($0, 1) }
let loadMore = reachedBottom
.withLatestFrom(hasNext.asObservable())
.filter { $0 }
.withLatestFrom(lastItemsRequest.asObservable())
.filterNil()
.map { ($0.query, $0.page + 1) }
Observable.merge(firstLoad, loadMore)
.flatMap { [weak self] query, page -> Observable<ItemsRequest> in
self.map { .just(ItemsRequest(page: page, perPage: $0.perPage, query: query)) } ?? .empty()
}
.bind(to: _lastItemsRequest)
.disposed(by: disposeBag)
_lastItemsRequest.asObservable()
.filterNil()
.distinctUntilChanged { $0.page == $1.page && $0.query == $1.query }
.subscribe(onNext: { [weak self] request in
self?.searchAction.execute(request)
})
.disposed(by: disposeBag)
}
}
| mit | f6671c86539ad144b31e5556da303140 | 36.411765 | 112 | 0.571104 | 5.069973 | false | false | false | false |
CrazyKids/ADSideMenu | ADSideMenuSample/ADSideMenuSample/Controllers/ADRightMenuViewController.swift | 1 | 1346 | //
// ADRightMenuViewController.swift
// ADSideMenuSample
//
// Created by duanhongjin on 16/6/17.
// Copyright © 2016年 CrazyKids. All rights reserved.
//
import UIKit
class ADRightMenuViewController: UIViewController, UITableViewDataSource {
var tableView: UITableView?
let tableData = ["小明", "小红", "小兰", "小邓"]
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds)
tableView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView?.dataSource = self
// tableView?.backgroundColor = UIColor.clearColor()
tableView?.tableFooterView = UIView(frame: CGRect.zero)
tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView!)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
cell.selectionStyle = .none
cell.textLabel?.text = tableData[indexPath.row]
cell.textLabel?.textAlignment = .right
return cell
}
}
| mit | 0a995eca6d1f2f93ffc6d215ebedd858 | 30.595238 | 100 | 0.669179 | 4.933086 | false | false | false | false |
shaps80/Stack | Pod/Classes/Transaction.swift | 1 | 4650 | /*
Copyright © 2015 Shaps Mohsenin. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY SHAPS MOHSENIN `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 APP BUSINESS 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 CoreData
/// A transaction provides a type-safe implementation for performing any write action to CoreData
public class Transaction: Readable, Writable {
/// Returns the stack associated with this transaction
private(set) var stack: Stack
/// Returns the context associated with this transaction
private(set) var context: NSManagedObjectContext
/**
Internal: Initializes a new transaction for the specified Stack
- parameter stack: The stack this transaction will be applied to
- parameter context: The context this transaction will be applied to
- returns: A new Transaction
*/
init(stack: Stack, context: NSManagedObjectContext) {
self.stack = stack
self.context = context
}
/**
Inserts a new entity of the specified class. Usage: `insert() as EntityName`
*/
public func insert<T: NSManagedObject>() throws -> T {
guard let entityName = stack.entityNameForManagedObjectClass(T) where entityName != NSStringFromClass(NSManagedObject) else {
throw StackError.EntityNameNotFoundForClass(T)
}
guard let object = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as? T else {
throw StackError.EntityNotFoundInStack(stack, entityName)
}
return object as T
}
/**
Fetches (or inserts if not found) an entity with the specified identifier
*/
public func fetchOrInsert<T: NSManagedObject, U: StackManagedKey>(key: String, identifier: U) throws -> T {
let results = try fetchOrInsert(key, identifiers: [identifier]) as [T]
return results.first!
}
/**
Fetches (or inserts if not found) entities with the specified identifiers
*/
public func fetchOrInsert<T : NSManagedObject, U : StackManagedKey>(key: String, identifiers: [U]) throws -> [T] {
let query = Query<T>(key: key, identifiers: identifiers)
let request = try fetchRequest(query)
guard let results = try context.executeFetchRequest(request) as? [T] else {
throw StackError.FetchError(nil)
}
if results.count == identifiers.count {
return results
}
var objects = [T]()
if let existingIds = (results as NSArray).valueForKey(key) as? [U] {
for id in identifiers {
if !existingIds.contains(id) {
let result = try insert() as T
result.setValue(id, forKeyPath: key)
objects.append(result)
}
}
}
return objects as [T]
}
/**
Performs a fetch using the specified NSManagedObjectID
- parameter objectID: The objectID to use for this fetch
- throws: An error will be thrown if the query cannot be performed
- returns: The resulting object or nil
*/
public func fetch<T: NSManagedObject>(objectWithID objectID: NSManagedObjectID) throws -> T? {
let stack = _stack()
let context = stack.currentThreadContext()
return try context.existingObjectWithID(objectID) as? T
}
/**
Deletes the specified objects
*/
public func delete<T: NSManagedObject>(objects: T...) throws {
try delete(objects: objects)
}
/**
Deletes the specified objects
*/
public func delete<T: NSManagedObject>(objects objects: [T]) throws {
for object in objects {
context.deleteObject(object)
}
}
}
| mit | eadf35c3489608dbfe4368515989d4c0 | 33.437037 | 132 | 0.71069 | 4.79773 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.