repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PiHanHsu/myscorebaord_lite
|
refs/heads/master
|
myscoreboard_lite/Protocol/RoundedView.swift
|
mit
|
1
|
//
// RoundedView.swift
// myscoreboard_lite
//
// Created by PiHan on 2017/10/10.
// Copyright © 2017年 PiHan. All rights reserved.
//
import Foundation
import UIKit
protocol RoundedView {}
extension RoundedView where Self: UIView {
func roundedView() {
if (self.frame.size.height != self.frame.size.width){
self.frame.size.height = min(self.frame.size.height, self.frame.size.width)
self.frame.size.width = min(self.frame.size.height, self.frame.size.width)
}
layer.cornerRadius = layer.frame.size.height * 0.5
self.clipsToBounds = true
self.contentMode = .scaleAspectFill
}
}
extension UIImageView: RoundedView{}
|
1b7489430395a7ba04ae376f65e36181
| 25.730769 | 87 | 0.669065 | false | false | false | false |
Barry-Wang/iOS-Animation-Guide-Swift
|
refs/heads/master
|
AnimationGuide1-circle/AnimationGuide/YMCircleLayer.swift
|
apache-2.0
|
1
|
//
// YMCircleLayer.swift
// AnimationGuide
//
// Created by barryclass on 15/11/13.
// Copyright © 2015年 barry. All rights reserved.
//
import UIKit
enum MovePoint {
// 连接点 A B C D 生成一个圆, Move_B 表示向左移动,移动B点
case Move_B, Move_D
}
let OutSideRectSize:CGFloat = 120
class YMCircleLayer: CALayer {
var outSideRect = CGRectZero
var movePoint:MovePoint = MovePoint.Move_B
var progress:Float = 0.5{
didSet {
let paddingWidth:CGFloat = (self.bounds.size.width - OutSideRectSize) / 2
self.outSideRect = CGRectMake( (self.position.x - OutSideRectSize / 2) + CGFloat(progress - 0.5) * paddingWidth, self.position.y - OutSideRectSize / 2, OutSideRectSize, OutSideRectSize)
if progress > 0.5 {
self.movePoint = MovePoint.Move_B
} else {
self.movePoint = MovePoint.Move_D
}
// CALayer在第一次出现的时候不会主动调用 drawInContext
self.setNeedsDisplay()
}
}
override func drawInContext(ctx: CGContext) {
//画最外面的正方形,在这个正方形里面画圆
CGContextSetLineWidth(ctx, 5)
CGContextSetStrokeColorWithColor(ctx, UIColor.greenColor().CGColor)
// 设置为虚线模式
CGContextSetLineDash(ctx, 0, [3,3], 2)
CGContextStrokeRect(ctx, self.outSideRect)
CGContextStrokePath(ctx)
CGContextSetStrokeColorWithColor(ctx, UIColor.yellowColor().CGColor)
// offset, moveDistance 都是些经验值
let offset = OutSideRectSize / 3.6
let moveDistance = (self.outSideRect.width * 1 / 6) * CGFloat(fabs(self.progress - 0.5) * 2)
let rectCenter = CGPointMake(self.outSideRect.origin.x + OutSideRectSize / 2, self.outSideRect.origin.y + OutSideRectSize / 2)
let point_A = CGPointMake(rectCenter.x, self.outSideRect.origin.y + moveDistance)
// 当向左移动时,使B的x坐标增加,使其成近似椭圆状
let point_B = CGPointMake(self.movePoint == MovePoint.Move_B ? rectCenter.x + OutSideRectSize / 2 + moveDistance * 2 : rectCenter.x + OutSideRectSize / 2, rectCenter.y)
let point_C = CGPointMake(rectCenter.x, rectCenter.y + OutSideRectSize / 2 - moveDistance)
let point_D = CGPointMake(self.movePoint == MovePoint.Move_D ? self.outSideRect.origin.x - moveDistance * 2 : self.outSideRect.origin.x, rectCenter.y)
// let rectBizerpath = UIBezierPath()
// rectBizerpath.moveToPoint(point_A)
// rectBizerpath.addLineToPoint(point_B)
// rectBizerpath.addLineToPoint(point_C)
// rectBizerpath.addLineToPoint(point_D)
// rectBizerpath.closePath()
// CGContextAddPath(ctx, rectBizerpath.CGPath)
// CGContextStrokePath(ctx)
// 合成贝塞尔曲线所需要的控制点
let point_AB1 = CGPointMake(point_A.x + offset, point_A.y)
//判断控制点的位置使其形状变化更加真实
let point_AB2 = CGPointMake(point_B.x, self.movePoint == MovePoint.Move_B ? point_B.y - offset + moveDistance : point_B.y - offset)
let point_BC1 = CGPointMake(point_B.x, self.movePoint == MovePoint.Move_B ? point_B.y + offset - moveDistance : point_B.y + offset)
let point_BC2 = CGPointMake(point_C.x + offset, point_C.y)
let point_CD1 = CGPointMake(point_C.x - offset, point_C.y)
let point_CD2 = CGPointMake(point_D.x, self.movePoint == MovePoint.Move_D ? point_D.y + offset - moveDistance : point_D.y + offset)
let point_DA1 = CGPointMake(point_D.x, self.movePoint == MovePoint.Move_D ? point_D.y - offset + moveDistance : point_D.y - offset )
let point_DA2 = CGPointMake(point_A.x - offset, point_A.y)
let circlePath = UIBezierPath()
CGContextSetLineDash(ctx, 0, nil, 0)
CGContextSetStrokeColorWithColor(ctx, UIColor.purpleColor().CGColor)
circlePath.moveToPoint(point_A)
circlePath.addCurveToPoint(point_B, controlPoint1: point_AB1, controlPoint2: point_AB2)
circlePath.addCurveToPoint(point_C, controlPoint1: point_BC1, controlPoint2: point_BC2)
circlePath.addCurveToPoint(point_D, controlPoint1: point_CD1, controlPoint2: point_CD2)
circlePath.addCurveToPoint(point_A, controlPoint1: point_DA1, controlPoint2: point_DA2)
CGContextSetStrokeColorWithColor(ctx, UIColor.whiteColor().CGColor)
CGContextSetFillColorWithColor(ctx, UIColor.orangeColor().CGColor)
CGContextAddPath(ctx, circlePath.CGPath)
CGContextDrawPath(ctx, CGPathDrawingMode.EOFillStroke)
}
}
|
239ab211a71f246f27e0f91a56970d4f
| 40.558559 | 197 | 0.643616 | false | false | false | false |
terietor/GTForms
|
refs/heads/master
|
Source/Forms/TextFields/TextFieldView.swift
|
mit
|
1
|
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SnapKit
protocol FormTextFieldViewType {
var textFieldViewType: TextFieldViewType { get }
}
protocol TextFieldViewType: class {
var textField: UITextField { get }
weak var delegate: TextFieldViewDelegate? { get set }
}
protocol TextFieldViewDelegate: class {
func textFieldViewShouldReturn(
_ textFieldView: TextFieldViewType
) -> Bool
}
class TextFieldView<T: UITextField, L: UILabel> :
ControlLabelView<L>,
TextFieldViewType,
UITextFieldDelegate
{
override var formAxis: FormAxis {
didSet { configureUI() }
}
var textField: UITextField {
return self.field
}
lazy private(set) var field: T = {
let textField = T()
textField.addTarget(
self,
action: #selector(editingChanged),
for: .editingChanged
)
textField.borderStyle = .none
textField.delegate = self
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
var textWillChange: ((_ text: String) -> (Bool))?
var textDidChange: ((_ text: String) -> ())?
var didPressReturnButton: (() -> ())?
weak var delegate: TextFieldViewDelegate?
override init() {
super.init()
self.control = self.field
configureUI()
}
private func configureUI() {
configureView() { (label, control) in
if self.formAxis == .horizontal {
label.snp.remakeConstraints() { make in
make.left.equalTo(self)
make.top.equalTo(self)
make.width.equalTo(self).multipliedBy(0.3)
make.bottom.equalTo(self)
} // end label
control.snp.remakeConstraints() { make in
make.left.equalTo(label.snp.right).offset(10)
make.right.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self)
} // end control
} else {
label.snp.remakeConstraints() { make in
make.top.equalTo(self)
make.leading.equalTo(self).offset(10)
make.trailing.equalTo(self).offset(-10)
}
control.snp.remakeConstraints() { make in
make.top.equalTo(label.snp.bottom).offset(10)
make.bottom.equalTo(self)
make.leading.equalTo(self).offset(10)
make.trailing.equalTo(self).offset(-10)
}
}
} // end configureView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func editingChanged() {
guard let
text = self.field.text
else { return }
self.textDidChange?(text)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let delegate = self.delegate else {
print("\(#file):\(#line): Missing Delegate!!")
return false
}
if !delegate.textFieldViewShouldReturn(self) {
textField.resignFirstResponder()
}
return false
}
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
guard let
textWillChange = self.textWillChange
else { return true }
return textWillChange(string)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.didPressReturnButton?()
}
}
|
422c07ba438eca61d97ddc97bd7ff398
| 30.343949 | 82 | 0.603536 | false | false | false | false |
richardpiazza/GraphPoint
|
refs/heads/main
|
Sources/GraphPoint/CartesianPoint.swift
|
mit
|
1
|
import Foundation
import Swift2D
/// A point within a `CartesianPlane`
///
/// The x & y coordinates of a `CartesianPoint` represent the offset from the planes 'origin' {0, 0}.
///
/// ## Example
///
/// ```swift
/// let plane = CartesianPlane(size: Size(width: 100, height: 100))
/// // plane.cartesianOrigin == Point(x: 50, y: 50)
/// let point1 = Point(x: 75, y: 25)
/// let cartesianPoint1 = CartesianPoint(x: 25, y: 25)
/// // point1 == cartesianPoint1
/// let point2 = Point(x: 25, y: 75)
/// let cartesianPoint2 = CartesianPoint(x: -25, y: -25)
/// // point2 == cartesianPoint2
/// ```
public typealias CartesianPoint = Point
public extension CartesianPoint {
/// The minimum axis for a `CartesianPlane` that would contain this point.
var minimumAxis: Double {
return max(abs(x), abs(y))
}
}
public extension CartesianPoint {
/// Calculates the `CartesianPoint` for a given degree and radius from the _origin_.
///
/// Uses the mathematical **Law of Sines**.
///
/// - parameters:
/// - radius: The straight line distance from the _origin_.
/// - degree: The angular degree (0-360), clockwise from the x-axis.
/// - returns:A `CartesianPoint` with offsets from the _origin_.
static func make(for radius: Radius, degree: Degree, clockwise: Bool = true) throws -> CartesianPoint {
guard degree >= 0.0, degree <= 360.0 else {
throw GraphPointError.invalidDegree(degree)
}
guard radius >= 0.0 else {
throw GraphPointError.invalidRadius(radius)
}
guard radius > 0.0 else {
return .zero
}
let rightAngle: Double = 90.0
let sinRight = sin(rightAngle.radians)
var rise: Double = 0.0
var run: Double = 0.0
var point: CartesianPoint = .zero
switch clockwise {
case true:
if degree > 315 {
rise = 360.0 - degree
run = 180.0 - rightAngle - rise
point.x = (radius / sinRight) * sin(run.radians)
point.y = (radius / sinRight) * sin(rise.radians)
} else if degree > 270 {
run = degree - 270.0
rise = 180.0 - rightAngle - run
point.x = (radius / sinRight) * sin(run.radians)
point.y = (radius / sinRight) * sin(rise.radians)
} else if degree > 225 {
run = 270.0 - degree
rise = 180.0 - rightAngle - run
point.x = -1.0 * (radius / sinRight) * sin(run.radians)
point.y = (radius / sinRight) * sin(rise.radians)
} else if degree > 180 {
rise = degree - 180.0
run = 180.0 - rightAngle - rise
point.x = -1.0 * (radius / sinRight) * sin(run.radians)
point.y = (radius / sinRight) * sin(rise.radians)
} else if degree > 135 {
rise = 180.0 - degree
run = 180.0 - rightAngle - rise
point.x = -1.0 * (radius / sinRight) * sin(run.radians)
point.y = -1.0 * (radius / sinRight) * sin(rise.radians)
} else if degree > 90 {
run = degree - 90.0
rise = 180.0 - rightAngle - run
point.x = -1.0 * (radius / sinRight) * sin(run.radians)
point.y = -1.0 * (radius / sinRight) * sin(rise.radians)
} else if degree > 45 {
run = 90.0 - degree
rise = 180.0 - rightAngle - run
point.x = (radius / sinRight) * sin(run.radians)
point.y = -1.0 * (radius / sinRight) * sin(rise.radians)
} else if degree >= 0 {
rise = degree
run = 180.0 - rightAngle - rise
point.x = (radius / sinRight) * sin(run.radians)
point.y = -1.0 * (radius / sinRight) * sin(rise.radians)
}
case false:
// TODO: Handled anti-clockwise
break
}
return point
}
/// Calculates the `CartesianPoint` for a given degree and radius from the _origin_ limited by another point.
///
/// Uses the **Pythagorean Theorem** to solve for the intercept:
/// * **c**: calculated based on `degree` and `radius`.
/// * **a**: supplied via the `point` (x/y based on closest axis)
///
/// - parameters:
/// - radius: The straight line distance from the _origin_.
/// - degree: The angular degree (0-360), clockwise from the x-axis.
/// - modifier: The point used to clip or expand the result. The nearest axis value is used.
static func make(for radius: Radius, degree: Degree, modifier: CartesianPoint, clockwise: Bool = true) throws -> CartesianPoint {
guard degree >= 0.0, degree <= 360.0 else {
throw GraphPointError.invalidDegree(degree)
}
guard radius >= 0.0 else {
throw GraphPointError.invalidRadius(radius)
}
guard radius > 0.0 else {
return .zero
}
var point = CartesianPoint()
switch clockwise {
case true:
if (degree >= 315) {
point.x = sqrt(pow(radius, 2) - pow(modifier.y, 2))
point.y = modifier.y
} else if (degree >= 270) {
point.x = modifier.x
point.y = sqrt(pow(radius, 2) - pow(modifier.x, 2))
} else if (degree >= 225) {
point.x = modifier.x
point.y = sqrt(pow(radius, 2) - pow(modifier.x, 2))
} else if (degree >= 180) {
point.x = -(sqrt(pow(radius, 2) - pow(modifier.y, 2)))
point.y = modifier.y
} else if (degree >= 135) {
point.x = -(sqrt(pow(radius, 2) - pow(modifier.y, 2)))
point.y = modifier.y
} else if (degree >= 90) {
point.x = modifier.x
point.y = -(sqrt(pow(radius, 2) - pow(modifier.x, 2)))
} else if (degree >= 45) {
point.x = modifier.x
point.y = -(sqrt(pow(radius, 2) - pow(modifier.x, 2)))
} else if (degree >= 0) {
point.x = sqrt(pow(radius, 2) - pow(modifier.y, 2))
point.y = modifier.y
}
case false:
//TODO: Determine if calculations should be modified.
break
}
return point
}
}
|
a61711319a2037a001dc65b76ab72321
| 38.383234 | 133 | 0.512544 | false | false | false | false |
v2panda/DaysofSwift
|
refs/heads/master
|
swift2.3/My-CarouselEffect/Interest.swift
|
mit
|
1
|
//
// Interest.swift
// My-CarouselEffect
//
// Created by Panda on 16/2/22.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
class Interest {
// MARK: - Public API
var title = ""
var description = ""
var numberOfMembers = 0
var numberOfPosts = 0
var featuredImage : UIImage!
init(title : String, description : String, featuredImage : UIImage!){
self.title = title
self.description = description
self.featuredImage = featuredImage
numberOfMembers = 1
numberOfPosts = 1
}
// MARK: - Private
// dummy data
static func createInterests() -> [Interest]{
return [
Interest(title: "Hello there, i miss you", description: "We love backpack and adventures! We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "hello")),
Interest(title: "🐳🐳🐳🐳🐳", description: "We love romantic stories. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "dudu")!),
Interest(title: "Training like this, #bodyline", description: "Create beautiful apps. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "bodyline")!),
Interest(title: "I'm hungry, indeed.", description: "Cars and aircrafts and boats and sky. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "wave")!),
Interest(title: "Dark Varder, #emoji", description: "Meet life with full presence. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "darkvarder")!),
Interest(title: "I have no idea, bitch", description: "Get up to date with breaking-news. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. 🐧⛺️✨", featuredImage: UIImage(named: "hhhhh")!),
]
}
}
|
c6bd4bf139df0e72efc66fb9aaa53ffc
| 50.840909 | 263 | 0.672807 | false | false | false | false |
wibosco/ASOS-Consumer
|
refs/heads/master
|
ASOSConsumer/ViewControllers/Category/CategoryViewController.swift
|
mit
|
1
|
//
// CategoryViewController.swift
// ASOSConsumer
//
// Created by William Boles on 02/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
import PureLayout
class CategoryViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, ProductCollectionViewCellDelegate {
//MARK: - Accessors
var category : Category? {
didSet {
self.categoryLabel.text = self.category?.title
self.refresh(self.category!)
}
}
var categoryProducts: Array<CategoryProduct>?
private lazy var categoryLabel: UILabel = {
let categoryLabel = UILabel.newAutoLayoutView()
categoryLabel.textAlignment = NSTextAlignment.Center
categoryLabel.backgroundColor = UIColor.lightGrayColor()
return categoryLabel
}()
private lazy var collectionView: UICollectionView = {
let verticalPadding: CGFloat = 8.0
let hozitionalPadding: CGFloat = 10.0
let scalingFactor: CGFloat = 0.87
let cellWidth = (self.view.frame.size.width - (hozitionalPadding * 4)) / 2
let cellHeight = cellWidth * scalingFactor
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: verticalPadding, left: hozitionalPadding, bottom: verticalPadding, right: hozitionalPadding)
layout.itemSize = CGSize(width: cellWidth, height: cellHeight)
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(ProductCollectionViewCell.self, forCellWithReuseIdentifier: ProductCollectionViewCell.reuseIdentifier())
return collectionView
}()
private lazy var loadingView: LoadingView = {
let loadingView = LoadingView.init(frame: self.view.frame)
return loadingView
}()
//MARK: - ViewLifecycle
override func viewDidLoad() {
super.viewDidLoad()
/*-----------------*/
self.view.addSubview(self.collectionView)
self.view.addSubview(self.categoryLabel)
}
//MARK: - Constraints
override func updateViewConstraints() {
self.categoryLabel.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view)
self.categoryLabel.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Top, ofView: self.view, withOffset: 44.0)
self.categoryLabel.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view)
self.categoryLabel.autoSetDimension(ALDimension.Height, toSize: 20.0)
/*-----------------*/
self.collectionView.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.view)
self.collectionView.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: self.categoryLabel, withOffset: -44.0)
self.collectionView.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.view)
self.collectionView.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Bottom, ofView: self.view)
/*-----------------*/
super.updateViewConstraints()
}
//MARK: - DataRetrieval
private func refresh(category: Category) {
self.view.addSubview(self.loadingView)
CategoryProductsAPIManager.retrieveCategoryProducts(category) {[weak self] (category, categoryProducts) -> Void in
if let strongSelf = self {
if (category.isEqual(strongSelf.category)) {
strongSelf.categoryProducts = categoryProducts
strongSelf.collectionView.reloadData()
strongSelf.loadingView.removeFromSuperview()
}
}
}
}
//MARK: - UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numberOfItemsInSection = 0
if (self.categoryProducts != nil) {
numberOfItemsInSection = self.categoryProducts!.count
}
return numberOfItemsInSection
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ProductCollectionViewCell.reuseIdentifier(), forIndexPath: indexPath) as! ProductCollectionViewCell
let categoryProduct = self.categoryProducts![indexPath.row]
cell.productPriceLabel.text = categoryProduct.displayPrice!
cell.favourited = SessionManager.sharedInstance.isFavourited(categoryProduct)
cell.delegate = self
let preview = categoryProduct.preview!
MediaAPIManager.retrieveMediaAsset(preview) { (media, mediaImage) -> Void in
if (preview.isEqual(media)) {
cell.productImageView.image = mediaImage
}
}
return cell
}
//MARK: - UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let categoryProduct = self.categoryProducts![indexPath.row]
let productViewController = ProductViewController.init(categoryProduct: categoryProduct)
self.navigationController?.pushViewController(productViewController, animated: true)
}
//MARK: - ProductCollectionViewCellDelegate
func didDoubleTapOnProduct(sender: ProductCollectionViewCell) {
let indexPath = self.collectionView.indexPathForCell(sender)
let categoryProduct = self.categoryProducts![indexPath!.row]
if (SessionManager.sharedInstance.isFavourited(categoryProduct)) {
let indexOfCategoryProduct = SessionManager.sharedInstance.favouriteProducts.indexOf(categoryProduct)
SessionManager.sharedInstance.favouriteProducts.removeAtIndex(indexOfCategoryProduct!)
} else {
SessionManager.sharedInstance.favouriteProducts.append(categoryProduct)
}
}
}
|
49c3310fc96ec0e39fe7023c1a7599a5
| 36.465517 | 172 | 0.65823 | false | false | false | false |
HaloWang/FangYuan
|
refs/heads/master
|
FangYuan/ConstraintManager.swift
|
mit
|
1
|
//
// ConstraintManager.swift
// FangYuan
//
// Created by 王策 on 16/5/6.
// Copyright © 2016年 WangCe. All rights reserved.
//
import UIKit
// MARK: - Init & Properties
/// 约束依赖管理者
class ConstraintManager {
fileprivate init() {}
static let singleton = ConstraintManager()
var holder = ConstraintHolder()
/// - Todo: 重要的还是做到按照 superview 分组遍历以提高性能
/// - Todo: 有没有集散型的并发遍历?
/// 还没有被赋值到 UIView.Ruler 上的约束
var unsetConstraints = Set<Constraint>()
/// 已经被设定好的,存储起来的约束,用于以后抽取出来再次使用
var storedConstraints = Set<Constraint>()
}
// MARK: - Public Methods
extension ConstraintManager {
/**
从某个视图得到约束
- parameter from: 约束依赖视图
- parameter section: 约束区间
*/
class func pushConstraintFrom(_ from:UIView, section: Constraint.Section) {
assert(!Thread.isMainThread, _fy_noMainQueueAssert)
let newConstraint = Constraint(from: from, to: nil, section: section)
singleton.holder.set(newConstraint, at: section)
}
/// - Todo: setConstraint 是生成『渲染队列』的最佳时机了吧
/// - Todo: 这个『渲染队列』还可以抽象成一个专门计算高度的类方法?
/**
设定约束到某个视图上
- parameter to: 约束目标
- parameter section: 约束区间
- parameter value: 约束固定值
*/
class func popConstraintTo(_ to:UIView, section: Constraint.Section, value:CGFloat) {
assert(!Thread.isMainThread, _fy_noMainQueueAssert)
// 这个方法应该被优先调用,可能出现 fy_XXX(a) 替换 fy_XXX(chainXXX) 的情况
singleton.removeDuplicateConstraintOf(to, at: section)
// 如果对应区间上没有 holder,则认为 fy_XXX() 的参数中没有调用 chainXXX,直接返回,不进行后续操作
guard let _constraint = singleton.holder.constraintAt(section) else {
return
}
_constraint.to = to
_constraint.value = value
singleton.unsetConstraints.insert(_constraint)
singleton.holder.clearConstraintAt(section)
assert(singleton.noConstraintCirculationWith(_constraint),
"There is a constraint circulation between\n\(to)\n- and -\n\(_constraint.from)\n".fy_alert)
}
class func layout(_ view:UIView) {
let usingFangYuanSubviews = view.usingFangYuanSubviews
guard usingFangYuanSubviews.count > 0 else {
return
}
_fy_waitLayoutQueue()
singleton.layout(usingFangYuanSubviews)
}
/// 当某个依赖发生变化时,寻找相关的依赖,并重新根据存储的值赋值
/// 为了能保证『自动重置相关约束』,这个方法会在 `UIView.fy_XXX` 时从 `settedConstraints` 中检查相关的约束。
/// 并将其从新添加到 `constraints` 中
///
/// - Important:
/// 这里面已经产生了递归调用了:fy_XXX -> [This Method] -> fy_XXX -> [This Method] -> ...
/// 这样可以保证每次设定了约束了之后,所有与之相关的约束都会被重新设定
/// - Todo: 部分方法不应该遍历两次的!这里的性能还有提升空间
/// - Todo: horizontal 的意义并不明显啊
class func resetRelatedConstraintFrom(_ view:UIView, isHorizontal horizontal:Bool) {
assert(!Thread.isMainThread, _fy_noMainQueueAssert)
singleton.storedConstraints.forEach { constraint in
if let _from = constraint.from , _from == view {
if horizontal == constraint.section.horizontal {
switch constraint.section {
case .left:
constraint.to.fy_left(view.chainRight + constraint.value)
case .right:
constraint.to.fy_right(view.chainLeft + constraint.value)
case .top:
constraint.to.fy_top(view.chainBottom + constraint.value)
case .bottom:
constraint.to.fy_bottom(view.chainTop + constraint.value)
}
}
}
}
}
}
// MARK: - Private Methods
// MARK: Layout
private extension ConstraintManager {
/// - Todo: UITableView.addSubiew 后,调用 UITableView 的 layoutSubviews 并不会被触发?
/// 核心布局方法
/// - Todo: 这个算法相当于使用了什么排序?
/// - Todo: 能不能尽量写成函数而非方法?
/// - Todo: 还是把两部分合并一下,整理成一步算法吧
func layout(_ views: [UIView]) {
assert(Thread.isMainThread, _fy_MainQueueAssert)
guard hasUnsetConstraints(unsetConstraints, of: views) else {
views.forEach { view in
view.layoutWithFangYuan()
}
return
}
// 注意,应该保证下面的代码在执行时,不能直接遍历 constraints 来设定 layoutingViews,因为 _fangyuan_layout_queue 可能会对 layoutingViews 中的 UIView 添加新的约束,导致 hasSetConstraints 始终为 false
// 当然,objc_sync_enter 也是一种解决方案,但是这里我并不想阻塞 _fangyuan_layout_queue 对 unsetConstraints 的访问
var _views = Set(views)
var constraints = unsetConstraints
var shouldRepeat: Bool
repeat {
shouldRepeat = false
_views.forEach { view in
if hasSetConstraints(constraints, to: view) {
view.layoutWithFangYuan()
constraints = setConstraints(constraints, from: view)
// 在被遍历的数组中移除该 view
_views.remove(view)
} else {
shouldRepeat = true
}
}
} while shouldRepeat
}
func hasUnsetConstraints(_ constraints:Set<Constraint>, of views:[UIView]) -> Bool {
guard constraints.count != 0 else {
return false
}
/// - Todo: 外层遍历遍历谁会更快?或者两个一起遍历?
for view in views {
if !hasSetConstraints(constraints, to: view) {
return true
}
}
return false
}
/// 给定的约束中,已经没有用来约束 view 的约束了
func hasSetConstraints(_ constraints:Set<Constraint>, to view:UIView) -> Bool {
for constraint in constraints {
// ⚠️ Crash when scroll tableview too fast
// "fatal error: unexpectedly found nil while unwrapping an Optional value"
// `constraint.to` is nil
if constraint.to == view {
return false
}
}
return true
}
/// 确定了该 UIView.frame 后,装载指定 Constraint 至 to.ruler.section 中
/// - Todo: 参数可变性还是一个问题!
func setConstraints(_ constraints:Set<Constraint>, from view: UIView) -> Set<Constraint> {
var _constraints = constraints
_constraints.forEach { constraint in
if constraint.from == view {
_fy_layoutQueue {
self.storedConstraintsInsert(constraint)
}
let _from = constraint.from
let _to = constraint.to
let _value = constraint.value
switch constraint.section {
case .top:
_to?.rulerY.a = (_from?.frame.origin.y)! + (_from?.frame.height)! + _value
case .bottom:
_to?.rulerY.c = (_from?.superview!.frame.height)! - (_from?.frame.origin.y)! + _value
case .left:
_to?.rulerX.a = (_from?.frame.origin.x)! + (_from?.frame.width)! + _value
case .right:
_to?.rulerX.c = (_from?.superview!.frame.width)! - (_from?.frame.origin.x)! + _value
}
_constraints.remove(constraint)
}
}
return _constraints
}
}
// MARK: Assistant
private extension ConstraintManager {
func storedConstraintsInsert(_ constraint:Constraint) {
assert(!Thread.isMainThread, _fy_noMainQueueAssert)
storedConstraints.forEach { constraint in
if constraint.to == nil || constraint.from == nil {
storedConstraints.remove(constraint)
} else if constraint.to == constraint.to && constraint.section == constraint.section {
storedConstraints.remove(constraint)
}
}
storedConstraints.insert(constraint)
}
/// 按照程序逻辑,一个 view 最多同时只能在一个区间上拥有一个约束
func removeDuplicateConstraintOf(_ view:UIView, at section: Constraint.Section) {
assert(!Thread.isMainThread, _fy_noMainQueueAssert)
unsetConstraints.forEach { constraint in
if constraint.to == nil || constraint.from == nil {
unsetConstraints.remove(constraint)
} else if constraint.to == view && constraint.section == section {
unsetConstraints.remove(constraint)
}
}
}
/// Check constraint circulation
///
/// - Todo: Only 2 ? What about 3, 4, 5...?
func noConstraintCirculationWith(_ constraint:Constraint) -> Bool {
assert(!Thread.isMainThread, _fy_noMainQueueAssert)
return unsetConstraints.filter {
$0.to == constraint.from && $0.from == constraint.to
}.count == 0
}
}
|
5c0526273a68a3e08194a9b83cceefe7
| 32.906615 | 160 | 0.572756 | false | false | false | false |
zendobk/SwiftUtils
|
refs/heads/master
|
Sources/Classes/Label.swift
|
apache-2.0
|
1
|
//
// Label.swift
// SwiftUtils
//
// Created by DaoNV on 10/5/15.
// Copyright © 2016 Asian Tech Co., Ltd. All rights reserved.
//
import UIKit
open class Label: UILabel {
open var edgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
override open func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var rect = edgeInsets.inset(bounds)
rect = super.textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines)
return edgeInsets.inverse.inset(rect)
}
override open func drawText(in rect: CGRect) {
super.drawText(in: edgeInsets.inset(rect))
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += (edgeInsets.left + edgeInsets.right)
size.height += (edgeInsets.top + edgeInsets.bottom)
return size
}
}
|
48c5b7f0aba92abf1350b2e80b149f63
| 29.266667 | 112 | 0.674009 | false | false | false | false |
CodaFi/Bedrock
|
refs/heads/master
|
Bedrock/IndexSet.swift
|
mit
|
1
|
//
// IndexSet.swift
// Bedrock
//
// Created by Robert Widmann on 6/14/15.
// Copyright © 2015 Robert Mozayeni. All rights reserved.
//
/// An `IndexSet` is an immutable collection of unique Index Types.
public struct IndexSet<T: protocol<ForwardIndexType, Comparable>> {
public var count : Int {
return _ranges.reduce(0, combine: { (total, r) in countRange(r) + total })
}
/// Creates an empty index set.
public init() {
_ranges = []
}
/// Creates an index set with an index.
public init(index: T) {
self = IndexSet().indexSetByAddingIndex(index)
}
/// Creates an index set with an index range.
public init(indexesInRange : Range<T>) {
self = IndexSet().indexSetByAddingRange(indexesInRange)
}
/// Creates an index set that contains all the indexes of the receiver plus a given index.
public func indexSetByAddingIndex(i: T) -> IndexSet<T> {
return self.indexSetByAddingRange(i...i)
}
/// Creates an index set that contains all the indexes of the receiver plus a given range.
public func indexSetByAddingRange(r: Range<T>) -> IndexSet<T> {
let idx = insertionIndexForIndex(r.startIndex, rightBound: _ranges.count - 1)
var copiedRanges = _ranges
copiedRanges.insert(r, atIndex: idx)
mergeRangesUpToIndex(&copiedRanges, idx: idx)
if idx > 0 {
mergeRangesAroundIndex(&copiedRanges, idx: idx - 1)
}
if idx < (self.count - 1) {
mergeRangesAroundIndex(&copiedRanges, idx: idx)
}
return IndexSet(copiedRanges)
}
/// Indicates whether the index set contains a specific index.
public func containsIndex(i: T) -> Bool {
return self.rangeIndexForIndex(i, rightBound: _ranges.count - 1) != -1
}
private let _ranges : Array<Range<T>>
}
/// MARK: Private Bits
/// NSIndexSet is really a bunch of NSRanges stuck up in series. We have to take extra care when
/// inserting or removing ranges that we don't perturb their neighbors, or split and merge them as
/// necessary. Every index in the set belongs somewhere in some range.
extension IndexSet {
private init(_ ranges: Array<Range<T>>) {
_ranges = ranges
}
private func mergeRangesAroundIndex(inout mRanges: [Range<T>], idx: Int) {
if idx >= mRanges.count - 1 {
return
}
// If we don't quite stretch to reach the start of the next range we're done.
if advance(mRanges[idx].endIndex, 1) != mRanges[idx + 1].startIndex {
return
}
removeRanges(&mRanges, idx: idx + 1, count: 1)
}
/// Tries to find the rightmost range a range at the given position can be merged into, then
/// merges it.
private func mergeRangesUpToIndex(inout ranges: [Range<T>], idx: Int) {
let targetRange = ranges[idx]
var rightmostRangeindex = idx
for var i = idx; i < ranges.count; i++ {
// Search until we can search no more
if !rangeIntersectsRange(ranges[i], targetRange) {
break
}
rightmostRangeindex = i
}
// No sense in merging ourself
if rightmostRangeindex == idx {
return
}
// Merge
let r = unionRanges(targetRange, ranges[rightmostRangeindex])
removeRanges(&ranges, idx: idx + 1, count: rightmostRangeindex - idx)
ranges[idx] = r
}
/// Mostly for convenience.
private func removeRanges(inout ranges: [Range<T>], idx: Int, count: Int) {
ranges.removeRange((idx + count)..<ranges.endIndex)
}
/// Searches the ranges for the position of the range containing the index.
///
/// On error this function returns -1. It is _not helpful_ for insertion. Use
/// `insertionIndexForIndex` for that.
private func rangeIndexForIndex(idx: T, leftBound: Int = 0, rightBound: Int) -> Int {
if self.count == 0 {
return -1
}
let mid = (leftBound + rightBound) / 2
let midRange = _ranges[mid]
if leftBound == rightBound {
if contains(midRange, idx) {
return leftBound
} else {
return -1
}
}
if contains(midRange, idx) {
return mid
}
/// Look ma, a binary search.
if idx < midRange.startIndex {
return self.rangeIndexForIndex(idx, leftBound: leftBound, rightBound: mid)
} else {
return self.rangeIndexForIndex(idx, leftBound: mid + 1, rightBound: rightBound)
}
}
/// Searches the ranges for the first position of a range that could contain the index.
private func insertionIndexForIndex(idx: T, leftBound: Int = 0, rightBound: Int) -> Int {
if self.count == 0 {
return 0
}
let mid = (leftBound + rightBound) / 2
let midRange = _ranges[mid]
if leftBound == rightBound {
if idx <= midRange.endIndex {
return leftBound
} else {
return leftBound + 1
}
}
if idx <= midRange.endIndex {
return self.insertionIndexForIndex(idx, leftBound: leftBound, rightBound: mid)
} else {
return self.insertionIndexForIndex(idx, leftBound: mid + 1, rightBound: rightBound)
}
}
}
private func countRange<T: ForwardIndexType>(r: Range<T>) -> Int {
var count = 0
for _ in r {
count++
}
return count
}
/// Because no Foundation.
private func rangeIntersectsRange<T: protocol<ForwardIndexType, Comparable>>(range: Range<T>, other: Range<T>) -> Bool {
if range.endIndex <= other.startIndex {
return true
} else if range.startIndex <= other.endIndex {
return true
}
return false
}
/// Turns out Comparable Ranges are Monoids.
private func unionRanges<T: protocol<ForwardIndexType, Comparable>>(xs: Range<T>...) -> Range<T> {
return xs.reduce(xs[0], combine: { (rng, next) in (min(rng.startIndex, next.startIndex)...max(rng.startIndex, next.startIndex)) })
}
|
8db8cbe181f152506cc9893a02bf28c9
| 27.829787 | 131 | 0.68893 | false | false | false | false |
rsaenzi/MyCurrencyConverterApp
|
refs/heads/master
|
MyCurrencyConverterApp/MyCurrencyConverterApp/App/BusinessRules/BusinessRules.swift
|
mit
|
1
|
//
// BusinessRules.swift
// MyCurrencyConverterApp
//
// Created by Rigoberto Sáenz Imbacuán on 8/6/16.
// Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved.
//
class BusinessRules {
// --------------------------------------------------
// Members
// --------------------------------------------------
var rates = RuleGetExchangeRates.getUniqueInstance()!
// --------------------------------------------------
// Singleton: Unique Instance
// --------------------------------------------------
private static let instance = BusinessRules()
private init() {}
// --------------------------------------------------
// Singleton: One-Time Access
// --------------------------------------------------
private static var instanceDelivered = false
/**
Creates and returns the unique allowed instance of this class
- returns: Unique instance the first time this method is called, nil otherwise
*/
static func getUniqueInstance() -> BusinessRules? {
// If this is the first time this method is called...
if instanceDelivered == false {
// Create and return the instance
instanceDelivered = true
return instance
}
return nil
}
}
|
3b5bd4851cb4d328322794c25f904265
| 30.272727 | 105 | 0.469091 | false | false | false | false |
wmcginty/Shifty
|
refs/heads/main
|
Sources/Shifty/Model/Shift/Shift.Target.swift
|
mit
|
1
|
//
// Shift.Target.swift
// Shifty
//
// Created by Will McGinty on 5/2/16.
// Copyright © 2016 will.mcginty. All rights reserved.
//
import UIKit
public extension Shift {
/// Represents a single target of a shifting `UIView` - usually either the source or the destination.
struct Target {
// MARK: - Typealias
public typealias AlongsideAnimation = (_ replicant: UIView, _ destination: Shift.Target, _ snapshot: Snapshot) -> Void
// MARK: - ReplicantInsertionStrategy Subtype
public enum ReplicantInsertionStrategy {
case standard
case above(UIView)
case below(UIView)
case custom((_ replicant: UIView, _ container: UIView) -> Void)
func insert(replicant: UIView, into container: UIView) {
switch self {
case .standard: container.addSubview(replicant)
case .above(let other): container.insertSubview(replicant, aboveSubview: other)
case .below(let other): container.insertSubview(replicant, belowSubview: other)
case .custom(let handler): handler(replicant, container)
}
}
}
// MARK: - Properties
/// The view acting as a target of the shift. This view can be either the source or the destination.
public let view: UIView
/// The identifier assigned to this `Target`. Each identifier in the source will match an identifier in the destination.
public let identifier: Identifier
/// The method used to configure the view. Defaults to .snapshot.
public let replicationStrategy: ReplicationStrategy
/// A set of animations that will be executed simultaneously with animations that drive the shift (both positional and visual).
/// - Important: In the case that the `Shift` is utilizing a `VisualAnimationBehavior` not equal to `.none`, these animations will take precendence - though creating an
/// animation that contradicts an animation created by the `VisualAnimationBehavior` may produce undesirable visual side effects.
public var alongsideAnimations: AlongsideAnimation?
// MARK: - Initializers
public init(view: UIView, identifier: Identifier, replicationStrategy: ReplicationStrategy = .snapshot, alongsideAnimations: AlongsideAnimation? = nil) {
self.view = view
self.identifier = identifier
self.replicationStrategy = replicationStrategy
self.alongsideAnimations = alongsideAnimations
}
// MARK: - Modification
var debug: Target { return Target(view: view, identifier: identifier, replicationStrategy: .debug()) }
public func replicating(using strategy: ReplicationStrategy) -> Shift.Target {
return Shift.Target(view: view, identifier: identifier, replicationStrategy: strategy)
}
}
}
// MARK: - Interface
public extension Shift.Target {
func configuredReplicant(in container: UIView, with insertionStrategy: ReplicantInsertionStrategy = .standard, afterScreenUpdates: Bool) -> UIView {
let replicant = replicationStrategy.configuredShiftingView(for: view, afterScreenUpdates: afterScreenUpdates)
insertionStrategy.insert(replicant: replicant, into: container)
applyPositionalState(to: replicant, in: container)
return replicant
}
func applyPositionalState(to view: UIView, in container: UIView) {
snapshot().applyPositionalState(to: view)
}
func cleanup(replicant: UIView, restoreNativeView: Bool = true) {
replicant.removeFromSuperview()
if restoreNativeView {
configureNativeView(hidden: false)
}
}
/// Returns a `Snapshot` of the current state of the `Target`.
func snapshot() -> Snapshot {
return Snapshot(view: view)
}
func configureNativeView(hidden: Bool) {
view.isHidden = hidden
}
}
// MARK: - Hashable
extension Shift.Target: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
public static func == (lhs: Shift.Target, rhs: Shift.Target) -> Bool {
return lhs.identifier == rhs.identifier
}
}
|
b23e173c5664a759c13b46cff29adf9f
| 37.911504 | 176 | 0.647259 | false | false | false | false |
Mindera/Alicerce
|
refs/heads/master
|
Sources/View/ReusableView.swift
|
mit
|
1
|
import UIKit
public protocol ReusableView {
static var reuseIdentifier: String { get }
}
public extension ReusableView where Self: UIView {
static var reuseIdentifier: String { return "\(self)" }
}
extension UICollectionReusableView: ReusableView {}
extension UITableViewCell: ReusableView {}
extension UITableViewHeaderFooterView: ReusableView {}
// MARK: - UICollectionView Reusable properties
public extension UICollectionView {
func register<T: UICollectionViewCell>(_ cellType: T.Type) {
register(cellType, forCellWithReuseIdentifier: cellType.reuseIdentifier)
}
func register<T: UICollectionViewCell & NibView>(_ cellType: T.Type) {
register(cellType.nib, forCellWithReuseIdentifier: cellType.reuseIdentifier)
}
func register<T: UICollectionReusableView>(_ viewType: T.Type, forSupplementaryViewOfKind kind: String) {
register(viewType, forSupplementaryViewOfKind: kind, withReuseIdentifier: viewType.reuseIdentifier)
}
func register<T: UICollectionReusableView & NibView>(_ viewType: T.Type, forSupplementaryViewOfKind kind: String) {
register(viewType.nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: viewType.reuseIdentifier)
}
func dequeueCell<T: UICollectionViewCell>(`for` indexPath: IndexPath) -> T {
let anyCell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath)
guard let cell = anyCell as? T else {
fatalError("🔥 Dequeued Cell with identifier `\(T.reuseIdentifier)` for \(indexPath) is not of " +
"type `\(T.self)`! Found: `\(type(of: anyCell))`. Forgot to register?")
}
return cell
}
func dequeueSupplementaryView<T: UICollectionReusableView>(forElementKind elementKind: String,
at indexPath: IndexPath) -> T {
let anySupplementaryView = dequeueReusableSupplementaryView(ofKind: elementKind,
withReuseIdentifier: T.reuseIdentifier,
for: indexPath)
guard let supplementaryView = anySupplementaryView as? T else {
fatalError("🔥 Dequeued SupplementaryView with element kind `\(elementKind)`, " +
"identifier `\(T.reuseIdentifier)` for \(indexPath) is not of type `\(T.self)`! " +
"Found: `\(type(of: anySupplementaryView))`. Forgot to register?")
}
return supplementaryView
}
func cell<T: UICollectionViewCell>(`for` indexPath: IndexPath) -> T {
guard let anyCell = cellForItem(at: indexPath) else {
fatalError("🔥 No Cell returned for \(indexPath)! Looking for `dequeueCell`?")
}
guard let cell = anyCell as? T else {
fatalError("🔥 Cell at \(indexPath) is not of type: `\(T.self)`! Found: `\(type(of: anyCell))`")
}
return cell
}
func supplementaryView<T: UICollectionReusableView>(forElementKind elementKind: String,
at indexPath: IndexPath) -> T {
guard let anySupplementaryView = supplementaryView(forElementKind: elementKind, at: indexPath) else {
fatalError("🔥 No supplementary view returned with element kind `\(elementKind)` for \(indexPath)! " +
"Looking for `dequeueSupplementaryView`?")
}
guard let supplementaryView = anySupplementaryView as? T else {
fatalError("🔥 SupplementaryView with element kind `\(elementKind)` is not of type: `\(T.self)`! " +
"Found `\(type(of: anySupplementaryView))`")
}
return supplementaryView
}
}
// MARK: - UITableView Reusable properties
public extension UITableView {
func register<T: UITableViewCell>(_ cellType: T.Type) {
register(cellType, forCellReuseIdentifier: cellType.reuseIdentifier)
}
func register<T: UITableViewCell & NibView>(_ cellType: T.Type) {
register(cellType.nib, forCellReuseIdentifier: cellType.reuseIdentifier)
}
func registerHeaderFooterView<T: UITableViewHeaderFooterView>(_ viewType: T.Type) {
register(viewType, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier)
}
func registerHeaderFooterView<T: UITableViewHeaderFooterView & NibView>(_ viewType: T.Type) {
register(viewType.nib, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier)
}
func dequeueCell<T: UITableViewCell>(`for` indexPath: IndexPath) -> T {
let anyCell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath)
guard let cell = anyCell as? T else {
fatalError("🔥 Dequeued Cell with identifier `\(T.reuseIdentifier)` for \(indexPath) is not of " +
"type `\(T.self)`! Found: `\(type(of: anyCell))`. Forgot to register?")
}
return cell
}
func dequeueHeaderFooterView<T: UITableViewHeaderFooterView>() -> T {
let anyHeaderFooterView = dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier)
guard let view = anyHeaderFooterView as? T else {
fatalError("🔥 Dequeued HeaderFooterView with identifier `\(T.reuseIdentifier)` is not of " +
"type `\(T.self)`! Found: `\(type(of: anyHeaderFooterView))`. Forgot to register?")
}
return view
}
func cell<T: UITableViewCell>(`for` indexPath: IndexPath) -> T {
guard let anyCell = cellForRow(at: indexPath) else {
fatalError("🔥 No Cell returned for \(indexPath)! Looking for `dequeueCell`?")
}
guard let cell = anyCell as? T else {
fatalError("🔥 Cell at \(indexPath) is not of type: `\(T.self)`! Found: `\(type(of: anyCell))`. " +
"Forgot to register?")
}
return cell
}
func headerView<T: UITableViewHeaderFooterView>(forSection section: Int) -> T {
guard let anyHeaderView = headerView(forSection: section) else {
fatalError("🔥 No HeaderView returned for section: \(section)! Looking for `dequeueHeaderFooterView`?")
}
guard let view = anyHeaderView as? T else {
fatalError("🔥 HeaderView for section: \(section) is not of type: `\(T.self)`! " +
"Found `\(type(of: anyHeaderView))`. Forgot to register?")
}
return view
}
func footerView<T: UITableViewHeaderFooterView>(forSection section: Int) -> T {
guard let anyFooterView = footerView(forSection: section) else {
fatalError("🔥 No FooterView returned for section: \(section)! Looking for `dequeueHeaderFooterView`?")
}
guard let view = anyFooterView as? T else {
fatalError("🔥 FooterView for section: \(section) is not of type: `\(T.self)`! " +
"Found `\(type(of: anyFooterView))`. Forgot to register?")
}
return view
}
}
|
af96929496c97b05799ac8819e880640
| 40.552941 | 119 | 0.629955 | false | false | false | false |
ytfhqqu/iCC98
|
refs/heads/master
|
iCC98/iCC98/MessageContentViewController.swift
|
mit
|
1
|
//
// MessageContentViewController.swift
// iCC98
//
// Created by Duo Xu on 5/20/17.
// Copyright © 2017 Duo Xu.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import CC98Kit
class MessageContentViewController: BaseWebViewController {
@IBOutlet weak var replyButton: UIBarButtonItem!
// MARK: - Data
/**
设置数据。
- parameter messageInfo: 短消息的信息。
- parameter currentUserName: 当前登录用户的用户名。
*/
func setData(messageInfo: MessageInfo, currentUserName: String?) {
super.setData(code: messageInfo.content ?? "", codeType: .ubb)
self.messageInfo = messageInfo
self.currentUserName = currentUserName
updateUI()
}
/// 短消息的信息。
private var messageInfo: MessageInfo?
/// 当前登录用户的用户名。
private var currentUserName: String?
// MARK: - UI
// 更新 UI
private func updateUI() {
if let messageInfo = messageInfo {
if let senderName = messageInfo.senderName, senderName != currentUserName {
replyButton?.isEnabled = true
} else {
// 系统消息和自己发出的消息都不能回复
replyButton?.isEnabled = false
}
}
}
// 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.
// 目标控制器可能包含 `UINavigationController`,这种情况下需要把它下面的控制器取出来
var destinationVC = segue.destination
if let navigationController = destinationVC as? UINavigationController {
destinationVC = navigationController.visibleViewController ?? destinationVC
}
// 发消息
if segue.identifier == "Reply To Message", let messageInfo = messageInfo, let newMessageTVC = destinationVC as? NewMessageTableViewController {
newMessageTVC.setData(newMessageType: .reply(quotedMessageInfo: messageInfo))
}
}
}
|
b998f13b1865a808797ac62242a5e5a5
| 38.222222 | 151 | 0.684293 | false | false | false | false |
kingsic/SGPagingView
|
refs/heads/master
|
SGPagingView/Example/SuspensionPro/SuspensionProVC.swift
|
mit
|
2
|
//
// SuspensionProVC.swift
// SGPagingView
//
// Created by kingsic on 2021/10/20.
// Copyright © 2021 kingsic. All rights reserved.
//
import UIKit
let pro_headerViewHeight: CGFloat = 270
let pro_pagingTitleViewHeight: CGFloat = 40
let navHeight: CGFloat = 44 + UIScreen.statusBarHeight
class SuspensionProVC: UIViewController {
lazy var pagingTitleView: SGPagingTitleView = {
let configure = SGPagingTitleViewConfigure()
configure.color = .lightGray
configure.selectedColor = .black
configure.indicatorType = .Dynamic
configure.indicatorColor = .orange
configure.showBottomSeparator = false
let frame = CGRect.init(x: 0, y: pro_headerViewHeight, width: view.frame.size.width, height: pro_pagingTitleViewHeight)
let titles = ["精选", "微博", "相册"]
let pagingTitle = SGPagingTitleView(frame: frame, titles: titles, configure: configure)
pagingTitle.delegate = self
return pagingTitle
}()
var tempBaseSubVCs: [BaseSubProVC] = []
lazy var pagingContentView: SGPagingContentScrollView = {
let vc1 = SubProVC()
let vc2 = SubTitleProVC()
let vc3 = SubProVC()
let vcs = [vc1, vc2, vc3]
tempBaseSubVCs = vcs
let tempRect: CGRect = CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
let pagingContent = SGPagingContentScrollView(frame: tempRect, parentVC: self, childVCs: vcs)
pagingContent.delegate = self
return pagingContent
}()
lazy var headerView: UIView = {
let headerView: UIView = UIView()
headerView.backgroundColor = .red
headerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: pro_headerViewHeight)
let pan = UIPanGestureRecognizer(target: self, action: #selector(pan_action))
headerView.addGestureRecognizer(pan)
let btn = UIButton(type: .custom)
let btn_width: CGFloat = 200
let btn_x = 0.5 * (view.frame.width - btn_width)
btn.frame = CGRect(x: btn_x, y: pro_headerViewHeight - 100, width: btn_width, height: 50)
btn.layer.cornerRadius = 10
btn.backgroundColor = .black
btn.setTitle("You know?I can click", for: .normal)
btn.addTarget(self, action: #selector(temp_btn_action), for: .touchUpInside)
headerView.addSubview(btn)
return headerView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .white
view.addSubview(UIView())
view.addSubview(pagingContentView)
view.addSubview(headerView)
view.addSubview(pagingTitleView)
tempLastPagingTitleViewY = pro_headerViewHeight
// 监听子视图发出的通知
NotificationCenter.default.addObserver(self, selector: #selector(subTableViewDidScroll), name: NSNotification.Name(NNProSubScrollViewDidScroll), object: nil)
}
var tempSubScrollView: UIScrollView?
var tempLastPagingTitleViewY: CGFloat = 0
var tempLastPoint: CGPoint = .zero
deinit {
print("SuspensionProVC")
}
}
extension SuspensionProVC {
@objc func pan_action(pan: UIPanGestureRecognizer) {
if pan.state == .began {
} else if pan.state == .changed {
let currenrPoint: CGPoint = pan.translation(in: pan.view)
let distanceY = currenrPoint.y - tempLastPoint.y
tempLastPoint = currenrPoint
let baseSubVC = tempBaseSubVCs[pagingTitleView.index]
var contentOffset: CGPoint = baseSubVC.scrollView!.contentOffset
contentOffset.y += -distanceY
if contentOffset.y <= -pro_subScrollViewContentOffsetY {
contentOffset.y = -pro_subScrollViewContentOffsetY
}
baseSubVC.scrollView?.contentOffset = contentOffset
} else {
pan.setTranslation(.zero, in: pan.view)
tempLastPoint = .zero
}
}
}
extension SuspensionProVC {
@objc func subTableViewDidScroll(noti: Notification) {
let scrollingScrollView = noti.userInfo!["scrollingScrollView"] as! UIScrollView
let offsetDifference: CGFloat = noti.userInfo!["offsetDifference"] as! CGFloat
var distanceY: CGFloat = 0
let baseSubVC = tempBaseSubVCs[pagingTitleView.index]
// 当前滚动的 scrollView 不是当前显示的 scrollView 直接返回
guard scrollingScrollView == baseSubVC.scrollView else {
return
}
var pagingTitleViewFrame: CGRect = pagingTitleView.frame
guard pagingTitleViewFrame.origin.y >= navHeight else {
return
}
let scrollViewContentOffsetY = scrollingScrollView.contentOffset.y
// 往上滚动
if offsetDifference > 0 && scrollViewContentOffsetY + pro_subScrollViewContentOffsetY > 0 {
if (scrollViewContentOffsetY + pro_subScrollViewContentOffsetY + pagingTitleView.frame.origin.y) > pro_headerViewHeight || scrollViewContentOffsetY + pro_subScrollViewContentOffsetY < 0 {
pagingTitleViewFrame.origin.y += -offsetDifference
if pagingTitleViewFrame.origin.y <= navHeight {
pagingTitleViewFrame.origin.y = navHeight
}
}
} else { // 往下滚动
if (scrollViewContentOffsetY + pagingTitleView.frame.origin.y + pro_subScrollViewContentOffsetY) < pro_headerViewHeight {
pagingTitleViewFrame.origin.y = -scrollViewContentOffsetY - pro_pagingTitleViewHeight
if pagingTitleViewFrame.origin.y >= pro_headerViewHeight {
pagingTitleViewFrame.origin.y = pro_headerViewHeight
}
}
}
// 更新 pagingTitleView 的 frame
pagingTitleView.frame = pagingTitleViewFrame
// 更新 headerView 的 frame
var headerViewFrame: CGRect = headerView.frame
headerViewFrame.origin.y = pagingTitleView.frame.origin.y - pro_headerViewHeight
headerView.frame = headerViewFrame
distanceY = pagingTitleViewFrame.origin.y - tempLastPagingTitleViewY
tempLastPagingTitleViewY = pagingTitleView.frame.origin.y
/// 让其余控制器的 scrollView 跟随当前正在滚动的 scrollView 而滚动
otherScrollViewFollowingScrollingScrollView(scrollView: scrollingScrollView, distanceY: distanceY)
}
/// 让其余控制器的 scrollView 跟随当前正在滚动的 scrollView 而滚动
func otherScrollViewFollowingScrollingScrollView(scrollView: UIScrollView, distanceY: CGFloat) {
var baseSubVC: BaseSubProVC
for (index, _) in tempBaseSubVCs.enumerated() {
baseSubVC = tempBaseSubVCs[index]
if baseSubVC.scrollView == scrollView {
continue
} else {
if let tempScrollView = baseSubVC.scrollView {
var contentOffSet: CGPoint = tempScrollView.contentOffset
contentOffSet.y += -distanceY
tempScrollView.contentOffset = contentOffSet
}
}
}
}
}
extension SuspensionProVC: SGPagingTitleViewDelegate, SGPagingContentViewDelegate {
func pagingTitleView(titleView: SGPagingTitleView, index: Int) {
pagingContentView.setPagingContentView(index: index)
}
func pagingContentView(contentView: SGPagingContentView, progress: CGFloat, currentIndex: Int, targetIndex: Int) {
pagingTitleView.setPagingTitleView(progress: progress, currentIndex: currentIndex, targetIndex: targetIndex)
}
func pagingContentViewDidScroll() {
let baseSubVC: BaseSubProVC = tempBaseSubVCs[pagingTitleView.index]
if let tempScrollView = baseSubVC.scrollView {
if (tempScrollView.contentSize.height) < UIScreen.main.bounds.size.width {
tempScrollView.setContentOffset(CGPoint(x: 0, y: -pro_subScrollViewContentOffsetY), animated: false)
}
}
}
}
extension SuspensionProVC {
@objc func temp_btn_action() {
print("temp_btn_action")
}
}
|
f61f33e2ae4a42e721d5bcc5cd7fc817
| 38.68599 | 199 | 0.650639 | false | false | false | false |
AjayOdedara/CoreKitTest
|
refs/heads/master
|
CoreKit/CoreKit/ImageService.swift
|
mit
|
1
|
//
// ImageService.swift
// CllearworksCoreKit
//
// Created by Tim Sneed on 6/22/15.
// Copyright (c) 2015 Cllearworks. All rights reserved.
//
import UIKit
public class ImageService: NSObject {
public enum ImageMode:String {
case Uniform = "Uniform"
case Zoom = "Zoom"
case Pad = "Pad"
var description : String {
get {
return self.rawValue
}
}
}
public enum VerticalCrop: String {
case Center = "Center"
case Top = "Top"
case Bottom = "Bottom"
var verticalValue : String {
get {
return self.rawValue
}
}
}
public enum HorizontalCrop: String {
case Center = "Center"
case Left = "Left"
case Right = "Right"
var horizontalValue : String {
get {
return self.rawValue
}
}
}
public func buildImageString(imageName:String, imageMode:ImageMode, size:CGSize, scale:CGFloat)-> NSURL{
return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)&mode=\(imageMode.description)&width=\(Int(size.width * scale))&height=\(Int(size.height * scale))")!
}
public func buildImageString(imageName:String, imageMode:ImageMode, size:CGSize)-> NSURL{
return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)&mode=\(imageMode.description)&width=\(Int(size.width))&height=\(Int(size.height))")!
}
//removed the imagemode to get full image
public func buildImageString(imageName:String, size:CGSize)-> NSURL{
return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)")!
}
public func buildImageString(imageName:String, imageMode:ImageMode, size:CGSize, scale:CGFloat, cropAnchorV:VerticalCrop, cropAnchorH: HorizontalCrop)-> NSURL{
return NSURL(string: CustomCoreKit.repository().apiRoot + "/v1/Images?imagePath=\(imageName)&mode=\(imageMode.description)&width=\(Int(size.width * scale))&height=\(Int(size.height * scale))&cropAnchorV=\(cropAnchorV.verticalValue)&cropAnchorH=\(cropAnchorH.horizontalValue)")!
}
public func buildImageUrl(urlString: String, imageMode: ImageMode, size: CGSize) -> NSURL {
let scale = UIScreen().scale
return NSURL(string: urlString + "&mode=\(imageMode)&width=\(Int(size.width * scale))&height=\(Int(size.height * scale))")!
}
}
|
031cd9645e4f5c9c594801c71e4e0682
| 34.126761 | 285 | 0.642743 | false | false | false | false |
FUKUZAWA-Tadashi/FHCCommander
|
refs/heads/master
|
fhcc/State.swift
|
mit
|
1
|
//
// State.swift
// fhcc
//
// Created by 福澤 正 on 2014/06/25.
// Copyright (c) 2014年 Fukuzawa Technology. All rights reserved.
//
import Foundation
class State {
// 測位精度がこれより低ければ(大きければ)、その位置情報は捨てる
class var ACCURACY_LIMIT: Double { return 100.0 }
private let USER_DEFAULTS_KEY = "FHC_State"
var fhcAddress: String
var mailAddr: String
var password: String
var homeLatitude: Double
var homeLongitude: Double
var homeRegionRadius: Double
var farRegionRadius: Double
var homeSSID: String
var fhcSecret: String
var fhcOfficialSite: String
var applianceOfOutgo: String
var actionOfOutgo: String
var applianceOfReturnHome: String
var actionOfReturnHome: String
var sensorUpdateInterval: Int
var actionsDict: Dictionary<String, [String]>
var judgeUsingLan: Bool
class var VOICE_COMMAND: String { return "< 音声コマンド >" }
class var ACTIONS_DICT_DEFAULTS: Dictionary<String, [String]> {
return [
VOICE_COMMAND : [
"いってきます", "ただいま"
],
"家電1" : [
"すいっちおん", "でんげんきって"
],
"家電2" : [
"でんげんいれて", "すいっちおふ"
]
]
}
private let KEY_FHC_ADDRESS = "fhcAddress"
private let KEY_MAIL_ADDR = "mailAddr"
private let KEY_PASSWORD = "password"
private let KEY_HOME_LATITUDE = "homeLatitude"
private let KEY_HOME_LONGITUDE = "homeLongitude"
private let KEY_HOME_REGION_RADIUS = "homeRegionRadius"
private let KEY_FAR_REGION_RADIUS = "farRegionRadius"
private let KEY_HOME_SSID = "homeSSID"
private let KEY_FHC_SECRET = "fhcSecret"
private let KEY_FHC_OFFICIAL_SITE = "fhcOfficialSite"
private let KEY_APPLIANCE_OF_OUTGO = "applianceOfOutgo"
private let KEY_ACTION_OF_OUTGO = "actionOfOutgo"
private let KEY_APPLIANCE_OF_RETURN_HOME = "applianceOfReturnHome"
private let KEY_ACTION_OF_RETURN_HOME = "actionOfReturnHome"
private let KEY_SENSOR_UPDATE_INTERVAL = "sensorUpdateInterval"
private let KEY_JUDGE_USING_LAN = "judgeUsingLan"
private let KEY_AD_KEYS = "ad_keys"
private let KEY_AD_VAL = "ad_val_"
init () {
fhcAddress = "fhc.local"
mailAddr = ""
password = ""
homeLatitude = 0.0
homeLongitude = 0.0
homeRegionRadius = 20.0
farRegionRadius = 200.0
homeSSID = ""
fhcSecret = ""
fhcOfficialSite = "fhc.rti-giken.jp"
applianceOfOutgo = ""
actionOfOutgo = ""
applianceOfReturnHome = ""
actionOfReturnHome = ""
sensorUpdateInterval = 30
actionsDict = State.ACTIONS_DICT_DEFAULTS
judgeUsingLan = true
}
func loadFromUserDefaults () -> Bool {
var defaults = NSUserDefaults.standardUserDefaults()
var failed = false
func chk_load_string(key:String) -> String! {
let x = defaults.stringForKey(key)
if x == nil {
NSLog("load state failed on '\(key)'")
failed = true
}
return x
}
func chk_load_object(key:String) -> AnyObject! {
let x: AnyObject! = defaults.objectForKey(key)
if x == nil {
NSLog("load state failed on '\(key)'")
failed = true
}
return x
}
func chk_load_string_array(key:String) -> [String]! {
let x: [AnyObject]! = defaults.stringArrayForKey(key)
if x == nil {
NSLog("load state failed on '\(key)'")
failed = true
return nil
}
return x as [String]
}
fhcAddress = chk_load_string(KEY_FHC_ADDRESS) ?? "fhc.local"
mailAddr = chk_load_string(KEY_MAIL_ADDR) ?? ""
password = chk_load_string(KEY_PASSWORD) ?? ""
homeLatitude = defaults.doubleForKey(KEY_HOME_LATITUDE)
homeLongitude = defaults.doubleForKey(KEY_HOME_LONGITUDE)
homeRegionRadius = defaults.doubleForKey(KEY_HOME_REGION_RADIUS)
farRegionRadius = defaults.doubleForKey(KEY_FAR_REGION_RADIUS)
homeSSID = chk_load_string(KEY_HOME_SSID) ?? ""
fhcSecret = chk_load_string(KEY_FHC_SECRET) ?? ""
fhcOfficialSite = chk_load_string(KEY_FHC_OFFICIAL_SITE) ?? "fhc.rti-giken.jp"
applianceOfOutgo = chk_load_string(KEY_APPLIANCE_OF_OUTGO) ?? ""
actionOfOutgo = chk_load_string(KEY_ACTION_OF_OUTGO) ?? ""
applianceOfReturnHome = chk_load_string(KEY_APPLIANCE_OF_RETURN_HOME) ?? ""
actionOfReturnHome = chk_load_string(KEY_ACTION_OF_RETURN_HOME) ?? ""
if homeRegionRadius == 0.0 { homeRegionRadius = 20.0 }
if farRegionRadius == 0.0 { farRegionRadius = 200.0 }
if (failed) {
sensorUpdateInterval = 30
judgeUsingLan = true
} else {
sensorUpdateInterval = defaults.integerForKey(KEY_SENSOR_UPDATE_INTERVAL)
judgeUsingLan = defaults.boolForKey(KEY_JUDGE_USING_LAN)
}
var adict = Dictionary<String, [String]>()
let ad_keys = chk_load_string_array(KEY_AD_KEYS)
if ad_keys != nil {
for (i,k) in enumerate(ad_keys!) {
let x = chk_load_string_array(KEY_AD_VAL + "\(i)")
if x != nil {
adict[k] = x
}
}
}
if adict.count > 0 { actionsDict = adict }
return !failed
}
func saveToUserDefaults () {
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(fhcAddress, forKey: KEY_FHC_ADDRESS)
defaults.setObject(mailAddr, forKey: KEY_MAIL_ADDR)
defaults.setObject(password, forKey: KEY_PASSWORD)
defaults.setDouble(homeLatitude, forKey: KEY_HOME_LATITUDE)
defaults.setDouble(homeLongitude, forKey: KEY_HOME_LONGITUDE)
defaults.setDouble(homeRegionRadius, forKey: KEY_HOME_REGION_RADIUS)
defaults.setDouble(farRegionRadius, forKey: KEY_FAR_REGION_RADIUS)
defaults.setObject(homeSSID, forKey: KEY_HOME_SSID)
defaults.setObject(fhcSecret, forKey: KEY_FHC_SECRET)
defaults.setObject(fhcOfficialSite, forKey: KEY_FHC_OFFICIAL_SITE)
defaults.setObject(applianceOfOutgo, forKey: KEY_APPLIANCE_OF_OUTGO)
defaults.setObject(actionOfOutgo, forKey: KEY_ACTION_OF_OUTGO)
defaults.setObject(applianceOfReturnHome, forKey: KEY_APPLIANCE_OF_RETURN_HOME)
defaults.setObject(actionOfReturnHome, forKey: KEY_ACTION_OF_RETURN_HOME)
defaults.setInteger(sensorUpdateInterval, forKey: KEY_SENSOR_UPDATE_INTERVAL)
defaults.setBool(judgeUsingLan, forKey: KEY_JUDGE_USING_LAN)
let ad_keys = actionsDict.keys.array
defaults.setObject(ad_keys.map{NSString(string:$0)}, forKey: KEY_AD_KEYS)
for (i,k) in enumerate(ad_keys) {
let ad_val = actionsDict[k]!.map{NSString(string:$0)}
defaults.setObject(ad_val, forKey: KEY_AD_VAL + "\(i)")
}
defaults.synchronize()
}
}
|
06d7c9b66e9e4860bfb6ff93966ddca3
| 36.03125 | 87 | 0.612463 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
refs/heads/develop
|
WordPressKit/WordPressKitTests/PeopleServiceRemoteTests.swift
|
gpl-2.0
|
2
|
import Foundation
import XCTest
@testable import WordPressKit
class PeopleServiceRemoteTests: RemoteTestCase, RESTTestable {
// MARK: - Constants
let siteID = 321
let userID = 1111
let validUsername = "jimthetester"
let viewerID = 123
let followerID = 987
let invalidSiteID = 888
let invalidUserID = 9999
let invalidUsername = "someInvalidUser"
let newInviteEndpoint = "invites/new"
let validateInviteEndpoint = "invites/validate"
let getRolesSuccessMockFilename = "site-roles-success.json"
let getRolesBadJsonFailureMockFilename = "site-roles-bad-json-failure.json"
let getRolesBadAuthMockFilename = "site-roles-auth-failure.json"
let updateRoleSuccessMockFilename = "site-users-update-role-success.json"
let updateRoleUnknownUserFailureMockFilename = "site-users-update-role-unknown-user-failure.json"
let updateRoleUnknownSiteFailureMockFilename = "site-users-update-role-unknown-site-failure.json"
let updateRoleBadJsonFailureMockFilename = "site-users-update-role-bad-json-failure.json"
let validationSuccessMockFilename = "people-validate-invitation-success.json"
let validationFailureMockFilename = "people-validate-invitation-failure.json"
let sendSuccessMockFilename = "people-send-invitation-success.json"
let sendFailureMockFilename = "people-send-invitation-failure.json"
let deleteUserSuccessMockFilename = "site-users-delete-success.json"
let deleteUserAuthFailureMockFilename = "site-users-delete-auth-failure.json"
let deleteUserBadJsonFailureMockFilename = "site-users-delete-bad-json-failure.json"
let deleteUserNonMemberFailureMockFilename = "site-users-delete-not-member-failure.json"
let deleteUserSiteOwnerFailureMockFilename = "site-users-delete-site-owner-failure.json"
let deleteFollowerSuccessMockFilename = "site-followers-delete-success.json"
let deleteFollowerFailureMockFilename = "site-followers-delete-failure.json"
let deleteFollowerAuthFailureMockFilename = "site-followers-delete-auth-failure.json"
let deleteFollowerBadJsonFailureMockFilename = "site-followers-delete-bad-json-failure.json"
let deleteViewerSuccessMockFilename = "site-viewers-delete-success.json"
let deleteViewerFailureMockFilename = "site-viewers-delete-failure.json"
let deleteViewerAuthFailureMockFilename = "site-viewers-delete-auth-failure.json"
let deleteViewerBadJsonFailureMockFilename = "site-viewers-delete-bad-json.json"
// MARK: - Properties
var remote: PeopleServiceRemote!
var siteRolesEndpoint: String { return "sites/\(siteID)/roles" }
var siteUserEndpoint: String { return "sites/\(siteID)/users/\(userID)" }
var siteUnknownUserEndpoint: String { return "sites/\(siteID)/users/\(invalidUserID)" }
var unknownSiteUserEndpoint: String { return "sites/\(invalidSiteID)/users/\(userID)" }
var siteUserDeleteEndpoint: String { return "sites/\(siteID)/users/\(userID)/delete" }
var siteViewerDeleteEndpoint: String { return "sites/\(siteID)/viewers/\(viewerID)/delete" }
var siteFollowerDeleteEndpoint: String { return "sites/\(siteID)/followers/\(followerID)/delete" }
// MARK: - Overridden Methods
override func setUp() {
super.setUp()
remote = PeopleServiceRemote(wordPressComRestApi: getRestApi())
}
override func tearDown() {
super.tearDown()
remote = nil
}
// MARK: - User Tests
func testDeleteUserWithBadAuthUserFails() {
let expect = expectation(description: "Delete user with bad auth failure")
stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserAuthFailureMockFilename, contentType: .ApplicationJSON, status: 403)
remote.deleteUser(siteID, userID: userID, success: { roles in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteUserWithSiteOwnerFails() {
let expect = expectation(description: "Delete user with site owner failure")
stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserSiteOwnerFailureMockFilename, contentType: .ApplicationJSON, status: 403)
remote.deleteUser(siteID, userID: userID, success: { roles in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteUserWithNonMemberFails() {
let expect = expectation(description: "Delete user with non site member failure")
stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserNonMemberFailureMockFilename, contentType: .ApplicationJSON, status: 400)
remote.deleteUser(siteID, userID: userID, success: { roles in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.invalidInput.rawValue, "The error code should be 0 - invalid input")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteUserWithValidUserSucceeds() {
let expect = expectation(description: "Delete user success")
stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserSuccessMockFilename,
contentType: .ApplicationJSON)
remote.deleteUser(siteID, userID: userID, success: {
expect.fulfill()
}, failure: { error in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteUserWithServerErrorFails() {
let expect = expectation(description: "Delete user with server error failure")
stubRemoteResponse(siteUserDeleteEndpoint, data: Data(), contentType: .NoContentType, status: 500)
remote.deleteUser(siteID, userID: userID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteUserWithBadJsonFails() {
let expect = expectation(description: "Delete user with invalid json response failure")
stubRemoteResponse(siteUserDeleteEndpoint, filename: deleteUserBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200)
remote.deleteUser(siteID, userID: userID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
// MARK: - Follower Tests
func testDeleteFollowerWithInvalidFollowerFails() {
let expect = expectation(description: "Delete non-follower failure")
stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerFailureMockFilename,
contentType: .ApplicationJSON, status: 404)
remote.deleteFollower(siteID, userID: followerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteFollowerWithBadAuthFails() {
let expect = expectation(description: "Delete follower with bad auth failure")
stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerAuthFailureMockFilename, contentType: .ApplicationJSON, status: 403)
remote.deleteFollower(siteID, userID: followerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteFollowerWithValidFollowerSucceeds() {
let expect = expectation(description: "Delete follower success")
stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerSuccessMockFilename,
contentType: .ApplicationJSON)
remote.deleteFollower(siteID, userID: followerID, success: {
expect.fulfill()
}, failure: { error in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteFollowerWithServerErrorFails() {
let expect = expectation(description: "Delete follower with server error failure")
stubRemoteResponse(siteFollowerDeleteEndpoint, data: Data(), contentType: .NoContentType, status: 500)
remote.deleteFollower(siteID, userID: followerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteFollowerWithBadJsonFails() {
let expect = expectation(description: "Delete follower with invalid json response failure")
stubRemoteResponse(siteFollowerDeleteEndpoint, filename: deleteFollowerBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200)
remote.deleteFollower(siteID, userID: followerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
// MARK: - Viewer Tests
func testDeleteViewerWithInvalidViewerFails() {
let expect = expectation(description: "Delete viewer failure")
stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerFailureMockFilename,
contentType: .ApplicationJSON, status: 404)
remote.deleteViewer(siteID, userID: viewerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteViewerWithValidViewerSucceeds() {
let expect = expectation(description: "Delete viewer success")
stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerSuccessMockFilename,
contentType: .ApplicationJSON)
remote.deleteViewer(siteID, userID: viewerID, success: {
expect.fulfill()
}, failure: { error in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteViewerWithBadAuthFails() {
let expect = expectation(description: "Delete viewer with bad auth failure")
stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerAuthFailureMockFilename, contentType: .ApplicationJSON, status: 403)
remote.deleteViewer(siteID, userID: viewerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteViewerWithServerErrorFails() {
let expect = expectation(description: "Delete viewer with server error failure")
stubRemoteResponse(siteViewerDeleteEndpoint, data: Data(), contentType: .NoContentType, status: 500)
remote.deleteViewer(siteID, userID: viewerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testDeleteViewerWithBadJsonFails() {
let expect = expectation(description: "Delete viewer with invalid json response failure")
stubRemoteResponse(siteViewerDeleteEndpoint, filename: deleteViewerBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200)
remote.deleteViewer(siteID, userID: viewerID, success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
// MARK: - Role Tests
func testGetSiteRolesSucceeds() {
let expect = expectation(description: "Get site roles success")
stubRemoteResponse(siteRolesEndpoint, filename: getRolesSuccessMockFilename,
contentType: .ApplicationJSON)
remote.getUserRoles(siteID, success: { roles in
XCTAssertFalse(roles.isEmpty, "The returned roles array should not be empty")
XCTAssertTrue(roles.count == 4, "There should be 4 roles returned")
expect.fulfill()
}, failure: { error in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testGetSiteRolesWithServerErrorFails() {
let expect = expectation(description: "Get site roles with server error failure")
stubRemoteResponse(siteRolesEndpoint, data: Data(), contentType: .NoContentType, status: 500)
remote.getUserRoles(siteID, success: { roles in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testGetSiteRolesWithBadAuthFails() {
let expect = expectation(description: "Get site roles with bad auth failure")
stubRemoteResponse(siteRolesEndpoint, filename: getRolesBadAuthMockFilename, contentType: .ApplicationJSON, status: 403)
remote.getUserRoles(siteID, success: { roles in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.authorizationRequired.rawValue, "The error code should be 2 - authorization_required")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testGetSiteRolesWithBadJsonFails() {
let expect = expectation(description: "Get site roles with invalid json response failure")
stubRemoteResponse(siteRolesEndpoint, filename: getRolesBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200)
remote.getUserRoles(siteID, success: { roles in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testUpdateUserRoleSucceeds() {
let expect = expectation(description: "Update user role success")
stubRemoteResponse(siteUserEndpoint, filename: updateRoleSuccessMockFilename, contentType: .ApplicationJSON)
let change = "administrator"
remote.updateUserRole(siteID, userID: userID, newRole: change, success: { updatedPerson in
XCTAssertEqual(updatedPerson.role, change, "The returned user's role should be the same as the updated role.")
expect.fulfill()
}, failure: { error in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testUpdateUserRoleWithUnknownUserFails() {
let expect = expectation(description: "Update role with unknown user failure")
stubRemoteResponse(siteUnknownUserEndpoint, filename: updateRoleUnknownUserFailureMockFilename, contentType: .ApplicationJSON, status: 404)
let change = "administrator"
remote.updateUserRole(siteID, userID: invalidUserID, newRole: change, success: { updatedPerson in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testUpdateUserRoleWithUnknownSiteFails() {
let expect = expectation(description: "Update role with unknown site failure")
stubRemoteResponse(unknownSiteUserEndpoint, filename: updateRoleUnknownSiteFailureMockFilename, contentType: .ApplicationJSON, status: 403)
let change = "administrator"
remote.updateUserRole(invalidSiteID, userID: userID, newRole: change, success: { updatedPerson in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testUpdateUserRoleWithServerErrorFails() {
let expect = expectation(description: "Update role with server error failure")
stubRemoteResponse(siteUserEndpoint, data: Data(), contentType: .NoContentType, status: 500)
let change = "administrator"
remote.updateUserRole(siteID, userID: userID, newRole: change, success: { updatedPerson in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
let error = error as NSError
XCTAssertEqual(error.domain, String(reflecting: WordPressComRestApiError.self), "The error domain should be WordPressComRestApiError")
XCTAssertEqual(error.code, WordPressComRestApiError.unknown.rawValue, "The error code should be 7 - unknown")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testUpdateUserRoleWithBadJsonFails() {
let expect = expectation(description: "Update role with invalid json response failure")
stubRemoteResponse(siteUserEndpoint, filename: updateRoleBadJsonFailureMockFilename, contentType: .ApplicationJSON, status: 200)
let change = "administrator"
remote.updateUserRole(siteID, userID: userID, newRole: change, success: { updatedPerson in
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
// MARK: - Invite Tests
func testSendInvitationToInvalidUsernameFails() {
let expect = expectation(description: "Send invite failure")
stubRemoteResponse(newInviteEndpoint, filename: sendFailureMockFilename, contentType: .ApplicationJSON)
remote.sendInvitation(siteID, usernameOrEmail: invalidUsername, role: "follower", message: "", success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testSendInvitationToValidUsernameSucceeds() {
let expect = expectation(description: "Send invite success")
stubRemoteResponse(newInviteEndpoint, filename: sendSuccessMockFilename, contentType: .ApplicationJSON)
remote.sendInvitation(siteID, usernameOrEmail: validUsername, role: "follower", message: "", success: {
expect.fulfill()
}, failure: { error in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testValidateInvitationWithInvalidUsernameFails() {
let expect = expectation(description: "Validate invite failure")
stubRemoteResponse(validateInviteEndpoint, filename: validationFailureMockFilename, contentType: .ApplicationJSON)
remote.validateInvitation(siteID, usernameOrEmail: invalidUsername, role: "follower", success: {
XCTFail("This callback shouldn't get called")
expect.fulfill()
}, failure: { error in
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
func testValidateInvitationWithValidUsernameSucceeds() {
let expect = expectation(description: "Validate invite success")
stubRemoteResponse(validateInviteEndpoint, filename: validationSuccessMockFilename, contentType: .ApplicationJSON)
remote.validateInvitation(siteID, usernameOrEmail: validUsername, role: "follower", success: {
expect.fulfill()
}, failure: { error in
XCTFail("This callback shouldn't get called")
expect.fulfill()
})
waitForExpectations(timeout: timeout, handler: nil)
}
}
|
e23372a26084ea98733b1fba56f82e41
| 44.620626 | 150 | 0.680163 | false | true | false | false |
ajsnow/Shear
|
refs/heads/master
|
Shear/Sequence.swift
|
mit
|
1
|
// Copyright 2016 The Shear Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
import Foundation
// MARK: - Sequence
public extension TensorProtocol {
/// Slices the TensorProtocol into a sequence of `TensorSlice`s on its nth `deminsion`.
func sequence(_ deminsion: Int) -> [Tensor<Element>] {
if (isEmpty || isScalar) && deminsion == 0 { // TODO: Consider making sequencing scalar or empty arrays an error.
return [Tensor(self)]
}
guard deminsion < rank else { fatalError("An array cannot be sequenced on a deminsion it does not have") }
let viewIndices = [TensorIndex](repeating: TensorIndex.all, count: rank)
return (0..<shape[deminsion]).map {
var nViewIndices = viewIndices
nViewIndices[deminsion] = .singleValue($0)
return self[nViewIndices]
}
}
/// Slices the TensorProtocol on its first dimension.
/// Since our DenseTensor is stored in Row-Major order, sequencing on the first
/// dimension allows for better memory access patterns than any other sequence.
var sequenceFirst: [Tensor<Element>] {
return sequence(0)
}
/// Slices the TensorProtocol on its last dimension.
/// Tends to not be cache friendly...
var sequenceLast: [Tensor<Element>] {
return sequence(rank != 0 ? rank - 1 : 0)
}
/// Returns a sequence containing pairs of cartesian indices and `Element`s.
public func coordinate() -> AnySequence<([Int], Element)> {
let indexGenerator = makeRowMajorIndexGenerator(shape)
return AnySequence(AnyIterator {
guard let indices = indexGenerator.next() else { return nil }
return (indices, self[indices]) // TODO: Linear indexing is cheaper for DenseTensors. Consider specializing.
})
}
}
|
0c46cf817c1cb519586d57dc17067862
| 39.708333 | 121 | 0.646366 | false | false | false | false |
aleph7/HDF5Kit
|
refs/heads/master
|
Source/Dataspace.swift
|
mit
|
1
|
// Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of HDF5Kit. The full HDF5Kit copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#if SWIFT_PACKAGE
import CHDF5
#endif
public class Dataspace {
var id: hid_t
init(id: hid_t) {
self.id = id
guard id >= 0 else {
fatalError("Failed to create Dataspace")
}
selectionDims = []
selectionDims = dims
}
deinit {
let status = H5Sclose(id)
assert(status >= 0, "Failed to close Dataspace")
}
public internal(set) var selectionDims: [Int]
/// Create a Dataspace
public init(dims: [Int]) {
let dims64 = dims.map({ hsize_t(bitPattern: hssize_t($0)) })
id = dims64.withUnsafeBufferPointer { pointer in
return H5Screate_simple(Int32(dims.count), pointer.baseAddress, nil)
}
guard id >= 0 else {
fatalError("Failed to create Dataspace")
}
selectionDims = dims
}
/// Create a Dataspace for use in a chunked Dataset. No component of `maxDims` should be less than the corresponding element of `dims`. Elements of `maxDims` can have a value of -1, those dimension will have an unlimited size.
public init(dims: [Int], maxDims: [Int]) {
let dims64 = dims.map({ hsize_t(bitPattern: hssize_t($0)) })
let maxDims64 = maxDims.map({ hsize_t(bitPattern: hssize_t($0)) })
id = withExtendedLifetime((dims64, maxDims64)) {
return H5Screate_simple(Int32(dims.count), dims64, maxDims64)
}
guard id >= 0 else {
fatalError("Failed to create Dataspace")
}
selectionDims = dims
}
public convenience init(_ space: Dataspace) {
self.init(id: H5Scopy(space.id))
}
/// The total number of elements in the Dataspace
public var size: Int {
let result = H5Sget_simple_extent_npoints(id)
guard result >= 0 else {
fatalError("Failed to get Dataspace size")
}
return Int(result)
}
/// The size of each dimension in the Dataspace
public var dims: [Int] {
let rank = Int(H5Sget_simple_extent_ndims(id))
var dims = [hsize_t](repeating: 0, count: rank)
dims.withUnsafeMutableBufferPointer { pointer in
guard H5Sget_simple_extent_dims(id, pointer.baseAddress, nil) >= 0 else {
fatalError("Coulnd't get the dimensons of the Dataspace")
}
}
return dims.map({ Int(hssize_t(bitPattern: $0)) })
}
/// The maximum size of each dimension in the Dataspace
public var maxDims: [Int] {
let rank = Int(H5Sget_simple_extent_ndims(id))
var maxDims = [hsize_t](repeating: 0, count: rank)
maxDims.withUnsafeMutableBufferPointer { pointer in
guard H5Sget_simple_extent_dims(id, nil, pointer.baseAddress) >= 0 else {
fatalError("Coulnd't get the dimensons of the Dataspace")
}
}
return maxDims.map({ Int(hssize_t(bitPattern: $0)) })
}
// MARK: - Selection
public var hasValidSelection: Bool {
return H5Sselect_valid(id) > 0
}
public var selectionSize: Int {
return Int(H5Sget_select_npoints(id))
}
/// Selects the entire dataspace.
public func selectAll() {
H5Sselect_all(id)
selectionDims = dims
}
/// Resets the selection region to include no elements.
public func selectNone() {
H5Sselect_none(id)
for i in 0..<selectionDims.count {
selectionDims[i] = 0
}
}
/// Select a hyperslab region.
///
/// - parameter start: Specifies the offset of the starting element of the specified hyperslab.
/// - parameter stride: Chooses array locations from the dataspace with each value in the stride array determining how many elements to move in each dimension. Stride values of 0 are not allowed. If the stride parameter is `nil`, a contiguous hyperslab is selected (as if each value in the stride array were set to 1).
/// - parameter count: Determines how many blocks to select from the dataspace, in each dimension.
/// - parameter block: Determines the size of the element block selected from the dataspace. If the block parameter is set to `nil`, the block size defaults to a single element in each dimension (as if each value in the block array were set to 1).
public func select(start: [Int], stride: [Int]?, count: [Int]?, block: [Int]?) {
let start64 = start.map({ hsize_t(bitPattern: hssize_t($0)) })
let stride64 = stride?.map({ hsize_t(bitPattern: hssize_t($0)) })
let count64 = count?.map({ hsize_t(bitPattern: hssize_t($0)) })
let block64 = block?.map({ hsize_t(bitPattern: hssize_t($0)) })
withExtendedLifetime((start64, stride64, count64, block64)) { () -> Void in
H5Sselect_hyperslab(id, H5S_SELECT_SET, start64, pointerOrNil(stride64), pointerOrNil(count64), pointerOrNil(block64))
}
selectionDims = count ?? dims
}
/// Select a hyperslab region.
public func select(_ slices: HyperslabIndexType...) {
select(slices)
}
/// Select a hyperslab region.
public func select(_ slices: [HyperslabIndexType]) {
let dims = self.dims
let rank = dims.count
var start = [Int](repeating: 0, count: rank)
var stride = [Int](repeating: 1, count: rank)
var count = [Int](repeating: 0, count: rank)
var block = [Int](repeating: 1, count: rank)
for (index, slice) in slices.enumerated() {
start[index] = slice.start
stride[index] = slice.stride
if slice.blockCount != HyperslabIndex.all {
count[index] = slice.blockCount
} else {
count[index] = dims[index] - slice.start
}
block[index] = slice.blockSize
}
select(start: start, stride: stride, count: count, block: block)
}
/// This function allows the same shaped selection to be moved to different locations within a dataspace without requiring it to be redefined.
public func offset(_ offset: [Int]) {
let offset64 = offset.map({ hssize_t($0) })
offset64.withUnsafeBufferPointer { (pointer) -> Void in
H5Soffset_simple(id, pointer.baseAddress)
}
}
}
func pointerOrNil(_ array: [hsize_t]?) -> UnsafePointer<hsize_t>? {
if let array = array {
return UnsafePointer(array)
}
return nil
}
|
6a4c5ff8ae93b7eefcec9ffe9ae81042
| 37.314286 | 322 | 0.618792 | false | false | false | false |
BareFeetWare/BFWControls
|
refs/heads/develop
|
BFWControls/Modules/Layout/View/FlowView.swift
|
mit
|
1
|
//
// FlowView.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 23/3/19.
// Copyright © 2019 BareFeetWare. All rights reserved.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
@IBDesignable open class FlowView: UIView {
// MARK: - Variables
@IBInspectable var gapWidth: CGFloat = 0.0
@IBInspectable var gapHeight: CGFloat = 0.0
private lazy var heightConstraint: NSLayoutConstraint = {
NSLayoutConstraint(item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1.0,
constant: 100.0)
}()
// MARK: - Functions
private func subviewFramesThatFit(_ size: CGSize) -> [CGRect] {
var subviewFrames: [CGRect] = []
var startPoint = CGPoint.zero
var maxRowHeight = CGFloat(0.0)
for subview in subviews {
let subviewSize = subview.sizeThatFits(.noIntrinsicMetric)
var leftGap = startPoint.x == 0.0 ? 0.0 : gapWidth
let availableWidth = size.width - startPoint.x
if availableWidth < subviewSize.width + leftGap {
// Move to start of next row
startPoint.y += maxRowHeight + gapHeight
startPoint.x = 0.0
maxRowHeight = 0.0
leftGap = 0.0
}
maxRowHeight = max(maxRowHeight, subviewSize.height)
let subviewFrame = CGRect(origin: CGPoint(x: startPoint.x + leftGap, y: startPoint.y),
size: subviewSize)
subviewFrames.append(subviewFrame)
startPoint.x += leftGap + subviewSize.width
}
return subviewFrames
}
// MARK: - UIView
open override var intrinsicContentSize: CGSize {
return subviews.reduce(CGSize.zero) { (size, subview) in
let subviewSize = subview.sizeThatFits(.noIntrinsicMetric)
let leftGap = size.width == 0.0 ? 0.0 : gapWidth
return CGSize(width: size.width + leftGap + subviewSize.width,
height: max(size.height, subviewSize.height))
}
}
open override func layoutSubviews() {
let subviewFrames = subviewFramesThatFit(bounds.size)
heightConstraint.constant = subviewFrames.last?.maxY ?? 0.0
heightConstraint.isActive = true
super.layoutSubviews()
zip(subviews, subviewFrames).forEach { $0.frame = $1 }
}
}
fileprivate extension CGSize {
static let noIntrinsicMetric = CGSize(width: UIView.noIntrinsicMetric,
height: UIView.noIntrinsicMetric)
}
|
52423fc63677ceceae4e886f4c1df335
| 34.185185 | 98 | 0.567719 | false | false | false | false |
steelwheels/KiwiGraphics
|
refs/heads/master
|
Source/Primitives/KGCircle.swift
|
gpl-2.0
|
1
|
/**
* @file KGCircule.swift
* @brief Define KGCircule data structure
* @par Copyright
* Copyright (C) 2016 Steel Wheels Project
*/
import Foundation
import CoreGraphics
public struct KGCircle {
var mCenter: CGPoint
var mRadius: CGFloat
private var mBounds: CGRect
public init(center c: CGPoint, radius r: CGFloat){
mCenter = c
mRadius = r
mBounds = KGCircle.updateBounds(center: c, radius: r)
}
public var center: CGPoint {
get { return mCenter }
}
public var radius: CGFloat {
get { return mRadius }
}
public var bounds: CGRect {
get { return mBounds }
}
public var description: String {
let cstr = mCenter.description
let rstr = NSString(format: "%.2lf", mRadius)
return "{center:\(cstr) radius:\(rstr)}"
}
private static func updateBounds(center c: CGPoint, radius r: CGFloat) -> CGRect {
let origin = CGPoint(x: c.x - r, y: c.y - r)
let diameter = r * 2
let size = CGSize(width: diameter, height: diameter)
return CGRect(origin: origin, size: size)
}
}
|
6ed1c2162365190480ad62b88c01e231
| 20.3125 | 83 | 0.678397 | false | false | false | false |
WalterCreazyBear/Swifter30
|
refs/heads/master
|
UIElements/UIElements/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// UIElements
//
// Created by Bear on 2017/6/20.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let cellIdentify = "cellIdentify"
let elements:[String] = {
let eles = ["Label","Text","Gesture","Massive"]
return eles
}()
let tableView :UITableView = {
let tableView:UITableView = UITableView.init()
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.title = "UIElements"
self.setupTableView()
}
fileprivate func setupTableView(){
self.tableView.frame = self.view.bounds
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.backgroundColor = UIColor.white
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentify)
self.view.addSubview(self.tableView)
}
}
extension ViewController:UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.elements.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentify)
cell?.textLabel?.text = self.elements[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var vc:UIViewController?;
if(elements[indexPath.row] == "Label")
{
vc = UILabelViewController()
}
else if(elements[indexPath.row] == "Text")
{
vc = UITextViewController()
}
else if(elements[indexPath.row] == "Gesture")
{
vc = GetureViewController()
}
else if(elements[indexPath.row] == "Massive")
{
vc = UIMassiveViewController()
}
guard vc != nil else {
return;
}
self.navigationController?.pushViewController(vc!, animated: true)
}
}
|
65b4d5f06106dabbac0a68d7bc1bf7ff
| 27.26506 | 100 | 0.614237 | false | false | false | false |
dehesa/Utilities
|
refs/heads/master
|
Sources/common/foundation/Calendrical.swift
|
mit
|
2
|
import Foundation
public extension Calendar {
/// Returns the start of the day (00:00:00) for the given date.
/// - parameter date: Date indicating the targeted day.
/// - returns: The beginning of the targeted day.
public func beginningOfDay(for date: Date) -> Date {
var result = self.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date)
result.calendar = self
result.timeZone = self.timeZone
(result.hour, result.minute, result.second, result.nanosecond) = (0, 0, 0, 0) // There are 1_000_000_000 nanoseconds in a second
return result.date!
}
/// Returns the end of the day (23:59:59) for the given date.
/// - parameter date: Date indicating the targeted day.
/// - returns: The end of the targeted day.
public func endOfDay(for date: Date) -> Date {
var result = self.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: date)
result.calendar = self
result.timeZone = self.timeZone
(result.hour, result.minute, result.second, result.nanosecond) = (23, 59, 59, 500_000_000) // There are 1_000_000_000 nanoseconds in a second
return result.date!
}
/// Returns the next day (tomorrow) of the given date (with the same time).
/// - parameter date: Date indicating the targeted day.
/// - returns: The day after the targeted day.
public func nextDay(for date: Date) -> Date {
return self.date(byAdding: .day, value: 1, to: date)!
}
/// Returns the previous day (yesterday) of the given date (with the same time).
/// - parameter date: Date indicating the previous day.
/// - returns: The day previous to the targeted day.
public func previousDay(for date: Date) -> Date {
return self.date(byAdding: .day, value: -1, to: date)!
}
/// Returns the number of days between the given days.
/// - parameter dayA: The first day on the interval.
/// - parameter dayB: The last day on the interval.
/// - returns: Integer counting the number of days between the first and last day in the range.
public func numDaysBetween(_ dayA: Date, _ dayB: Date) -> Int {
var result = self.dateComponents([.day], from: dayA, to: dayB)
result.calendar = self
result.timeZone = self.timeZone
return result.day!
}
}
|
750c9ef927cf68f3f4979823599aac9a
| 44.886792 | 150 | 0.634046 | false | false | false | false |
WhisperSystems/Signal-iOS
|
refs/heads/master
|
SignalMessaging/attachments/OWSVideoPlayer.swift
|
gpl-3.0
|
1
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import AVFoundation
@objc
public protocol OWSVideoPlayerDelegate: class {
func videoPlayerDidPlayToCompletion(_ videoPlayer: OWSVideoPlayer)
}
@objc
public class OWSVideoPlayer: NSObject {
@objc
public let avPlayer: AVPlayer
let audioActivity: AudioActivity
let shouldLoop: Bool
@objc
weak public var delegate: OWSVideoPlayerDelegate?
@objc
convenience public init(url: URL) {
self.init(url: url, shouldLoop: false)
}
@objc
public init(url: URL, shouldLoop: Bool) {
self.avPlayer = AVPlayer(url: url)
self.audioActivity = AudioActivity(audioDescription: "[OWSVideoPlayer] url:\(url)", behavior: .playback)
self.shouldLoop = shouldLoop
super.init()
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidPlayToCompletion(_:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
}
// MARK: Dependencies
var audioSession: OWSAudioSession {
return Environment.shared.audioSession
}
// MARK: Playback Controls
@objc
public func pause() {
avPlayer.pause()
audioSession.endAudioActivity(self.audioActivity)
}
@objc
public func play() {
let success = audioSession.startAudioActivity(self.audioActivity)
assert(success)
guard let item = avPlayer.currentItem else {
owsFailDebug("video player item was unexpectedly nil")
return
}
if item.currentTime() == item.duration {
// Rewind for repeated plays, but only if it previously played to end.
avPlayer.seek(to: CMTime.zero)
}
avPlayer.play()
}
@objc
public func stop() {
avPlayer.pause()
avPlayer.seek(to: CMTime.zero)
audioSession.endAudioActivity(self.audioActivity)
}
@objc(seekToTime:)
public func seek(to time: CMTime) {
avPlayer.seek(to: time)
}
// MARK: private
@objc
private func playerItemDidPlayToCompletion(_ notification: Notification) {
self.delegate?.videoPlayerDidPlayToCompletion(self)
if shouldLoop {
avPlayer.seek(to: CMTime.zero)
avPlayer.play()
} else {
audioSession.endAudioActivity(self.audioActivity)
}
}
}
|
237f6128a5e15d792b0c10e53bd6a409
| 25.131313 | 112 | 0.615385 | false | false | false | false |
Lollipop95/WeiBo
|
refs/heads/master
|
WeiBo/WeiBo/Classes/View/Main/NewFeature/WBWelcomeView.swift
|
mit
|
1
|
//
// WBWelcomeView.swift
// WeiBo
//
// Created by Ning Li on 2017/5/5.
// Copyright © 2017年 Ning Li. All rights reserved.
//
import UIKit
/// 欢迎视图
class WBWelcomeView: UIView {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
/// 创建欢迎视图
class func welcomeView() -> WBWelcomeView {
let nib = UINib(nibName: "WBWelcomeView", bundle: nil)
let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView
v.frame = UIScreen.main.bounds
return v
}
override func awakeFromNib() {
super.awakeFromNib()
guard let urlString = WBNetworkManager.shared.userAccount.avatar_large,
let url = URL(string: urlString)
else {
return
}
iconView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big"))
iconView.layer.masksToBounds = true
iconView.layer.cornerRadius = iconView.bounds.width * 0.5
}
override func didMoveToWindow() {
super.didMoveToWindow()
layoutIfNeeded()
topConstraint.constant = 120
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [],
animations: {
self.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 1,
animations: {
self.tipLabel.alpha = 1
}, completion: { (_) in
self.removeFromSuperview()
})
}
}
}
|
6385915d87b6dd5c2bd2bb27941c9287
| 26.768116 | 95 | 0.505741 | false | false | false | false |
ingresse/ios-sdk
|
refs/heads/dev
|
IngresseSDK/Model/TransactionSession.swift
|
mit
|
1
|
//
// Copyright © 2017 Ingresse. All rights reserved.
//
public class TransactionSession: NSObject, Codable {
@objc public var id: String = ""
@objc public var dateTime: DateTime?
}
public class DateTime: NSObject, Codable {
@objc public var date: String = ""
@objc public var time: String = ""
var tms: String?
var dateTime: String = ""
@objc public var timestamp: String {
return tms ?? dateTime
}
enum CodingKeys: String, CodingKey {
case tms = "timestamp"
case date
case time
case dateTime
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
tms = try container.decodeIfPresent(String.self, forKey: .tms)
date = container.decodeKey(.date, ofType: String.self)
time = container.decodeKey(.time, ofType: String.self)
dateTime = container.decodeKey(.dateTime, ofType: String.self)
}
}
|
98270d8108a071c34e5e15b59919877f
| 27.228571 | 71 | 0.643725 | false | false | false | false |
satorun/MultiSelectionCollectionViewSample
|
refs/heads/master
|
MultiSelectionCollectionViewSample/MultiSelectionCell.swift
|
mit
|
1
|
//
// MultiSelectionCell.swift
// MultiSelectionCollectionViewSample
//
// Created by satorun on 2/3/15.
// Copyright (c) 2015 satorun. All rights reserved.
//
import UIKit
class MultiSelectionCell: UICollectionViewCell {
@IBOutlet weak var button: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var leadingSpaceConstraint: NSLayoutConstraint!
let kAnimationDuration = 0.4
var item : ModelItem?
var isEditMode:Bool = false {
didSet(oldEditMode) {
p_view(true)
}
}
var isSelected:Bool = false {
didSet(oldSelected) {
item!.isSelected = isSelected
p_view(false)
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setData(data: ModelItem) -> Void {
item = data
titleLabel.text = item!.title
isSelected = item!.isSelected!
}
func didSelect() {
if isEditMode {
isSelected = !isSelected // invert
} else {
// 編集モードじゃないときの処理
}
}
func p_view(animated: Bool) {
if isEditMode {
if isSelected {
p_selectedViewAtEditMode(animated)
} else {
p_unSelectedViewAtEditMode(animated)
}
} else {
if isSelected {
p_selectedViewAtNormalMode(animated)
} else {
p_unSelectedViewAtNormalMode(animated)
}
}
}
func p_selectedViewAtEditMode(animated: Bool) {
leadingSpaceConstraint.constant = 34
let duration = animated ? kAnimationDuration : 0
unowned let unownedSelf = self
UIView.animateWithDuration(duration, animations: { () -> Void in
unownedSelf.layoutIfNeeded()
unownedSelf.button.alpha = 1
unownedSelf.backgroundColor = UIColor.blueColor()
})
}
func p_selectedViewAtNormalMode(animated: Bool) {
leadingSpaceConstraint.constant = 0
let duration = animated ? kAnimationDuration : 0
unowned let unownedSelf = self
UIView.animateWithDuration(duration, animations: { () -> Void in
unownedSelf.layoutIfNeeded()
unownedSelf.button.alpha = 0
unownedSelf.backgroundColor = UIColor.yellowColor()
})
}
func p_unSelectedViewAtEditMode(animated: Bool) {
leadingSpaceConstraint.constant = 34
let duration = animated ? kAnimationDuration : 0
unowned let unownedSelf = self
UIView.animateWithDuration(duration, animations: { () -> Void in
unownedSelf.layoutIfNeeded()
unownedSelf.button.alpha = 1
unownedSelf.backgroundColor = UIColor.whiteColor()
})
}
func p_unSelectedViewAtNormalMode(animated: Bool) {
leadingSpaceConstraint.constant = 0
unowned let unownedSelf = self
let duration = animated ? kAnimationDuration : 0
UIView.animateWithDuration(duration, animations: { () -> Void in
unownedSelf.layoutIfNeeded()
unownedSelf.button.alpha = 0
unownedSelf.backgroundColor = UIColor.whiteColor()
})
}
}
|
2fa140bf4f6232eef643c9c2c2d02604
| 29.514019 | 72 | 0.599265 | false | false | false | false |
CoderJackyHuang/SwiftExtensionCodes
|
refs/heads/master
|
SwiftExtensionCodes/UIView+HYBExtension.swift
|
mit
|
1
|
//
// UIView+HYBExtension.swift
// SwiftExtensionCollection
//
// Created by huangyibiao on 15/9/22.
// Copyright © 2015年 huangyibiao. All rights reserved.
//
import UIKit
/// UIView's useful extensions.
///
/// Author: huangyibiao
/// Github: http://github.com/CoderJackyHuang/
/// Blog: http://www.hybblog.com/
public extension UIView {
// MARK: Frame API
/// Get/set self.frame.origin
var hyb_origin: CGPoint {
get { return self.frame.origin }
set { self.frame.origin = newValue }
}
// Get/set self.frame.origin.x
var hyb_originX: CGFloat {
get { return self.hyb_origin.x }
set { self.hyb_origin.x = newValue }
}
// Get/set self.frame.origin.y
var hyb_originY: CGFloat {
get { return self.hyb_origin.y }
set { self.hyb_origin.y = newValue }
}
/// Get/set self.frame.size.width
var hyb_width: CGFloat {
get { return self.frame.size.width }
set { self.frame.size.width = newValue }
}
/// Get/set self.frame.size.height
var hyb_height: CGFloat {
get { return self.frame.size.height }
set { self.frame.size.height = newValue }
}
/// Get/set self.frame.size
var hyb_size: CGSize {
get { return self.frame.size }
set { self.frame.size = newValue }
}
/// Get/set self.frame.size.width + self.frame.origin.x
var hyb_rightX: CGFloat {
get { return self.frame.size.width + self.frame.origin.x }
set { self.hyb_originX = newValue - self.hyb_width }
}
/// Get/set self.frame.size.height + self.frame.origin.y
var hyb_bottomX: CGFloat {
get { return self.frame.size.height + self.frame.origin.y }
set { self.hyb_originY = newValue - self.hyb_height }
}
/// Get/set self.center.x
var hyb_centerX: CGFloat {
get { return self.center.x }
set { self.center.x = newValue }
}
/// Get/set self.center.y
var hyb_centerY: CGFloat {
get { return self.center.y }
set { self.center.y = newValue }
}
/// Get/set self.center
var hyb_center: CGPoint {
get { return self.center }
set { self.center = newValue }
}
}
|
6afb9a87485e4d825f86562e9a143d84
| 23.738095 | 63 | 0.636013 | false | false | false | false |
fleurdeswift/code-editor
|
refs/heads/master
|
CodeEditorView/Theme.swift
|
mit
|
1
|
//
// Theme.swift
// CodeEditorView
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Foundation
public class Theme : Hashable, Equatable {
public enum Base {
case Dark
}
public let base: Base;
public let customized: Bool = false;
internal(set) public var backgroundDraw: Bool;
internal(set) public var backgroundColor: CGColorRef;
internal(set) public var leftSidebarBackgroundColor: CGColorRef;
internal(set) public var leftSidebarBorderColor: CGColorRef;
internal(set) public var lineNumberColor: CGColorRef;
internal(set) public var lineNumberSelectedColor: CGColorRef;
internal(set) public var lineNumberFontName: String;
internal(set) public var textFontName: String;
internal(set) public var textFontSize: CGFloat;
internal(set) public var textFontColor: CGColorRef;
internal(set) public var breakpointEnabledFillColor: CGColorRef;
internal(set) public var breakpointDisabledFillColor: CGColorRef;
internal(set) public var breakpointDisabledStrokeColor: CGColorRef;
internal(set) public var instructionPointerFillColor: CGColorRef;
internal(set) public var instructionPointerStrokeColor: CGColorRef;
public init(_ base: Base) {
self.base = base;
switch (base) {
case .Dark:
backgroundDraw = true;
backgroundColor = CGColorCreateGenericRGB(30.0 / 255.0, 32.0 / 255.0, 40.0 / 255.0, 1.0);
leftSidebarBackgroundColor = CGColorCreateGenericRGB(48.0 / 255.0, 49.0 / 255.0, 57.0 / 255.0, 1.0);
leftSidebarBorderColor = CGColorCreateGenericRGB(64.0 / 255.0, 66.0 / 255.0, 73.0 / 255.0, 1.0);
lineNumberColor = CGColorCreateGenericGray(0.5, 1.0);
lineNumberSelectedColor = CGColorCreateGenericGray(1.0, 1.0);
lineNumberFontName = "Arial Narrow";
textFontName = "Menlo";
textFontSize = 11.0;
textFontColor = CGColorCreateGenericGray(1, 1);
breakpointEnabledFillColor = CGColorCreateGenericRGB( 63.0 / 255.0, 112.0 / 255.0, 181.0 / 255.0, 1.0);
breakpointDisabledFillColor = CGColorCreateGenericRGB(161.0 / 255.0, 186.0 / 255.0, 328.0 / 255.0, 1.0);
breakpointDisabledStrokeColor = CGColorCreateGenericRGB(181.0 / 255.0, 201.0 / 255.0, 224.0 / 255.0, 1.0);
instructionPointerFillColor = CGColorCreateGenericRGB(183.0 / 255.0, 216.0 / 255.0, 169.0 / 255.0, 1.0);
instructionPointerStrokeColor = CGColorCreateGenericRGB(140.0 / 255.0, 161.0 / 255.0, 126.0 / 255.0, 1.0);
}
}
public var hashValue: Int {
get {
return backgroundDraw.hashValue ^
backgroundColor.hashValue ^
leftSidebarBackgroundColor.hashValue ^
leftSidebarBorderColor.hashValue ^
lineNumberColor.hashValue ^
lineNumberSelectedColor.hashValue ^
lineNumberFontName.hashValue ^
textFontName.hashValue ^
textFontSize.hashValue ^
breakpointEnabledFillColor.hashValue ^
breakpointDisabledFillColor.hashValue ^
breakpointDisabledStrokeColor.hashValue ^
instructionPointerFillColor.hashValue ^
instructionPointerStrokeColor.hashValue;
}
}
}
public func == (left: Theme, right: Theme) -> Bool {
return left.backgroundDraw == right.backgroundDraw &&
left.backgroundColor == right.backgroundColor &&
left.leftSidebarBackgroundColor == right.leftSidebarBackgroundColor &&
left.leftSidebarBorderColor == right.leftSidebarBorderColor &&
left.lineNumberColor == right.lineNumberColor &&
left.lineNumberSelectedColor == right.lineNumberSelectedColor &&
left.lineNumberFontName == right.lineNumberFontName &&
left.textFontName == right.textFontName &&
left.textFontSize == right.textFontSize &&
left.breakpointEnabledFillColor == right.breakpointEnabledFillColor &&
left.breakpointDisabledFillColor == right.breakpointDisabledFillColor &&
left.breakpointDisabledStrokeColor == right.breakpointDisabledStrokeColor &&
left.instructionPointerFillColor == right.instructionPointerFillColor &&
left.instructionPointerStrokeColor == right.instructionPointerStrokeColor;
}
|
1273e2d6aef0adeecfaaba4e1dcc85e3
| 44.834951 | 118 | 0.629528 | false | false | false | false |
TG908/iOS
|
refs/heads/master
|
TUM Campus App/PersistentUserData.swift
|
gpl-3.0
|
1
|
//
// PersistentUserData.swift
// TUM Campus App
//
// Created by Mathias Quintero on 12/16/16.
// Copyright © 2016 LS1 TUM. All rights reserved.
//
import Sweeft
enum PersistendUserData: StatusSerializable {
case no
case some(lrzID: String, token: String)
var serialized: [String : Any] {
switch self {
case .no:
return [:]
case .some(let lrzID, let token):
return [
"lrzID": lrzID,
"token": token,
]
}
}
init?(from status: [String : Any]) {
guard let lrzID = status["lrzID"] as? String,
let token = status["token"] as? String else {
return nil
}
self = .some(lrzID: lrzID, token: token)
}
var user: User? {
switch self {
case .no:
return nil
case .some(let lrzID, let token):
return User(lrzID: lrzID, token: token)
}
}
}
struct PersistentUser: ObjectStatus {
static var key: AppDefaults = .login
static var defaultValue: PersistendUserData = .no
}
|
666e58c4d3e202ff3fd6b43cc3a274d2
| 21.86 | 57 | 0.524059 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios
|
refs/heads/master
|
Frameworks/TBAData/Sources/Event/EventStatusQual.swift
|
mit
|
1
|
import CoreData
import Foundation
import TBAKit
extension EventStatusQual {
public var numTeams: Int? {
return getValue(\EventStatusQual.numTeamsRaw)?.intValue
}
public var status: String? {
return getValue(\EventStatusQual.statusRaw)
}
public var eventStatus: EventStatus? {
return getValue(\EventStatusQual.eventStatusRaw)
}
public var ranking: EventRanking? {
return getValue(\EventStatusQual.rankingRaw)
}
}
@objc(EventStatusQual)
public class EventStatusQual: NSManagedObject {
@nonobjc public class func fetchRequest() -> NSFetchRequest<EventStatusQual> {
return NSFetchRequest<EventStatusQual>(entityName: EventStatusQual.entityName)
}
@NSManaged var numTeamsRaw: NSNumber?
@NSManaged var statusRaw: String?
@NSManaged var eventStatusRaw: EventStatus?
@NSManaged var rankingRaw: EventRanking?
}
extension EventStatusQual: Managed {
public static func insert(_ model: TBAEventStatusQual, eventKey: String, teamKey: String, in context: NSManagedObjectContext) -> EventStatusQual {
let predicate = NSPredicate(format: "(%K == %@ AND %K == %@) OR (%K == %@ AND %K == %@)",
#keyPath(EventStatusQual.rankingRaw.eventRaw.keyRaw), eventKey,
#keyPath(EventStatusQual.rankingRaw.teamRaw.keyRaw), teamKey,
#keyPath(EventStatusQual.eventStatusRaw.eventRaw.keyRaw), eventKey,
#keyPath(EventStatusQual.eventStatusRaw.teamRaw.keyRaw), teamKey)
return findOrCreate(in: context, matching: predicate, configure: { (eventStatusQual) in
if let numTeams = model.numTeams {
eventStatusQual.numTeamsRaw = NSNumber(value: numTeams)
} else {
eventStatusQual.numTeamsRaw = nil
}
eventStatusQual.statusRaw = model.status
eventStatusQual.updateToOneRelationship(relationship: #keyPath(EventStatusQual.rankingRaw), newValue: model.ranking) {
return EventRanking.insert($0, sortOrderInfo: model.sortOrder, extraStatsInfo: nil, eventKey: eventKey, in: context)
}
})
}
}
extension EventStatusQual: Orphanable {
public var isOrphaned: Bool {
// EventStatusQual is an orphan if it's not attached to a Ranking or an EventStatus
let hasRanking = (rankingRaw != nil)
let hasStatus = (eventStatusRaw != nil)
return !hasRanking && !hasStatus
}
}
|
614d5c56bd980869f22f1b7b2b7ead05
| 34.597222 | 150 | 0.653921 | false | false | false | false |
iXieYi/Weibo_DemoTest
|
refs/heads/master
|
Weibo_DemoTest/Weibo_DemoTest/Common.swift
|
mit
|
1
|
//
// Common.swift
// Weibo_DemoTest
//
// Created by 谢毅 on 16/12/13.
// Copyright © 2016年 xieyi. All rights reserved.
//
/// 目的:提供全局共享属性、方法,类似于pch文件
import UIKit
/// MARK:- 全局通知定义
//切换根视图控制器通知 - 一定要与系统区别,一定要有前缀
let WBSwitchRootViewControllerNotification = "WBSwitchRootViewControllerNotification"
//选中照片的通知
let WBStatusSelectPhotoNotification = "WBStatusSelectPhotoNotification"
/// 选中照片的KEY -indexpath
let WBStatusSelectPhotoIndexPath = "WBStatusSelectPhotoIndexPath"
/// 图片数组 - url数组
let WBStatusSelectPhotoUrlKey = "WBStatusSelectPhotoUrlKey"
//全局外观渲染颜色->延展出皮肤的管理类,
let WBAppearanceTintColor = UIColor.orangeColor()
///MARK:-全局函数
/// 延迟在主线程执行的函数
///
/// - parameter delta: 延迟时间
/// - parameter callFunc: 要执行的闭包
func delay(delta:Double,callFunc:()->()){
//延迟方法
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, Int64(delta * Double(NSEC_PER_SEC))),
dispatch_get_main_queue()) {
callFunc()
}
}
|
8c3d4ae58a9eda6c6f7a88e851d04431
| 22.170732 | 85 | 0.714436 | false | false | false | false |
inlined/griddle
|
refs/heads/master
|
Griddle/ManagedObject.swift
|
mit
|
1
|
//
// ManagedObject.swift
// Griddle
//
// Created by Thomas Bouldin on 6/6/15.
// Copyright (c) 2015 Inlined. All rights reserved.
//
import Foundation
import Eventful
import Firebase
protocol UnsafeYielder {
func yieldUnsafe(val: AnyObject!)
}
public class Property<T : AnyObject> : Observable<T>, UnsafeYielder {
var target: ManagedObject!
let keyPath: String
public init(keyPath: String) {
self.keyPath = keyPath
}
public func bind(target: ManagedObject) {
assert(self.target == nil)
self.target = target
}
func yieldUnsafe(val: AnyObject!) {
yield(val as? T)
}
func set(val: T!) {
target.set(val, forKeyPath:keyPath)
}
}
infix operator <- { assignment }
func <-<T : AnyObject>(property: Property<T>, val: T!) {
property.set(val)
}
public class ManagedObject {
private var serverData = FDataSnapshot()
private var dirtyData = [String:AnyObject]()
private var yielders = [String:UnsafeYielder]()
private var ref : Firebase!
private var eventHandle: UInt = 0
public init(atURL: String) {
ref = Firebase(url:atURL)
eventHandle = ref.observeEventType(.Value, withBlock: { [unowned self] snapshot in
self.updateSnapshot(snapshot)
})
}
func get(keyPath: String) -> AnyObject? {
if let dirtyVal: AnyObject = dirtyData[keyPath] {
if dirtyVal is NSNull {
return nil
}
return dirtyVal
}
return serverData.valueForKeyPath(keyPath)
}
func set(value: AnyObject!, forKeyPath: String) {
dirtyData[forKeyPath] = value ?? NSNull()
yielders[forKeyPath]?.yieldUnsafe(value)
}
// TODO: Make Promise<Void> easier to use; right now it can't even be initialized.
public func save() -> Promise<Int> {
let done = Promise<Int>()
ref.updateChildValues(dirtyData) { err, _ in
if err == nil {
// TODO: dirtyData needs to be purged, but when will we get the updated snapshot?
done.resolve(0)
} else {
done.fail(err)
}
}
return done
}
// TODO(Thomas): Don't send events for data which hasn't changed.
func updateSnapshot(snapshot: FDataSnapshot!) {
serverData = snapshot
for child in snapshot.children {
let typedChild = child as! FDataSnapshot
if let yielder = yielders[typedChild.key] {
yielder.yieldUnsafe(typedChild.value)
}
}
}
/*
public func property<T>(keyPath: String) -> Property<T> {
if let existing = yielders[keyPath] {
return existing as! Property<T>
}
let newProp = Property<T>(target:self, keyPath:keyPath)
yielders[keyPath] = newProp
return newProp
}*/
}
|
ba9863c281140d5d97af61ae4ddb8c3e
| 23.592593 | 89 | 0.651977 | false | false | false | false |
niklassaers/Bolt-swift
|
refs/heads/master
|
Sources/SSLKeyGeneratorConfig.swift
|
bsd-3-clause
|
1
|
import Foundation
public struct SSLKeyGeneratorConfig {
public let signingRequestFileName: String
public let countryName: String
public let stateOrProvinceName: String
public let localityName: String
public let organizationName: String
public let orgUnitName: String
public let commonName: String
public let emailAddress: String
public let companyName: String
public init(
signingRequestFileName: String,
countryName: String,
stateOrProvinceName: String,
localityName: String,
organizationName: String,
orgUnitName: String,
commonName: String,
emailAddress: String,
companyName: String) {
self.signingRequestFileName = signingRequestFileName
self.countryName = countryName
self.stateOrProvinceName = stateOrProvinceName
self.localityName = localityName
self.organizationName = organizationName
self.orgUnitName = orgUnitName
self.commonName = commonName
self.emailAddress = emailAddress
self.companyName = companyName
}
public init(json: [String:Any]) {
signingRequestFileName = json["signingRequestFileName"] as? String ?? "csr.csr"
countryName = json["countryName"] as? String ?? "DK"
stateOrProvinceName = json["stateOrProvinceName"] as? String ?? "Esbjerg"
localityName = json["localityName"] as? String ?? ""
organizationName = json["organizationName"] as? String ?? "Bolt-swift"
orgUnitName = json["orgUnitName"] as? String ?? ""
commonName = json["commonName"] as? String ?? ""
emailAddress = json["emailAddress"] as? String ?? ""
companyName = json["companyName"] as? String ?? ""
}
}
|
ed8d1b3fd229ed36568a02efe4e3db0b
| 35.791667 | 87 | 0.669875 | false | false | false | false |
jakepolatty/HighSchoolScienceBowlPractice
|
refs/heads/master
|
High School Science Bowl Practice/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// High School Science Bowl Practice
//
// Created by Jake Polatty on 7/11/17.
// Copyright © 2017 Jake Polatty. All rights reserved.
//
import UIKit
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 1, height: 1))
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
let mainMenuController = MainMenuViewController()
window?.rootViewController = mainMenuController
window?.makeKeyAndVisible()
UIApplication.shared.statusBarStyle = .lightContent
let barColorPixel = UIImage.imageWithColor(color: UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.35))
UINavigationBar.appearance().setBackgroundImage(barColorPixel, for: UIBarMetrics.default)
UINavigationBar.appearance().shadowImage = barColorPixel
UINavigationBar.appearance().isTranslucent = true
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().layer.cornerRadius = 10
UINavigationBar.appearance().titleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary([NSAttributedString.Key.foregroundColor.rawValue: UIColor.white])
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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
|
17b19a0f1852983d058fad55b3e8b1a5
| 49 | 285 | 0.73519 | false | false | false | false |
adolfrank/Swift_practise
|
refs/heads/master
|
25-day/25-day/FifthViewController.swift
|
mit
|
1
|
//
// FifthViewController.swift
// 25-day
//
// Created by Hongbo Yu on 16/5/19.
// Copyright © 2016年 Frank. All rights reserved.
//
import UIKit
class FifthViewController: UIViewController {
@IBOutlet weak var trump1: UIImageView!
@IBOutlet weak var trump2: UIImageView!
@IBOutlet weak var trump3: UIImageView!
@IBOutlet weak var trump4: UIImageView!
@IBOutlet weak var trump5: UIImageView!
@IBOutlet weak var trump6: UIImageView!
@IBOutlet weak var trump7: UIImageView!
@IBOutlet weak var trump8: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func spin() {
UIView.animateWithDuration(0.8, delay: 0, options: .CurveLinear, animations: {
self.trump1.transform = CGAffineTransformRotate(self.trump1.transform, CGFloat(M_PI))
self.trump2.transform = CGAffineTransformRotate(self.trump2.transform, CGFloat(M_PI))
self.trump3.transform = CGAffineTransformRotate(self.trump3.transform, CGFloat(M_PI))
self.trump4.transform = CGAffineTransformRotate(self.trump4.transform, CGFloat(M_PI))
self.trump5.transform = CGAffineTransformRotate(self.trump5.transform, CGFloat(M_PI))
self.trump6.transform = CGAffineTransformRotate(self.trump6.transform, CGFloat(M_PI))
self.trump7.transform = CGAffineTransformRotate(self.trump7.transform, CGFloat(M_PI))
self.trump8.transform = CGAffineTransformRotate(self.trump8.transform, CGFloat(M_PI))
}) { (finished) -> Void in
self.spin()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.spin()
}
}
|
11cb6e82dcfa47cb4bd0ca4a84b5d5aa
| 30.793103 | 97 | 0.652928 | false | false | false | false |
beanything/BAWebsite
|
refs/heads/master
|
Sources/App/main.swift
|
mit
|
1
|
import Foundation
import Vapor
import HTTP
//Create Droplet
let app = Droplet()
// Middleware
// use 404.leaf for notFound status and error.leaf for all other errors
// errorPageMiddleware must be added to droplet via availableMiddleware to be called
// after file middleware! That avoids throwing 404 errors for files that are served from Public folder
let errorPageMiddleware = ErrorPageMiddleware("error", errorViews: [Status.notFound: "404"])
// set cache control for .html files to a short TTL and everything else to a long TTL
let cacheControlMiddleware = CacheControlMiddleware(1800, longTTL: 2592000)
// allow cross-origin-resources-requests from docs for webfonts and assets
let corsMiddleWware = CorsMiddleware("http://docs.swiftybeaver.com", pathPatterns: ["webfonts", ".png", ".jpg", ".less"])
// add middlewares to droplet. FileMiddleWare has to come at the end to make 404 pages work
app.middleware.append(cacheControlMiddleware)
app.middleware.append(corsMiddleWware)
app.middleware.append(errorPageMiddleware)
app.middleware.append(FileMiddleware(publicDir: "Public")) // serve static files from Public folder
errorPageMiddleware.droplet = app // required for error view rendering
//Routes
// Home Index
app.get { request in
return try app.view.make("index")
}
// Get Invited
app.get("invite") { request in
return try app.view.make("invite", ["title": "Get Invited"])
}
// Redirect Routes
app.get("signup") { request in
return Response(redirect: "invite")
}
app.get("getinvited") { request in
return Response(redirect: "invite")
}
// Sign In
app.get("signin") { request in
return try app.view.make("sign-in", ["title": "Sign In"])
}
// Jobs
app.get("jobs") { request in
return try app.view.make("jobs", ["title": "Jobs"])
}
app.get("ui") { request in
return try app.view.make("ui-kit.html", ["title": "UI Kit"])
}
app.run()
|
4bf6b605b1237c8e42fbb06a079a14c2
| 30.213115 | 122 | 0.72479 | false | false | false | false |
inacioferrarini/York
|
refs/heads/master
|
Example/Tests/York/Presenter/CollectionViewCellPresenterTests.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// 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 XCTest
import CoreData
import York
class CollectionViewCellPresenterTests: XCTestCase {
// MARK: - Properties
static let cellReuseIdBlock: ((_ indexPath: IndexPath) -> String) = { (indexPath: IndexPath) -> String in
return "ReuseCellID"
}
static var blockExecutionTest = ""
// MARK: - Supporting Methods
func createCollectionViewCellPresenter() -> CollectionViewCellPresenter<UICollectionViewCell, EntityTest> {
let presenter = CollectionViewCellPresenter<UICollectionViewCell, EntityTest>(
configureCellBlock: { (cell: UICollectionViewCell, entity: EntityTest) -> Void in
CollectionViewCellPresenterTests.blockExecutionTest = "testExecuted"
}, cellReuseIdentifierBlock: CollectionViewCellPresenterTests.cellReuseIdBlock)
return presenter
}
// MARK: - Tests
func test_collectionViewCellPresenterFields_configureCellBlock() {
let testAppContext = TestUtil().testAppContext()
let context = testAppContext.coreDataStack.managedObjectContext
let presenter = self.createCollectionViewCellPresenter()
let cell = UICollectionViewCell()
let helper = CoreDataUtil(inManagedObjectContext: context)
let entity = helper.createTestMass(withSize: 1, usingInitialIndex: 1, inSection: 1, initialOrderValue: 1).first!
presenter.configureCellBlock(cell, entity)
XCTAssertEqual(CollectionViewCellPresenterTests.blockExecutionTest, "testExecuted")
}
func test_collectionViewCellPresenterFields_reuseIdentifier() {
let presenter = self.createCollectionViewCellPresenter()
let presenterReuseId = presenter.cellReuseIdentifierBlock(IndexPath(row: 0, section: 0))
let testReuseId = CollectionViewCellPresenterTests.cellReuseIdBlock(IndexPath(row: 0, section: 0))
XCTAssertEqual(presenterReuseId, testReuseId)
}
}
|
43dd7585f750be5ba1b3a6e3f40c2381
| 41.684932 | 120 | 0.731065 | false | true | false | false |
ngquerol/Diurna
|
refs/heads/master
|
App/Sources/Views/StoriesTableView.swift
|
mit
|
1
|
//
// StoriesTableView.swift
// Diurna
//
// Created by Nicolas Gaulard-Querol on 22/07/2017.
// Copyright © 2017 Nicolas Gaulard-Querol. All rights reserved.
//
import AppKit
import HackerNewsAPI
class StoriesTableView: NSTableView {
// MARK: Methods
override func drawGrid(inClipRect clipRect: NSRect) {}
override func menu(for event: NSEvent) -> NSMenu? {
let point = convert(event.locationInWindow, from: nil)
let rowAtPoint = row(at: point)
guard rowAtPoint != -1 else { return nil }
let menu = NSMenu(title: "Story Context Menu")
let item =
menu
.addItem(withTitle: "Open in browser", action: .openStoryInBrowser, keyEquivalent: "")
guard
let cellView = view(
atColumn: 0,
row: rowAtPoint,
makeIfNecessary: false
) as? StoryCellView,
let story = cellView.objectValue as? Story
else {
return nil
}
item.representedObject = story
return menu
}
@objc func openStoryInBrowser(_ sender: NSMenuItem) {
guard let story = sender.representedObject as? Story else { return }
let storyURL = HNWebpage.item(story.id).path
do {
try NSWorkspace.shared.open(storyURL, options: .withoutActivation, configuration: [:])
} catch let error as NSError {
NSAlert(error: error).runModal()
}
}
}
// MARK: - Selectors
extension Selector {
fileprivate static let openStoryInBrowser = #selector(StoriesTableView.openStoryInBrowser(_:))
}
|
df9d987394d82b7004e02c039c464472
| 25.672131 | 98 | 0.611555 | false | false | false | false |
dobleuber/my-swift-exercises
|
refs/heads/master
|
Challenge2/Challenge2/DetailViewController.swift
|
mit
|
1
|
//
// DetailViewController.swift
// Challenge2
//
// Created by Wbert Castro on 13/06/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
import Social
class DetailViewController: UIViewController {
@IBOutlet weak var countryImageView: UIImageView!
var selectedCountry: String?
override func viewDidLoad() {
super.viewDidLoad()
title = selectedCountry
if let flagToLoad = selectedCountry {
countryImageView.image = UIImage(named: flagToLoad)
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareFlag))
}
func shareFlag() -> Void {
if let vc = SLComposeViewController(forServiceType: SLServiceTypeFacebook) {
vc.setInitialText("Checkout this amazing flag!")
vc.add(countryImageView.image)
present(vc, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
b906c0d4dfde970b42e8008bbc8e6556
| 27.769231 | 133 | 0.663102 | false | false | false | false |
MaximKotliar/Bindy
|
refs/heads/master
|
Tests/TransformationsTests.swift
|
mit
|
1
|
//
// TransformationsTests.swift
//
//
// Created by Alexander Karpov on 21.01.2021.
//
import XCTest
@testable import Bindy
final class TransformationsTests: XCTestCase {
func testMap() {
let observable = Observable<String>("test")
let mapped = observable.map { $0.count }
let asyncExpectation = expectation(description: "Expect to call")
mapped.bind(self) { old, new in
guard old == 4 else { return }
guard new == 0 else { return }
asyncExpectation.fulfill()
}
observable.value = ""
waitForExpectations(timeout: 1, handler: nil)
}
func testArrayMap() {
let observable = Observable(["one", "two", "three"])
let mapped: Observable<[Int]> = observable.map { $0.count }
let asyncExpectation = expectation(description: "Expect to call")
mapped.bind(self) { old, new in
guard old == [3, 3, 5] else { return }
guard new == [4] else { return }
asyncExpectation.fulfill()
}
observable.value = ["four"]
waitForExpectations(timeout: 1, handler: nil)
}
func testCompactMap() {
let observable = Observable(["test", "test", nil])
let compactMapped = observable.compactMap { $0 }
let asyncExpectation = expectation(description: "Expect not call")
asyncExpectation.isInverted = true
compactMapped.bind(self) { value in
guard value == ["test", "test", "test"] else { return }
asyncExpectation.fulfill()
}
observable.value.append("test")
waitForExpectations(timeout: 1, handler: nil)
}
func testReduce() {
let observable = Observable(["test", "test"])
let reduced = observable.reduce(0) { $0 + $1.count }
let asyncExpectation = expectation(description: "Expect to call")
reduced.bind(self) { value in
guard value == 12 else { return }
asyncExpectation.fulfill()
}
observable.value.append("test")
waitForExpectations(timeout: 1, handler: nil)
}
func testFilter() {
let observable = Observable(["test", "test", "notTest"])
let filtered = observable.filter { $0 == "test" }
let asyncExpectation = expectation(description: "Expect to call")
filtered.bind(self) { value in
guard value.count == 3 else { return }
asyncExpectation.fulfill()
}
observable.value.append("test")
waitForExpectations(timeout: 1, handler: nil)
}
static var allTests = [
("testMap", testMap),
("testArrayMap", testArrayMap),
("testCompactMap", testCompactMap),
("testReduce", testReduce),
("testFilter", testFilter)
]
}
|
762905923e19d68cd1930399bf8bb3c1
| 32.795181 | 74 | 0.587522 | false | true | false | false |
attaswift/Attabench
|
refs/heads/master
|
OptimizingCollections.attabench/Sources/BTree.swift
|
mit
|
2
|
//
// UnoptimizedBTree.swift
// Benchmark
//
// Created by Károly Lőrentey on 2017-02-09.
// Copyright © 2017 Károly Lőrentey.
//
struct BTree<Element: Comparable> {
fileprivate var root: Node<Element>
init(order: Int) {
self.root = Node(order: order)
}
}
fileprivate final class Node<Element: Comparable> {
let order: Int
var mutationCount: Int = 0
var elements: [Element] = []
var children: [Node] = []
init(order: Int) {
self.order = order
}
}
import Darwin
let cacheSize: Int = {
var result: Int = 0
var size = MemoryLayout<Int>.size
if sysctlbyname("hw.l1dcachesize", &result, &size, nil, 0) == -1 {
return 32768
}
return result
}()
extension BTree {
init() {
let order = cacheSize / (4 * MemoryLayout<Element>.stride)
self.init(order: Swift.max(16, order))
}
}
extension BTree {
public func forEach(_ body: (Element) throws -> Void) rethrows {
try root.forEach(body)
}
}
extension Node {
func forEach(_ body: (Element) throws -> Void) rethrows {
if children.count == 0 {
try elements.forEach(body)
}
else {
for i in 0 ..< elements.count {
try children[i].forEach(body)
try body(elements[i])
}
try children[elements.count].forEach(body)
}
}
}
extension Node {
internal func slot(of element: Element) -> (match: Bool, index: Int) {
var start = 0
var end = elements.count
while start < end {
let mid = start + (end - start) / 2
if elements[mid] < element {
start = mid + 1
}
else {
end = mid
}
}
let match = start < elements.count && elements[start] == element
return (match, start)
}
}
extension BTree {
public func contains(_ element: Element) -> Bool {
return root.contains(element)
}
}
extension Node {
func contains(_ element: Element) -> Bool {
let slot = self.slot(of: element)
if slot.match { return true }
guard !children.isEmpty else { return false }
return children[slot.index].contains(element)
}
}
extension BTree {
fileprivate mutating func makeRootUnique() -> Node<Element> {
if isKnownUniquelyReferenced(&root) { return root }
root = root.clone()
return root
}
}
extension Node {
func clone() -> Node {
let clone = Node(order: order)
clone.elements = self.elements
clone.children = self.children
return clone
}
}
extension Node {
func makeChildUnique(_ slot: Int) -> Node {
guard !isKnownUniquelyReferenced(&children[slot]) else {
return children[slot]
}
let clone = children[slot].clone()
children[slot] = clone
return clone
}
}
extension Node {
var isLeaf: Bool { return children.isEmpty }
var isTooLarge: Bool { return elements.count >= order }
}
private struct Splinter<Element: Comparable> {
let separator: Element
let node: Node<Element>
}
extension Node {
func split() -> Splinter<Element> {
let count = elements.count
let middle = count / 2
let separator = elements[middle]
let node = Node(order: order)
node.elements.append(contentsOf: elements[middle + 1 ..< count])
elements.removeSubrange(middle ..< count)
if !isLeaf {
node.children.append(contentsOf: children[middle + 1 ..< count + 1])
children.removeSubrange(middle + 1 ..< count + 1)
}
return Splinter(separator: separator, node: node)
}
}
extension Node {
func insert(_ element: Element) -> (old: Element?, splinter: Splinter<Element>?) {
let slot = self.slot(of: element)
if slot.match {
// The element is already in the tree.
return (self.elements[slot.index], nil)
}
mutationCount += 1
if self.isLeaf {
elements.insert(element, at: slot.index)
return (nil, self.isTooLarge ? self.split() : nil)
}
let (old, splinter) = makeChildUnique(slot.index).insert(element)
guard let s = splinter else { return (old, nil) }
elements.insert(s.separator, at: slot.index)
children.insert(s.node, at: slot.index + 1)
return (nil, self.isTooLarge ? self.split() : nil)
}
}
extension BTree {
@discardableResult
public mutating func insert(_ element: Element) -> (inserted: Bool, memberAfterInsert: Element) {
let root = makeRootUnique()
let (old, splinter) = root.insert(element)
if let splinter = splinter {
let r = Node<Element>(order: root.order)
r.elements = [splinter.separator]
r.children = [root, splinter.node]
self.root = r
}
return (old == nil, old ?? element)
}
}
private struct PathElement<Element: Comparable> {
unowned(unsafe) let node: Node<Element>
var slot: Int
init(_ node: Node<Element>, _ slot: Int) {
self.node = node
self.slot = slot
}
}
extension PathElement {
var isLeaf: Bool { return node.isLeaf }
var isAtEnd: Bool { return slot == node.elements.count }
var value: Element? {
guard slot < node.elements.count else { return nil }
return node.elements[slot]
}
var child: Node<Element> {
return node.children[slot]
}
}
extension PathElement: Equatable {
static func ==(left: PathElement, right: PathElement) -> Bool {
return left.node === right.node && left.slot == right.slot
}
}
public struct BTreeIndex<Element: Comparable> {
fileprivate weak var root: Node<Element>?
fileprivate let mutationCount: Int
fileprivate var path: [PathElement<Element>]
fileprivate var current: PathElement<Element>
init(startOf tree: BTree<Element>) {
self.root = tree.root
self.mutationCount = tree.root.mutationCount
self.path = []
self.current = PathElement(tree.root, 0)
while !current.isLeaf { push(0) }
}
init(endOf tree: BTree<Element>) {
self.root = tree.root
self.mutationCount = tree.root.mutationCount
self.path = []
self.current = PathElement(tree.root, tree.root.elements.count)
}
}
extension BTreeIndex {
fileprivate func validate(for root: Node<Element>) {
precondition(self.root === root)
precondition(self.mutationCount == root.mutationCount)
}
fileprivate static func validate(_ left: BTreeIndex, _ right: BTreeIndex) {
precondition(left.root === right.root)
precondition(left.mutationCount == right.mutationCount)
precondition(left.root != nil)
precondition(left.mutationCount == left.root!.mutationCount)
}
}
extension BTreeIndex {
fileprivate mutating func push(_ slot: Int) {
path.append(current)
current = PathElement(current.node.children[current.slot], slot)
}
fileprivate mutating func pop() {
current = self.path.removeLast()
}
}
extension BTreeIndex {
fileprivate mutating func formSuccessor() {
precondition(!current.isAtEnd, "Cannot advance beyond endIndex")
current.slot += 1
if current.isLeaf {
while current.isAtEnd, current.node !== root {
pop()
}
}
else {
while !current.isLeaf {
push(0)
}
}
}
}
extension BTreeIndex {
fileprivate mutating func formPredecessor() {
if current.isLeaf {
while current.slot == 0, current.node !== root {
pop()
}
precondition(current.slot > 0, "Cannot go below startIndex")
current.slot -= 1
}
else {
while !current.isLeaf {
let c = current.child
push(c.isLeaf ? c.elements.count - 1 : c.elements.count)
}
}
}
}
extension BTreeIndex: Comparable {
public static func ==(left: BTreeIndex, right: BTreeIndex) -> Bool {
BTreeIndex.validate(left, right)
return left.current == right.current
}
public static func <(left: BTreeIndex, right: BTreeIndex) -> Bool {
BTreeIndex.validate(left, right)
switch (left.current.value, right.current.value) {
case let (.some(a), .some(b)): return a < b
case (.none, _): return false
default: return true
}
}
}
extension BTree: SortedSet {
public typealias Index = BTreeIndex<Element>
public var startIndex: Index { return Index(startOf: self) }
public var endIndex: Index { return Index(endOf: self) }
public subscript(index: Index) -> Element {
get {
index.validate(for: root)
return index.current.value!
}
}
public func formIndex(after i: inout Index) {
i.validate(for: root)
i.formSuccessor()
}
public func formIndex(before i: inout Index) {
i.validate(for: root)
i.formPredecessor()
}
public func index(after i: Index) -> Index {
i.validate(for: root)
var i = i
i.formSuccessor()
return i
}
public func index(before i: Index) -> Index {
i.validate(for: root)
var i = i
i.formPredecessor()
return i
}
}
extension BTree {
public var count: Int {
return root.count
}
}
extension Node {
var count: Int {
return children.reduce(elements.count) { $0 + $1.count }
}
}
public struct BTreeIterator<Element: Comparable>: IteratorProtocol {
let tree: BTree<Element>
var index: BTreeIndex<Element>
init(_ tree: BTree<Element>) {
self.tree = tree
self.index = tree.startIndex
}
public mutating func next() -> Element? {
guard let result = index.current.value else { return nil }
index.formSuccessor()
return result
}
}
extension BTree {
public func makeIterator() -> BTreeIterator<Element> {
return BTreeIterator(self)
}
}
|
69f61099bfa4a7d780e2fb44f8b748fc
| 25.191327 | 101 | 0.585663 | false | false | false | false |
SnapFresh/SnapFresh
|
refs/heads/develop
|
iOS/SnapFresh/Constants.swift
|
apache-2.0
|
3
|
/*
* Copyright 2015 Marco Abundo, Ysiad Ferreiras, Aaron Bannert, Jeremy Canfield and Michelle Koeth
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/*!
@struct Constants
@abstract
SnapFresh constants
*/
struct Constants {
// SnapFresh API base URL
static let kSnapFreshBaseURL = "http://snapfresh.org"
// SnapFresh API endpoint
static let kSnapFreshEndpoint = "/retailers/nearaddy.json/"
// USDA farmers market API base URL
static let kUSDABaseURL = "http://search.ams.usda.gov"
// USDA farmers market location search API endpoint
static let kUSDAFarmersMarketSearchEndpoint = "/farmersmarkets/mobile/mobile.svc/locSearch?"
// USDA farmers market detail API endpoint
static let kUSDAFarmersMarketDetailEndpoint = "/farmersmarkets/v1/data.svc/mktDetail?"
// SnapFresh timeout interval
static let kSnapFreshTimeout: NSTimeInterval = 10.0
// Animation duration
static let kAnimationDuration: NSTimeInterval = 0.5
// Edge insets
static let kEdgeInsetPhone: CGFloat = 40.0
static let kEdgeInsetPad: CGFloat = 100.0
// Map image name
static let kMapImageName = "103-map"
// List image name
static let kListImageName = "259-list"
// Notifications posted when responses are returned
static let kSNAPRetailersDidLoadNotification = "SNAPRetailersDidLoadNotification"
static let kSNAPRetailersDidNotLoadNotification = "SNAPRetailersDidNotLoadNotification"
static let kFarmersMarketsDidLoadNotification = "FarmersMarketsDidLoadNotification"
static let kFarmersMarketsDidNotLoadNotification = "FarmersMarketsDidNotLoadNotification"
}
|
467b5b60a759bcd1176b70728b23d7cb
| 34.57377 | 98 | 0.753456 | false | false | false | false |
paulicelli/RadioButton
|
refs/heads/master
|
RadioButton/RoundButton.swift
|
mit
|
1
|
/*
------------------------------------------------------------------------------
MIT License
Copyright (c) 2017 Sabino Paulicelli
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.
------------------------------------------------------------------------------
RoundButton.swift
------------------------------------------------------------------------------
*/
import UIKit
final class RoundButton: UIButton {
var borderWidth: CGFloat = 2.0
var primaryColor: UIColor = UIColor.blue
var primaryColorWithAlpha: UIColor {
return primaryColor.withAlphaComponent(0.25)
}
override public var buttonType: UIButtonType {
return .custom
}
override public func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = bounds.size.width * 0.5
self.clipsToBounds = true
setupColors()
}
func setupColors() {
switch self.state {
case UIControlState.normal:
super.backgroundColor = .white
self.setTitleColor(primaryColor, for: state)
self.layer.borderColor = primaryColor.cgColor
self.layer.borderWidth = borderWidth
default:
super.backgroundColor = primaryColorWithAlpha
self.setTitleColor(.white, for: state)
}
}
}
|
187105069aa6e173cb4b17b180eb0af1
| 32.044118 | 80 | 0.660436 | false | false | false | false |
wang-chuanhui/CHSDK
|
refs/heads/master
|
Source/Transformation/StringTransform.swift
|
mit
|
1
|
//
// StringTransform.swift
// CHSDK
//
// Created by 王传辉 on 2017/8/4.
// Copyright © 2017年 王传辉. All rights reserved.
//
import Foundation
extension StringTransform where Self: CustomStringConvertible {
public func _toString() -> String {
return self.description
}
}
extension NSString: StringTransform {}
extension String: StringTransform {}
extension Int: StringTransform {}
extension Int8: StringTransform {}
extension Int16: StringTransform {}
extension Int32: StringTransform {}
extension Int64: StringTransform {}
extension UInt: StringTransform {}
extension UInt8: StringTransform {}
extension UInt16: StringTransform {}
extension UInt32: StringTransform {}
extension UInt64: StringTransform {}
extension Float: StringTransform {}
extension Double: StringTransform {}
extension Bool: StringTransform {}
extension RawRepresentable where RawValue: StringTransform {
func _toString() -> String {
return self.rawValue._toString()
}
}
extension NSNumber: StringTransform {
public func _toString() -> String {
if NSStringFromClass(type(of: self)) == "__NSCFBoolean" {
if boolValue {
return "true"
}else {
return "false"
}
}
return stringValue
}
}
extension StringTransform {
func _jsonString() -> String? {
if let json = (self as? Transformational)?.___toJSONValue() {
if JSONSerialization.isValidJSONObject(json) {
do {
let data = try JSONSerialization.data(withJSONObject: json)
if let string = String(data: data, encoding: String.Encoding.utf8) {
return string
}
} catch {
handle(error)
}
}
}
return nil
}
}
extension NSArray: StringTransform {
public func _toString() -> String {
if let jsonString = _jsonString() {
return jsonString
}
do {
let data = try JSONSerialization.data(withJSONObject: self, options: [])
let string = String(data: data, encoding: .utf8)
return string ?? description
} catch {
}
return description
}
}
extension Array: StringTransform {
public func _toString() -> String {
if let jsonString = _jsonString() {
return jsonString
}
do {
let data = try JSONSerialization.data(withJSONObject: self, options: [])
let string = String(data: data, encoding: .utf8)
return string ?? description
} catch {
}
return description
}
}
extension NSDictionary: StringTransform {
public func _toString() -> String {
if let jsonString = _jsonString() {
return jsonString
}
do {
let data = try JSONSerialization.data(withJSONObject: self, options: [])
let string = String(data: data, encoding: .utf8)
return string ?? description
} catch {
}
return description
}
}
extension Dictionary: StringTransform {
public func _toString() -> String {
if let jsonString = _jsonString() {
return jsonString
}
do {
let data = try JSONSerialization.data(withJSONObject: self, options: [])
let string = String(data: data, encoding: .utf8)
return string ?? description
} catch {
}
return description
}
}
|
80835f7eae447c9bc2c1ac02e88a14e7
| 25.705882 | 88 | 0.574615 | false | false | false | false |
kevll/LLImagePicker
|
refs/heads/master
|
LLImagePicker/LLImagePickerController.swift
|
mit
|
1
|
//
// LLImagePickerController.swift
// BuyInterflow
//
// Created by kevin on 2017/3/27.
// Copyright © 2017年 Ecommerce. All rights reserved.
//
import UIKit
import Photos
@available(iOS 8.0, *)
public final class LLImagePickerController: UIViewController {
private var navController: UINavigationController!
public var checkImg: UIImage?
public var minimumNumberOfSelection: UInt! = 1 // default is 1
public var maximumNumberOfSelection: UInt?
public var albumNavTitle: String? = "相册"
public var cancelTitle: String? = "取消"
public var confirmTitle: String? = "确定"
public var openPhotoAuthorPrompt: String? = "请先前往设置打开App访问相册权限"
public var downloadIcloudImagePrompt: String? = "请在系统相册下载iCloud图片后重试。"
public var alreadySelectionNumPrompt: String? = "已选择%d张图片"
public var didFinishPickingAssets: ((_ imagePickerController: LLImagePickerController ,_ assets: Array<PHAsset>)->Void)?
public override func viewDidLoad() {
super.viewDidLoad()
setAlbumsViewController()
}
internal func setAlbumsViewController(){
weak var selfWeak:LLImagePickerController! = self
let imagePickerController = LLAlbumsViewController()
imagePickerController.checkImg = checkImg
imagePickerController.minimumNumberOfSelection = minimumNumberOfSelection
imagePickerController.maximumNumberOfSelection = maximumNumberOfSelection
imagePickerController.albumNavTitle = albumNavTitle
imagePickerController.cancelTitle = cancelTitle
imagePickerController.confirmTitle = confirmTitle
imagePickerController.openPhotoAuthorPrompt = openPhotoAuthorPrompt
imagePickerController.downloadIcloudImagePrompt = downloadIcloudImagePrompt
imagePickerController.alreadySelectionNumPrompt = alreadySelectionNumPrompt
imagePickerController.didFinishPickingAssets = { (assets: Array<PHAsset>) in
selfWeak.didFinishPickingAssets?(selfWeak,assets)
}
navController = UINavigationController.init(rootViewController: imagePickerController)
navController.view.frame = self.view.bounds
imagePickerController.backBtnClick = {
selfWeak.dismiss(animated: true, completion: nil)
}
self.view.addSubview(navController.view)
}
}
|
64a94ccd02c3bca1acb6964ba5031939
| 39 | 124 | 0.73178 | false | false | false | false |
stripe/stripe-ios
|
refs/heads/master
|
StripePayments/StripePayments/API Bindings/Models/PaymentMethods/STPPaymentMethodBillingDetails.swift
|
mit
|
1
|
//
// STPPaymentMethodBillingDetails.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 3/5/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
/// Billing information associated with a `STPPaymentMethod` that may be used or required by particular types of payment methods.
/// - seealso: https://stripe.com/docs/api/payment_methods/object#payment_method_object-billing_details
public class STPPaymentMethodBillingDetails: NSObject, STPAPIResponseDecodable, STPFormEncodable {
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
/// Billing address.
@objc public var address: STPPaymentMethodAddress?
/// Email address.
@objc public var email: String?
/// Full name.
@objc public var name: String?
/// Billing phone number (including extension).
@objc public var phone: String?
@objc public private(set) var allResponseFields: [AnyHashable: Any] = [:]
/// :nodoc:
@objc public override var description: String {
let props = [
// Object
String(format: "%@: %p", NSStringFromClass(STPPaymentMethodBillingDetails.self), self),
// Properties
"name = \(name ?? "")",
"phone = \(phone ?? "")",
"email = \(email ?? "")",
"address = \(String(describing: address))",
]
return "<\(props.joined(separator: "; "))>"
}
/// :nodoc:
@objc public override required init() {
super.init()
}
// MARK: - STPFormEncodable
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:address)): "address",
NSStringFromSelector(#selector(getter:email)): "email",
NSStringFromSelector(#selector(getter:name)): "name",
NSStringFromSelector(#selector(getter:phone)): "phone",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
// MARK: - NSCopying
@objc(copyWithZone:) func copy(with zone: NSZone? = nil) -> Any {
let copyBillingDetails = type(of: self).init()
copyBillingDetails.allResponseFields = allResponseFields
copyBillingDetails.address = address?.copy() as? STPPaymentMethodAddress
copyBillingDetails.email = email
copyBillingDetails.name = name
copyBillingDetails.phone = phone
return copyBillingDetails
}
// MARK: - Equality
/// :nodoc:
@objc
public override func isEqual(_ other: Any?) -> Bool {
return isEqual(to: other as? STPPaymentMethodBillingDetails)
}
func isEqual(to other: STPPaymentMethodBillingDetails?) -> Bool {
if self === other {
return true
}
guard let other = other else {
return false
}
if !((additionalAPIParameters as NSDictionary).isEqual(to: other.additionalAPIParameters)) {
return false
}
return
address == other.address && email == other.email && name == other.name
&& phone == other.phone
}
// MARK: - STPAPIResponseDecodable
@objc
public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? {
guard let response = response else {
return nil
}
let dict = response.stp_dictionaryByRemovingNulls()
let billingDetails = self.init()
billingDetails.allResponseFields = response
billingDetails.address = STPPaymentMethodAddress.decodedObject(
fromAPIResponse: dict.stp_dictionary(forKey: "address")
)
billingDetails.email = dict.stp_string(forKey: "email")
billingDetails.name = dict.stp_string(forKey: "name")
billingDetails.phone = dict.stp_string(forKey: "phone")
return billingDetails
}
}
/// :nodoc:
extension STPPaymentMethodBillingDetails {
/// Convenience initializer for creating an `STPPaymentMethodBillingDetails` instance with a postal and country code
@objc convenience init(
postalCode: String,
countryCode: String? = Locale.autoupdatingCurrent.regionCode
) {
self.init()
let address = STPPaymentMethodAddress()
address.postalCode = postalCode
address.country = countryCode
self.address = address
}
}
|
97e5a061a5b6094f1b9a1176e610c39f
| 32.416667 | 129 | 0.63251 | false | false | false | false |
crazypoo/PTools
|
refs/heads/master
|
Pods/SwifterSwift/Sources/SwifterSwift/SwiftStdlib/ArrayExtensions.swift
|
mit
|
1
|
//
// ArrayExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 SwifterSwift
//
// MARK: - Methods
public extension Array {
/// SwifterSwift: Insert an element at the beginning of array.
///
/// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5]
/// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
mutating func prepend(_ newElement: Element) {
insert(newElement, at: 0)
}
/// SwifterSwift: Safely swap values at given index positions.
///
/// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
mutating func safeSwap(from index: Index, to otherIndex: Index) {
guard index != otherIndex else { return }
guard startIndex..<endIndex ~= index else { return }
guard startIndex..<endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
/// SwifterSwift: Sort an array like another array based on a key path. If the other array doesn't contain a certain value, it will be sorted last.
///
/// [MyStruct(x: 3), MyStruct(x: 1), MyStruct(x: 2)].sorted(like: [1, 2, 3], keyPath: \.x)
/// -> [MyStruct(x: 1), MyStruct(x: 2), MyStruct(x: 3)]
///
/// - Parameters:
/// - otherArray: array containing elements in the desired order.
/// - keyPath: keyPath indiciating the property that the array should be sorted by
/// - Returns: sorted array.
func sorted<T: Hashable>(like otherArray: [T], keyPath: KeyPath<Element, T>) -> [Element] {
let dict = otherArray.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset }
return sorted {
guard let thisIndex = dict[$0[keyPath: keyPath]] else { return false }
guard let otherIndex = dict[$1[keyPath: keyPath]] else { return true }
return thisIndex < otherIndex
}
}
}
// MARK: - Methods (Equatable)
public extension Array where Element: Equatable {
/// SwifterSwift: Remove all instances of an item from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5]
/// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"]
///
/// - Parameter item: item to remove.
/// - Returns: self after removing all instances of item.
@discardableResult
mutating func removeAll(_ item: Element) -> [Element] {
removeAll(where: { $0 == item })
return self
}
/// SwifterSwift: Remove all instances contained in items parameter from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4]
/// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"]
///
/// - Parameter items: items to remove.
/// - Returns: self after removing all instances of all items in given array.
@discardableResult
mutating func removeAll(_ items: [Element]) -> [Element] {
guard !items.isEmpty else { return self }
removeAll(where: { items.contains($0) })
return self
}
/// SwifterSwift: Remove all duplicate elements from Array.
///
/// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"]
///
/// - Returns: Return array with all duplicate elements removed.
@discardableResult
mutating func removeDuplicates() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the method
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
return self
}
/// SwifterSwift: Return array with all duplicate elements removed.
///
/// [1, 1, 2, 2, 3, 3, 3, 4, 5].withoutDuplicates() -> [1, 2, 3, 4, 5])
/// ["h", "e", "l", "l", "o"].withoutDuplicates() -> ["h", "e", "l", "o"])
///
/// - Returns: an array of unique elements.
///
func withoutDuplicates() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the method
return reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare.
///
/// - Parameter path: Key path to compare, the value must be Equatable.
/// - Returns: an array of unique elements.
func withoutDuplicates<E: Equatable>(keyPath path: KeyPath<Element, E>) -> [Element] {
return reduce(into: [Element]()) { (result, element) in
if !result.contains(where: { $0[keyPath: path] == element[keyPath: path] }) {
result.append(element)
}
}
}
/// SwifterSwift: Returns an array with all duplicate elements removed using KeyPath to compare.
///
/// - Parameter path: Key path to compare, the value must be Hashable.
/// - Returns: an array of unique elements.
func withoutDuplicates<E: Hashable>(keyPath path: KeyPath<Element, E>) -> [Element] {
var set = Set<E>()
return filter { set.insert($0[keyPath: path]).inserted }
}
}
|
b6fac9096da7070b2c07c5caf2a9a9a0
| 38.352518 | 151 | 0.550091 | false | false | false | false |
BlurredSoftware/BSWFoundation
|
refs/heads/develop
|
Sources/BSWFoundation/Parse/JSONParser.swift
|
mit
|
1
|
//
// Created by Pierluigi Cifani.
// Copyright (c) 2016 TheLeftBit SL. All rights reserved.
//
import Foundation
import Task; import Deferred
public enum JSONParser {
private static let queue = DispatchQueue(label: "com.bswfoundation.JSONParser")
public static let jsonDecoder = JSONDecoder()
public static let Options: JSONSerialization.ReadingOptions = [.allowFragments]
public static func parseData<T: Decodable>(_ data: Data) -> Task<T> {
let task: Task<T> = Task.async(upon: queue, onCancel: Error.canceled) {
let result: Task<T>.Result = self.parseData(data)
return try result.extract()
}
return task
}
public static func dataIsNull(_ data: Data) -> Bool {
guard let j = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else {
return false
}
guard let _ = j as? NSNull else {
return false
}
return true
}
public static func parseDataAsJSONPrettyPrint(_ data: Data) -> String? {
guard let json = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else { return nil }
let options: JSONSerialization.WritingOptions = {
if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) {
return [.fragmentsAllowed,.withoutEscapingSlashes]
} else {
return [.fragmentsAllowed]
}
}()
guard let prettyPrintedData = try? JSONSerialization.data(withJSONObject: json, options: options) else { return nil }
return String(data: prettyPrintedData, encoding: .utf8)
}
public static func errorMessageFromData(_ data: Data) -> String? {
guard let j = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else {
return nil
}
guard let dictionary = j as? [String: String] else {
return nil
}
return dictionary["error"]
}
static public func parseData<T: Decodable>(_ data: Data) -> Task<T>.Result {
guard T.self != VoidResponse.self else {
let response = VoidResponse.init() as! T
return .success(response)
}
/// Turns out that on iOS 12, parsing basic types using
/// Swift's `Decodable` is failing for some unknown
/// reasons. To lazy to file a radar...
/// So here we're instead using the good and trusted
/// `NSJSONSerialization` class
if T.self == Bool.self || T.self == Int.self || T.self == String.self {
if let output = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) as? T {
return .success(output)
} else {
return .failure(Error.malformedJSON)
}
}
if let provider = T.self as? DateDecodingStrategyProvider.Type {
jsonDecoder.dateDecodingStrategy = .formatted(provider.dateDecodingStrategy)
} else {
jsonDecoder.dateDecodingStrategy = .formatted(iso8601DateFormatter)
}
let result: Task<T>.Result
do {
let output: T = try jsonDecoder.decode(T.self, from: data)
result = .success(output)
} catch let decodingError as DecodingError {
switch decodingError {
case .keyNotFound(let missingKey, let context):
print("*ERROR* decoding, key \"\(missingKey)\" is missing, Context: \(context)")
result = .failure(Error.malformedSchema)
case .typeMismatch(let type, let context):
print("*ERROR* decoding, type \"\(type)\" mismatched, context: \(context)")
result = .failure(Error.malformedSchema)
case .valueNotFound(let type, let context):
print("*ERROR* decoding, value not found \"\(type)\", context: \(context)")
result = .failure(Error.malformedSchema)
case .dataCorrupted(let context):
print("*ERROR* Data Corrupted \"\(context)\")")
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
print("*ERROR* incoming JSON: \(string)")
}
result = .failure(Error.malformedJSON)
@unknown default:
result = .failure(Error.unknownError)
}
} catch {
result = .failure(Error.unknownError)
}
return result
}
//MARK: Error
public enum Error: Swift.Error {
case malformedJSON
case malformedSchema
case unknownError
case canceled
}
}
#if canImport(Combine)
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension JSONParser {
static func parseData<T: Decodable>(_ data: Data) -> CombineTask<T> {
let task: Task<T> = self.parseData(data)
return task.future
}
static func parseData<T: Decodable>(_ data: Data) -> Swift.Result<T, Swift.Error> {
return parseData(data).swiftResult
}
}
#endif
public protocol DateDecodingStrategyProvider {
static var dateDecodingStrategy: DateFormatter { get }
}
private var iso8601DateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}
extension Array: DateDecodingStrategyProvider where Element: DateDecodingStrategyProvider {
public static var dateDecodingStrategy: DateFormatter {
return Element.dateDecodingStrategy
}
}
|
958667835820d8ff46458a93869df7a2
| 35.452229 | 125 | 0.605452 | false | false | false | false |
StevenUpForever/FBSimulatorControl
|
refs/heads/master
|
fbsimctl/FBSimulatorControlKit/Sources/SimulatorRunners.swift
|
bsd-3-clause
|
2
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
import FBSimulatorControl
extension FileOutput {
func makeWriter() throws -> FBFileWriter {
switch self {
case .path(let path):
return try FBFileWriter(forFilePath: path, blocking: true)
case .standardOut:
return FBFileWriter(fileHandle: FileHandle.standardOutput, blocking: true)
}
}
}
struct SimulatorCreationRunner : Runner {
let context: iOSRunnerContext<CreationSpecification>
func run() -> CommandResult {
do {
for configuration in self.configurations {
self.context.reporter.reportSimpleBridge(.create, .started, configuration)
let simulator = try self.context.simulatorControl.set.createSimulator(with: configuration)
self.context.defaults.updateLastQuery(FBiOSTargetQuery.udids([simulator.udid]))
self.context.reporter.reportSimpleBridge(.create, .ended, simulator)
}
return .success(nil)
} catch let error as NSError {
return .failure("Failed to Create Simulator \(error.description)")
}
}
fileprivate var configurations: [FBSimulatorConfiguration] { get {
switch self.context.value {
case .allMissingDefaults:
return self.context.simulatorControl.set.configurationsForAbsentDefaultSimulators()
case .individual(let configuration):
return [configuration.simulatorConfiguration]
}
}}
}
struct SimulatorActionRunner : Runner {
let context: iOSRunnerContext<(Action, FBSimulator)>
func run() -> CommandResult {
let (action, simulator) = self.context.value
let reporter = SimulatorReporter(simulator: simulator, format: self.context.format, reporter: self.context.reporter)
defer {
simulator.userEventSink = nil
}
let context = self.context.replace((action, simulator, reporter))
return SimulatorActionRunner.makeRunner(context).run()
}
static func makeRunner(_ context: iOSRunnerContext<(Action, FBSimulator, SimulatorReporter)>) -> Runner {
let (action, simulator, reporter) = context.value
let covariantTuple: (Action, FBiOSTarget, iOSReporter) = (action, simulator, reporter)
if let runner = iOSActionProvider(context: context.replace(covariantTuple)).makeRunner() {
return runner
}
switch action {
case .approve(let bundleIDs):
return iOSTargetRunner.simple(reporter, .approve, StringsSubject(bundleIDs)) {
try simulator.authorizeLocationSettings(bundleIDs)
}
case .clearKeychain(let maybeBundleID):
return iOSTargetRunner.simple(reporter, .clearKeychain, ControlCoreSubject(simulator)) {
if let bundleID = maybeBundleID {
try simulator.killApplication(withBundleID: bundleID)
}
try simulator.clearKeychain()
}
case .delete:
return iOSTargetRunner.simple(reporter, .delete, ControlCoreSubject(simulator)) {
try simulator.set!.delete(simulator)
}
case .erase:
return iOSTargetRunner.simple(reporter, .erase, ControlCoreSubject(simulator)) {
try simulator.erase()
}
case .focus:
return iOSTargetRunner.simple(reporter, .focus, ControlCoreSubject(simulator)) {
try simulator.focus()
}
case .keyboardOverride:
return iOSTargetRunner.simple(reporter, .keyboardOverride, ControlCoreSubject(simulator)) {
try simulator.setupKeyboard()
}
case .open(let url):
return iOSTargetRunner.simple(reporter, .open, url.bridgedAbsoluteString) {
try simulator.open(url)
}
case .relaunch(let appLaunch):
return iOSTargetRunner.simple(reporter, .relaunch, ControlCoreSubject(appLaunch)) {
try simulator.launchOrRelaunchApplication(appLaunch)
}
case .search(let search):
return SearchRunner(reporter, search)
case .serviceInfo(let identifier):
return ServiceInfoRunner(reporter: reporter, identifier: identifier)
case .shutdown:
return iOSTargetRunner.simple(reporter, .shutdown, ControlCoreSubject(simulator)) {
try simulator.set!.kill(simulator)
}
case .tap(let x, let y):
return iOSTargetRunner.simple(reporter, .tap, ControlCoreSubject(simulator)) {
let event = FBSimulatorHIDEvent.tapAt(x: x, y: y)
try event.perform(on: simulator.connect().connectToHID())
}
case .setLocation(let latitude, let longitude):
return iOSTargetRunner.simple(reporter, .setLocation, ControlCoreSubject(simulator)) {
try simulator.setLocation(latitude, longitude: longitude)
}
case .upload(let diagnostics):
return UploadRunner(reporter, diagnostics)
case .watchdogOverride(let bundleIDs, let timeout):
return iOSTargetRunner.simple(reporter, .watchdogOverride, StringsSubject(bundleIDs)) {
try simulator.overrideWatchDogTimer(forApplications: bundleIDs, withTimeout: timeout)
}
default:
return CommandResultRunner.unimplementedActionRunner(action, target: simulator, format: context.format)
}
}
}
private struct SearchRunner : Runner {
let reporter: SimulatorReporter
let search: FBBatchLogSearch
init(_ reporter: SimulatorReporter, _ search: FBBatchLogSearch) {
self.reporter = reporter
self.search = search
}
func run() -> CommandResult {
let simulator = self.reporter.simulator
let diagnostics = simulator.diagnostics.allDiagnostics()
let results = search.search(diagnostics)
self.reporter.report(.search, .discrete, ControlCoreSubject(results))
return .success(nil)
}
}
private struct ServiceInfoRunner : Runner {
let reporter: SimulatorReporter
let identifier: String
func run() -> CommandResult {
var pid: pid_t = 0
guard let _ = try? self.reporter.simulator.launchctl.serviceName(forBundleID: self.identifier, processIdentifierOut: &pid) else {
return .failure("Could not get service for name \(identifier)")
}
guard let processInfo = self.reporter.simulator.processFetcher.processFetcher.processInfo(for: pid) else {
return .failure("Could not get process info for pid \(pid)")
}
return .success(SimpleSubject(.serviceInfo, .discrete, ControlCoreSubject(processInfo)))
}
}
private struct UploadRunner : Runner {
let reporter: SimulatorReporter
let diagnostics: [FBDiagnostic]
init(_ reporter: SimulatorReporter, _ diagnostics: [FBDiagnostic]) {
self.reporter = reporter
self.diagnostics = diagnostics
}
func run() -> CommandResult {
var diagnosticLocations: [(FBDiagnostic, String)] = []
for diagnostic in diagnostics {
guard let localPath = diagnostic.asPath else {
return .failure("Could not get a local path for diagnostic \(diagnostic)")
}
diagnosticLocations.append((diagnostic, localPath))
}
let mediaPredicate = NSPredicate.forMediaPaths()
let media = diagnosticLocations.filter { (_, location) in
mediaPredicate.evaluate(with: location)
}
if media.count > 0 {
let paths = media.map { $0.1 }
let runner = iOSTargetRunner.simple(reporter, .upload, StringsSubject(paths)) {
try FBUploadMediaStrategy(simulator: self.reporter.simulator).uploadMedia(paths)
}
let result = runner.run()
switch result.outcome {
case .failure: return result
default: break
}
}
let basePath = self.reporter.simulator.auxillaryDirectory
let arbitraryPredicate = NSCompoundPredicate(notPredicateWithSubpredicate: mediaPredicate)
let arbitrary = diagnosticLocations.filter{ arbitraryPredicate.evaluate(with: $0.1) }
for (sourceDiagnostic, sourcePath) in arbitrary {
guard let destinationPath = try? sourceDiagnostic.writeOut(toDirectory: basePath as String) else {
return CommandResult.failure("Could not write out diagnostic \(sourcePath) to path")
}
let destinationDiagnostic = FBDiagnosticBuilder().updatePath(destinationPath).build()
self.reporter.report(.upload, .discrete, ControlCoreSubject(destinationDiagnostic))
}
return .success(nil)
}
}
|
ba63895e5ad26f02ce23508f607714e5
| 37.105505 | 133 | 0.713254 | false | false | false | false |
pjocprac/PTPopupWebView
|
refs/heads/master
|
Pod/Classes/PTPopupWebViewController.swift
|
mit
|
1
|
//
// PopupWebViewController.swift
// PTPopupWebView
//
// Created by Takeshi Watanabe on 2016/03/19.
// Copyright © 2016 Takeshi Watanabe. All rights reserved.
//
import Foundation
import UIKit
import WebKit
open class PTPopupWebViewController : UIViewController {
public enum PTPopupWebViewControllerBackgroundStyle {
// blur effect background
case blurEffect (UIBlurEffectStyle)
// opacity background
case opacity (UIColor?)
// transparent background
case transparent
}
public enum PTPopupWebViewControllerTransitionStyle {
/// Transition without style.
case none
/// Transition with fade in/out effect.
case fade (TimeInterval)
/// Transition with slide in/out effect.
case slide (PTPopupWebViewEffectDirection, TimeInterval, Bool)
/// Transition with spread out/in style
case spread (TimeInterval)
/// Transition with pop out/in style
case pop (TimeInterval, Bool)
}
public enum PTPopupWebViewEffectDirection {
case top, bottom, left, right
}
@IBOutlet weak fileprivate var contentView : UIView!
@IBOutlet weak fileprivate var blurView: UIVisualEffectView!
/// PTPopupWebView
open fileprivate(set) var popupView = PTPopupWebView().style(PTPopupWebViewControllerStyle())
/// Background Style
open fileprivate(set) var backgroundStyle : PTPopupWebViewControllerBackgroundStyle = .blurEffect(.dark)
/// Transition Style
open fileprivate(set) var transitionStyle : UIModalTransitionStyle = .crossDissolve
/// Popup Appear Style
open fileprivate(set) var popupAppearStyle : PTPopupWebViewControllerTransitionStyle = .pop(0.3, true)
/// Popup Disappear Style
open fileprivate(set) var popupDisappearStyle : PTPopupWebViewControllerTransitionStyle = .pop(0.3, true)
fileprivate let attributes = [
NSLayoutAttribute.top,
NSLayoutAttribute.left,
NSLayoutAttribute.bottom,
NSLayoutAttribute.right
]
fileprivate var constraints : [NSLayoutAttribute : NSLayoutConstraint] = [:]
override open func loadView() {
let bundle = Bundle(for: type(of: self))
switch backgroundStyle {
case .blurEffect(let blurStyle):
let nib = UINib(nibName: "PTPopupWebViewControllerBlur", bundle: bundle)
view = nib.instantiate(withOwner: self, options: nil).first as! UIView
blurView.effect = UIBlurEffect(style: blurStyle)
case .opacity(let color):
let view = UIView(frame: UIScreen.main.bounds)
self.view = view
self.contentView = view
self.contentView.backgroundColor = color
case .transparent:
let view = UIView(frame: UIScreen.main.bounds)
self.view = view
self.contentView = view
self.contentView.backgroundColor = .clear
}
}
override open func viewDidLoad() {
super.viewDidLoad()
popupView.delegate = self
self.contentView.addSubview(popupView)
popupView.translatesAutoresizingMaskIntoConstraints = false
for attribute in attributes {
let constraint = NSLayoutConstraint(
item : contentView, attribute: attribute, relatedBy: NSLayoutRelation.equal,
toItem: popupView, attribute: attribute, multiplier: 1.0, constant: 0.0)
contentView.addConstraint(constraint)
constraints[attribute] = constraint
}
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
switch popupAppearStyle {
case .none: popupView.alpha = 1
default : popupView.alpha = 0
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
switch popupAppearStyle {
case .none:
break
case .fade (let duration):
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: {self.popupView.alpha = 1}, completion: nil)
case .slide(let direction, let duration, let damping):
self.popupView.alpha = 1
switch direction {
case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.view.bounds.height)
case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height)
case .left : self.popupView.transform = CGAffineTransform(translationX: -self.view.bounds.width, y: 0)
case .right : self.popupView.transform = CGAffineTransform( translationX: self.view.bounds.width, y: 0)
}
let animations = {
self.popupView.transform = CGAffineTransform(translationX: 0, y: 0)
}
if damping {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil)
}
else {
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil)
}
case .spread (let duration):
popupView.alpha = 1
CATransaction.begin()
CATransaction.setCompletionBlock({
self.popupView.layer.mask = nil
})
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
let maskLayer = CALayer()
maskLayer.backgroundColor = UIColor.white.cgColor
maskLayer.cornerRadius = popupView.style?.cornerRadius ?? 0
let oldBounds = CGRect.zero
let newBounds = popupView.contentView.bounds
let revealAnimation = CABasicAnimation(keyPath: "bounds")
revealAnimation.fromValue = NSValue(cgRect: oldBounds)
revealAnimation.toValue = NSValue(cgRect: newBounds)
revealAnimation.duration = duration
maskLayer.frame = popupView.contentView.frame
popupView.layer.mask = maskLayer
maskLayer.add(revealAnimation, forKey: "revealAnimation")
CATransaction.commit()
case .pop (let duration, let damping):
popupView.alpha = 1
popupView.transform = CGAffineTransform(scaleX: 0, y: 0)
let animations = {
self.popupView.transform = CGAffineTransform(scaleX: 1, y: 1)
}
if damping {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil)
}
else {
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil)
}
}
}
/**
Set the background style (Default: .BlurEffect(.Dark))
- parameters:
- style: PTPopupWebViewControllerBackgroundStyle
*/
open func backgroundStyle(_ style: PTPopupWebViewControllerBackgroundStyle) -> Self {
self.backgroundStyle = style
return self
}
/**
Set the tansition style (Default: .CrossDissolve)
- parameters:
- style: UIModalTransitionStyle
*/
open func transitionStyle(_ style: UIModalTransitionStyle) -> Self {
self.transitionStyle = style
return self
}
/**
Set the popup appear style (Default: .None)
- parameters:
- style: PTPopupWebViewControllerTransitionStyle
*/
open func popupAppearStyle(_ style: PTPopupWebViewControllerTransitionStyle) -> Self {
self.popupAppearStyle = style
return self
}
/**
Set the popup disappear style (Default: .None)
- parameters:
- style: PTPopupWebViewControllerTransitionStyle
*/
open func popupDisappearStyle(_ style: PTPopupWebViewControllerTransitionStyle) -> Self {
self.popupDisappearStyle = style
return self
}
/**
Show the popup view.
Transition from the ViewController, which is
- foreground view controller (without argument)
- specified view controller (with argument)
- parameters:
- presentViewController: transition source ViewController
*/
open func show(_ presentViewController: UIViewController? = nil) {
modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
modalTransitionStyle = self.transitionStyle
if let presentViewController = presentViewController {
presentViewController.present(self, animated: true, completion: nil)
}
else {
var rootViewController = UIApplication.shared.keyWindow?.rootViewController;
if rootViewController != nil {
while ((rootViewController!.presentedViewController) != nil) {
rootViewController = rootViewController!.presentedViewController;
}
rootViewController!.present(self, animated: true, completion: nil)
}
}
}
override open var prefersStatusBarHidden : Bool {
return true
}
}
extension PTPopupWebViewController : PTPopupWebViewDelegate {
public func close() {
let completion:(Bool) -> Void = { completed in
self.dismiss(animated: true, completion: nil)
}
switch popupDisappearStyle {
case .none:
completion(true)
case .fade (let duration):
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: {self.popupView.alpha = 0}, completion: completion)
case .slide(let direction, let duration, let damping):
let animations = {
switch direction {
case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.view.bounds.height)
case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height)
case .left : self.popupView.transform = CGAffineTransform(translationX: -self.view.bounds.width, y: 0)
case .right : self.popupView.transform = CGAffineTransform( translationX: self.view.bounds.width, y: 0)
}
}
if damping {
let springAnimations = {
switch direction {
case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: self.popupView.bounds.height * 0.05)
case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.popupView.bounds.height * 0.05)
case .left : self.popupView.transform = CGAffineTransform( translationX: self.popupView.bounds.width * 0.05, y: 0)
case .right : self.popupView.transform = CGAffineTransform(translationX: -self.popupView.bounds.width * 0.05, y: 0)
}
}
UIView.animate(
withDuration: duration/3, delay: 0, options: UIViewAnimationOptions(),
animations: springAnimations,
completion: { completed in
UIView.animate(
withDuration: duration * 2/3, delay: 0, options: UIViewAnimationOptions(),
animations: animations,
completion: completion)
})
}
else {
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil)
}
case .spread (let duration):
CATransaction.begin()
CATransaction.setCompletionBlock({
completion(true)
})
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
let maskLayer = CALayer()
maskLayer.backgroundColor = UIColor.white.cgColor
maskLayer.cornerRadius = popupView.style?.cornerRadius ?? 0
let oldBounds = popupView.contentView.bounds
let newBounds = CGRect.zero
let revealAnimation = CABasicAnimation(keyPath: "bounds")
revealAnimation.fromValue = NSValue(cgRect: oldBounds)
revealAnimation.toValue = NSValue(cgRect: newBounds)
revealAnimation.duration = duration
revealAnimation.repeatCount = 0
maskLayer.frame = popupView.contentView.frame
maskLayer.bounds = CGRect.zero
popupView.layer.mask = maskLayer
maskLayer.add(revealAnimation, forKey: "revealAnimation")
CATransaction.commit()
case .pop (let duration, let damping):
if damping {
UIView.animate(
withDuration: duration/3, delay: 0, options: UIViewAnimationOptions(),
animations: {
self.popupView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
},
completion: { completed in
UIView.animate(
withDuration: duration * 2/3, delay: 0, options: UIViewAnimationOptions(),
animations: {
self.popupView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.0000001) // if 0, no animation
}, completion: completion)
})
}
else {
UIView.animate(
withDuration: duration, delay: 0, options: UIViewAnimationOptions(),
animations: {
self.popupView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.0000001)
}, completion: completion)
}
}
}
}
|
a4e779b600cdf2adf64b06fa6be3f4f9
| 39.308333 | 196 | 0.604507 | false | false | false | false |
iosexample/LearnSwift
|
refs/heads/master
|
Initialization.playground/Contents.swift
|
apache-2.0
|
1
|
//: Playground - noun: a place where people can play
import Cocoa
// The process of preparing an instance of a class.
struct Fahrenheit {
var temp: Double
init() {
temp = 32.0
}
}
var f = Fahrenheit()
struct Celsius {
var tempInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
tempInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
tempInCelsius = kelvin - 273.15
}
}
let boilingPoint = Celsius(fromFahrenheit: 212.0)
boilingPoint.tempInCelsius
let freezingPoint = Celsius(fromKelvin: 273.15)
// Struct initializer
struct Size {
var width: Double, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
//twoByTwo.width = 3.0
// Class initializer
/*
class Size {
var width: Double, height: Double
init(w: Double, h: Double) {
width = w
height = h
}
}
let twoByTwo = Size(w: 2.0, h: 2.0)
twoByTwo.width = 3.0
*/
/* Require initializers */
class SomeClass {
required init() {
}
deinit {
print("deinit from SomeClass")
}
}
class SomeSubclass: SomeClass {
required init() {
}
deinit {
print("deinit from SomeSubclass")
}
}
/* Deinitialization */
for i in 0...1 {
let someClass = SomeSubclass()
}
|
14c10dc793c199d5ae8957e2fd877d47
| 16.025974 | 52 | 0.608696 | false | false | false | false |
OpsLabJPL/MarsImagesIOS
|
refs/heads/main
|
MarsImagesIOS/MER.swift
|
apache-2.0
|
1
|
//
// MER.swift
// MarsImagesIOS
//
// Created by Mark Powell on 7/28/17.
// Copyright © 2017 Mark Powell. All rights reserved.
//
import Foundation
class MER: Mission {
let SOL = "Sol"
let LTST = "LTST"
let RMC = "RMC"
let COURSE = "Course"
enum TitleState {
case START,
SOL_NUMBER,
IMAGESET_ID,
INSTRUMENT_NAME,
MARS_LOCAL_TIME,
DISTANCE,
YAW,
PITCH,
ROLL,
TILT,
ROVER_MOTION_COUNTER
}
override init() {
super.init()
self.eyeIndex = 23
self.instrumentIndex = 1
self.sampleTypeIndex = 12
self.cameraFOVs["N"] = 0.78539816
self.cameraFOVs["P"] = 0.27925268
}
override func getSortableImageFilename(url: String) -> String {
let tokens = url.components(separatedBy: "/")
if tokens.count > 0 {
let filename = tokens[tokens.count-1]
if filename.hasPrefix("Sol") {
return "0" //sort Cornell Pancam images first
}
else if (filename.hasPrefix("1") || filename.hasPrefix("2")) && filename.count == 31 {
let index = filename.index(filename.startIndex, offsetBy: 23)
return filename.substring(from: index)
}
return filename
}
return url
}
override func rowTitle(_ title: String) -> String {
let merTitle = tokenize(title) as! MERTitle
if merTitle.instrumentName == "Course Plot" {
let distanceFormatted = String.localizedStringWithFormat("%.2f", merTitle.distance)
return "Drive for \(distanceFormatted) meters"
}
return merTitle.instrumentName
}
override func caption(_ title: String) -> String {
if let t = tokenize(title) as? MERTitle {
if (t.instrumentName == "Course Plot") {
return String(format:"Drive for %.2f meters on Sol %d", t.distance, t.sol)
}
else {
return "\(t.instrumentName) image taken on Sol \(t.sol)."
}
}
else {
return super.caption(title)
}
}
override func tokenize(_ title: String) -> Title {
var mer = MERTitle()
let tokens = title.components(separatedBy: " ")
var state = TitleState.START
for word in tokens {
if word == SOL {
state = TitleState.SOL_NUMBER
continue
}
else if word == LTST {
state = TitleState.MARS_LOCAL_TIME
continue
}
else if word == RMC {
state = TitleState.ROVER_MOTION_COUNTER
continue
}
var indices:[Int] = []
switch (state) {
case .START:
break
case .SOL_NUMBER:
mer.sol = Int(word)!
state = TitleState.IMAGESET_ID
break
case .IMAGESET_ID:
if word == COURSE {
mer = parseCoursePlotTitle(title: title, mer: mer)
return mer
} else {
mer.imageSetID = word
}
state = TitleState.INSTRUMENT_NAME
break
case .INSTRUMENT_NAME:
if mer.instrumentName.isEmpty {
mer.instrumentName = String(word)
} else {
mer.instrumentName.append(" \(word)")
}
break
case .MARS_LOCAL_TIME:
mer.marsLocalTime = word
break
case .ROVER_MOTION_COUNTER:
indices = word.components(separatedBy: "-").map { Int($0)! }
mer.siteIndex = indices[0]
mer.driveIndex = indices[1]
break
default:
print("Unexpected state in parsing image title: \(state)")
break
}
}
return mer
}
func parseCoursePlotTitle(title:String, mer: MERTitle) -> MERTitle {
let tokens = title.components(separatedBy: " ")
var state = TitleState.START
for word in tokens {
if word == COURSE {
mer.instrumentName = "Course Plot"
} else if word == "Distance" {
state = TitleState.DISTANCE
continue
} else if word == "yaw" {
state = TitleState.YAW
continue
} else if word == "pitch" {
state = TitleState.PITCH
continue
} else if word == "roll" {
state = TitleState.ROLL
continue
} else if word == "tilt" {
state = TitleState.TILT
continue
} else if word == "RMC" {
state = TitleState.ROVER_MOTION_COUNTER
continue
}
var indices:[Int] = []
switch (state) {
case .START:
break
case .DISTANCE:
mer.distance = Double(word)!
break
case .YAW:
mer.yaw = Double(word)!
break
case .PITCH:
mer.pitch = Double(word)!
break
case .ROLL:
mer.roll = Double(word)!
break
case .TILT:
mer.tilt = Double(word)!
break
case .ROVER_MOTION_COUNTER:
indices = word.components(separatedBy: "-").map { Int($0)! }
mer.siteIndex = indices[0]
mer.driveIndex = indices[1]
break
default:
print("Unexpected state in parsing course plot title: \(state)")
}
}
return mer
}
override func imageName(imageId: String) -> String {
if imageId.range(of:"False") != nil {
return "Color"
}
let irange = imageId.index(imageId.startIndex, offsetBy: instrumentIndex)..<imageId.index(imageId.startIndex, offsetBy: instrumentIndex+1)
let instrument = imageId[irange]
if instrument == "N" || instrument == "F" || instrument == "R" {
let erange = imageId.index(imageId.startIndex, offsetBy: eyeIndex)..<imageId.index(imageId.startIndex, offsetBy:eyeIndex+1)
let eye = imageId[erange]
if eye == "L" {
return "Left"
} else {
return "Right"
}
} else if instrument == "P" {
let prange = imageId.index(imageId.startIndex, offsetBy: eyeIndex)..<imageId.index(imageId.startIndex, offsetBy:eyeIndex+2)
return String(imageId[prange])
}
return ""
}
override func stereoImageIndices(imageIDs: [String]) -> (Int,Int)? {
let imageid = imageIDs[0]
let instrument = getInstrument(imageId: imageid)
if !isStereo(instrument: instrument) {
return nil
}
var leftImageIndex = -1;
var rightImageIndex = -1;
var index = 0;
for imageId in imageIDs {
let eye = getEye(imageId: imageId)
if leftImageIndex == -1 && eye=="L" && !imageId.hasPrefix("Sol") {
leftImageIndex = index;
}
if rightImageIndex == -1 && eye=="R" {
rightImageIndex = index;
}
index += 1;
}
if (leftImageIndex >= 0 && rightImageIndex >= 0) {
return (Int(leftImageIndex), Int(rightImageIndex))
}
return nil
}
func isStereo(instrument:String) -> Bool {
return instrument == "F" || instrument == "R" || instrument == "N" || instrument == "P"
}
override func getCameraId(imageId: String) -> String {
if imageId.range(of:"Sol") != nil {
return "P";
} else {
return imageId[1]
}
}
override func mastPosition() -> [Double] {
return [0.456,0.026,-1.0969]
}
}
class MERTitle: Title {
var distance = 0.0
var yaw = 0.0
var pitch = 0.0
var roll = 0.0
var tilt = 0.0
}
|
fadd0133b623fef79a576697777c7965
| 30.591078 | 146 | 0.479525 | false | false | false | false |
genedelisa/AVFoundationRecorder
|
refs/heads/master
|
AVFoundation Recorder/RecorderViewController.swift
|
mit
|
1
|
//
// RecorderViewController.swift
// SwiftAVFound
//
// Created by Gene De Lisa on 8/11/14.
// Copyright (c) 2014 Gene De Lisa. All rights reserved.
//
import UIKit
import AVFoundation
// swiftlint:disable file_length
// swiftlint:disable type_body_length
/**
Uses AVAudioRecorder to record a sound file and an AVAudioPlayer to play it back.
- Author: Gene De Lisa
*/
class RecorderViewController: UIViewController {
var recorder: AVAudioRecorder!
var player: AVAudioPlayer!
@IBOutlet var recordButton: UIButton!
@IBOutlet var stopButton: UIButton!
@IBOutlet var playButton: UIButton!
@IBOutlet var statusLabel: UILabel!
var meterTimer: Timer!
var soundFileURL: URL!
override func viewDidLoad() {
super.viewDidLoad()
stopButton.isEnabled = false
playButton.isEnabled = false
setSessionPlayback()
askForNotifications()
checkHeadphones()
}
@objc func updateAudioMeter(_ timer: Timer) {
if let recorder = self.recorder {
if recorder.isRecording {
let min = Int(recorder.currentTime / 60)
let sec = Int(recorder.currentTime.truncatingRemainder(dividingBy: 60))
let s = String(format: "%02d:%02d", min, sec)
statusLabel.text = s
recorder.updateMeters()
// if you want to draw some graphics...
//var apc0 = recorder.averagePowerForChannel(0)
//var peak0 = recorder.peakPowerForChannel(0)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
recorder = nil
player = nil
}
@IBAction func removeAll(_ sender: AnyObject) {
deleteAllRecordings()
}
@IBAction func record(_ sender: UIButton) {
print("\(#function)")
if player != nil && player.isPlaying {
print("stopping")
player.stop()
}
if recorder == nil {
print("recording. recorder nil")
recordButton.setTitle("Pause", for: .normal)
playButton.isEnabled = false
stopButton.isEnabled = true
recordWithPermission(true)
return
}
if recorder != nil && recorder.isRecording {
print("pausing")
recorder.pause()
recordButton.setTitle("Continue", for: .normal)
} else {
print("recording")
recordButton.setTitle("Pause", for: .normal)
playButton.isEnabled = false
stopButton.isEnabled = true
// recorder.record()
recordWithPermission(false)
}
}
@IBAction func stop(_ sender: UIButton) {
print("\(#function)")
recorder?.stop()
player?.stop()
meterTimer.invalidate()
recordButton.setTitle("Record", for: .normal)
let session = AVAudioSession.sharedInstance()
do {
try session.setActive(false)
playButton.isEnabled = true
stopButton.isEnabled = false
recordButton.isEnabled = true
} catch {
print("could not make session inactive")
print(error.localizedDescription)
}
//recorder = nil
}
@IBAction func play(_ sender: UIButton) {
print("\(#function)")
play()
}
func play() {
print("\(#function)")
var url: URL?
if self.recorder != nil {
url = self.recorder.url
} else {
url = self.soundFileURL!
}
print("playing \(String(describing: url))")
do {
self.player = try AVAudioPlayer(contentsOf: url!)
stopButton.isEnabled = true
player.delegate = self
player.prepareToPlay()
player.volume = 1.0
player.play()
} catch {
self.player = nil
print(error.localizedDescription)
}
}
func setupRecorder() {
print("\(#function)")
let format = DateFormatter()
format.dateFormat="yyyy-MM-dd-HH-mm-ss"
let currentFileName = "recording-\(format.string(from: Date())).m4a"
print(currentFileName)
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
self.soundFileURL = documentsDirectory.appendingPathComponent(currentFileName)
print("writing to soundfile url: '\(soundFileURL!)'")
if FileManager.default.fileExists(atPath: soundFileURL.absoluteString) {
// probably won't happen. want to do something about it?
print("soundfile \(soundFileURL.absoluteString) exists")
}
let recordSettings: [String: Any] = [
AVFormatIDKey: kAudioFormatAppleLossless,
AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
AVEncoderBitRateKey: 32000,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0
]
do {
recorder = try AVAudioRecorder(url: soundFileURL, settings: recordSettings)
recorder.delegate = self
recorder.isMeteringEnabled = true
recorder.prepareToRecord() // creates/overwrites the file at soundFileURL
} catch {
recorder = nil
print(error.localizedDescription)
}
}
func recordWithPermission(_ setup: Bool) {
print("\(#function)")
AVAudioSession.sharedInstance().requestRecordPermission {
[unowned self] granted in
if granted {
DispatchQueue.main.async {
print("Permission to record granted")
self.setSessionPlayAndRecord()
if setup {
self.setupRecorder()
}
self.recorder.record()
self.meterTimer = Timer.scheduledTimer(timeInterval: 0.1,
target: self,
selector: #selector(self.updateAudioMeter(_:)),
userInfo: nil,
repeats: true)
}
} else {
print("Permission to record not granted")
}
}
if AVAudioSession.sharedInstance().recordPermission() == .denied {
print("permission denied")
}
}
func setSessionPlayback() {
print("\(#function)")
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback, with: .defaultToSpeaker)
} catch {
print("could not set session category")
print(error.localizedDescription)
}
do {
try session.setActive(true)
} catch {
print("could not make session active")
print(error.localizedDescription)
}
}
func setSessionPlayAndRecord() {
print("\(#function)")
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
} catch {
print("could not set session category")
print(error.localizedDescription)
}
do {
try session.setActive(true)
} catch {
print("could not make session active")
print(error.localizedDescription)
}
}
func deleteAllRecordings() {
print("\(#function)")
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileManager = FileManager.default
do {
let files = try fileManager.contentsOfDirectory(at: documentsDirectory,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
// let files = try fileManager.contentsOfDirectory(at: documentsDirectory)
var recordings = files.filter({ (name: URL) -> Bool in
return name.pathExtension == "m4a"
// return name.hasSuffix("m4a")
})
for i in 0 ..< recordings.count {
// let path = documentsDirectory.appendPathComponent(recordings[i], inDirectory: true)
// let path = docsDir + "/" + recordings[i]
// print("removing \(path)")
print("removing \(recordings[i])")
do {
try fileManager.removeItem(at: recordings[i])
} catch {
print("could not remove \(recordings[i])")
print(error.localizedDescription)
}
}
} catch {
print("could not get contents of directory at \(documentsDirectory)")
print(error.localizedDescription)
}
}
func askForNotifications() {
print("\(#function)")
NotificationCenter.default.addObserver(self,
selector: #selector(RecorderViewController.background(_:)),
name: NSNotification.Name.UIApplicationWillResignActive,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(RecorderViewController.foreground(_:)),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(RecorderViewController.routeChange(_:)),
name: NSNotification.Name.AVAudioSessionRouteChange,
object: nil)
}
@objc func background(_ notification: Notification) {
print("\(#function)")
}
@objc func foreground(_ notification: Notification) {
print("\(#function)")
}
@objc func routeChange(_ notification: Notification) {
print("\(#function)")
if let userInfo = (notification as NSNotification).userInfo {
print("routeChange \(userInfo)")
//print("userInfo \(userInfo)")
if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt {
//print("reason \(reason)")
switch AVAudioSessionRouteChangeReason(rawValue: reason)! {
case AVAudioSessionRouteChangeReason.newDeviceAvailable:
print("NewDeviceAvailable")
print("did you plug in headphones?")
checkHeadphones()
case AVAudioSessionRouteChangeReason.oldDeviceUnavailable:
print("OldDeviceUnavailable")
print("did you unplug headphones?")
checkHeadphones()
case AVAudioSessionRouteChangeReason.categoryChange:
print("CategoryChange")
case AVAudioSessionRouteChangeReason.override:
print("Override")
case AVAudioSessionRouteChangeReason.wakeFromSleep:
print("WakeFromSleep")
case AVAudioSessionRouteChangeReason.unknown:
print("Unknown")
case AVAudioSessionRouteChangeReason.noSuitableRouteForCategory:
print("NoSuitableRouteForCategory")
case AVAudioSessionRouteChangeReason.routeConfigurationChange:
print("RouteConfigurationChange")
}
}
}
// this cast fails. that's why I do that goofy thing above.
// if let reason = userInfo[AVAudioSessionRouteChangeReasonKey] as? AVAudioSessionRouteChangeReason {
// }
/*
AVAudioSessionRouteChangeReasonUnknown = 0,
AVAudioSessionRouteChangeReasonNewDeviceAvailable = 1,
AVAudioSessionRouteChangeReasonOldDeviceUnavailable = 2,
AVAudioSessionRouteChangeReasonCategoryChange = 3,
AVAudioSessionRouteChangeReasonOverride = 4,
AVAudioSessionRouteChangeReasonWakeFromSleep = 6,
AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory = 7,
AVAudioSessionRouteChangeReasonRouteConfigurationChange NS_ENUM_AVAILABLE_IOS(7_0) = 8
routeChange Optional([AVAudioSessionRouteChangeReasonKey: 1, AVAudioSessionRouteChangePreviousRouteKey: <AVAudioSessionRouteDescription: 0x17557350,
inputs = (
"<AVAudioSessionPortDescription: 0x17557760, type = MicrophoneBuiltIn; name = iPhone Microphone; UID = Built-In Microphone; selectedDataSource = Bottom>"
);
outputs = (
"<AVAudioSessionPortDescription: 0x17557f20, type = Speaker; name = Speaker; UID = Built-In Speaker; selectedDataSource = (null)>"
)>])
routeChange Optional([AVAudioSessionRouteChangeReasonKey: 2, AVAudioSessionRouteChangePreviousRouteKey: <AVAudioSessionRouteDescription: 0x175562f0,
inputs = (
"<AVAudioSessionPortDescription: 0x1750c560, type = MicrophoneBuiltIn; name = iPhone Microphone; UID = Built-In Microphone; selectedDataSource = Bottom>"
);
outputs = (
"<AVAudioSessionPortDescription: 0x17557de0, type = Headphones; name = Headphones; UID = Wired Headphones; selectedDataSource = (null)>"
)>])
*/
}
func checkHeadphones() {
print("\(#function)")
// check NewDeviceAvailable and OldDeviceUnavailable for them being plugged in/unplugged
let currentRoute = AVAudioSession.sharedInstance().currentRoute
if !currentRoute.outputs.isEmpty {
for description in currentRoute.outputs {
if description.portType == AVAudioSessionPortHeadphones {
print("headphones are plugged in")
break
} else {
print("headphones are unplugged")
}
}
} else {
print("checking headphones requires a connection to a device")
}
}
@IBAction
func trim() {
print("\(#function)")
if self.soundFileURL == nil {
print("no sound file")
return
}
print("trimming \(soundFileURL!.absoluteString)")
print("trimming path \(soundFileURL!.lastPathComponent)")
let asset = AVAsset(url: self.soundFileURL!)
exportAsset(asset, fileName: "trimmed.m4a")
}
func exportAsset(_ asset: AVAsset, fileName: String) {
print("\(#function)")
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let trimmedSoundFileURL = documentsDirectory.appendingPathComponent(fileName)
print("saving to \(trimmedSoundFileURL.absoluteString)")
if FileManager.default.fileExists(atPath: trimmedSoundFileURL.absoluteString) {
print("sound exists, removing \(trimmedSoundFileURL.absoluteString)")
do {
if try trimmedSoundFileURL.checkResourceIsReachable() {
print("is reachable")
}
try FileManager.default.removeItem(atPath: trimmedSoundFileURL.absoluteString)
} catch {
print("could not remove \(trimmedSoundFileURL)")
print(error.localizedDescription)
}
}
print("creating export session for \(asset)")
if let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) {
exporter.outputFileType = AVFileType.m4a
exporter.outputURL = trimmedSoundFileURL
let duration = CMTimeGetSeconds(asset.duration)
if duration < 5.0 {
print("sound is not long enough")
return
}
// e.g. the first 5 seconds
let startTime = CMTimeMake(0, 1)
let stopTime = CMTimeMake(5, 1)
exporter.timeRange = CMTimeRangeFromTimeToTime(startTime, stopTime)
// // set up the audio mix
// let tracks = asset.tracksWithMediaType(AVMediaTypeAudio)
// if tracks.count == 0 {
// return
// }
// let track = tracks[0]
// let exportAudioMix = AVMutableAudioMix()
// let exportAudioMixInputParameters =
// AVMutableAudioMixInputParameters(track: track)
// exportAudioMixInputParameters.setVolume(1.0, atTime: CMTimeMake(0, 1))
// exportAudioMix.inputParameters = [exportAudioMixInputParameters]
// // exporter.audioMix = exportAudioMix
// do it
exporter.exportAsynchronously(completionHandler: {
print("export complete \(exporter.status)")
switch exporter.status {
case AVAssetExportSessionStatus.failed:
if let e = exporter.error {
print("export failed \(e)")
}
case AVAssetExportSessionStatus.cancelled:
print("export cancelled \(String(describing: exporter.error))")
default:
print("export complete")
}
})
} else {
print("cannot create AVAssetExportSession for asset \(asset)")
}
}
@IBAction
func speed() {
let asset = AVAsset(url: self.soundFileURL!)
exportSpeedAsset(asset, fileName: "trimmed.m4a")
}
func exportSpeedAsset(_ asset: AVAsset, fileName: String) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let trimmedSoundFileURL = documentsDirectory.appendingPathComponent(fileName)
let filemanager = FileManager.default
if filemanager.fileExists(atPath: trimmedSoundFileURL.absoluteString) {
print("sound exists")
}
print("creating export session for \(asset)")
if let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) {
exporter.outputFileType = AVFileType.m4a
exporter.outputURL = trimmedSoundFileURL
// AVAudioTimePitchAlgorithmVarispeed
// AVAudioTimePitchAlgorithmSpectral
// AVAudioTimePitchAlgorithmTimeDomain
exporter.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed
let duration = CMTimeGetSeconds(asset.duration)
if duration < 5.0 {
print("sound is not long enough")
return
}
// e.g. the first 5 seconds
// let startTime = CMTimeMake(0, 1)
// let stopTime = CMTimeMake(5, 1)
// let exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime)
// exporter.timeRange = exportTimeRange
// do it
exporter.exportAsynchronously(completionHandler: {
switch exporter.status {
case AVAssetExportSessionStatus.failed:
print("export failed \(String(describing: exporter.error))")
case AVAssetExportSessionStatus.cancelled:
print("export cancelled \(String(describing: exporter.error))")
default:
print("export complete")
}
})
}
}
}
// MARK: AVAudioRecorderDelegate
extension RecorderViewController: AVAudioRecorderDelegate {
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder,
successfully flag: Bool) {
print("\(#function)")
print("finished recording \(flag)")
stopButton.isEnabled = false
playButton.isEnabled = true
recordButton.setTitle("Record", for: UIControlState())
// iOS8 and later
let alert = UIAlertController(title: "Recorder",
message: "Finished Recording",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Keep", style: .default) {[unowned self] _ in
print("keep was tapped")
self.recorder = nil
})
alert.addAction(UIAlertAction(title: "Delete", style: .default) {[unowned self] _ in
print("delete was tapped")
self.recorder.deleteRecording()
})
self.present(alert, animated: true, completion: nil)
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder,
error: Error?) {
print("\(#function)")
if let e = error {
print("\(e.localizedDescription)")
}
}
}
// MARK: AVAudioPlayerDelegate
extension RecorderViewController: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("\(#function)")
print("finished playing \(flag)")
recordButton.isEnabled = true
stopButton.isEnabled = false
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("\(#function)")
if let e = error {
print("\(e.localizedDescription)")
}
}
}
|
36a069e3af78ded720fefe0040acfe22
| 35.563981 | 162 | 0.538777 | false | false | false | false |
jpush/jchat-swift
|
refs/heads/master
|
JChat/Src/Utilites/3rdParty/RecordVoice/JCAudioPlayerHelper.swift
|
mit
|
1
|
//
// JCAudioPlayerHelper.swift
// JChatSwift
//
// Created by oshumini on 16/2/26.
// Copyright © 2016年 HXHG. All rights reserved.
//
import UIKit
import AVFoundation
protocol JCAudioPlayerHelperDelegate: NSObjectProtocol {
func didAudioPlayerBeginPlay(_ AudioPlayer: AVAudioPlayer)
func didAudioPlayerStopPlay(_ AudioPlayer: AVAudioPlayer)
func didAudioPlayerPausePlay(_ AudioPlayer: AVAudioPlayer)
}
final class JCAudioPlayerHelper: NSObject {
var player: AVAudioPlayer!
weak var delegate: JCAudioPlayerHelperDelegate?
static let sharedInstance = JCAudioPlayerHelper()
private override init() {
super.init()
}
func managerAudioWithData(_ data:Data, toplay:Bool) {
if toplay {
playAudioWithData(data)
} else {
pausePlayingAudio()
}
}
func playAudioWithData(_ voiceData:Data) {
do {
//AVAudioSessionCategoryPlayback
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker)
} else {
// Fallback on earlier versions
}
} catch let error as NSError {
print("set category fail \(error)")
}
if player != nil {
player.stop()
player = nil
}
do {
let pl: AVAudioPlayer = try AVAudioPlayer(data: voiceData)
pl.delegate = self
pl.play()
player = pl
} catch let error as NSError {
print("alloc AVAudioPlayer with voice data fail with error \(error)")
}
UIDevice.current.isProximityMonitoringEnabled = true
}
func pausePlayingAudio() {
player?.pause()
}
func stopAudio() {
if player != nil && player.isPlaying {
player.stop()
}
UIDevice.current.isProximityMonitoringEnabled = false
delegate?.didAudioPlayerStopPlay(player)
}
}
extension JCAudioPlayerHelper: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
stopAudio()
}
}
|
2eb9712db6afe44952c74088686e8acd
| 26.951807 | 190 | 0.613362 | false | false | false | false |
startupthekid/CoordinatorKit
|
refs/heads/develop
|
CoordinatorKit/Core/NavigationCoordinator.swift
|
mit
|
1
|
//
// NavigationCoordinator.swift
// CoordinatorKit
//
// Created by Brendan Conron on 8/9/17.
// Copyright © 2017 Brendan Conron. All rights reserved.
//
import UIKit
import Foundation
public final class NavigationCoordinator: SceneCoordinator<UINavigationController>, UIGestureRecognizerDelegate, UINavigationControllerDelegate {
// MARK: - Coordinators
private(set) public var rootCoordinator: Coordinator?
// MARK: - Navigation State
private var coordinatorStack: Stack<Coordinator> = Stack()
private var controllerStack: Stack<UIViewController> = Stack()
// MARK: - Initialization
required public init<C>(rootCoordinator: SceneCoordinator<C>) {
self.rootCoordinator = rootCoordinator
super.init()
rootViewController = UINavigationController(rootViewController: rootCoordinator.rootViewController)
coordinatorStack.push(rootCoordinator)
controllerStack.push(rootCoordinator.rootViewController)
configure()
}
required public init() {
rootCoordinator = nil
super.init()
rootViewController = UINavigationController()
configure()
}
// MARK: - Configuration
private func configure() {
rootViewController.delegate = self
rootViewController.interactivePopGestureRecognizer?.delegate = self
rootViewController.view.backgroundColor = .clear
rootViewController.automaticallyAdjustsScrollViewInsets = false
}
/// Set the root coordinator on the navigation coordinator. This can only be used if the
/// the root coordinator wasn't set via the initializer already.
///
/// - Parameter coordinator: Root coordinator object.
public final func setRootCoordinator<C>(_ coordinator: SceneCoordinator<C>) {
guard coordinatorStack.isEmpty, controllerStack.isEmpty, rootCoordinator == nil else {
return
}
rootCoordinator = coordinator
rootViewController.pushViewController(coordinator.rootViewController, animated: false)
coordinatorStack.push(coordinator)
controllerStack.push(coordinator.rootViewController)
}
/// Push a coordinator onto the navigation coordinator.
///
/// - Parameters:
/// - coordinator: Coordinator to push.
/// - animated: Should the push be animated.
public func pushCoordinator<C>(coordinator: SceneCoordinator<C>, animated: Bool = true) {
if let topCoordinator = coordinatorStack.peek() {
pause(coordinator: topCoordinator)
}
start(sceneCoordinator: coordinator)
coordinatorStack.push(coordinator)
controllerStack.push(coordinator.rootViewController)
}
/// Pop a coordinator off the navigation stack.
///
/// - Parameter animated: Should the pop be animated.
public func popCoordinator(animated: Bool = true) {
guard let coordinator = coordinatorStack.peek() as? SceneCoordinator, rootCoordinator != coordinator else { return }
stop(sceneCoordinator: coordinator)
coordinatorStack.pop()
controllerStack.pop()
guard let topCoordinator = coordinatorStack.peek(), topCoordinator.isPaused else { return }
resume(coordinator: topCoordinator)
}
/// Hide or show the navigation bar.
///
/// - Parameters:
/// - hidden: Should the bar be hidden or shown.
/// - animated: Should the tranisition be animated.
func setNavigationBar(hidden: Bool, animated: Bool = false) {
rootViewController.setNavigationBarHidden(hidden, animated: animated)
}
// MARK: - Coordinator
override public func start() {
super.start()
guard let root = rootCoordinator else { return }
start(coordinator: root)
}
override public func stop() {
super.stop()
coordinatorStack.removeAll()
controllerStack.removeAll()
rootCoordinator = nil
}
override public func coordinatorDidRequestDismissal<C>(_ coordinator: SceneCoordinator<C>) {
// If the root coordinator is requesting dismisal, we request dismissal from our parent
if coordinator === rootCoordinator {
delegate => {
if let delegate = $0 as? SceneCoordinatorDelegate {
delegate.coordinatorDidRequestDismissal(self)
}
}
} else {
popCoordinator(animated: true)
}
}
// MARK: - UINavigationControllerDelegate
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
// While the view controller that was just shown does not equal the one on the top of the stack
// go through the stack until you find it
while controllerStack.peek() != viewController {
guard let coordinator = coordinatorStack.peek() else {
break
}
stop(coordinator: coordinator)
controllerStack.pop()
coordinatorStack.pop()
if let topCoordinator = coordinatorStack.peek(), controllerStack.peek() == viewController, topCoordinator.isPaused {
resume(coordinator: topCoordinator)
break
}
}
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// Necessary to get the child navigation controller’s interactive pop gesture recognizer to work.
return true
}
}
|
1a364f0d4da096456f777895d7dea875
| 36.686275 | 145 | 0.66129 | false | false | false | false |
firebase/firebase-ios-sdk
|
refs/heads/master
|
ReleaseTooling/Sources/Utils/String+Utils.swift
|
apache-2.0
|
1
|
/*
* Copyright 2021 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 Foundation
/// Utilities to simplify String operations.
public extension String {
/// Finds and returns the ranges of all occurrences of a given string within a given range of the String, subject to given options,
/// using the specified locale, if any.
/// - Returns: An an optional array of ranges where each range corresponds to an occurence of the substring in the given string.
func ranges<T: StringProtocol>(of substring: T, options: CompareOptions = .literal,
locale: Locale? = nil) -> [Range<Index>] {
var ranges: [Range<Index>] = []
let end = endIndex
var searchRange = startIndex ..< end
while searchRange.lowerBound < end {
guard let range = range(
of: substring,
options: options,
range: searchRange,
locale: locale
)
else { break }
ranges.append(range)
let shiftedStart = index(range.lowerBound, offsetBy: 1)
searchRange = shiftedStart ..< end
}
return ranges
}
}
|
b77228714968e8470989fd523a8ca88b
| 32.770833 | 133 | 0.677977 | false | false | false | false |
badoo/Chatto
|
refs/heads/master
|
ChattoAdditions/sources/Input/Photos/Photo/PhotosInputCell.swift
|
mit
|
1
|
/*
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
final class PhotosInputCell: UICollectionViewCell {
private struct Constants {
static let backgroundColor = UIColor(red: 231.0/255.0, green: 236.0/255.0, blue: 242.0/255.0, alpha: 1)
static let loadingIndicatorBackgoroundColor = UIColor.black.withAlphaComponent(0.70)
static let loadingIndicatorProgressColor = UIColor.white
static let loadingIncicatorProgressWidth: CGFloat = 1
static let accessibilityIdentifier = "chatto.inputbar.photos.cell.photo"
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private var imageView: UIImageView!
private func commonInit() {
self.clipsToBounds = true
self.imageView = UIImageView()
self.imageView.contentMode = .scaleAspectFill
self.contentView.addSubview(self.imageView)
self.contentView.backgroundColor = Constants.backgroundColor
self.accessibilityIdentifier = Constants.accessibilityIdentifier
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageView.frame = self.bounds
}
override func prepareForReuse() {
super.prepareForReuse()
self.image = nil
self.hideProgressView()
}
var image: UIImage? {
get {
return self.imageView.image
}
set {
self.imageView.image = newValue
}
}
// MARK: - Progress indicator -
fileprivate var progressView: CircleProgressIndicatorView?
func showProgressView() {
guard self.progressView == nil else { return }
let progressIndicator = CircleProgressIndicatorView.default()
progressIndicator.progressLineColor = Constants.loadingIndicatorProgressColor
progressIndicator.progressLineWidth = Constants.loadingIncicatorProgressWidth
progressIndicator.backgroundColor = Constants.loadingIndicatorBackgoroundColor
progressIndicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(progressIndicator)
self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: progressIndicator, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
self.progressView = progressIndicator
}
func updateProgress(_ progress: CGFloat) {
self.progressView?.setProgress(progress)
}
func hideProgressView() {
self.progressView?.removeFromSuperview()
self.progressView = nil
}
}
|
1bfe66f9354bb73f50c63e9efe1b8b5f
| 40.475728 | 176 | 0.722144 | false | false | false | false |
iOSWizards/AwesomeMedia
|
refs/heads/master
|
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestSeries.swift
|
mit
|
1
|
//
// SoulvanaSeries.swift
// Pods
//
// Created by Evandro Harrison Hoffmann on 7/23/18.
//
import Foundation
public struct QuestSeries : Codable, Equatable {
public let id: String?
public let coverAsset: QuestAsset?
public let media: [QuestMedia]?
public let favouriteMedia: [QuestMedia]?
public let featuredMedia: [QuestMedia]?
public let latestMedia: [QuestMedia]?
public let publishedAt: String?
public let slug: String?
public let subtitle: String?
public let title: String?
public let authors: [QuestAuthor]?
}
// MARK: - JSON Key
public struct SingleQuestSeriesDataKey: Codable {
public let data: SingleQuestSeriesKey
}
public struct SingleQuestSeriesKey: Codable {
public let series: QuestSeries
}
// MARK: - Equatable
extension QuestSeries {
static public func ==(lhs: QuestSeries, rhs: QuestSeries) -> Bool {
if lhs.id != rhs.id {
return false
}
if lhs.coverAsset != rhs.coverAsset {
return false
}
if lhs.title != rhs.title {
return false
}
if lhs.subtitle != rhs.subtitle {
return false
}
if lhs.publishedAt != rhs.publishedAt {
return false
}
if lhs.slug != rhs.slug {
return false
}
if lhs.media != rhs.media {
return false
}
if lhs.authors != rhs.authors {
return false
}
return true
}
}
|
9371a335f914f95e132edf0309ab00e1
| 20.30137 | 71 | 0.576206 | false | false | false | false |
nkirby/Humber
|
refs/heads/master
|
_lib/HMGithub/_src/Realm/GithubUser.swift
|
mit
|
1
|
// =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import RealmSwift
// =======================================================
public class GithubUser: Object {
public dynamic var login = ""
public dynamic var userID = ""
public dynamic var url = ""
public dynamic var type = ""
public dynamic var siteAdmin = false
public override class func primaryKey() -> String {
return "userID"
}
}
|
275e7bbc562bca6ee4fcd009725383b4
| 24.952381 | 58 | 0.447706 | false | false | false | false |
blinksh/blink
|
refs/heads/raw
|
Blink/CompleteUtils.swift
|
gpl-3.0
|
1
|
//////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
struct CompleteToken {
var value: String = ""
var quote: String.Element? = nil
var isRedirect: Bool = false
var prefix: String = ""
// unquaoted query
var query: String = ""
// if cmd is detected
var cmd: String? = nil
var jsStart: Int = 0
var jsPos: Int = 0
var jsLen: Int = 0
var canShowHint: Bool = false
}
struct CompleteUtils {
static func encode(str: String, quote: String.Element? = nil) -> String {
var result = str
result = result.replacingOccurrences(of: "\\", with: "\\\\")
result = result.replacingOccurrences(of: "|", with: "\\|")
guard let quote = quote else {
result = result.replacingOccurrences(of: " ", with: "\\ ")
return result
}
let q = String(quote)
result = result.replacingOccurrences(of: q, with: "\\" + q)
result = "\(q)\(result)\(q)"
return result
}
static func completeToken(_ input: String, cursor: Int) -> CompleteToken {
if input.isEmpty {
return CompleteToken()
}
let buf = Array(input)
let len = buf.count
let cursor = max(min(cursor, len), 0)
var start = 0;
var end = 0;
var i = 0;
var qch: String.Element? = nil
let quotes = "\"'"
var bs = 0
var isRedirect = false
var pos = 0
while i < cursor {
defer { i += 1 }
let ch = buf[i]
if ch == "\\" {
bs += 1
continue
}
defer {
bs = 0
}
if ch.isWhitespace && bs % 2 == 0 {
pos = i
continue
}
if ch == "|" && bs % 2 == 0 {
start = i
pos = i
isRedirect = false
continue
}
if ch == ">" && bs % 2 == 0 {
start = i
pos = i
isRedirect = true
continue
}
for quote in quotes {
if ch == quote && bs % 2 == 0 {
qch = quote
i += 1
while i < cursor {
defer { i += 1 }
let c = buf[i]
if c == "\\" {
bs += 1
continue
}
defer {
bs = 0
}
if c == quote && bs % 2 == 0 {
qch = nil
break
}
}
break
}
}
}
i = cursor
while i < len {
let ch = buf[i]
if ch == "\\" {
bs += 1
i += 1
continue
}
defer {
bs = 0
}
// we are inside quotes
if let quote = qch {
if ch == quote && bs % 2 == 0 {
i += 1
break
}
} else if (ch.isWhitespace || ch == "|" || ch == ">") && bs % 2 == 0 {
break
}
i += 1
}
end = i
while start < end {
let ch = buf[start]
if ch == " " || ch == "|" || ch == ">" {
start += 1
continue
}
break
}
if start > pos {
pos = start
}
while pos < cursor {
let ch = buf[pos]
if ch.isWhitespace {
pos += 1
} else {
break
}
}
let range = input.index(input.startIndex, offsetBy: start)..<input.index(input.startIndex, offsetBy: end)
let canShowHint = range.upperBound == input.endIndex
// if pos >= len {
// pos = len - 1
// }
//
// if start >= len {
// start = len - 1
// }
var cmd: String?
var prefix: String
var query = (cursor == 0 || pos >= len) ? "" : String(buf[pos..<cursor])
query = query.replacingOccurrences(of: "\\\\", with: "\\")
if let q = qch {
let qq = String(q)
query = query.replacingOccurrences(of: "\\" + qq, with: qq)
query.removeFirst()
} else {
query = query.replacingOccurrences(of: "\\ ", with: " ")
if query.first == "\"" && query.last == "\"" {
if query == "\"" {
query = ""
} else {
query = query.replacingOccurrences(of: "\\\"", with: "\"")
query.removeFirst()
query.removeLast()
}
qch = Character("\"")
} else if query.first == "'" && query.last == "'" {
if query == "'" {
query = ""
} else {
query = query.replacingOccurrences(of: "\\\'", with: "'")
query.removeFirst()
query.removeLast()
}
qch = Character("'")
}
}
if pos == start || pos > len {
cmd = nil
prefix = ""
} else {
prefix = String(buf[start..<pos])
if let cmdPart = prefix.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true).first {
cmd = String(cmdPart)
}
}
let jsStart = input.index(input.startIndex, offsetBy: start).utf16Offset(in: input)
let jsPos = input.index(input.startIndex, offsetBy: pos).utf16Offset(in: input)
let jsEnd = input.index(input.startIndex, offsetBy: end).utf16Offset(in: input)
return CompleteToken(
value: String(input[range]),
quote: qch,
isRedirect: isRedirect,
prefix: prefix,
query: query,
cmd: cmd,
jsStart: jsStart,
jsPos: jsPos,
jsLen: jsEnd - jsPos,
canShowHint: canShowHint
)
}
}
|
ee07fb45fbef776b78d3bc27deb01309
| 22.789855 | 109 | 0.490405 | false | false | false | false |
CLCreate/CLCDrag
|
refs/heads/master
|
DragComponent/DragComponent/DragComponent/BlockGestureRecognizer.swift
|
mit
|
1
|
//
// BlockGestureRecognizer.swift
// DragComponent
//
// Created by 陈龙 on 16/1/26.
// Copyright © 2016年 陈 龙. All rights reserved.
//
import UIKit
class BlockGestureRecognizer: UIGestureRecognizer {
// declare
typealias ActionBlock = () -> Void
var grPossibleAction : ActionBlock?
var grBeganAction : ActionBlock?
var grChangeAction : ActionBlock?
var grEndAction : ActionBlock?
var grCancleAction : ActionBlock?
var grFailedAction : ActionBlock?
// MARK: - Lifecycle
override init(target: AnyObject?, action: Selector) {
super.init(target: target, action: action)
}
convenience init(possibleAction : ActionBlock, beganAction : ActionBlock, changeAction : ActionBlock, cancleAction : ActionBlock, endAction : ActionBlock, failedAction : ActionBlock){
self.init(possibleAction : possibleAction, beganAction : beganAction, changeAction : changeAction, cancleAction : cancleAction, endAction : endAction)
grFailedAction = failedAction
}
convenience init (possibleAction : ActionBlock, beganAction : ActionBlock, changeAction : ActionBlock, cancleAction : ActionBlock, endAction : ActionBlock){
self.init(beganAction : beganAction, changeAction : changeAction, cancleAction : cancleAction, endAction : endAction)
grPossibleAction = possibleAction
}
convenience init(beganAction : ActionBlock, changeAction : ActionBlock, cancleAction : ActionBlock, endAction : ActionBlock){
self.init(beganAction : beganAction, changeAction : changeAction, endAction : endAction)
grCancleAction = cancleAction
}
convenience init(beganAction : ActionBlock, changeAction : ActionBlock, endAction : ActionBlock){
self.init()
grBeganAction = beganAction
grChangeAction = changeAction
grEndAction = endAction
}
}
|
6d6ab244adb3a1ea8c8c2a2b20f0abf2
| 34.181818 | 187 | 0.695607 | false | false | false | false |
hovansuit/FoodAndFitness
|
refs/heads/master
|
FoodAndFitness/Model/Core/Mapper.swift
|
mit
|
1
|
//
// Mapper.swift
// FoodAndFitness
//
// Created by Mylo Ho on 4/5/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
import RealmSwift
import RealmS
import SwiftDate
enum DataType: Int {
case object
case array
}
// generic type workaround
@discardableResult
private func ffmap<T: Object>(realm: RealmS, type: T.Type, json: JSObject) -> T? where T: Mappable {
return realm.map(T.self, json: json)
}
// generic type workaround
@discardableResult
private func ffmap<T: Object>(realm: RealmS, type: T.Type, json: JSArray) -> [T] where T: Mappable {
return realm.map(T.self, json: json)
}
extension Mapper where N: Object, N: Mappable {
func map(result: Result<JSObject>, type: DataType, completion: Completion) {
switch result {
case .success(let json):
guard let data = json["data"] else {
completion(.failure(FFError.json))
return
}
var result: Result<JSObject> = .failure(FFError.json)
switch type {
case .object:
if let js = data as? JSObject, js.keys.isNotEmpty {
let realm: RealmS = RealmS()
realm.write {
ffmap(realm: realm, type: N.self, json: js)
}
result = .success(json)
}
case .array:
if let js = data as? JSArray {
let realm = RealmS()
realm.write {
ffmap(realm: realm, type: N.self, json: js)
}
result = .success(json)
}
}
completion(result)
case .failure(_):
completion(result)
}
}
}
// MARK: Data Transform
final class DataTransform {
static let date = TransformOf<Date, String>(fromJSON: { (string: String?) -> Date? in
return string?.toDate(format: .date).absoluteDate
}, toJSON: { (date: Date?) -> String? in
return date?.ffDate(format: .date).toString(format: .date)
})
static let fullDate = TransformOf<Date, String>(fromJSON: { (string: String?) -> Date? in
return string?.toDate(format: .full, region: Region.GMT()).absoluteDate
}, toJSON: { (date: Date?) -> String? in
return date?.ffDate(format: .full).toString(format: .full)
})
static let dateTime = TransformOf<Date, String>(fromJSON: { (string: String?) -> Date? in
return string?.toDate(format: .dateTime).absoluteDate
}, toJSON: { (date: Date?) -> String? in
return date?.ffDate(format: .dateTime).toString(format: .dateTime)
})
}
|
ff824ad7ba079dc156a90d26c9648dcd
| 30.813953 | 100 | 0.567251 | false | false | false | false |
AlliterativeAnimals/AAFoundation
|
refs/heads/master
|
AAFoundation/Extensions.swift
|
apache-2.0
|
1
|
//
// Extensions.swift
// Line Puzzle
//
// Created by David Godfrey on 04/01/2017.
// Copyright © 2017 Alliterative Animals. All rights reserved.
//
import Foundation
import UIKit
public extension Comparable {
/**
* Ensures the returned value falls within the given bounds
*/
public func clamped(to bounds: ClosedRange<Self>) -> Self {
return min(max(self, bounds.lowerBound), bounds.upperBound)
}
}
public extension UIBezierPath {
/**
* Optimisation to only fill if required.
*
* Only fills if the path might be visible within the given CGRect
*/
public func fill(ifIntersectsWith rect: CGRect) {
if self.bounds.intersects(rect) {
self.fill()
}
}
/**
* Optimisation to only stroke if required.
*
* Only strokes if the path might be visible within the given CGRect
*/
public func stroke(ifIntersectsWith rect: CGRect) {
if self.bounds.intersects(rect) {
self.stroke()
}
}
}
public extension CGPoint {
/**
* Returns the location of this point after being moved by a vector
*
* - Parameter vector: to move the point by
*/
public func movedBy(vector: CGVector) -> CGPoint {
return CGPoint(x: self.x + vector.dx, y: self.y + vector.dy)
}
/**
* Returns true if the `otherPoint` is within `tolerance`
*
* Calculates the distance between points as the straight line between them.
*
* - Parameters:
* - otherPoint: to compare against
* - tolerance: to allow when comparing
*/
public func isCloseTo(point otherPoint: CGPoint, withTolerance tolerance: CGFloat = 0) -> Bool {
return abs(CGVector(dx: otherPoint.x - self.x, dy: otherPoint.y - self.y).squareMagnitude) < pow(tolerance, 2)
}
/**
* Hash value of the point, in the form "(x,y)".hashValue
*/
public var hashValue: Int {
return "(\(self.x),\(self.y))".hashValue
}
}
public extension CGVector {
/**
* The square of the vector's magnitude.
*
* Avoids a (slow, expensive) call to `sqrt`, so is to be preferred when you are only comparing vectors and do not need the exact magnitude.
*/
public var squareMagnitude: CGFloat {
return (dx * dx) + (dy * dy)
}
/**
* The magitude (length) of the vector.
*
* See also `squareMagnitude` for a faster alternative avoiding a `sqrt` call if the literal magnitude is not required.
*/
public var magnitude: CGFloat {
return sqrt(self.squareMagnitude)
}
/**
* The inverse of the current vector
*/
public var inverse: CGVector {
return CGVector(dx: -self.dx, dy: -self.dy)
}
/**
* Returns the dot product with another given vector
*
* - Parameter otherVector: The other vector to calculate the dot product with
*/
public func getDotProduct(withVector otherVector: CGVector) -> CGFloat {
return (self.dx * otherVector.dx) + (self.dy * otherVector.dy)
}
/**
* Scales the vector by the given multiplier and returns a new vector
*
* - Parameter byMultiplier: the multiplier to scale by
*/
public func scale(byMultiplier multiplier: CGFloat) -> CGVector {
return CGVector(dx: self.dx * multiplier, dy: self.dy * multiplier)
}
/**
* Scales the vector by the given multiplier and returns a new vector
*
* - Parameter byMultiplier: the multiplier to scale by
*/
public func scale(byMultiplier multiplier: Int) -> CGVector {
return self.scale(byMultiplier: CGFloat(multiplier))
}
/**
* Convenience initialiser to calculate vector between two points.
*/
public init(originPoint: CGPoint, destinationPoint: CGPoint) {
self.dx = destinationPoint.x - originPoint.x
self.dy = destinationPoint.y - originPoint.y
}
}
public extension Collection where Indices.Iterator.Element == Index {
/**
* Returns the element at the specified index iff it is within bounds, otherwise nil.
* - Parameter index: index of collection to return, if available
*/
public subscript (safe index: Index) -> Generator.Element? {
return indices.contains(index) ? self[index] : nil
}
}
public extension CGRect {
/**
* Returns true if any of the given CGPoints are within the CGRect
*/
public func contains(anyOf points: Array<CGPoint>, includingOnBoundary: Bool = true) -> Bool {
for point in points {
if self.contains(point, includingOnBoundary: includingOnBoundary) {
return true
}
}
return false
}
/**
* Returns true if all of the given CGPoints are within the CGRect
*/
public func contains(allOf points: Array<CGPoint>, includingOnBoundary: Bool = true) -> Bool {
for point in points {
if !self.contains(point, includingOnBoundary: includingOnBoundary) {
return false
}
}
return true
}
/**
* Returns true if the CGRect contains the given CGPoint
*/
public func contains(_ point: CGPoint, includingOnBoundary: Bool) -> Bool {
guard includingOnBoundary else {
return self.contains(point)
}
let x = point.x
let y = point.y
return x <= self.maxX && x >= self.minX && y <= self.maxY && y >= self.minY
}
/**
* Longest edge length (either width or height) of the CGRect
*/
public var longestEdgeLength: CGFloat {
return max(self.size.width, self.size.height)
}
/**
* Shorted edge length (either width or height) of the CGRect
*/
public var shortestEdgeLength: CGFloat {
return min(self.size.width, self.size.height)
}
/**
* Returns a CGRect moved by the given vector.
*
* Retains size, only the origin is updated.
*/
public func movedBy(vector: CGVector) -> CGRect {
return CGRect(origin: self.origin.movedBy(vector: vector), size: self.size)
}
// Center
public var pointCenter: CGPoint {
return self.pointMidXMidY
}
public var pointMidXMidY: CGPoint {
return CGPoint(x: self.midX, y: self.midY)
}
// EightCorners - NOTE: Didn't do "top left" or similar, because that depends on the coordinate system (views vs scenekit nodes, for example)
public var pointMinXMinY: CGPoint {
return CGPoint(x: self.minX, y: self.minY)
}
public var pointMidXMinY: CGPoint {
return CGPoint(x: self.midX, y: self.minY)
}
public var pointMaxXMinY: CGPoint {
return CGPoint(x: self.maxX, y: self.minY)
}
public var pointMaxXMidY: CGPoint {
return CGPoint(x: self.maxX, y: self.midY)
}
public var pointMaxXMaxY: CGPoint {
return CGPoint(x: self.maxX, y: self.maxY)
}
public var pointMidXMaxY: CGPoint {
return CGPoint(x: self.midX, y: self.maxY)
}
public var pointMinXMaxY: CGPoint {
return CGPoint(x: self.minX, y: self.maxY)
}
public var pointMinXMidY: CGPoint {
return CGPoint(x: self.minX, y: self.midY)
}
}
public extension UIView {
/**
* All ancestors of the current view (including itsself)
*/
public var hierarchy: Array<UIView> {
var ancestors: Array<UIView> = [ self ]
var currentView = self
while let currentSuperview = currentView.superview {
ancestors.append(currentSuperview)
currentView = currentSuperview
}
return ancestors
}
}
public extension UIColor {
/**
* Convenience initializer to start from a HSBA object
*/
public convenience init(hsba: HSBA) {
self.init(hue: hsba.hue, saturation: hsba.saturation, brightness: hsba.brightness, alpha: hsba.alpha)
}
/**
* Creates a new color based on the current color using the given saturation
*
* - Parameter saturation: the value to set to; the range depends on the color space for the color, however in sRGB the range is 0.0...1.0
*/
public func with(saturation: CGFloat) -> UIColor {
var hsba = self.hsba
hsba.saturation = saturation
return type(of: self).init(hue: hsba.hue, saturation: hsba.saturation, brightness: hsba.brightness, alpha: hsba.alpha)
}
/**
* Returns a HSBA representation of the color.
*/
public var hsba: HSBA {
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return HSBA(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
}
/**
* Represents a color in Hue/Saturation/Brightness/Alpha format.
*
* As this allows the reader to visualise properties of the colour more easily than RGB, this may be preferred to standard UIColors or RGB values.
*/
public struct HSBA {
/**
* The hue of the color.
*
* This is often between 0.0...1.0, but depends on the color space the color will be presented in.
*
* - Note: If saturation or brightness are zero, the hue may not make sense. For example, `UIColor.black.hsba` and UIColor.white.hsba` both have a hue of 0º, if you take only the hue and replace saturation and brightness values this will generate a red color.
*/
public var hue: CGFloat
/**
* The saturation of the color.
*
* This is often between 0.0...1.0, but depends on the color space the color will be presented in.
*/
public var saturation: CGFloat
/**
* The brightness of the color.
*
* This is often between 0.0...1.0, but depends on the color space the color will be presented in.
*/
public var brightness: CGFloat
/**
* The alpha (opacity) of the color.
*
* This is often between 0.0...1.0, but depends on the color space the color will be presented in.
*
* Lower values denote a less opaque color.
*/
public var alpha: CGFloat
/**
* Converts the HSBA back into a UIColor for display.
*/
public var uiColor: UIColor {
return UIColor(hue: self.hue, saturation: self.saturation, brightness: self.brightness, alpha: self.alpha)
}
/**
* Converts the HSBA back into a CGColor for display.
*/
public var cgColor: CGColor {
return self.uiColor.cgColor
}
}
public extension UIBezierPath {
/**
* Convenience initialiser to create a full-circle path without having to explicitly state angles.
*/
public convenience init(arcCenter: CGPoint, radius: CGFloat, clockwise: Bool = true) {
self.init(arcCenter: arcCenter, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: clockwise)
}
/**
* Generates a smoothed line through given points
*
* - Parameters:
* - points: points to draw the line through
* - closed: if true, the line is closed to form a continuous path
*
* From a [github comment by Jérôme Gangneux](https://github.com/jnfisher/ios-curve-interpolation/issues/6)
*/
public static func interpolateHermiteFor(points: Array<CGPoint>, closed: Bool = false) -> UIBezierPath {
guard points.count >= 2 else {
return UIBezierPath()
}
if points.count == 2 {
let bezierPath = UIBezierPath()
bezierPath.move(to: points[0])
bezierPath.addLine(to: points[1])
return bezierPath
}
let nCurves = closed ? points.count : points.count - 1
let path = UIBezierPath()
for i in 0..<nCurves {
var curPt = points[i]
var prevPt: CGPoint, nextPt: CGPoint, endPt: CGPoint
if i == 0 {
path.move(to: curPt)
}
var nexti = (i+1)%points.count
var previ = (i-1 < 0 ? points.count-1 : i-1)
prevPt = points[previ]
nextPt = points[nexti]
endPt = nextPt
var mx: CGFloat
var my: CGFloat
if closed || i > 0 {
mx = (nextPt.x - curPt.x) * CGFloat(0.5)
mx += (curPt.x - prevPt.x) * CGFloat(0.5)
my = (nextPt.y - curPt.y) * CGFloat(0.5)
my += (curPt.y - prevPt.y) * CGFloat(0.5)
}
else {
mx = (nextPt.x - curPt.x) * CGFloat(0.5)
my = (nextPt.y - curPt.y) * CGFloat(0.5)
}
var ctrlPt1 = CGPoint.zero
ctrlPt1.x = curPt.x + mx / CGFloat(3.0)
ctrlPt1.y = curPt.y + my / CGFloat(3.0)
curPt = points[nexti]
nexti = (nexti + 1) % points.count
previ = i;
prevPt = points[previ]
nextPt = points[nexti]
if closed || i < nCurves-1 {
mx = (nextPt.x - curPt.x) * CGFloat(0.5)
mx += (curPt.x - prevPt.x) * CGFloat(0.5)
my = (nextPt.y - curPt.y) * CGFloat(0.5)
my += (curPt.y - prevPt.y) * CGFloat(0.5)
}
else {
mx = (curPt.x - prevPt.x) * CGFloat(0.5)
my = (curPt.y - prevPt.y) * CGFloat(0.5)
}
var ctrlPt2 = CGPoint.zero
ctrlPt2.x = curPt.x - mx / CGFloat(3.0)
ctrlPt2.y = curPt.y - my / CGFloat(3.0)
path.addCurve(to: endPt, controlPoint1: ctrlPt1, controlPoint2: ctrlPt2)
}
if closed {
path.close()
}
return path
}
}
@available(iOS 10.0, *)
public extension UIImage {
public struct RotationOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let flipOnVerticalAxis = RotationOptions(rawValue: 1)
public static let flipOnHorizontalAxis = RotationOptions(rawValue: 2)
}
/**
* Rotates the image with the given options.
*
* - Parameters:
* - rotationAngleRadians: the angle to rotate the image by
* - options: Options while rendering, eg: whether or not to flip on an axis
*
* - Returns: A rotated image, or nil if the image could not be rendered.
*/
func rotated(by rotationAngleRadians: CGFloat, options: RotationOptions = []) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
let rotationInRadians = rotationAngleRadians
let transform = CGAffineTransform(rotationAngle: rotationInRadians)
var rect = CGRect(origin: .zero, size: self.size).applying(transform)
rect.origin = .zero
let renderer = UIGraphicsImageRenderer(size: rect.size)
return renderer.image { renderContext in
renderContext.cgContext.translateBy(x: rect.midX, y: rect.midY)
renderContext.cgContext.rotate(by: rotationInRadians)
let x: CGFloat = options.contains(.flipOnVerticalAxis) ? -1.0 : 1.0
let y: CGFloat = options.contains(.flipOnHorizontalAxis) ? 1.0 : -1.0
renderContext.cgContext.scaleBy(x: x, y: y)
let drawRect = CGRect(origin: CGPoint(x: -self.size.width/2, y: -self.size.height/2), size: self.size)
renderContext.cgContext.draw(cgImage, in: drawRect)
}
}
}
/**
* Represents the result of diff-ing two collections
*/
public struct DiffResult<T: Hashable> {
/**
* Items only found in the first collection
*
* > [1,2].diff(other: [2,3]).uniqueToFirst
* Set([1])
*
* - Note: Does not retain the original order of items.
*/
public let uniqueToFirst: Set<T>
/**
* Items only found in the second collection
*
* > [1,2].diff(other: [2,3]).uniqueToFirst
* Set([3])
*
* - Note: Does not retain the original order of items.
*/
public let uniqueToSecond: Set<T>
/**
* Items only found in both collections
*
* > [1,2].diff(other: [2,3]).uniqueToFirst
* Set([2])
*
* - Note: Does not retain the original order of items.
*/
public let containedInBoth: Set<T>
/**
* (computed) Items in the first collection
*
* > [1,2].diff(other: [2,3]).uniqueToFirst
* Set([1,2])
*
* - Note: Does not retain the original order of items.
*/
public var containedInFirst: Set<T> { return self.uniqueToFirst.union(self.containedInBoth) }
/**
* (computed) Items in the second collection
*
* > [1,2].diff(other: [2,3]).uniqueToFirst
* Set([2,3])
*
* - Note: Does not retain the original order of items.
*/
public var containedInSecond: Set<T> { return self.uniqueToSecond.union(self.containedInBoth) }
}
public extension Array where Element: Hashable {
/**
* Returns the difference between two given arrays
*
* - Parameter other: Other array to compare against ('second' in the DiffResult)
*
* - Returns: A DiffResult object repressenting the differences between the arrays
*/
public func diff(other: Array<Element>) -> DiffResult<Element> {
let firstSet = Set(self)
let secondSet = Set(other)
return DiffResult<Element>(uniqueToFirst: firstSet.subtracting(secondSet), uniqueToSecond: secondSet.subtracting(firstSet), containedInBoth: firstSet.intersection(secondSet))
}
}
public extension NSLayoutConstraint {
#if swift(>=3.2)
// Not required, added to the language in Swift 4
#else
/**
* Convenience initalizer to also set the priority during init
*/
public convenience init(
item: Any,
attribute firstAttribute: NSLayoutAttribute,
relatedBy: NSLayoutRelation,
toItem: Any?,
attribute secondAttribute: NSLayoutAttribute,
multiplier: CGFloat,
constant: CGFloat,
priority: UILayoutPriority
) {
self.init(item: item, attribute: firstAttribute, relatedBy: relatedBy, toItem: toItem, attribute: secondAttribute, multiplier: multiplier, constant: constant)
self.priority = priority
}
#endif
}
public extension URL {
/**
* Convenience optional initializer to avoid another 'if let' block
*/
public init?(string: String?, relativeTo: URL? = nil) {
if let string = string {
self.init(string: string, relativeTo: relativeTo)
} else {
return nil
}
}
}
public extension UIImage {
/**
* Scales image to given width, preserving ratio.
*
* - Parameter width: width to scale to
*/
public func scaleImage(toWidth width: CGFloat) -> UIImage? {
let scalingRatio = width / self.size.width
let newHeight = scalingRatio * self.size.height
return self.scaleImage(toSize: CGSize(width: width, height: newHeight))
}
/**
* Scales image to given height, preserving ratio.
*
* - Parameter height: height to scale to
*/
public func scaleImage(toHeight height: CGFloat) -> UIImage? {
let scalingRatio = height / self.size.height
let newWidth = scalingRatio * self.size.width
return self.scaleImage(toSize: CGSize(width: newWidth, height: height))
}
/**
* Scales image to given size, ignoring original ratio.
*
* - Parameter size: to scale to
*/
public func scaleImage(toSize size: CGSize) -> UIImage? {
let newRect = CGRect(x: 0, y: 0, width: size.width, height: size.height).integral
UIGraphicsBeginImageContextWithOptions(size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
context.interpolationQuality = .high
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)
context.concatenate(flipVertical)
context.draw(self.cgImage!, in: newRect)
let newImage = UIImage(cgImage: context.makeImage()!)
UIGraphicsEndImageContext()
return newImage
}
return nil
}
}
public extension URL {
public enum URLQueryItemsError: Error {
case CannotGetComponents(fromUrl: URL)
case CannotGetUrl(fromComponents: URLComponents)
}
private func getComponents() throws -> URLComponents {
// Get components from current URL
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true) else {
throw URLQueryItemsError.CannotGetComponents(fromUrl: self)
}
return components
}
/**
* Replaces the given query items.
*
* Also adds missing keys if they were not in the original query items.
*
* let aUrl = "http://example.com?foo=bar"
* let replacements = [ "foo" : "replaced", "bar": "added" ]
* print(
* URL(string: aUrl)
* .replacing(queryItems: replacements)
* .absoluteString
* )
*
* output:
*
* "http://example.com?foo=baz&bar=added"
*
* - Parameter queryItems: String Dictionary of keys to replace in query items
*/
public func replacing(queryItems: [String:String]) throws -> URL {
var components = try self.getComponents()
let bannedKeys = Array(queryItems.keys)
components.queryItems = (components.queryItems ?? []).filter({ !bannedKeys.contains($0.name) })
for (key, value) in queryItems {
components.queryItems?.append(URLQueryItem(name: key, value: value))
}
guard let url = components.url else {
throw URLQueryItemsError.CannotGetUrl(fromComponents: components)
}
return url
}
/**
* Removes the given query item keys
*
* let aUrl = "http://example.com?foo=bar&baz=quux"
* let removals = [ "foo", "corge" ]
* print(
* URL(string: aUrl)
* .replacing(queryItems: replacements)
* .absoluteString
* )
*
* output:
*
* "http://example.com?baz=quux"
*
* - Parameter queryItems: Array of keys to remove from query items
*/
public func removing(queryItems: [String]) throws -> URL {
var components = try self.getComponents()
let bannedKeys = queryItems
components.queryItems = (components.queryItems ?? []).filter({ !bannedKeys.contains($0.name) })
guard let url = components.url else {
throw URLQueryItemsError.CannotGetUrl(fromComponents: components)
}
return url
}
}
public extension CGAffineTransform {
/**
* Calculates the X scale involved in the transformation
*
* - Note: this uses `sqrt` so is a relatively expensive calculation. If it is possible to record the scale some other way it may be more efficient.
*/
var xScale: CGFloat {
return sqrt(self.a * self.a + self.c * self.c);
}
/**
* Calculates the Y scale involved in the transformation
*
* - Note: this uses `sqrt` so is a relatively expensive calculation. If it is possible to record the scale some other way it may be more efficient.
*/
var yScale: CGFloat {
return sqrt(self.b * self.b + self.d * self.d);
}
}
|
63c6a5132e015de6a3843e0da3f6fb27
| 31.04261 | 263 | 0.591423 | false | false | false | false |
toohotz/IQKeyboardManager
|
refs/heads/master
|
Demo/Swift_Demo/ViewController/SpecialCaseViewController.swift
|
mit
|
1
|
//
// SpecialCaseViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import Foundation
import UIKit
class SpecialCaseViewController: UIViewController, UISearchBarDelegate, UITextFieldDelegate, UITextViewDelegate, UIPopoverPresentationControllerDelegate {
@IBOutlet private var customWorkTextField : UITextField!
@IBOutlet private var textField6 : UITextField!
@IBOutlet private var textField7 : UITextField!
@IBOutlet private var textField8 : UITextField!
@IBOutlet private var switchInteraction1 : UISwitch!
@IBOutlet private var switchInteraction2 : UISwitch!
@IBOutlet private var switchInteraction3 : UISwitch!
@IBOutlet private var switchEnabled1 : UISwitch!
@IBOutlet private var switchEnabled2 : UISwitch!
@IBOutlet private var switchEnabled3 : UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
textField6.userInteractionEnabled = switchInteraction1.on
textField7.userInteractionEnabled = switchInteraction2.on
textField8.userInteractionEnabled = switchInteraction3.on
textField6.enabled = switchEnabled1.on
textField7.enabled = switchEnabled2.on
textField8.enabled = switchEnabled3.on
updateUI()
}
@IBAction func showAlertClicked (barButton : UIBarButtonItem!) {
let alertController = UIAlertController(title: "IQKeyboardManager", message: "It doesn't affect UIAlertController (Doesn't add IQToolbar on it's textField", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
alertController.addTextFieldWithConfigurationHandler({ (textField : UITextField) in
textField.placeholder = "Username"
})
alertController.addTextFieldWithConfigurationHandler({ (textField : UITextField) in
textField.placeholder = "Password"
textField.secureTextEntry = true
})
self.presentViewController(alertController, animated: true, completion: nil)
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func updateUI() {
textField6.placeholder = (textField6.enabled ? "enabled" : "" ) + "," + (textField6.userInteractionEnabled ? "userInteractionEnabled" : "" )
textField7.placeholder = (textField7.enabled ? "enabled" : "" ) + "," + (textField7.userInteractionEnabled ? "userInteractionEnabled" : "" )
textField8.placeholder = (textField8.enabled ? "enabled" : "" ) + "," + (textField8.userInteractionEnabled ? "userInteractionEnabled" : "" )
}
func switch1UserInteractionAction(sender: UISwitch) {
textField6.userInteractionEnabled = sender.on
updateUI()
}
func switch2UserInteractionAction(sender: UISwitch) {
textField7.userInteractionEnabled = sender.on
updateUI()
}
func switch3UserInteractionAction(sender: UISwitch) {
textField8.userInteractionEnabled = sender.on
updateUI()
}
func switch1Action(sender: UISwitch) {
textField6.enabled = sender.on
updateUI()
}
func switch2Action(sender: UISwitch) {
textField7.enabled = sender.on
updateUI()
}
func switch3Action(sender: UISwitch) {
textField8.enabled = sender.on
updateUI()
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if (textField == customWorkTextField) {
if(textField.isAskingCanBecomeFirstResponder == false) {
let alertController = UIAlertController(title: "IQKeyboardManager", message: "Do your custom work here", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
return false
} else {
return true
}
}
func textFieldDidBeginEditing(textField: UITextField) {
switchEnabled1.enabled = false
switchEnabled2.enabled = false
switchEnabled3.enabled = false
switchInteraction1.enabled = false
switchInteraction2.enabled = false
switchInteraction3.enabled = false
}
func textFieldDidEndEditing(textField: UITextField) {
switchEnabled1.enabled = true
switchEnabled2.enabled = true
switchEnabled3.enabled = true
switchInteraction1.enabled = true
switchInteraction2.enabled = true
switchInteraction3.enabled = true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "SettingsNavigationController" {
let controller = segue.destinationViewController
controller.modalPresentationStyle = .Popover
controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
let heightWidth = max(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds));
controller.preferredContentSize = CGSizeMake(heightWidth, heightWidth)
controller.popoverPresentationController?.delegate = self
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) {
self.view.endEditing(true)
}
override func shouldAutorotate() -> Bool {
return true
}
}
|
a7c5338a2eba99582808a07eeae031f9
| 36.117647 | 188 | 0.665135 | false | false | false | false |
steelwheels/Coconut
|
refs/heads/master
|
CoconutData/Source/Value/CNStorage.swift
|
lgpl-2.1
|
1
|
/*
* @file CNStorage.swift
* @brief Define CNStorage class
* @par Copyright
* Copyright (C) 2021 Steel Wheels Project
*/
#if os(iOS)
import UIKit
#endif
import Foundation
private class CNStorageCache
{
private var mPath: CNValuePath
private var mIsDirty: Bool
public init(path p: CNValuePath){
mPath = p
mIsDirty = true
}
public var path: CNValuePath { get { return mPath }}
public var isDirty: Bool {
get { return mIsDirty }
set(newval) { mIsDirty = newval }
}
}
private class CNStorageCallback
{
public typealias EventFunction = CNStorage.EventFunction
private var mPath: CNValuePath
private var mEventFunction: EventFunction
public init(path p: CNValuePath, eventFunc efunc: @escaping EventFunction){
mPath = p
mEventFunction = efunc
}
public var path: CNValuePath { get { return mPath }}
public var eventFunc: EventFunction { get { return mEventFunction }}
}
public class CNStorage
{
public typealias EventFunction = () -> Void
private var mSourceDirectory: URL
private var mCacheDirectory: URL
private var mFilePath: String
private var mRootValue: CNMutableValue
private var mCache: Dictionary<Int, CNStorageCache>
private var mNextCacheId: Int
private var mEventFunctions: Dictionary<Int, CNStorageCallback>
private var mNextEventFuncId: Int
private var mLock: NSLock
// packdir: Root directory for package (*.jspkg)
// fpath: The location of data file against packdir
public init(sourceDirectory srcdir: URL, cacheDirectory cachedir: URL, filePath fpath: String) {
mSourceDirectory = srcdir
mCacheDirectory = cachedir
mFilePath = fpath
mRootValue = CNMutableDictionaryValue(sourceDirectory: srcdir, cacheDirectory: cachedir)
mCache = [:]
mNextCacheId = 0
mEventFunctions = [:]
mNextEventFuncId = 0
mLock = NSLock()
}
public var description: String { get {
return "{srcdir=\(mSourceDirectory.path), cachedir=\(mCacheDirectory.path), file=\(mFilePath)}"
}}
private var sourceFile: URL { get { return mSourceDirectory.appendingPathComponent(mFilePath) }}
private var cacheFile: URL { get { return mCacheDirectory.appendingPathComponent(mFilePath) }}
public func load() -> Result<CNValue, NSError> {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
/* Copy source file to cache file */
let srcfile = self.sourceFile
let cachefile = self.cacheFile
guard let contents = CNStorage.createCacheFile(cacheFile: cachefile, sourceFile: srcfile) else {
let err = NSError.fileError(message: "Failed to create cache file: \(cachefile.path)")
return .failure(err)
}
let parser = CNValueParser()
let result: Result<CNValue, NSError>
switch parser.parse(source: contents as String) {
case .success(let val):
mRootValue = CNMutableValue.valueToMutableValue(from: val, sourceDirectory: mSourceDirectory, cacheDirectory: mCacheDirectory)
result = .success(val)
case .failure(let err):
result = .failure(err)
}
return result
}
public static func createCacheFile(cacheFile cache: URL, sourceFile source: URL) -> String? {
let fmanager = FileManager.default
guard fmanager.fileExists(atURL: source) else {
CNLog(logLevel: .error, message: "Source file \(source.path) is NOT exist", atFunction: #function, inFile: #file)
return nil
}
if fmanager.fileExists(atURL: cache){
/* Already exist */
return cache.loadContents() as String?
} else {
/* File is not exist */
if fmanager.copyFile(sourceFile: source, destinationFile: cache, doReplace: false) {
return cache.loadContents() as String?
} else {
CNLog(logLevel: .error, message: "Failed to create cache file: \(cache.path)", atFunction: #function, inFile: #file)
return nil
}
}
}
public func removeCacheFile() -> Result<CNValue, NSError> {
if let err = FileManager.default.removeFile(atURL: self.cacheFile) {
return .failure(err)
} else {
return self.load()
}
}
public func allocateCache(forPath path: CNValuePath) -> Int {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
let cache = CNStorageCache(path: path)
let cid = mNextCacheId
mCache[mNextCacheId] = cache
mNextCacheId += 1
return cid
}
public func removeCache(cacheId cid: Int) {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
mCache[cid] = nil
}
public func isDirty(cacheId cid: Int) -> Bool {
if let cache = mCache[cid] {
return cache.isDirty
} else {
CNLog(logLevel: .error, message: "Unknown cache id: \(cid)", atFunction: #function, inFile: #file)
return false
}
}
private func setDirty(at path: CNValuePath) {
for cache in mCache.values {
if cache.path.isIncluded(in: path) {
cache.isDirty = true
}
}
}
public func setClean(cacheId cid: Int) {
if let cache = mCache[cid] {
cache.isDirty = false
} else {
CNLog(logLevel: .error, message: "Unknown cache id: \(cid)", atFunction: #function, inFile: #file)
}
}
public func allocateEventFunction(forPath path: CNValuePath, eventFunc efunc: @escaping EventFunction) -> Int {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
let cbfunc = CNStorageCallback(path: path, eventFunc: efunc)
let eid = mNextEventFuncId
mEventFunctions[mNextEventFuncId] = cbfunc
mNextEventFuncId += 1
return eid
}
public func removeEventFunction(eventFuncId eid: Int) {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
mEventFunctions[eid] = nil
}
public func value(forPath path: CNValuePath) -> CNValue? {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
if let elms = normalizeValuePath(valuePath: path) {
switch mRootValue.value(forPath: elms) {
case .success(let val):
return val
case .failure(let err):
CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file)
}
}
return nil
}
public func set(value val: CNValue, forPath path: CNValuePath) -> Bool {
/* Mutex lock and unlock */
mLock.lock() ; defer { mLock.unlock() ; triggerCallbacks(path: path)}
var result: Bool
if let elms = normalizeValuePath(valuePath: path) {
if let err = mRootValue.set(value: val, forPath: elms) {
/* Some error occured */
CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file)
result = false
} else {
/* No error */
mRootValue.labelTable().clear()
setDirty(at: path)
result = true
}
} else {
result = false
}
return result
}
public func append(value val: CNValue, forPath path: CNValuePath) -> Bool {
/* Mutex lock and unlock */
mLock.lock() ; defer { mLock.unlock() ; triggerCallbacks(path: path)}
if let elms = normalizeValuePath(valuePath: path) {
if let err = mRootValue.append(value: val, forPath: elms) {
CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file)
return false
} else {
mRootValue.labelTable().clear()
setDirty(at: path)
return true
}
} else {
return false
}
}
public func delete(forPath path: CNValuePath) -> Bool {
/* Mutex lock and unlock */
mLock.lock() ; defer { mLock.unlock() }
setDirty(at: path)
if let elms = normalizeValuePath(valuePath: path) {
if let err = mRootValue.delete(forPath: elms) {
CNLog(logLevel: .error, message: "Error: \(err.toString())", atFunction: #function, inFile: #file)
return false
} else {
/* No error */
mRootValue.labelTable().clear()
return true
}
} else {
return false
}
}
private func normalizeValuePath(valuePath path: CNValuePath) -> Array<CNValuePath.Element>? {
if let ident = path.identifier {
if var topelms = mRootValue.labelTable().labelToPath(label: ident, in: mRootValue) {
topelms.append(contentsOf: path.elements)
return topelms
} else {
CNLog(logLevel: .error, message: "Failed to find label: \(ident)", atFunction: #function, inFile: #file)
}
}
return path.elements
}
private func triggerCallbacks(path pth: CNValuePath) {
for event in mEventFunctions.values {
if event.path.isIncluded(in: pth) {
event.eventFunc()
}
}
}
public func segments(traceOption trace: CNValueSegmentTraceOption) -> Array<CNMutableValueSegment> {
return CNSegmentsInValue(value: mRootValue, traceOption: trace)
}
public func save() -> Bool {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
let cachefile = self.cacheFile
let pathes = cachefile.deletingLastPathComponent()
if !FileManager.default.fileExists(atPath: pathes.path) {
if let err = FileManager.default.createDirectories(directory: pathes) {
CNLog(logLevel: .error, message: err.toString(), atFunction: #function, inFile: #file)
return false // stop the save operation
}
}
/* Save into the file */
if save(value: mRootValue, outFile: cachefile) {
return true
} else {
CNLog(logLevel: .error, message: "Failed to store storage: \(cachefile.path)", atFunction: #function, inFile: #file)
return false
}
}
private func save(value val: CNMutableValue, outFile file: URL) -> Bool {
/* save it self */
var result = true
if mRootValue.isDirty {
let txt = val.toValue().toScript().toStrings().joined(separator: "\n")
if file.storeContents(contents: txt + "\n") {
val.isDirty = false
} else {
CNLog(logLevel: .error, message: "Failed to store storage: \(file.path)", atFunction: #function, inFile: #file)
result = false
}
}
/* save segmented values */
let refs = CNSegmentsInValue(value: val, traceOption: .traceNonNull)
for ref in refs {
if let cval = ref.context {
if !save(value: cval, outFile: ref.cacheFile) {
result = false
}
}
}
return result
}
public func toValue() -> CNValue {
/* Mutex lock */
mLock.lock() ; defer { mLock.unlock() }
return mRootValue.toValue()
}
}
|
4f8c228586dfa11315379cf1db8687c7
| 27.709302 | 129 | 0.685703 | false | false | false | false |
Alan007/iOS-Study-Demo
|
refs/heads/master
|
Swift版的FMDB和CoreData学习_转/SwiftFMDB/DB.swift
|
apache-2.0
|
28
|
//
// DB.swift
// SwiftFMDBDemo
//
// Created by Limin Du on 11/15/14.
// Copyright (c) 2014 GoldenFire.Do. All rights reserved.
//
import Foundation
class DB {
class var sharedInstance: DB {
struct Static {
static var instance: DB?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = DB()
Static.instance?.initDatabase()
}
return Static.instance!
}
class var tableName:String {
return "table1"
}
private var db:FMDatabase?
func getDatabase()->FMDatabase? {
return db
}
private func initDatabase()->Bool {
var result:Bool = false
let table_name = DB.tableName
let documentPath : AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0]
let dbPath:String = documentPath.stringByAppendingPathComponent("demo.db")
let filemanager = NSFileManager.defaultManager()
if !filemanager.fileExistsAtPath(dbPath) {
result = filemanager.createFileAtPath(dbPath, contents: nil, attributes: nil)
if !result {
return false
}
}
db = FMDatabase(path: dbPath)
if db == nil {
return false
}
db!.logsErrors = true
if db!.open() {
//db!.shouldCacheStatements()
/*if db!.tableExists(table_name) {
db!.executeUpdate("DROP TABLE \(table_name)", withArgumentsInArray: nil)
}*/
if !db!.tableExists(table_name) {
var creat_table = "CREATE TABLE \(table_name) (id INTEGER PRIMARY KEY, name VARCHAR(80), description VARCHAR(80))"
result = db!.executeUpdate(creat_table, withArgumentsInArray: nil)
}
}
println("init : \(result)")
return result
}
func closeDatabase() {
db?.close()
}
}
|
1b35136d32d082e7a6f77beea24e87e2
| 25.3625 | 130 | 0.53817 | false | false | false | false |
wireapp/wire-ios-data-model
|
refs/heads/develop
|
Source/Model/Conversation/ZMConversation+Message.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
private let log = ZMSLog(tag: "Conversations")
extension ZMConversation {
/// An error describing why a message couldn't be appended to the conversation.
public enum AppendMessageError: LocalizedError, Equatable {
case missingManagedObjectContext
case malformedNonce
case failedToProcessMessageData(reason: String)
case messageIsEmpty
case failedToRemoveImageMetadata
case invalidImageUrl
case invalidFileUrl
case fileSharingIsRestricted
public var errorDescription: String? {
switch self {
case .missingManagedObjectContext:
return "The managed object context is missing."
case .malformedNonce:
return "Encountered a malformed nonce."
case .failedToProcessMessageData(let reason):
return "Failed to process generic message data. Reason: \(reason)"
case .messageIsEmpty:
return "Can not send empty text messages."
case .failedToRemoveImageMetadata:
return "Failed to remove image metatdata."
case .invalidImageUrl:
return "Invalid image url."
case .invalidFileUrl:
return "Invalid file url."
case .fileSharingIsRestricted:
return "File sharing is restricted."
}
}
}
/// Appends a button action message.
///
/// - Parameters:
/// - id: The id of the button action.
/// - referenceMessageId: The id of the message which this action references.
/// - nonce: The nonce of the button action message.
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
///
/// - Returns:
/// The appended message.
@discardableResult
func appendButtonAction(havingId id: String, referenceMessageId: UUID, nonce: UUID = UUID()) throws -> ZMClientMessage {
let buttonAction = ButtonAction(buttonId: id, referenceMessageId: referenceMessageId)
return try appendClientMessage(with: GenericMessage(content: buttonAction, nonce: nonce), hidden: true)
}
/// Appends a location message.
///
/// - Parameters:
/// - locationData: The data describing the location.
/// - nonce: The nonce of the location message.
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
///
/// - Returns:
/// The appended message.
@discardableResult
public func appendLocation(with locationData: LocationData, nonce: UUID = UUID()) throws -> ZMConversationMessage {
let locationContent = Location.with {
if let name = locationData.name {
$0.name = name
}
$0.latitude = locationData.latitude
$0.longitude = locationData.longitude
$0.zoom = locationData.zoomLevel
}
let message = GenericMessage(content: locationContent, nonce: nonce, expiresAfter: activeMessageDestructionTimeoutValue)
return try appendClientMessage(with: message)
}
/// Appends a knock message.
///
/// - Parameters:
/// - nonce: The nonce of the knock message.
///
/// - Throws:
/// `AppendMessageError` if the message couldn't be appended.
///
/// - Returns:
/// The appended message.
@discardableResult
public func appendKnock(nonce: UUID = UUID()) throws -> ZMConversationMessage {
let content = Knock.with { $0.hotKnock = false }
let message = GenericMessage(content: content, nonce: nonce, expiresAfter: activeMessageDestructionTimeoutValue)
return try appendClientMessage(with: message)
}
/// Appends a text message.
///
/// - Parameters:
/// - content: The message content.
/// - mentions: The list of mentioned participants.
/// - quotedMessage: The message being replied to.
/// - fetchLinkPreview: Whether link previews should be fetched.
/// - nonce: The nonce of the message.
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
///
/// - Returns:
/// The appended message.
@discardableResult
public func appendText(content: String,
mentions: [Mention] = [],
replyingTo quotedMessage: ZMConversationMessage? = nil,
fetchLinkPreview: Bool = true,
nonce: UUID = UUID()) throws -> ZMConversationMessage {
guard !(content as NSString).zmHasOnlyWhitespaceCharacters() else {
throw AppendMessageError.messageIsEmpty
}
let text = Text(content: content, mentions: mentions, linkPreviews: [], replyingTo: quotedMessage as? ZMOTRMessage)
let genericMessage = GenericMessage(content: text, nonce: nonce, expiresAfter: activeMessageDestructionTimeoutValue)
let clientMessage = try appendClientMessage(with: genericMessage, expires: true, hidden: false, configure: {
$0.linkPreviewState = fetchLinkPreview ? .waitingToBeProcessed : .done
$0.needsLinkAttachmentsUpdate = fetchLinkPreview
$0.quote = quotedMessage as? ZMMessage
})
if let notificationContext = managedObjectContext?.notificationContext {
NotificationInContext(name: ZMConversation.clearTypingNotificationName,
context: notificationContext,
object: self).post()
}
return clientMessage
}
/// Append an image message.
///
/// - Parameters:
/// - url: A url locating some image data.
/// - nonce: The nonce of the message.
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
///
/// - Returns:
/// The appended message.
@discardableResult
public func appendImage(at URL: URL, nonce: UUID = UUID()) throws -> ZMConversationMessage {
guard
URL.isFileURL,
ZMImagePreprocessor.sizeOfPrerotatedImage(at: URL) != .zero,
let imageData = try? Data.init(contentsOf: URL, options: [])
else {
throw AppendMessageError.invalidImageUrl
}
return try appendImage(from: imageData)
}
/// Append an image message.
///
/// - Parameters:
/// - imageData: Data representing an image.
/// - nonce: The nonce of the message.
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
///
/// - Returns:
/// The appended message.
@discardableResult
public func appendImage(from imageData: Data, nonce: UUID = UUID()) throws -> ZMConversationMessage {
guard let moc = managedObjectContext else {
throw AppendMessageError.missingManagedObjectContext
}
guard let imageData = try? imageData.wr_removingImageMetadata() else {
throw AppendMessageError.failedToRemoveImageMetadata
}
// mimeType is assigned first, to make sure UI can handle animated GIF file correctly.
let mimeType = imageData.mimeType ?? ""
// We update the size again when the the preprocessing is done.
let imageSize = ZMImagePreprocessor.sizeOfPrerotatedImage(with: imageData)
let asset = WireProtos.Asset(imageSize: imageSize,
mimeType: mimeType,
size: UInt64(imageData.count))
return try append(asset: asset, nonce: nonce, expires: true, prepareMessage: { message in
moc.zm_fileAssetCache.storeAssetData(message, format: .original, encrypted: false, data: imageData)
})
}
/// Append a file message.
///
/// - Parameters:
/// - fileMetadata: Data describing the file.
/// - nonce: The nonce of the message.
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
///
/// - Returns:
/// The appended message.
@discardableResult
public func appendFile(with fileMetadata: ZMFileMetadata, nonce: UUID = UUID()) throws -> ZMConversationMessage {
guard let moc = managedObjectContext else {
throw AppendMessageError.missingManagedObjectContext
}
guard let data = try? Data.init(contentsOf: fileMetadata.fileURL, options: .mappedIfSafe) else {
throw AppendMessageError.invalidFileUrl
}
return try append(asset: fileMetadata.asset, nonce: nonce, expires: false) { (message) in
moc.zm_fileAssetCache.storeAssetData(message, encrypted: false, data: data)
if let thumbnailData = fileMetadata.thumbnail {
moc.zm_fileAssetCache.storeAssetData(message, format: .original, encrypted: false, data: thumbnailData)
}
}
}
private func append(asset: WireProtos.Asset,
nonce: UUID,
expires: Bool,
prepareMessage: (ZMAssetClientMessage) -> Void) throws -> ZMAssetClientMessage {
guard let moc = managedObjectContext else {
throw AppendMessageError.missingManagedObjectContext
}
let message: ZMAssetClientMessage
do {
message = try ZMAssetClientMessage(asset: asset,
nonce: nonce,
managedObjectContext: moc,
expiresAfter: activeMessageDestructionTimeoutValue?.rawValue)
} catch {
throw AppendMessageError.failedToProcessMessageData(reason: error.localizedDescription)
}
guard !message.isRestricted else {
throw AppendMessageError.fileSharingIsRestricted
}
message.sender = ZMUser.selfUser(in: moc)
if expires {
message.setExpirationDate()
}
append(message)
unarchiveIfNeeded()
prepareMessage(message)
message.updateCategoryCache()
message.prepareToSend()
return message
}
/// Appends a new message to the conversation.
///
/// - Parameters:
/// - genericMessage: The generic message that should be appended.
/// - expires: Whether the message should expire or tried to be send infinitively.
/// - hidden: Whether the message should be hidden in the conversation or not
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
@discardableResult
public func appendClientMessage(with genericMessage: GenericMessage,
expires: Bool = true,
hidden: Bool = false,
configure: ((ZMClientMessage) -> Void)? = nil) throws -> ZMClientMessage {
guard let moc = managedObjectContext else {
throw AppendMessageError.missingManagedObjectContext
}
guard let nonce = UUID(uuidString: genericMessage.messageID) else {
throw AppendMessageError.malformedNonce
}
let message = ZMClientMessage(nonce: nonce, managedObjectContext: moc)
configure?(message)
do {
try message.setUnderlyingMessage(genericMessage)
} catch {
moc.delete(message)
throw AppendMessageError.failedToProcessMessageData(reason: error.localizedDescription)
}
do {
try append(message, expires: expires, hidden: hidden)
} catch {
moc.delete(message)
throw error
}
return message
}
/// Appends a new message to the conversation.
///
/// - Parameters:
/// - message: The message that should be appended.
/// - expires: Whether the message should expire or tried to be send infinitively.
/// - hidden: Whether the message should be hidden in the conversation or not
///
/// - Throws:
/// - `AppendMessageError` if the message couldn't be appended.
private func append(_ message: ZMClientMessage, expires: Bool, hidden: Bool) throws {
guard let moc = managedObjectContext else {
throw AppendMessageError.missingManagedObjectContext
}
message.sender = ZMUser.selfUser(in: moc)
if expires {
message.setExpirationDate()
}
if hidden {
message.hiddenInConversation = self
} else {
append(message)
unarchiveIfNeeded()
message.updateCategoryCache()
message.prepareToSend()
}
}
}
@objc
extension ZMConversation {
// MARK: - Objective-C compability methods
@discardableResult @objc(appendMessageWithText:)
public func _appendText(content: String) -> ZMConversationMessage? {
return try? appendText(content: content)
}
@discardableResult @objc(appendMessageWithText:fetchLinkPreview:)
public func _appendText(content: String, fetchLinkPreview: Bool) -> ZMConversationMessage? {
return try? appendText(content: content, fetchLinkPreview: fetchLinkPreview)
}
@discardableResult @objc(appendText:mentions:fetchLinkPreview:nonce:)
public func _appendText(content: String,
mentions: [Mention],
fetchLinkPreview: Bool,
nonce: UUID) -> ZMConversationMessage? {
return try? appendText(content: content,
mentions: mentions,
fetchLinkPreview: fetchLinkPreview,
nonce: nonce)
}
@discardableResult @objc(appendText:mentions:replyingToMessage:fetchLinkPreview:nonce:)
public func _appendText(content: String,
mentions: [Mention],
replyingTo quotedMessage: ZMConversationMessage?,
fetchLinkPreview: Bool,
nonce: UUID) -> ZMConversationMessage? {
return try? appendText(content: content,
mentions: mentions,
replyingTo: quotedMessage,
fetchLinkPreview: fetchLinkPreview,
nonce: nonce)
}
@discardableResult @objc(appendKnock)
public func _appendKnock() -> ZMConversationMessage? {
return try? appendKnock()
}
@discardableResult @objc(appendMessageWithLocationData:)
public func _appendLocation(with locationData: LocationData) -> ZMConversationMessage? {
return try? appendLocation(with: locationData)
}
@discardableResult @objc(appendMessageWithImageData:)
public func _appendImage(from imageData: Data) -> ZMConversationMessage? {
return try? appendImage(from: imageData)
}
@discardableResult @objc(appendImageFromData:nonce:)
public func _appendImage(from imageData: Data, nonce: UUID) -> ZMConversationMessage? {
return try? appendImage(from: imageData, nonce: nonce)
}
@discardableResult @objc(appendImageAtURL:nonce:)
public func _appendImage(at URL: URL, nonce: UUID) -> ZMConversationMessage? {
return try? appendImage(at: URL, nonce: nonce)
}
@discardableResult @objc(appendMessageWithFileMetadata:)
public func _appendFile(with fileMetadata: ZMFileMetadata) -> ZMConversationMessage? {
return try? appendFile(with: fileMetadata)
}
@discardableResult @objc(appendFile:nonce:)
public func _appendFile(with fileMetadata: ZMFileMetadata, nonce: UUID) -> ZMConversationMessage? {
return try? appendFile(with: fileMetadata, nonce: nonce)
}
}
|
a8adc221076a0d2d75c10f0c9a9bb4b0
| 35.701099 | 128 | 0.613929 | false | false | false | false |
GoodMorningCody/EverybodySwift
|
refs/heads/master
|
WeatherDemo/WeatherDemo/WeatherViewController.swift
|
mit
|
1
|
//
// WeatherViewController.swift
// WeatherDemo
//
// Created by Cody on 2015. 1. 11..
// Copyright (c) 2015년 TIEKLE. All rights reserved.
//
import UIKit
import CoreLocation
class WeatherViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var currentLocation : CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateCurrentLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateCurrentLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined && locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization")) == true {
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
currentLocation = locations[locations.count - 1] as? CLLocation
manager.stopUpdatingLocation()
getWehaterButton?.enabled = true
}
@IBOutlet var getWehaterButton : UIButton?
@IBOutlet var gettedWehaterTextView : UITextView?
@IBAction func touchedGetWeatherButton(sender: UIButton) {
let urlString = "http://api.openweathermap.org/data/2.5/weather?lat=\(currentLocation!.coordinate.latitude)&lon=\(currentLocation!.coordinate.longitude)"
if let url = NSURL(string: urlString) {
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue(), completionHandler: { (response, data, error) -> Void in
let jsonObject : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil)
if let weather = jsonObject?["weather"] as? NSArray {
if weather.count>0 {
self.gettedWehaterTextView?.text = weather[0]["description"] as? NSString
return
}
}
self.gettedWehaterTextView?.text = "날씨 정보를 가져오지 못했습니다."
})
}
}
}
|
0a0349eb6590da77764d4488615fd477
| 37.738462 | 180 | 0.661239 | false | false | false | false |
jad6/CV
|
refs/heads/master
|
Swift/Jad's CV/Sections/ExperienceDetail/ExperienceDetailView.swift
|
bsd-3-clause
|
1
|
//
// ExperienceDetailView.swift
// Jad's CV
//
// Created by Jad Osseiran on 24/07/2014.
// Copyright (c) 2014 Jad. All rights reserved.
//
import UIKit
class ExperienceDetailView: DynamicTypeView {
//MARK:- Constants
private struct LayoutConstants {
struct Padding {
static let top: CGFloat = 20.0
static let betweenVerticalLarge: CGFloat = 15.0
static let betweenVerticalSmall: CGFloat = 3.0
}
static let imagveViewSize = CGSize(width: 70.0, height: 70.0)
static let imageViewMaskingRadius: CGFloat = 18.0
}
//MARK:- Properties
let organisationImageView = UIImageView()
let positionLabel = UILabel()
let organisationLabel = UILabel()
let dateLabel = UILabel()
let textView = FormattedTextView()
//MARK:- Init
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.organisationImageView.frame.size = LayoutConstants.imagveViewSize
self.organisationImageView.maskToRadius(LayoutConstants.imageViewMaskingRadius)
self.addSubview(self.organisationImageView)
self.addSubview(self.positionLabel)
self.addSubview(self.organisationLabel)
self.addSubview(self.dateLabel)
if UIDevice.isPad() {
self.textView.textContainerInset = UIEdgeInsets(top: 0.0, left: 44.0, bottom: 0.0, right: 44.0)
} else {
self.textView.textContainerInset = UIEdgeInsets(top: 0.0, left: 20.0, bottom: 0.0, right: 20.0)
}
self.addSubview(self.textView)
self.backgroundColor = UIColor.backgroundGrayColor()
}
convenience init() {
self.init(frame: CGRectZero)
}
//MARK:- Layout
override func layoutSubviews() {
super.layoutSubviews()
organisationImageView.frame.origin.y = LayoutConstants.Padding.top
organisationImageView.centerHorizontallyWithReferenceRect(self.bounds)
positionLabel.frame.size = positionLabel.sizeThatFits(bounds.size).ceilSize
positionLabel.frame.origin.y = organisationImageView.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge
positionLabel.centerHorizontallyWithReferenceRect(self.bounds)
organisationLabel.frame.size = organisationLabel.sizeThatFits(bounds.size).ceilSize
organisationLabel.frame.origin.y = positionLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall
organisationLabel.centerHorizontallyWithReferenceRect(self.bounds)
dateLabel.frame.size = dateLabel.sizeThatFits(bounds.size).ceilSize
dateLabel.frame.origin.y = organisationLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalSmall
dateLabel.centerHorizontallyWithReferenceRect(self.bounds)
textView.frame.origin.y = dateLabel.frame.maxY + LayoutConstants.Padding.betweenVerticalLarge
textView.frame.size.width = bounds.size.width
textView.frame.size.height = bounds.size.height - textView.frame.origin.y
}
//MARK:- Dynamic type
override func reloadDynamicTypeContent() {
positionLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
organisationLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
dateLabel.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
textView.font = DynamicTypeFont.preferredFontForTextStyle(UIFontTextStyleBody)
}
}
|
8b5de3c21cdaf228186f1b277cdeabbc
| 36.428571 | 118 | 0.693566 | false | false | false | false |
beyerss/CalendarKit
|
refs/heads/master
|
CalendarKit/Month.swift
|
mit
|
1
|
//
// Month.swift
// CalendarKit
//
// Created by Steven Beyers on 6/7/15.
// Copyright (c) 2015 Beyers Apps, LLC. All rights reserved.
//
import UIKit
private let monthFormatter = MonthFormatter()
internal class Month: NSObject {
var date: NSDate
/**
* Creates a Month object for the date given
*
* @param monthDate Any date in the month that needs to be created
**/
required init(monthDate: NSDate) {
date = monthDate
}
/**
* Returns the name of the month that this object represents.
*
* @return The string representation of the current month
**/
func monthName() -> String {
return monthFormatter.formatter.stringFromDate(date)
}
/**
* Will determine if the current month is equal to the object specified.
* The items will be equal if the following conditions are met:
* 1) The object specified is a Month object
* 2) The month of the Month object specified is the same as the current Month's month
* 3) The year of the Month object specified is the same as the current Month's year
*
* @param object AnyObject that needs to be compared against the current Month
* @return A Bool. True if the two objects are equal, otherwise false.
**/
override func isEqual(object: AnyObject?) -> Bool {
if let otherMonth = object as? Month {
let myComponents = NSCalendar.currentCalendar().components([.Month, .Year], fromDate: date)
let otherComponents = NSCalendar.currentCalendar().components([.Month, .Year], fromDate: otherMonth.date)
if (myComponents.month == otherComponents.month && myComponents.year == otherComponents.year) {
return true
}
}
return false
}
/**
Sets the format used when getting the month name.
*/
func useMonthFormat(format: String) {
monthFormatter.formatter.dateFormat = format
}
}
/**
* This extension will give us class methods to create a month based off of a previous month
**/
extension Month {
/**
* Convenience initializer so that a month can be created based
* on another month.
*
* @param otherMonth The base month used as a reference to create a new Month
* @param offset The number of months between the otherMonth and the desired month
**/
convenience init(otherMonth: Month, offsetMonths offset: Int) {
let date = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: offset, toDate: otherMonth.date, options: [])!
self.init(monthDate: date)
}
}
/**
* This extension will provide helpers for determining the correct date
**/
extension Month {
/**
* This returns the days in the current month
**/
func numberOfDaysInMonth() -> Int {
let calendar = NSCalendar.currentCalendar()
var components = calendar.components([.Day, .Month, .Year], fromDate: date)
components.day = 1
let firstDayDate = calendar.dateFromComponents(components)
let delta : NSDateComponents = NSDateComponents()
delta.month = 1
delta.day = -1
let newDate = calendar.dateByAddingComponents(delta, toDate: firstDayDate!, options: [])
if let lastDayDate = newDate {
components = calendar.components(.Day, fromDate: lastDayDate)
return components.day
}
return -1
}
/**
* This returns the first day of the week as an integer value from 0-6 (Sunday - Saturday)
**/
func firstDayOfWeek() -> Int {
let calendar = NSCalendar.currentCalendar()
var components = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: date)
components.day = 1
components = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: calendar.dateFromComponents(components)!)
var day = components.weekday
day -= 1
return day
}
/**
* This returns the number of weeks for this month
**/
func weeksInMonth() -> Int {
let numberOfDays = numberOfDaysInMonth()
let firstDay = firstDayOfWeek()
let totalDaysNeeded = numberOfDays + firstDay
var numberOfWeeks = totalDaysNeeded / 7
let remainder = totalDaysNeeded % 7
if (remainder > 0) {
numberOfWeeks += 1
}
return numberOfWeeks
}
func getDateForCell(indexPath path: NSIndexPath) -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: date)
var dayOfMonth = path.row
let firstDay = firstDayOfWeek()
// subtract the offset to account for the first day of the week
dayOfMonth -= (firstDay - 1)
var dateToReturn: NSDate?
components.day = dayOfMonth
// The date is in the current month
let newDate = calendar.dateFromComponents(components)
dateToReturn = newDate
if let returnDate = dateToReturn {
return returnDate
} else {
// If I was not able to determine the date I'm just going to return toay's date
return date
}
}
func isDateOutOfMonth(testDate: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Month], fromDate: testDate)
let currentComponents = calendar.components([.Month], fromDate: date)
if (components.month == currentComponents.month) {
return false
}
return true
}
}
/**
This is a singleton so that we only ever have to create one month formatter
*/
private class MonthFormatter {
lazy var formatter: NSDateFormatter = {
let newFormatter = NSDateFormatter()
newFormatter.dateFormat = "MMMM"
return newFormatter
}()
}
|
edd33c385c7adc5287ad2238e299a638
| 30.242268 | 126 | 0.62102 | false | false | false | false |
sseitov/v-Chess-Swift
|
refs/heads/master
|
v-Chess/MainController.swift
|
gpl-3.0
|
1
|
//
// MainController.swift
// WD Content
//
// Created by Сергей Сейтов on 24.02.17.
// Copyright © 2017 V-Channel. All rights reserved.
//
import UIKit
import AMSlideMenu
class MainController: AMSlideMenuMainViewController, AMSlideMenuDelegate {
private var rightMenuIsOpened = false
override open var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return .all
}
override func viewDidLoad() {
super.viewDidLoad()
self.isInitialStart = false
self.slideMenuDelegate = self
}
func disableSlider() {
self.disableSlidePanGestureForRightMenu()
self.disableSlidePanGestureForLeftMenu()
}
override func primaryMenu() -> AMPrimaryMenu {
return AMPrimaryMenuRight
}
// MARK: - Right menu
override func initialIndexPathForRightMenu() -> IndexPath! {
if let choice = UserDefaults.standard.value(forKey: "lastMenuChoice") as? Int {
return IndexPath(row: choice, section: 0)
} else {
return IndexPath(row: 0, section: 0)
}
}
override func segueIdentifierForIndexPath(inRightMenu indexPath: IndexPath!) -> String! {
switch indexPath.row {
case 1:
return "archive"
case 2:
return "community"
default:
return "play"
}
}
override func rightMenuWidth() -> CGFloat {
return IS_PAD() ? 320 : 260
}
override func deepnessForRightMenu() -> Bool {
return true
}
override func maxDarknessWhileRightMenu() -> CGFloat {
return 0.5
}
// MARK: - Common
override func configureSlideLayer(_ layer: CALayer!) {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 1
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 5
layer.masksToBounds = false
layer.shadowPath = UIBezierPath(rect: self.view.layer.bounds).cgPath
}
override func openAnimationCurve() -> UIViewAnimationOptions {
return .curveEaseOut
}
override func closeAnimationCurve() -> UIViewAnimationOptions {
return .curveEaseOut
}
private func rightMenuFrame() -> CGRect {
return CGRect(x: self.view.bounds.size.width - rightMenuWidth(), y: 0, width: rightMenuWidth(), height: self.view.bounds.size.height)
}
override func openRightMenu(animated: Bool) {
super.openRightMenu(animated: animated)
self.rightMenu.view.frame = rightMenuFrame()
}
func rightMenuWillOpen() {
rightMenuIsOpened = true
}
func rightMenuDidClose() {
rightMenuIsOpened = false
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if rightMenuIsOpened {
self.currentActiveNVC.view.alpha = 0
coordinator.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) in
self.rightMenu.view.frame = self.rightMenuFrame()
}) { (context: UIViewControllerTransitionCoordinatorContext) in
UIView.animate(withDuration: 0.2, animations: {
self.currentActiveNVC.view.alpha = 1
})
}
}
}
/*
// 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.
}
*/
}
|
3c649fd2806aab1d9d1cff19f978e0fa
| 28.78125 | 141 | 0.633526 | false | false | false | false |
cuappdev/podcast-ios
|
refs/heads/master
|
old/Podcast/PlayButton.swift
|
mit
|
1
|
//
// PlayButton.swift
// Podcast
//
// Created by Kevin Greer on 3/11/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
class PlayButton: Button {
let buttonTitlePadding: CGFloat = 7
override init() {
super.init()
setImage(#imageLiteral(resourceName: "play_feed_icon"), for: .normal)
setImage(#imageLiteral(resourceName: "play_feed_icon_selected"), for: .selected)
setImage(#imageLiteral(resourceName: "error_icon"), for: .disabled)
setTitle("Play", for: .normal)
setTitle("Playing", for: .selected)
setTitle("", for: .disabled)
titleLabel?.font = ._12RegularFont()
contentHorizontalAlignment = .left
setTitleColor(.offBlack, for: .normal)
setTitleColor(.sea, for: .selected)
titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonTitlePadding, bottom: 0, right: 0)
}
func configure(for episode: Episode) {
if let _ = episode.audioURL {
isEnabled = true
isSelected = episode.isPlaying
titleEdgeInsets = UIEdgeInsets(top: 0, left: buttonTitlePadding, bottom: 0, right: 0)
} else {
titleEdgeInsets = .zero
isEnabled = false
isUserInteractionEnabled = false
titleLabel?.numberOfLines = 2
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
c04e7bed44493cca895b4596ca85aa5b
| 31.130435 | 97 | 0.61705 | false | false | false | false |
newlix/swift-syncable-api
|
refs/heads/master
|
Tests/NSJSONSerializationTests.swift
|
mit
|
1
|
import XCTest
import LessMock
import SyncableAPI
import RealmSwift
class JSONSerializationTests: XCTestCase {
override func setUp() {
super.setUp()
clearBeforeTesting()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSkipUnderscore() {
let fake = Fake()
fake._hidden = "not show"
let json = NSJSONSerialization.JSONObjectWithRealmObject(fake)
XCTAssertNil(json["_hidden"])
}
func testReferenceClassId() {
let fake = Fake()
fake.id = "567"
let parent = Parent()
parent.fake = fake
let json = NSJSONSerialization.JSONObjectWithRealmObject(parent)
let fakeId = json["fakeId"] as! String
XCTAssertEqual(fakeId, "567")
}
func testAttribute() {
let fake = Fake()
fake.updateTimestamp = 0.02
let json = NSJSONSerialization.JSONObjectWithRealmObject(fake)
let updateTimestamp = json["updateTimestamp"] as! Double
XCTAssertEqualWithAccuracy(updateTimestamp, 0.02, accuracy: 0.001)
}
}
|
67999e6633ba15520794c3df5e1a3967
| 26.840909 | 111 | 0.626939 | false | true | false | false |
abertelrud/swift-package-manager
|
refs/heads/main
|
Tests/PackagePluginAPITests/PathTests.swift
|
apache-2.0
|
2
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import PackagePlugin
import XCTest
class PathAPITests: XCTestCase {
func testBasics() throws {
let path = Path("/tmp/file.foo")
XCTAssertEqual(path.lastComponent, "file.foo")
XCTAssertEqual(path.stem, "file")
XCTAssertEqual(path.extension, "foo")
XCTAssertEqual(path.removingLastComponent(), Path("/tmp"))
}
func testEdgeCases() throws {
let path = Path("/tmp/file.foo")
XCTAssertEqual(path.removingLastComponent().removingLastComponent().removingLastComponent(), Path("/"))
}
}
|
759265ab8a9275ead08b895735aafe4e
| 34.366667 | 111 | 0.589067 | false | true | false | false |
pupboss/vfeng
|
refs/heads/master
|
vfeng/ShowDetailViewController.swift
|
gpl-2.0
|
1
|
//
// ShowDetailViewController.swift
// vfeng
//
// Created by Li Jie on 10/25/15.
// Copyright © 2015 PUPBOSS. All rights reserved.
//
import UIKit
class ShowDetailViewController: UIViewController {
var detailArr: Array<String> = []
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var rewardLabel: UILabel!
@IBOutlet weak var infoLabel: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.imgView.image = UIImage.init(data: NSData.init(contentsOfURL: NSURL(string: self.detailArr[0])!)!)
self.nameLabel.text = detailArr[1]
self.rewardLabel.text = detailArr[3]
self.infoLabel.text = detailArr[2]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
98594141397049f8ab672b8c446c42bb
| 23.236842 | 111 | 0.65798 | false | false | false | false |
chicio/RangeUISlider
|
refs/heads/master
|
Source/Logic/KnobGestureManager.swift
|
mit
|
1
|
//
// KnobGestureManager.swift
// RangeUISlider
//
// Created by Fabrizio Duroni on 03/02/21.
// 2021 Fabrizio Duroni.
//
import UIKit
class KnobGestureManager {
private unowned let bar: Bar
private unowned let knobs: Knobs
private unowned let knobGestureManagerDelegate: KnobGestureManagerDelegate
private let stepCalculator: StepCalculator
init(bar: Bar, knobs: Knobs, knobGestureManagerDelegate: KnobGestureManagerDelegate) {
self.bar = bar
self.knobs = knobs
self.knobGestureManagerDelegate = knobGestureManagerDelegate
self.stepCalculator = StepCalculator()
}
func moveLeftKnob(gesture: GestureData) {
recognize(gesture: gesture, updateKnob: updateLeftKnobPositionUsing)
}
func moveRightKnob(gesture: GestureData) {
recognize(gesture: gesture, updateKnob: updateRightKnobPositionUsing)
}
private func recognize(gesture: GestureData, updateKnob: (GestureData) -> Void) {
if gesture.gestureRecognizer.state == .began {
rangeSelectionStartedForKnobUsing(gesture: gesture, updateKnob: updateKnob)
}
if gesture.gestureRecognizer.state == .changed {
updateKnobAndRangeUsing(gesture: gesture, updateKnob: updateKnob)
}
if gesture.gestureRecognizer.state == .ended {
knobGestureManagerDelegate.rangeSelectionFinished(userInteraction: true)
}
}
private func rangeSelectionStartedForKnobUsing(gesture: GestureData, updateKnob: (GestureData) -> Void) {
updateKnob(gesture)
knobGestureManagerDelegate.rangeChangeStarted()
}
private func updateKnobAndRangeUsing(gesture: GestureData, updateKnob: (GestureData) -> Void) {
updateKnob(gesture)
knobGestureManagerDelegate.rangeSelectionUpdate()
}
private func updateLeftKnobPositionUsing(gesture: GestureData) {
let userInterfaceDirection = UIView.userInterfaceLayoutDirection(for: gesture.semanticContentAttribute)
if userInterfaceDirection == UIUserInterfaceLayoutDirection.rightToLeft {
let positionForKnob = bar.frame.width - positionForKnobGiven(
xLocationInBar: gesture.gestureRecognizer.location(in: bar).x,
gesture: gesture
)
let positionRightKnob = -1 * knobs.rightKnob.xPositionConstraint.constant
if positionForKnob >= 0 && (bar.frame.width - positionForKnob) >= positionRightKnob {
knobs.leftKnob.xPositionConstraint.constant = positionForKnob
}
} else {
let positionForKnob = positionForKnobGiven(
xLocationInBar: gesture.gestureRecognizer.location(in: bar).x,
gesture: gesture
)
let positionRightKnob = bar.frame.width + knobs.rightKnob.xPositionConstraint.constant
if positionForKnob >= 0 && positionForKnob <= positionRightKnob {
knobs.leftKnob.xPositionConstraint.constant = positionForKnob
}
}
}
private func updateRightKnobPositionUsing(gesture: GestureData) {
let userInterfaceDirection = UIView.userInterfaceLayoutDirection(for: gesture.semanticContentAttribute)
if userInterfaceDirection == UIUserInterfaceLayoutDirection.rightToLeft {
let xLocationInBar = gesture.gestureRecognizer.location(in: bar).x
let positionForKnob = -1 * positionForKnobGiven(
xLocationInBar: xLocationInBar,
gesture: gesture
)
if positionForKnob <= 0 &&
xLocationInBar <= (bar.frame.width - knobs.leftKnob.xPositionConstraint.constant) {
knobs.rightKnob.xPositionConstraint.constant = positionForKnob
}
} else {
let xLocationInBar = gesture.gestureRecognizer.location(in: bar).x
let positionForKnob = positionForKnobGiven(
xLocationInBar: xLocationInBar - bar.frame.width,
gesture: gesture
)
if positionForKnob <= 0 && xLocationInBar >= knobs.leftKnob.xPositionConstraint.constant {
knobs.rightKnob.xPositionConstraint.constant = positionForKnob
}
}
}
private func positionForKnobGiven(xLocationInBar: CGFloat, gesture: GestureData) -> CGFloat {
let stepWidth = stepCalculator.calculateStepWidth(
stepIncrement: gesture.stepIncrement,
scale: gesture.scale,
barWidth: bar.frame.width
)
return (xLocationInBar / stepWidth).rounded(FloatingPointRoundingRule.down) * stepWidth
}
}
|
faff4e9e0bb3556b70e2fb5a36071c76
| 41.678899 | 111 | 0.674549 | false | false | false | false |
jagajithmk/SubmitButton
|
refs/heads/master
|
SubmitButton/Classes/SubmitButton.swift
|
mit
|
1
|
//
// SubmitButton.swift
//
// Created by Jagajith M Kalarickal on 02/12/16.
// Copyright © 2016 Jagajith M Kalarickal. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public enum ButtonState {
case ready
case loading
case finishing
case finished
}
public enum ButtonLoadingType {
case continuous
case timeLimited
}
public enum ButtonCompletionStatus {
case success
case canceled
case failed
}
private struct Constants {
static let contextID = "kAnimationIdentifier"
static let layerAnimation = "kLayerAnimation"
static let cancelButtonTitle = "Cancelled"
static let prepareLoadingAnimDuration: TimeInterval = 0.2
static let resetLinesPositionAnimDuration: TimeInterval = 0.2
static let finishLoadingAnimDuration: TimeInterval = 0.3
static let bounceDuration: TimeInterval = 0.3
static let borderWidth: CGFloat = 5
static let minFontSize: CGFloat = 17
static let maxFontSize: CGFloat = 19
static let minOpacity: Float = 0
static let maxOpacity: Float = 1
static let minStrokeEndPosition: CGFloat = 0
static let maxStrokeEndPosition: CGFloat = 1
static let requestDuration: CGFloat = 1.0
static let frequencyUpdate: CGFloat = 0.1
static let borderBounceKeyTime: [NSNumber] = [0, 0.9, 1]
static let errorCrossMarkXShift: CGFloat = 15
static let errorCrossMarkYShift: CGFloat = 15
static let cancelButtonTag: Int = 100
static let cancelMarkXShift: CGFloat = 17
static let cancelMarkYShift: CGFloat = 17
static let cancelButtonHeight: CGFloat = 40
static let cancelButtonWidth: CGFloat = 40
}
private struct AnimKeys {
static let bounds = "bounds"
static let backgroundColor = "backgroundColor"
static let position = "position"
static let lineRotation = "lineRotation"
static let transform = "transform"
static let borderWidth = "borderWidth"
static let opacity = "opacity"
static let transformRotationZ = "transform.rotation.z"
}
enum AnimContext: String {
case LoadingStart
case LoadingFinishing
}
public typealias CompletionType = (SubmitButton) -> Void
@IBDesignable
open class SubmitButton: UIButton {
// MARK: - Public variables
/// Button loading type
open var loadingType: ButtonLoadingType = ButtonLoadingType.timeLimited
/// Color of dots and line in loading state
@IBInspectable open var dotColor: UIColor = #colorLiteral(red: 0, green: 0.8250309825, blue: 0.6502585411, alpha: 1)
/// Color of error button
@IBInspectable open var errorColor: UIColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
/// Color of cancelled button state
@IBInspectable open var cancelledButtonColor: UIColor = #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1)
/// Line width of the border
@IBInspectable open var lineWidth: CGFloat = 3
/// Border Color
@IBInspectable open var borderColor: UIColor = #colorLiteral(red: 0, green: 0.8250309825, blue: 0.6502585411, alpha: 1) {
didSet {
borderLayer.borderColor = borderColor.cgColor
}
}
/// Lines count on loading state
open var linesCount: UInt = 2
/// Measure in radians
@IBInspectable open var dotLength: CGFloat = 0.1
/// Time for pass one lap
@IBInspectable open var velocity: Double = 2
/// Loading center Color
@IBInspectable open var loadingCenterColor: UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
/// Button background color
@IBInspectable open var startBackgroundColor: UIColor! = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) {
didSet {
layer.backgroundColor = startBackgroundColor.cgColor
}
}
/// Button title color
@IBInspectable open var startTitleColor: UIColor! = #colorLiteral(red: 0, green: 0.8250309825, blue: 0.6502585411, alpha: 1) {
didSet {
setTitleColor(startTitleColor, for: UIControlState())
}
}
/// Show cancel option while loading
@IBInspectable open var cancelEnabled: Bool = false
/// Color of error button
@IBInspectable open var cancelOptionColor: UIColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1)
@IBInspectable open var startText: String = "Submit" {
didSet {
setTitle(startText, for: UIControlState())
}
}
open var currState: ButtonState {
return buttonState
}
open var frequencyOfUpdate: CGFloat {
return Constants.frequencyUpdate
}
// MARK: - Private Vars
fileprivate lazy var borderLayer: CALayer = {
let layer = CALayer()
layer.borderWidth = Constants.borderWidth
layer.borderColor = self.borderColor.cgColor
layer.backgroundColor = nil
return layer
}()
fileprivate lazy var progressLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.fillColor = nil
layer.strokeColor = self.dotColor.cgColor
layer.bounds = self.circleBounds
layer.path = UIBezierPath(arcCenter: self.boundsCenter, radius: self.boundsCenter.y - self.lineWidth / 2,
startAngle: CGFloat(-M_PI_2), endAngle: 3*CGFloat(M_PI_2), clockwise: true).cgPath
layer.strokeEnd = Constants.minStrokeEndPosition
layer.lineCap = kCALineCapRound
layer.lineWidth = self.lineWidth
return layer
}()
fileprivate lazy var checkMarkLayer: CAShapeLayer = {
return self.createCheckMark()
}()
fileprivate lazy var errorCrossMarkLayer: CAShapeLayer = {
return self.createErrorCrossMark()
}()
fileprivate lazy var cancelLayer: CAShapeLayer = {
return self.createCancel()
}()
fileprivate var buttonState: ButtonState = .ready {
didSet {
handleButtonState( buttonState )
}
}
fileprivate var circleBounds: CGRect {
var newRect = startBounds
newRect?.size.width = startBounds.height
return newRect!
}
fileprivate var boundsCenter: CGPoint {
return CGPoint(x: circleBounds.midX, y: circleBounds.midY)
}
fileprivate var boundsStartCenter: CGPoint {
return CGPoint(x: startBounds.midX, y: startBounds.midY)
}
fileprivate var isCancelEnabled: Bool = false
// Constraints for button
fileprivate var conWidth: NSLayoutConstraint!
fileprivate var conHeight: NSLayoutConstraint!
fileprivate var startBounds: CGRect!
fileprivate let prepareGroup = DispatchGroup()
fileprivate let finishLoadingGroup = DispatchGroup()
fileprivate var progress: CGFloat = 0
fileprivate var timer: Timer?
fileprivate var taskCompletion: CompletionType?
//intiate the update of the progress of progress bar
func updateLoadingProgress() {
guard progress <= 1 else {
timer?.invalidate()
self.stopAnimate()
progress = 0
return
}
progress += self.progressPerFrequency
self.updateProgress( progress )
}
// MARK: - UIButton
public override init(frame: CGRect) {
super.init(frame: frame)
setupCommon()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupCommon()
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupCommon()
}
open override func layoutSubviews() {
super.layoutSubviews()
if buttonState == .ready {
layoutStartBounds()
}
layer.cornerRadius = bounds.midY
}
// MARK: - Public Methods
//Function to reset button view
open func resetToReady() {
progress = 0
isCancelEnabled = false
buttonState = .ready
borderLayer.removeAllAnimations()
layer.removeAllAnimations()
checkMarkLayer.removeAllAnimations()
errorCrossMarkLayer.removeAllAnimations()
clearLayerContext()
CATransaction.begin()
CATransaction.setDisableActions( true )
layer.backgroundColor = startBackgroundColor.cgColor
checkMarkLayer.opacity = Constants.minOpacity
errorCrossMarkLayer.opacity = Constants.minOpacity
borderLayer.borderWidth = Constants.borderWidth
borderLayer.borderColor = borderColor.cgColor
progressLayer.removeFromSuperlayer()
progressLayer.strokeEnd = Constants.minStrokeEndPosition
CATransaction.commit()
setTitle(startText, for: UIControlState())
setTitleColor(startTitleColor, for: UIControlState())
titleLabel?.layer.opacity = Constants.maxOpacity
}
open func startAnimate() {
if buttonState != .ready {
resetToReady()
}
buttonState = .loading
}
open func stopAnimate() {
guard buttonState != .finishing && buttonState != .finished else {
return
}
buttonState = .finishing
}
// update of the progress of progress bar
open func updateProgress(_ progress: CGFloat) {
progressLayer.strokeEnd = progress
}
open func taskCompletion(completion: @escaping CompletionType) {
taskCompletion = completion
}
lazy var progressPerFrequency: CGFloat = {
let progressPerSecond = 1.0 / Constants.requestDuration
return CGFloat(progressPerSecond * Constants.frequencyUpdate)
}()
// MARK: - Selector && Action
func touchUpInside(_ sender: SubmitButton) {
if self.buttonState != .loading {
//*Code to reset buton after submit, comment these if not needed
guard !isSelected else {
if currState == .finished {
resetToReady()
isSelected = false
}
return
}//*
titleLabel?.font = UIFont.systemFont(ofSize: Constants.minFontSize)
guard buttonState != .finished else {
return
}
startAnimate()
}
}
}
// MARK: - Private Methods
extension SubmitButton {
fileprivate func layoutStartBounds() {
startBounds = bounds
borderLayer.bounds = startBounds
borderLayer.cornerRadius = startBounds.midY
borderLayer.position = CGPoint(x: startBounds.midX, y: startBounds.midY)
}
// MARK: Button Setup
fileprivate func setupCommon() {
addTarget(self, action: #selector(SubmitButton.touchUpInside(_:)), for: .touchUpInside)
contentEdgeInsets = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20)
setupButton()
}
//Function to setup button properties
fileprivate func setupButton() {
setTitle(startText, for: UIControlState())
layer.cornerRadius = bounds.midY
layer.borderColor = borderColor.cgColor
layer.addSublayer( borderLayer )
setTitleColor(startTitleColor, for: UIControlState())
}
//Function to remove temporary layer
fileprivate func clearLayerContext() {
for sublayer in layer.sublayers! {
if sublayer == borderLayer || sublayer == checkMarkLayer || sublayer == errorCrossMarkLayer {
continue
}
if sublayer is CAShapeLayer {
sublayer.removeFromSuperlayer()
}
}
}
// MARK: Managing button state
fileprivate func handleButtonState(_ state: ButtonState) {
switch state {
case .ready:
break
case .loading:
prepareLoadingAnimation({
if self.loadingType == ButtonLoadingType.timeLimited {
self.startProgressLoadingAnimation()
} else {
self.startLoadingAnimation()
}
})
case .finishing:
finishAnimation()
case .finished:
break
}
}
// MARK: Animations Configuring
//add button width animation
fileprivate func addButtonWidthAnimation() {
let boundAnim = CABasicAnimation(keyPath: AnimKeys.bounds)
boundAnim.toValue = NSValue(cgRect: circleBounds)
let colorAnim = CABasicAnimation(keyPath: AnimKeys.backgroundColor)
colorAnim.toValue = startTitleColor.cgColor
let layerGroup = CAAnimationGroup()
layerGroup.animations = [boundAnim, colorAnim]
layerGroup.duration = Constants.prepareLoadingAnimDuration
layerGroup.delegate = self
layerGroup.fillMode = kCAFillModeForwards
layerGroup.isRemovedOnCompletion = false
layerGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
assignContext(.LoadingStart, anim: layerGroup)
layer.add(layerGroup, forKey: AnimKeys.bounds)
}
//add button border position and size animation
fileprivate func addBorderPositionAndSizeDecreasingAnimation() {
let borderAnim = CABasicAnimation(keyPath: AnimKeys.borderWidth)
borderAnim.toValue = lineWidth
let borderBounds = CABasicAnimation(keyPath: AnimKeys.bounds)
borderBounds.toValue = NSValue(cgRect: circleBounds)
let borderPosition = CABasicAnimation(keyPath: AnimKeys.position)
borderPosition.toValue = NSValue(cgPoint: boundsCenter)
let borderGroup = CAAnimationGroup()
borderGroup.animations = [borderAnim, borderBounds, borderPosition]
borderGroup.duration = Constants.prepareLoadingAnimDuration
borderGroup.delegate = self
borderGroup.fillMode = kCAFillModeForwards
borderGroup.isRemovedOnCompletion = false
borderGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
assignContext(.LoadingStart, anim: borderGroup)
borderLayer.add(borderGroup, forKey: nil)
}
// For adding time for loading
fileprivate func addTimerForLimitedTimeLoadingAnimation() {
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: TimeInterval(frequencyOfUpdate), target:self,
selector: #selector(SubmitButton.updateLoadingProgress),
userInfo: nil, repeats: true)
}
// animate button to loading state, use completion to start loading animation
fileprivate func prepareLoadingAnimation(_ completion: (() -> Void)?) {
addButtonWidthAnimation()
prepareGroup.enter()
addBorderPositionAndSizeDecreasingAnimation()
prepareGroup.enter()
borderLayer.borderColor = UIColor.lightGray.cgColor
isSelected = true
if self.loadingType == ButtonLoadingType.timeLimited {
addTimerForLimitedTimeLoadingAnimation()
}
prepareGroup.notify(queue: DispatchQueue.main) {
self.borderLayer.borderWidth = self.lineWidth
self.borderLayer.bounds = self.circleBounds
self.borderLayer.position = self.boundsCenter
self.layer.backgroundColor = self.loadingCenterColor.cgColor
self.bounds = self.circleBounds
self.borderLayer.removeAllAnimations()
self.layer.removeAllAnimations()
completion?()
}
titleLabel?.layer.opacity = Constants.minOpacity
}
// start loading animation, that show progress
fileprivate func startProgressLoadingAnimation() {
progressLayer.position = boundsCenter
layer.insertSublayer(progressLayer, above: borderLayer)
if cancelEnabled {
addCancelOptionWhileLoading()
}
}
// start default loading
fileprivate func startLoadingAnimation() {
let arCenter = boundsCenter
let radius = circleBounds.midX - lineWidth / 2
var lines = [CAShapeLayer]()
let lineOffset: CGFloat = 2 * CGFloat(M_PI) / CGFloat(linesCount)
for i in 0..<linesCount {
let line = CAShapeLayer()
let startAngle = lineOffset * CGFloat(i)
line.path = UIBezierPath(arcCenter: arCenter,
radius: radius,
startAngle: startAngle,
endAngle: startAngle + dotLength,
clockwise: true).cgPath
line.bounds = circleBounds
line.strokeColor = dotColor.cgColor
line.lineWidth = lineWidth
line.fillColor = dotColor.cgColor
line.lineCap = kCALineCapRound
layer.insertSublayer(line, above: borderLayer)
line.position = arCenter
lines.append( line )
}
let opacityAnim = CABasicAnimation(keyPath: AnimKeys.opacity)
opacityAnim.fromValue = 0
let rotation = CABasicAnimation(keyPath: AnimKeys.transformRotationZ)
rotation.byValue = NSNumber(value: 2*M_PI as Double)
rotation.duration = velocity
rotation.repeatCount = Float.infinity
for line in lines {
line.add(rotation, forKey: AnimKeys.lineRotation)
line.add(opacityAnim, forKey: nil)
}
if cancelEnabled {
addCancelOptionWhileLoading()
}
}
// Finishing animation
fileprivate func finishAnimation() {
layer.masksToBounds = true
// lines
let lines = layer.sublayers!.filter {
guard $0 != checkMarkLayer && $0 != borderLayer else {
return false
}
return $0 is CAShapeLayer
}
// rotation for lines
let rotation = CABasicAnimation(keyPath: AnimKeys.transform)
rotation.toValue = NSValue(caTransform3D: CATransform3DIdentity)
rotation.duration = Constants.finishLoadingAnimDuration
rotation.delegate = self
assignContext(.LoadingFinishing, anim: rotation)
for line in lines {
rotation.fromValue = NSValue(caTransform3D: ((line.presentation() as? CAShapeLayer)?.transform)!)
line.add(rotation, forKey: AnimKeys.lineRotation)
finishLoadingGroup.enter()
}
finishLoadingGroup.notify(queue: DispatchQueue.main) {
self.taskCompletion!(self)
}
}
//Complete animation based on user input
open func completeAnimation(status: ButtonCompletionStatus) {
if cancelEnabled && isCancelEnabled && status != .canceled {
return
}
timer?.invalidate()
viewWithTag(Constants.cancelButtonTag)?.removeFromSuperview()
self.checkMarkAndBoundsAnimation(completionStatus: status)
self.clearLayerContext()
}
//Add button border expanding
fileprivate func addButtonBorderIncreasingAnimation() {
let proportions: [CGFloat] = [ circleBounds.width / startBounds.width, 0.9, 1]
var bounces = [NSValue]()
for i in 0..<proportions.count {
let rect = CGRect(origin: startBounds.origin, size: CGSize(width: startBounds.width * proportions[i],
height: startBounds.height))
bounces.append( NSValue(cgRect: rect) )
}
let borderBounce = CAKeyframeAnimation(keyPath: AnimKeys.bounds)
borderBounce.keyTimes = Constants.borderBounceKeyTime
borderBounce.values = bounces
borderBounce.duration = Constants.bounceDuration
borderBounce.beginTime = CACurrentMediaTime() + Constants.resetLinesPositionAnimDuration
borderBounce.delegate = self
borderBounce.isRemovedOnCompletion = false
borderBounce.fillMode = kCAFillModeBoth
assignContext(.LoadingFinishing, anim: borderBounce)
borderLayer.add(borderBounce, forKey: nil)
finishLoadingGroup.enter()
}
//Add button border position animation
fileprivate func addButtonBorderPositionUpdationAnimation() {
let borderPosition = CABasicAnimation(keyPath: AnimKeys.position)
borderPosition.toValue = NSValue(cgPoint: boundsStartCenter)
borderPosition.duration = Constants.bounceDuration * Constants.borderBounceKeyTime[1].doubleValue
borderPosition.beginTime = CACurrentMediaTime() + Constants.resetLinesPositionAnimDuration
borderPosition.delegate = self
borderPosition.isRemovedOnCompletion = false
borderPosition.fillMode = kCAFillModeBoth
assignContext(.LoadingFinishing, anim: borderPosition)
borderLayer.add(borderPosition, forKey: nil)
finishLoadingGroup.enter()
}
//Add button bound animation
fileprivate func addButtonBoundsAnimation(completionStatus: ButtonCompletionStatus) {
let boundsAnim = CABasicAnimation(keyPath: AnimKeys.bounds)
boundsAnim.fromValue = NSValue(cgRect: (layer.presentation()!).bounds)
boundsAnim.toValue = NSValue(cgRect: startBounds)
let colorAnim = CABasicAnimation(keyPath: AnimKeys.backgroundColor)
if completionStatus == .success {
colorAnim.toValue = dotColor.cgColor
colorAnim.fromValue = dotColor.cgColor
} else if completionStatus == .failed {
colorAnim.toValue = errorColor.cgColor
colorAnim.fromValue = errorColor.cgColor
} else {
colorAnim.toValue = cancelledButtonColor.cgColor
colorAnim.fromValue = cancelledButtonColor.cgColor
}
let layerGroup = CAAnimationGroup()
layerGroup.animations = [boundsAnim, colorAnim]
layerGroup.duration = Constants.bounceDuration * Constants.borderBounceKeyTime[1].doubleValue
layerGroup.beginTime = CACurrentMediaTime() + Constants.resetLinesPositionAnimDuration
layerGroup.delegate = self
layerGroup.fillMode = kCAFillModeBoth
layerGroup.isRemovedOnCompletion = false
assignContext(.LoadingFinishing, anim: layerGroup)
layer.add(layerGroup, forKey: AnimKeys.bounds)
layer.bounds = startBounds
finishLoadingGroup.enter()
}
//Add button expanding animation
fileprivate func addButtonPositionAndSizeIncreasingAnimation(status: ButtonCompletionStatus) {
addButtonBorderIncreasingAnimation()
addButtonBorderPositionUpdationAnimation()
addButtonBoundsAnimation(completionStatus: status)
}
//Add check mark and border expanding animation
fileprivate func checkMarkAndBoundsAnimation(completionStatus: ButtonCompletionStatus) {
self.borderLayer.opacity = Constants.maxOpacity
layer.masksToBounds = false
addButtonPositionAndSizeIncreasingAnimation(status: completionStatus)
if completionStatus == .success {
//Adding tick mark
self.layer.backgroundColor = self.dotColor.cgColor
borderLayer.borderColor = dotColor.cgColor
checkMarkLayer.position = CGPoint(x: layer.bounds.midX, y: layer.bounds.midY)
if checkMarkLayer.superlayer == nil {
checkMarkLayer.path = pathForMark().cgPath
layer.addSublayer( checkMarkLayer )
}
} else if completionStatus == .failed {
self.layer.backgroundColor = errorColor.cgColor
borderLayer.borderColor = errorColor.cgColor
errorCrossMarkLayer.position = CGPoint(x: layer.bounds.midX, y: layer.bounds.midY)
if errorCrossMarkLayer.superlayer == nil {
errorCrossMarkLayer.path = pathForCrossMark(XShift: Constants.errorCrossMarkXShift,
YShift: Constants.errorCrossMarkYShift).cgPath
layer.addSublayer( errorCrossMarkLayer )
}
} else {
self.layer.backgroundColor = cancelledButtonColor.cgColor
borderLayer.borderColor = cancelledButtonColor.cgColor
setTitle(Constants.cancelButtonTitle, for: UIControlState())
setTitleColor(UIColor.white, for: UIControlState())
}
finishLoadingGroup.notify(queue: DispatchQueue.main) {
UIView.animate(withDuration: 0.5, animations: {
if completionStatus == .success {
self.checkMarkLayer.opacity = Constants.maxOpacity
} else if completionStatus == .failed {
self.errorCrossMarkLayer.opacity = Constants.maxOpacity
} else {
self.titleLabel?.alpha = CGFloat(Constants.maxOpacity)
}
})
self.buttonState = .finished
}
}
// MARK: Check mark
// Configuring check mark layer
fileprivate func createMarkLayer() -> CAShapeLayer {
// configure layer
let layer = CAShapeLayer()
layer.bounds = circleBounds
layer.opacity = Constants.minOpacity
layer.fillColor = nil
layer.strokeColor = startBackgroundColor.cgColor
layer.lineCap = kCALineCapRound
layer.lineJoin = kCALineJoinRound
layer.lineWidth = lineWidth
return layer
}
//Function for creating the check mark layer
fileprivate func createCheckMark() -> CAShapeLayer {
let checkmarkLayer = createMarkLayer()
return checkmarkLayer
}
fileprivate func createErrorCrossMark() -> CAShapeLayer {
let crossmarkLayer = createMarkLayer()
return crossmarkLayer
}
fileprivate func createCancel() -> CAShapeLayer {
let cancelLayer = createMarkLayer()
return cancelLayer
}
//Function for drawing the check mark
fileprivate func pathForMark() -> UIBezierPath {
// geometry of the layer
let percentShiftY: CGFloat = 0.4
let percentShiftX: CGFloat = -0.2
let firstRadius = 0.5 * circleBounds.midY
let lastRadius = 1 * circleBounds.midY
let firstAngle = CGFloat(-3 * M_PI_4)
let lastAngle = CGFloat(-1 * M_PI_4)
var startPoint = CGPoint(x: firstRadius * cos(firstAngle), y: firstRadius * sin(firstAngle))
var midPoint = CGPoint.zero
var endPoint = CGPoint(x: lastRadius * cos(lastAngle), y: lastRadius * sin(lastAngle))
let correctedPoint = CGPoint(x: boundsCenter.x + (boundsCenter.x * percentShiftX),
y: boundsCenter.y + (boundsCenter.y * percentShiftY))
startPoint.addPoint( correctedPoint )
midPoint.addPoint( correctedPoint )
endPoint.addPoint( correctedPoint )
let path = UIBezierPath()
path.move( to: startPoint )
path.addLine( to: midPoint )
path.addLine( to: endPoint )
return path
}
fileprivate func pathForCrossMark(XShift: CGFloat, YShift: CGFloat) -> UIBezierPath {
// geometry for crossmark layer
let firstStartPoint = CGPoint(x: XShift, y: YShift)
let firstEndPoint = CGPoint(x: circleBounds.maxX - XShift, y: circleBounds.maxY - XShift)
let secondStartPoint = CGPoint(x: circleBounds.maxX - XShift, y: circleBounds.minY + YShift)
let secondEndPoint = CGPoint(x: circleBounds.minX + XShift, y: circleBounds.maxY - YShift)
let path = UIBezierPath()
path.move(to: firstStartPoint)
path.addLine(to: firstEndPoint)
path.move(to: secondStartPoint)
path.addLine(to: secondEndPoint)
return path
}
fileprivate func addCancelOptionWhileLoading() {
let button = UIButton(type: .custom)
button.tag = Constants.cancelButtonTag
button.frame = CGRect(x: layer.bounds.midX-Constants.cancelButtonWidth/2,
y: layer.bounds.midY-Constants.cancelButtonHeight/2,
width: Constants.cancelButtonWidth,
height: Constants.cancelButtonHeight)
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.clipsToBounds = true
let tempLayer = CAShapeLayer()
tempLayer.bounds = button.frame
tempLayer.fillColor = nil
tempLayer.strokeColor = cancelOptionColor.cgColor
tempLayer.lineCap = kCALineCapRound
tempLayer.lineJoin = kCALineJoinRound
tempLayer.lineWidth = lineWidth
tempLayer.position = CGPoint(x: button.layer.bounds.midX, y: button.layer.bounds.midY)
tempLayer.path = pathForCrossMark(XShift: Constants.cancelMarkXShift, YShift: Constants.cancelMarkYShift).cgPath
button.layer.addSublayer( tempLayer )
button.addTarget(self, action: #selector(cancelButtonPressed), for: .touchUpInside)
self.addSubview(button)
}
func cancelButtonPressed() {
isCancelEnabled = true
completeAnimation(status: .canceled)
}
fileprivate func assignContext(_ context: AnimContext, anim: CAAnimation ) {
anim.setValue(context.rawValue, forKey: Constants.contextID)
}
fileprivate func assignLayer(_ aLayer: CALayer, anim: CAAnimation) {
anim.setValue(aLayer, forKey: Constants.layerAnimation)
}
}
// MARK: - Animation Delegate
extension SubmitButton : CAAnimationDelegate {
public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard flag else {
return
}
guard let contextRawValue = anim.value( forKey: Constants.contextID ) as? String else {
return
}
let context = AnimContext(rawValue: contextRawValue)!
switch context {
case .LoadingStart:
prepareGroup.leave()
case .LoadingFinishing:
finishLoadingGroup.leave()
}
}
}
// MARK: CGPoint customization
extension CGPoint {
fileprivate mutating func addPoint(_ point: CGPoint) {
x += point.x
y += point.y
}
}
|
f82bf63ff011bce7436992a7401a1a97
| 41.846047 | 141 | 0.657031 | false | false | false | false |
darthpelo/TimerH2O
|
refs/heads/develop
|
TimerH2O/TimerH2O/Views/TH2OWaterPickerView.swift
|
mit
|
1
|
//
// TH2OWaterPickerView.swift
// TimerH2O
//
// Created by Alessio Roberto on 29/10/16.
// Copyright © 2016 Alessio Roberto. All rights reserved.
//
import UIKit
class TH2OWaterPickerView: UIView {
@IBOutlet weak var pickerTitleLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var pickerView: UIPickerView!
fileprivate let numbers = (0...9).map {"\($0)"}
fileprivate var amount = ["0", "0", "0", "0"]
typealias DoneAmount = (Int) -> Void
fileprivate var doneAmount: DoneAmount?
private var parentView: UIView?
@IBAction func doneButtonPressed(_ sender: AnyObject) {
guard let amount = Converter.convert(amount: amount) else {
return
}
doneAmount?(amount)
}
func loadPickerView() -> TH2OWaterPickerView? {
guard let view = R.nib.th2OWaterPickerView.firstView(owner: self) else {
return nil
}
view.frame.origin.y = UIScreen.main.bounds.height
view.frame.size.width = UIScreen.main.bounds.width
return view
}
func configure(onView: UIView, withCallback: @escaping DoneAmount) {
doneAmount = withCallback
parentView = onView
self.frame.origin.y = onView.frame.size.height
pickerTitleLabel.text = R.string.localizable.setsessionWaterpickerTitle()
doneButton.setTitle(R.string.localizable.done(), for: .normal)
pickerView.selectRow(2, inComponent: 0, animated: false)
amount[0] = "2"
UIApplication.shared.keyWindow?.addSubview(self)
}
func isTo(show: Bool) {
guard let height = parentView?.frame.size.height else {
return
}
UIView.animate(withDuration: 0.3,
animations: {
if show {
self.frame.origin.y = height - self.frame.size.height
} else {
self.frame.origin.y = height
}
}, completion: nil)
}
}
extension TH2OWaterPickerView: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 4
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return numbers.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return numbers[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
amount[component] = numbers[row]
}
}
|
c4c88e25a27bcbbe4d8ee1e9b7965540
| 30.045455 | 111 | 0.601757 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
refs/heads/master
|
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Presentation/User Stories/Player/View/PlayerViewController.swift
|
mit
|
1
|
//
// PlayerPlayerViewController.swift
// AsciiArtPlayer
//
// Created by Sergey Teryokhin on 20/12/2016.
// Copyright © 2016 iMacDev. All rights reserved.
//
import QorumLogs
import AsyncDisplayKit
import UIKit
import SwiftyAttributes
import SnapKit
class PlayerViewController: UIViewController, PlayerViewInput {
@IBOutlet var scrollView: UIScrollView!
var displayNode: ASTextNode!
var asciiArtString: NSAttributedString? {
didSet {
guard let myString = asciiArtString else {
return
}
self.displayNode?.attributedText = myString
self.displayNode?.view.frame.size = CGSize(width: myString.size().width + 2.0,
height: myString.size().height + 2.0)
self.updateMinZoomScaleForSize(size: self.view.bounds.size)
}
}
var output: PlayerViewOutput!
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
output.viewIsReady()
}
// MARK: PlayerViewInput
func setupInitialState() {
self.setupUI()
}
//MARK: UI
func setupUI() {
let node = ASTextNode()
let myAttributedString = NSAttributedString(string: "")
node.attributedText = myAttributedString
node.isUserInteractionEnabled = true
self.scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height)
self.automaticallyAdjustsScrollViewInsets = false
self.scrollView.addSubnode(node)
node.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(5)
make.right.equalToSuperview().offset(-5)
make.top.equalToSuperview().offset(5)
make.bottom.equalToSuperview().offset(-5)
}
node.backgroundColor = UIColor.white
self.displayNode = node
self.navigationItem.hidesBackButton = true
let backButton = UIBarButtonItem(title: "My Back", style: .plain, target: self, action: #selector(backAction))
self.navigationItem.leftBarButtonItem = backButton
}
func displayText(_ text: String, font: UIFont) {
let string = NSAttributedString(string: text)
self.asciiArtString = string.withFont(font)
}
private func updateMinZoomScaleForSize(size: CGSize) {
guard let calculatedSize = self.displayNode.attributedText?.size() else {
return
}
let widthScale = size.width / calculatedSize.width
let heightScale = size.height / calculatedSize.height
let minScale = min(widthScale, heightScale)
scrollView.minimumZoomScale = minScale
scrollView.maximumZoomScale = minScale*10
scrollView.zoomScale = minScale
}
///MARK: Action
func backAction() {
self.output.cancelAction()
}
}
extension PlayerViewController: UIScrollViewDelegate {
func viewForZooming(in: UIScrollView) -> UIView? {
return displayNode.view
}
}
|
5b7caf6122113100e107fb7f4c59d60c
| 28.842593 | 118 | 0.630779 | false | false | false | false |
IvanKalaica/GitHubSearch
|
refs/heads/master
|
GitHubSearch/GitHubSearch/Extensions/FormViewController+Extensions.swift
|
mit
|
1
|
//
// FormViewController+Extensions.swift
// GitHubSearch
//
// Created by Ivan Kalaica on 21/09/2017.
// Copyright © 2017 Kalaica. All rights reserved.
//
import Eureka
typealias TitleValuePair = (title: String, value: String?)
extension FormViewController {
func set(_ titleValuePair: TitleValuePair, forTag: String) {
guard let row = self.form.rowBy(tag: forTag) as? LabelRow else { return }
row.value = titleValuePair.value
row.title = titleValuePair.title
row.reload()
}
}
class EurekaLogoView: UIView {
let imageView: UIImageView
override init(frame: CGRect) {
self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 320, height: 130))
self.imageView.image = UIImage(named: "icon_github")
self.imageView.autoresizingMask = .flexibleWidth
super.init(frame: frame)
self.frame = CGRect(x: 0, y: 0, width: 320, height: 130)
self.imageView.contentMode = .scaleAspectFit
addSubview(self.imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
c74b96cf75a6b2eeec64416df6886862
| 29.837838 | 88 | 0.662577 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
iOS/MasterFeed/UpdateSelectionOperation.swift
|
mit
|
1
|
//
// UpdateSelectionOperation.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 2/22/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import UIKit
import RSCore
class UpdateSelectionOperation: MainThreadOperation {
// MainThreadOperation
public var isCanceled = false
public var id: Int?
public weak var operationDelegate: MainThreadOperationDelegate?
public var name: String? = "UpdateSelectionOperation"
public var completionBlock: MainThreadOperation.MainThreadOperationCompletionBlock?
private var coordinator: SceneCoordinator
private var dataSource: MasterFeedDataSource
private var tableView: UITableView
private var animations: Animations
init(coordinator: SceneCoordinator, dataSource: MasterFeedDataSource, tableView: UITableView, animations: Animations) {
self.coordinator = coordinator
self.dataSource = dataSource
self.tableView = tableView
self.animations = animations
}
func run() {
if dataSource.snapshot().numberOfItems > 0 {
if let indexPath = coordinator.currentFeedIndexPath {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.operationDelegate?.operationDidComplete(self)
}
tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: animations)
CATransaction.commit()
} else {
if let indexPath = tableView.indexPathForSelectedRow {
if animations.contains(.select) {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.operationDelegate?.operationDidComplete(self)
}
tableView.deselectRow(at: indexPath, animated: true)
CATransaction.commit()
} else {
tableView.deselectRow(at: indexPath, animated: false)
self.operationDelegate?.operationDidComplete(self)
}
} else {
self.operationDelegate?.operationDidComplete(self)
}
}
} else {
self.operationDelegate?.operationDidComplete(self)
}
}
}
|
a80bbdcad1755cf661b345631aa6f910
| 29.15625 | 120 | 0.750777 | false | false | false | false |
keyacid/keyacid-iOS
|
refs/heads/master
|
keyacid/EncryptViewController.swift
|
bsd-3-clause
|
1
|
//
// EncryptViewController.swift
// keyacid
//
// Created by Yuan Zhou on 6/24/17.
// Copyright © 2017 yvbbrjdr. All rights reserved.
//
import UIKit
class EncryptViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var signedAnonymous: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
textView.inputAccessoryView = DoneView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 40), textBox: textView)
}
func getSelectedRemoteProfile() -> RemoteProfile? {
if ProfilesTableViewController.selectedRemoteProfileIndex == -1 {
let remoteProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a remote profile!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
self.performSegue(withIdentifier: "ShowProfiles", sender: self)
})
remoteProfileNotSelected.addAction(OKAction)
self.present(remoteProfileNotSelected, animated: true, completion: nil)
return nil
}
return ProfilesTableViewController.remoteProfiles[ProfilesTableViewController.selectedRemoteProfileIndex]
}
func getSelectedLocalProfile() -> LocalProfile? {
if ProfilesTableViewController.selectedLocalProfileIndex == -1 {
let localProfileNotSelected: UIAlertController = UIAlertController.init(title: "Error", message: "You have to select a local profile!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
self.performSegue(withIdentifier: "ShowProfiles", sender: self)
})
localProfileNotSelected.addAction(OKAction)
self.present(localProfileNotSelected, animated: true, completion: nil)
return nil
}
return ProfilesTableViewController.localProfiles[ProfilesTableViewController.selectedLocalProfileIndex]
}
@IBAction func encryptClicked() {
let plainText: String = textView.text
var cipherText: String = ""
if plainText == "" {
let empty: UIAlertController = UIAlertController.init(title: "Error", message: "You have to encrypt something!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: { (action: UIAlertAction) in
self.textView.becomeFirstResponder()
})
empty.addAction(OKAction)
self.present(empty, animated: true, completion: nil)
return
}
if signedAnonymous.selectedSegmentIndex == 0 {
let remoteProfile: RemoteProfile? = getSelectedRemoteProfile()
if remoteProfile == nil {
return
}
let localProfile: LocalProfile? = getSelectedLocalProfile()
if localProfile == nil {
return
}
cipherText = Crypto.encrypt(data: plainText.data(using: String.Encoding.utf8)!, from: localProfile!, to: remoteProfile!).base64EncodedString()
if cipherText == "" {
let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrputed profile!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
empty.addAction(OKAction)
self.present(empty, animated: true, completion: nil)
return
}
textView.text = cipherText
} else {
let remoteProfile: RemoteProfile? = getSelectedRemoteProfile()
if remoteProfile == nil {
return
}
cipherText = Crypto.sealedEncrypt(data: plainText.data(using: String.Encoding.utf8)!, to: remoteProfile!).base64EncodedString()
if cipherText == "" {
let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Corrputed profile!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
empty.addAction(OKAction)
self.present(empty, animated: true, completion: nil)
return
}
textView.text = cipherText
}
UIPasteboard.general.string = cipherText
}
@IBAction func decryptClicked() {
let cipher: Data? = Data.init(base64Encoded: textView.text)
if cipher == nil {
let notBase64: UIAlertController = UIAlertController.init(title: "Error", message: "Invalid cipher!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
notBase64.addAction(OKAction)
self.present(notBase64, animated: true, completion: nil)
return
}
if signedAnonymous.selectedSegmentIndex == 0 {
let remoteProfile: RemoteProfile? = getSelectedRemoteProfile()
if remoteProfile == nil {
return
}
let localProfile: LocalProfile? = getSelectedLocalProfile()
if localProfile == nil {
return
}
let plainText: String = String.init(data: Crypto.decrypt(data: cipher!, from: remoteProfile!, to: localProfile!), encoding: String.Encoding.utf8)!
if plainText == "" {
let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
empty.addAction(OKAction)
self.present(empty, animated: true, completion: nil)
return
}
textView.text = plainText
} else {
let localProfile: LocalProfile? = getSelectedLocalProfile()
if localProfile == nil {
return
}
let plainText: String = String.init(data: Crypto.sealedDecrypt(data: cipher!, to: localProfile!), encoding: String.Encoding.utf8)!
if plainText == "" {
let empty: UIAlertController = UIAlertController.init(title: "Error", message: "Wrong profile or tampered data!", preferredStyle: .alert)
let OKAction: UIAlertAction = UIAlertAction.init(title: "OK", style: .default, handler: nil)
empty.addAction(OKAction)
self.present(empty, animated: true, completion: nil)
return
}
textView.text = plainText
}
}
}
|
36d32a38173612b497fe16b84c85d380
| 49.036232 | 173 | 0.623896 | false | false | false | false |
davidkuchar/codepath-04-twitterredux
|
refs/heads/master
|
Twitter/SidePanelViewController.swift
|
mit
|
1
|
//
// SidePanelViewController.swift
// Twitter
//
// Created by David Kuchar on 5/31/15.
// Copyright (c) 2015 David Kuchar. All rights reserved.
//
import UIKit
@objc enum MenuItem: Int {
case Mentions = -1
case Profile
case Timeline
}
@objc protocol SidePanelViewControllerDelegate {
optional func onMenuItemSelected(sender: AnyObject?, menuItem: MenuItem)
}
class SidePanelViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
weak var delegate: SidePanelViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SelectCell", forIndexPath: indexPath) as! SelectCell
switch MenuItem(rawValue: indexPath.row) {
case .Some(.Profile):
cell.nameLabel.text = "Your Profile"
case .Some(.Timeline):
cell.nameLabel.text = "Your Timeline"
default:
break
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch MenuItem(rawValue: indexPath.row) {
case .Some(.Profile):
delegate?.onMenuItemSelected?(self, menuItem: .Profile)
case .Some(.Timeline):
delegate?.onMenuItemSelected?(self, menuItem: .Timeline)
default:
break
}
}
@IBAction func onTapMentions(sender: AnyObject) {
delegate?.onMenuItemSelected?(self, menuItem: .Mentions)
}
}
|
84510adcf3bf4c754fc6ba854856c648
| 26.902778 | 116 | 0.653386 | false | false | false | false |
kiwitechnologies/ServiceClientiOS
|
refs/heads/master
|
ServiceClient/ServiceClient/TSGServiceClient/Utliity/TSGStringConstants.swift
|
mit
|
1
|
//
// StringConstants.swift
// ServiceSample
//
// Created by Yogesh Bhatt on 13/05/16.
// Copyright © 2016 kiwitech. All rights reserved.
//
import Foundation
let KEYS:String = "KEYS"
let MissingKeys:String = "MISSING_KEYS"
let INVALID_KEYS:String = "INVALID_KEYS"
let HEADERS:String = "HEADERS"
let Actions:String = "ACTIONS"
var errorStatus:[String:NSMutableArray]?
var missingParamKeys:[String:NSMutableArray]?
var missingInvalidParamKeys:[String:NSMutableArray]?
var missingHeaderKeys:[String:NSMutableArray]?
var missingHeaderParamKeys:[String:NSMutableArray]?
var invalidKeys:[String:NSMutableArray]? = [:]
var invalidHeaderKeys:[String:NSMutableArray]? = [:]
var alphaKey:NSMutableArray? = []
var alphaNumericKey:NSMutableArray? = []
var lengthKey:NSMutableArray? = []
var fileSizeKey:NSMutableArray? = []
var requiredKeys:NSMutableArray? = []
var emailKeys:NSMutableArray? = []
var numericKeys:NSMutableArray? = []
|
93575281e32ac4c464f099e8bfdc304a
| 22.525 | 52 | 0.756642 | false | false | false | false |
hustlzp/bemyeyes-ios
|
refs/heads/development
|
BeMyEyes Tests/ClientTest.swift
|
mit
|
2
|
//
// ClientTest.swift
// BeMyEyes
//
// Created by Tobias Due Munk on 18/11/14.
// Copyright (c) 2014 Be My Eyes. All rights reserved.
//
import UIKit
import XCTest
class ClientTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func newUser() -> (email: String, firstName: String, lastName: String, password: String, role: BMERole) {
let email = "iOSAppTest_" + String.random() + "@tt.com"
let firstName = "iOS App"
let lastName = "Tester"
let password = "12345678"
let role = BMERole.Blind
return (email, firstName, lastName, password, role)
}
func testSignup() {
let expectation = expectationWithDescription("Signup")
let (email, firstName, lastName, password, role) = newUser()
BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { (success, error) in
expectation.fulfill()
XCTAssert(success, "Failed sign up")
if let error = error {
XCTFail("...with error: " + error.localizedDescription)
}
if let user = BMEClient.sharedClient().currentUser {
XCTAssert(user.email == email, "Wrong email")
XCTAssert(user.firstName == firstName, "Wrong first name")
XCTAssert(user.lastName == lastName, "Wrong last name")
XCTAssert(user.role == role, "Wrong role")
} else {
XCTFail("No current user")
}
let token = BMEClient.sharedClient().token()
XCTAssert(token != nil, "No token")
}
waitForExpectationsWithTimeout(3, handler: nil)
}
func testLogin() {
let expectation = expectationWithDescription("Login")
let (email, firstName, lastName, password, role) = newUser()
BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { (success, error) in
BMEClient.sharedClient().loginWithEmail(email, password: password, deviceToken: nil, success: { token in
expectation.fulfill()
if let user = BMEClient.sharedClient().currentUser {
XCTAssert(user.email == email, "Wrong email")
XCTAssert(user.firstName == firstName, "Wrong first name")
XCTAssert(user.lastName == lastName, "Wrong last name")
XCTAssert(user.role == role, "Wrong role")
} else {
XCTFail("No current user")
}
let token = BMEClient.sharedClient().token()
XCTAssert(token != nil, "No token")
}, failure: { (error) -> Void in
XCTFail("Failed log in: " + error.localizedDescription)
expectation.fulfill()
})
}
waitForExpectationsWithTimeout(3, handler: nil)
}
func testLogout() {
let expectation = expectationWithDescription("Logout")
let (email, firstName, lastName, password, role) = newUser()
BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { (success, error) in
BMEClient.sharedClient().logoutWithCompletion(){ success, error in
expectation.fulfill()
XCTAssert(success, "Failed log out")
if let error = error {
XCTFail("...with error: " + error.localizedDescription)
}
let user = BMEClient.sharedClient().currentUser
XCTAssert(user == nil, "Shouldn't have current user")
}
}
waitForExpectationsWithTimeout(3, handler: nil)
}
func testInsertDeviceToken() {
let expectation = expectationWithDescription("Insert token")
let (email, firstName, lastName, password, role) = newUser()
BMEClient.sharedClient().createUserWithEmail(email, password: password, firstName: firstName, lastName: lastName, role: role) { success, error in
let newToken = "0f744707bebcf74f9b7c25d48e3358945f6aa01da5ddb387462c7eaf61bbad78"
BMEClient.sharedClient().upsertDeviceWithNewToken(newToken, production: false, completion: { (success, error) in
expectation.fulfill()
XCTAssert(success, "Failed insert")
if let error = error {
XCTFail("...with error: " + error.localizedDescription)
}
XCTAssert(GVUserDefaults.standardUserDefaults().deviceToken == newToken, "Wrong token")
})
}
waitForExpectationsWithTimeout(3, handler: nil)
}
}
extension String {
subscript (i: Int) -> String {
return String(Array(self)[i])
}
static func random() -> String {
return NSUUID().UUIDString
}
}
|
ab7bb19a9f1186621d507501d8aee98b
| 41.384 | 155 | 0.594753 | false | true | false | false |
iamjono/clingon
|
refs/heads/master
|
Sources/clingon/utilities/makeInitialize.swift
|
apache-2.0
|
1
|
//
// makeInitialize.swift
// clingon
//
// Created by Jonathan Guthrie on 2017-04-02.
//
//
import PerfectLib
func makeInitialize() throws {
let nl = "//"
let el = ""
var str: [String] = ["//"]
str.append("// initializeObjects.swift")
str.append("// \(fconfig.projectName)")
str.append(nl)
str.append("// Created by Jonathan Guthrie on 2017-02-20.")
str.append("// Copyright (C) 2017 PerfectlySoft, Inc.")
str.append(nl)
str.append("// Modified by Clingon: https://github.com/iamjono/clingon")
str.append(nl)
str.append("import PerfectLib")
str.append(el)
str.append("extension Utility {")
str.append(" static func initializeObjects() {")
var counter = 0
for cc in fconfig.classes {
if cc.includeSetup {
str.append(el)
str.append(" let a\(counter) = \(cc.name)()")
str.append(" try? a\(counter).setup()")
counter += 1
}
}
str.append(el)
str.append(" }")
str.append("}")
str.append("")
// Write file
do {
try writeFile("\(fconfig.destinationDir)/Sources/\(fconfig.projectName)/objects/initializeObjects.swift", contents: str)
} catch {
throw scaffoldError.fileWriteError
}
}
|
f4dc40122a3fa5bacf0a51c56f49b092
| 20.090909 | 122 | 0.644828 | false | true | false | false |
DylanModesitt/Verb
|
refs/heads/master
|
Verb/Verb/Event.swift
|
apache-2.0
|
1
|
//
// Event.swift
// noun
//
// Created by dcm on 12/23/15.
// Copyright © 2015 noun. All rights reserved.
//
import Foundation
import Parse
/*
@brief Create a new event given the desired name and the noun it belongs to
@init This method begins creates a new event object
@param name The name of the event to be created
@return The event PFObject created
*/
class Event {
/* The heart of Verb */
let event = PFObject(className: "Event")
var eventName: String
var numberOfMembers: Int
var upvotes: Int
var timeOfEvent: String
var isPrivate: Bool
var downvotes: Int
var nounParentObjectId: String
init(givenName: String, timeOfEvent: String, isPrivate: Bool, userCreatingEvent: PFUser, nounParentObjectId: String) throws {
self.eventName = givenName
self.timeOfEvent = timeOfEvent
self.isPrivate = isPrivate
self.numberOfMembers = 1
self.upvotes = 0
self.downvotes = 0
self.nounParentObjectId = nounParentObjectId
// Initialize the properties of the object
event["name"] = eventName
event["numberOfMembers"] = numberOfMembers
event["upvotes"] = upvotes
event["downvotes"] = downvotes
// Contact parent (noun the event is under) and save it to the parent. Otherwise, abandon the object.
do {
try ServerRequests().updateArray("Noun", objectID: nounParentObjectId, key: "events", valueToUpdate: event)
try ServerRequests().changeKeyByOne("Noun", objectID: nounParentObjectId, keyToIncrement: "numberOfEvents", increment: true)
} catch {
try event.delete()
throw errors.failureToAddEventToNoun
}
// TODO- Ad users and such. Users have a relationship with events
// Attempt to save directly. If not, save the object to the server eventually
do {
try event.save()
} catch {
event.saveEventually()
throw errors.failureToSaveData
}
}
// @returns The event PFObject
func getEvent() -> PFObject {
return event
}
// @returns the event's objectId
func getEventObjectID() -> String? {
if let _ = event.objectId {
return event.objectId!
} else {
return nil
}
}
}
|
a6ea10c9e09abdac419fd37649ae9fd8
| 26.455556 | 136 | 0.600162 | false | false | false | false |
matsuda/MuddlerKit
|
refs/heads/master
|
MuddlerKit/NSHTTPCookieStorageExtensions.swift
|
mit
|
1
|
//
// NSHTTPCookieStorageExtensions.swift
// MuddlerKit
//
// Created by Kosuke Matsuda on 2015/12/28.
// Copyright © 2015年 Kosuke Matsuda. All rights reserved.
//
import Foundation
//
// MARK: - archive & unarchive
//
extension Extension where Base: HTTPCookieStorage {
public func archivedData() -> Data? {
guard let cookies = base.cookies else { return nil }
return NSKeyedArchiver.archivedData(withRootObject: cookies)
}
public func unarchive(data: Data) {
guard let cookies = NSKeyedUnarchiver.unarchiveObject(with: data) as? [HTTPCookie] else {
return
}
cookies.forEach { base.setCookie($0) }
}
}
//
// MARK: - clear
//
extension Extension where Base: HTTPCookieStorage {
public func clearAll() {
guard let cookies = base.cookies else { return }
for cookie in cookies {
base.mk.clearCookie(cookie)
}
}
public func clear(forURL url: URL) {
guard let cookies = base.cookies(for: url) else { return }
for cookie in cookies {
base.mk.clearCookie(cookie)
}
}
///
/// http://mmasashi.hatenablog.com/entry/20101202/1292763345
///
public func clearCookie(_ cookie: HTTPCookie) {
guard var property = cookie.properties else {
base.deleteCookie(cookie)
return
}
base.deleteCookie(cookie)
property[HTTPCookiePropertyKey.expires] = Date(timeIntervalSinceNow: -3600)
if let newCookie = HTTPCookie(properties: property) {
base.setCookie(newCookie)
}
}
}
|
9fcfea6ed023154f3fe078c26a32873e
| 25.933333 | 97 | 0.623762 | false | false | false | false |
hironytic/Kiretan0
|
refs/heads/master
|
Kiretan0/View/Setting/TeamSelectionViewModel.swift
|
mit
|
1
|
//
// TeamSelectionViewModel.swift
// Kiretan0
//
// Copyright (c) 2017 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import RxSwift
public protocol TeamSelectionViewModel: ViewModel {
var tableData: Observable<[TableSectionViewModel]> { get }
}
public protocol TeamSelectionViewModelResolver {
func resolveTeamSelectionViewModel() -> TeamSelectionViewModel
}
extension DefaultResolver: TeamSelectionViewModelResolver {
public func resolveTeamSelectionViewModel() -> TeamSelectionViewModel {
return DefaultTeamSelectionViewModel(resolver: self)
}
}
public class DefaultTeamSelectionViewModel: TeamSelectionViewModel {
public typealias Resolver = NullResolver
public let tableData: Observable<[TableSectionViewModel]>
private let _resolver: Resolver
public init(resolver: Resolver) {
_resolver = resolver
let checkSubject = PublishSubject<String>()
let checkedItem = checkSubject.scan("") { $1 }
tableData = Observable.just([
StaticTableSectionViewModel(cells: [
CheckableTableCellViewModel(text: "うちのいえ", checked: checkedItem.map { $0 == "0" }, onSelect: checkSubject.mapObserver { "0" }),
CheckableTableCellViewModel(text: "バスケ部", checked: checkedItem.map { $0 == "1" }, onSelect: checkSubject.mapObserver { "1" }),
CheckableTableCellViewModel(text: "ほげほげ", checked: checkedItem.map { $0 == "2" }, onSelect: checkSubject.mapObserver { "2" }),
])
])
}
}
|
788921836ffd7d315ad4a466ee4bf66c
| 40.15625 | 143 | 0.719438 | false | false | false | false |
digipost/ios
|
refs/heads/master
|
Digipost/NSDate+Extensions.swift
|
apache-2.0
|
1
|
//
// Copyright (C) Posten Norge AS
//
// 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
extension Date {
func prettyStringWithJPGExtension()-> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM YY HH:mm:ss"
var dateString = "IMG "
dateString = dateString + dateFormatter.string(from: self)
dateString = dateString + ".jpg"
return dateString
}
func prettyStringWithMOVExtension()-> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM YY HH:mm:ss"
var dateString = "MOV "
dateString = dateString + dateFormatter.string(from: self)
dateString = dateString + ".mov"
return dateString
}
func dateOnly() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.YYYY"
return "\(dateFormatter.string(from: self))"
}
func timeOnly() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
return "\(dateFormatter.string(from: self))"
}
func dateByAdding(seconds: Int?) -> Date? {
if seconds == nil {
return nil
}
let calendar = Calendar.current
var components = DateComponents()
components.second = seconds!
return (calendar as NSCalendar).date(byAdding: components, to: self, options: NSCalendar.Options())
}
func isLaterThan(_ aDate: Date) -> Bool {
let isLater = self.compare(aDate) == ComparisonResult.orderedDescending
return isLater
}
}
|
c1c61501f07275939911034ea6c7eebd
| 31.848485 | 107 | 0.643911 | false | true | false | false |
robin24/bagtrack
|
refs/heads/master
|
BagTrack/View Controllers/Onboarding/OnboardingPushViewController.swift
|
mit
|
1
|
//
// OnboardingPushViewController.swift
// BagTrack
//
// Created by Robin Kipp on 13.10.17.
// Copyright © 2017 Robin Kipp. All rights reserved.
//
import UIKit
import UserNotifications
class OnboardingPushViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var allowButton: UIButton!
var center:UNUserNotificationCenter!
var pushActivationFailed = false
// MARK: - Methods
override func viewDidLoad() {
super.viewDidLoad()
textView.text = NSLocalizedString("When you enable push notifications, BagTrack will inform you when you get too far from your bags.\n\nTap “Allow Push Notifications” and confirm the following prompt to enable notifications (recommended), or tap “Next” in order to skip this step.", comment: "Onboarding message informing the user about the advantages of enabling push notifications.")
UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, textView)
center = UNUserNotificationCenter.current()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onAllowButtonTapped(_ sender: UIButton) {
if pushActivationFailed {
guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else {
fatalError("Error retrieving settings URL.")
}
UIApplication.shared.open(settingsURL, options: [:]) { _ in
DispatchQueue.main.async {
self.textView.text = NSLocalizedString("Thank you!", comment: "Shown when returning to the app from the settings screen.")
self.allowButton.isHidden = true
} }
return
}
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
if granted {
DispatchQueue.main.async {
self.textView.text = NSLocalizedString("Thank you for enabling push notifications!", comment: "Shown after push notifications were enabled.")
self.allowButton.isHidden = true
}
} else {
DispatchQueue.main.async {
self.textView.text = NSLocalizedString("Oops, something went wrong! We were unable to activate push notifications. Please tap “Settings” now to enable notifications, or tap “Next” if you prefer to do so later.", comment: "Shown when unable to activate notifications.")
self.pushActivationFailed = true
self.allowButton.setTitle(NSLocalizedString("Settings", comment: "Settings button."), for: .normal)
}
} }
}
}
|
6dc90b50895b13aa9c3f88961ce864a1
| 44.95082 | 393 | 0.65751 | false | false | false | false |
DroidsOnRoids/SwiftCarousel
|
refs/heads/master
|
Source/SwiftCarousel.swift
|
mit
|
1
|
/*
* Copyright (c) 2015 Droids on Roids LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
open class SwiftCarousel: UIView {
//MARK: - Properties
/// Current target with velocity left
internal var currentVelocityX: CGFloat?
/// Maximum velocity that swipe can reach.
internal var maxVelocity: CGFloat = 100.0
// Bool to know if item has been selected by Tapping
fileprivate var itemSelectedByTap = false
/// Number of items that were set at the start of init.
fileprivate var originalChoicesNumber = 0
/// Items that carousel shows. It is 3x more items than originalChoicesNumber.
fileprivate var choices: [UIView] = []
/// Main UIScrollView.
fileprivate var scrollView = UIScrollView()
/// Current selected index (between 0 and choices count).
fileprivate var currentSelectedIndex: Int?
/// Current selected index (between 0 and originalChoicesNumber).
fileprivate var currentRealSelectedIndex: Int?
/// Carousel delegate that handles events like didSelect.
open weak var delegate: SwiftCarouselDelegate?
/// Bool to set if by tap on item carousel should select it (scroll to it).
open var selectByTapEnabled = true
/// Scrolling type of carousel. You can constraint scrolling through items.
open var scrollType: SwiftCarouselScroll = .default {
didSet {
if case .max(let number) = scrollType , number <= 0 {
scrollType = .none
}
switch scrollType {
case .none:
scrollView.isScrollEnabled = false
case .max, .freely, .default:
scrollView.isScrollEnabled = true
}
}
}
/// Resize type of the carousel chosen from SwiftCarouselResizeType.
open var resizeType: SwiftCarouselResizeType = .withoutResizing(0.0) {
didSet {
setupViews(choices)
}
}
/// If selected index is < 0, set it as nil.
/// We won't check with count number since it might be set before assigning items.
open var defaultSelectedIndex: Int? {
didSet {
if (defaultSelectedIndex < 0) {
defaultSelectedIndex = nil
}
}
}
/// If there is defaultSelectedIndex and was selected, the variable is true.
/// Otherwise it is not.
open var didSetDefaultIndex: Bool = false
/// Current selected index (calculated by searching through views),
/// It returns index between 0 and originalChoicesNumber.
open var selectedIndex: Int? {
let view = viewAtLocation(CGPoint(x: scrollView.contentOffset.x + scrollView.frame.width / 2.0, y: scrollView.frame.minY))
guard var index = choices.index(where: { $0 == view }) else {
return nil
}
while index >= originalChoicesNumber {
index -= originalChoicesNumber
}
return index
}
/// Current selected index (calculated by searching through views),
/// It returns index between 0 and choices count.
fileprivate var realSelectedIndex: Int? {
let view = viewAtLocation(CGPoint(x: scrollView.contentOffset.x + scrollView.frame.width / 2.0, y: scrollView.frame.minY))
guard let index = choices.index(where: { $0 == view }) else {
return nil
}
return index
}
/// Carousel items. You can setup your carousel using this method (static items), or
/// you can also see `itemsFactory`, which uses closure for the setup.
/// Warning: original views are copied internally and are not guaranteed to be complete when the `didSelect` and `didDeselect` delegate methods are called. Use `itemsFactory` instead to avoid this limitation.
open var items: [UIView] {
get {
return [UIView](choices[choices.count / 3..<(choices.count / 3 + originalChoicesNumber)])
}
set {
originalChoicesNumber = newValue.count
(0..<3).forEach { counter in
let newViews: [UIView] = newValue.map { choice in
// Return original view if middle section
if counter == 1 {
return choice
} else {
do {
return try choice.copyView()
} catch {
fatalError("There was a problem with copying view.")
}
}
}
self.choices.append(contentsOf: newViews)
}
setupViews(choices)
}
}
/// Factory for carousel items. Here you specify how many items do you want in carousel
/// and you need to specify closure that will create that view. Remember that it should
/// always create new view, not give the same reference all the time.
/// If the factory closure returns a reference to a view that has already been returned, a SwiftCarouselError.ViewAlreadyAdded error is thrown.
/// You can always setup your carousel using `items` instead.
open func itemsFactory(itemsCount count: Int, factory: (_ index: Int) -> UIView) throws {
guard count > 0 else { return }
originalChoicesNumber = count
try (0..<3).forEach { counter in
let newViews: [UIView] = try stride(from: 0, to: count, by: 1).map { i in
let view = factory(i)
guard !self.choices.contains(view) else {
throw SwiftCarouselError.viewAlreadyAdded
}
return view
}
self.choices.append(contentsOf: newViews)
}
setupViews(choices)
}
// MARK: - Inits
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/**
Initialize carousel with items & frame.
- parameter frame: Carousel frame.
- parameter items: Items to put in carousel.
Warning: original views in `items` are copied internally and are not guaranteed to be complete when the `didSelect` and `didDeselect` delegate methods are called. Use `itemsFactory` instead to avoid this limitation.
*/
public convenience init(frame: CGRect, items: [UIView]) {
self.init(frame: frame)
setup()
self.items = items
}
deinit {
scrollView.removeObserver(self, forKeyPath: "contentOffset")
}
// MARK: - Setups
/**
Main setup function. Here should be everything that needs to be done once.
*/
fileprivate func setup() {
scrollView = UIScrollView()
scrollView.delegate = self
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.isScrollEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
addSubview(scrollView)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|",
options: .alignAllCenterX,
metrics: nil,
views: ["scrollView": scrollView])
)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|",
options: .alignAllCenterY,
metrics: nil,
views: ["scrollView": scrollView])
)
backgroundColor = .clear
scrollView.backgroundColor = .clear
scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.new, .old], context: nil)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(_:)))
gestureRecognizer.cancelsTouchesInView = false
gestureRecognizer.delegate = self
scrollView.addGestureRecognizer(gestureRecognizer)
}
/**
Setup views. Function that is fired up when setting the resizing type or items array.
- parameter views: Current items to setup.
*/
fileprivate func setupViews(_ views: [UIView]) {
var x: CGFloat = 0.0
if case .floatWithSpacing(_) = resizeType {
views.forEach { $0.sizeToFit() }
}
views.forEach { choice in
var additionalSpacing: CGFloat = 0.0
switch resizeType {
case .withoutResizing(let spacing): additionalSpacing = spacing
case .floatWithSpacing(let spacing): additionalSpacing = spacing
case .visibleItemsPerPage(let visibleItems):
choice.frame.size.width = scrollView.frame.width / CGFloat(visibleItems)
if (choice.frame.height > 0.0) {
let aspectRatio: CGFloat = choice.frame.width/choice.frame.height
choice.frame.size.height = floor(choice.frame.width * aspectRatio) > frame.height ? frame.height : floor(choice.frame.width * aspectRatio)
} else {
choice.frame.size.height = frame.height
}
}
choice.frame.origin.x = x
x += choice.frame.width + additionalSpacing
}
scrollView.subviews.forEach { $0.removeFromSuperview() }
views.forEach { scrollView.addSubview($0) }
layoutIfNeeded()
}
override open func layoutSubviews() {
super.layoutSubviews()
guard (scrollView.frame.width > 0 && scrollView.frame.height > 0) else { return }
var width: CGFloat = 0.0
switch resizeType {
case .floatWithSpacing(_), .withoutResizing(_):
width = choices.last!.frame.maxX
case .visibleItemsPerPage(_):
width = choices.reduce(0.0) { $0 + $1.frame.width }
}
scrollView.contentSize = CGSize(width: width, height: frame.height)
maxVelocity = scrollView.contentSize.width / 6.0
// We do not want to change the selected index in case of hiding and
// showing view, which also triggers layout.
// On the other hand this method can be triggered when the defaultSelectedIndex
// was set after the carousel init, so we check if the default index is != nil
// and that it wasn't set before.
guard currentSelectedIndex == nil ||
(didSetDefaultIndex == false && defaultSelectedIndex != nil) else { return }
// Center the view
if defaultSelectedIndex != nil {
selectItem(defaultSelectedIndex!, animated: false)
didSetDefaultIndex = true
} else {
selectItem(0, animated: false)
}
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let _ = change?[NSKeyValueChangeKey.newKey] , keyPath == "contentOffset" {
// with autolayout this seems to be quite usual, we want to wait
// until we have some size we can actualy work with
guard (scrollView.frame.width > 0 &&
scrollView.frame.height > 0) else { return }
let newOffset = scrollView.contentOffset
let segmentWidth = scrollView.contentSize.width / 3
var newOffsetX: CGFloat!
if (newOffset.x >= segmentWidth * 2.0) { // in the 3rd part
newOffsetX = newOffset.x - segmentWidth // move back one segment
} else if (newOffset.x + scrollView.bounds.width) <= segmentWidth { // First part
newOffsetX = newOffset.x + segmentWidth // move forward one segment
}
// We are in middle segment still so no need to scroll elsewhere
guard newOffsetX != nil && newOffsetX > 0 else {
return
}
self.scrollView.contentOffset.x = newOffsetX
self.delegate?.didScroll?(toOffset: self.scrollView.contentOffset)
}
}
// MARK: - Gestures
open func viewTapped(_ gestureRecognizer: UIGestureRecognizer) {
if selectByTapEnabled {
let touchPoint = gestureRecognizer.location(in: scrollView)
if let view = viewAtLocation(touchPoint), let index = choices.index(of: view) {
itemSelectedByTap = true
selectItem(index, animated: true, force: true)
}
}
}
// MARK: - Helpers
/**
Function that should be called when item was selected by Carousel.
It will deselect all items that were selected before, and send
notification to the delegate.
*/
internal func didSelectItem() {
guard let selectedIndex = self.selectedIndex, let realSelectedIndex = self.realSelectedIndex else {
return
}
didDeselectItem()
delegate?.didSelectItem?(item: choices[realSelectedIndex], index: selectedIndex, tapped: itemSelectedByTap)
itemSelectedByTap = false
currentSelectedIndex = selectedIndex
currentRealSelectedIndex = realSelectedIndex
currentVelocityX = nil
scrollView.isScrollEnabled = true
}
/**
Function that should be called when item was deselected by Carousel.
It will also send notification to the delegate.
*/
internal func didDeselectItem() {
guard let currentRealSelectedIndex = self.currentRealSelectedIndex, let currentSelectedIndex = self.currentSelectedIndex else {
return
}
delegate?.didDeselectItem?(item: choices[currentRealSelectedIndex], index: currentSelectedIndex)
}
/**
Detects if new point to scroll to will change the part (from the 3 parts used by Carousel).
First and third parts are not shown to the end user, we are managing the scrolling between
them behind the stage. The second part is the part user thinks it sees.
- parameter point: Destination point.
- returns: Bool that says if the part will change.
*/
fileprivate func willChangePart(_ point: CGPoint) -> Bool {
if (point.x >= scrollView.contentSize.width * 2.0 / 3.0 ||
point.x <= scrollView.contentSize.width / 3.0) {
return true
}
return false
}
/**
Get view (from the items array) at location (if it exists).
- parameter touchLocation: Location point.
- returns: UIView that contains that point (if it exists).
*/
fileprivate func viewAtLocation(_ touchLocation: CGPoint) -> UIView? {
for subview in scrollView.subviews where subview.frame.contains(touchLocation) {
return subview
}
return nil
}
/**
Get nearest view to the specified point location.
- parameter touchLocation: Location point.
- returns: UIView that is the nearest to that point (or contains that point).
*/
internal func nearestViewAtLocation(_ touchLocation: CGPoint) -> UIView {
var view: UIView!
if let newView = viewAtLocation(touchLocation) {
view = newView
} else {
// Now check left and right margins to nearest views
var step: CGFloat = 1.0
switch resizeType {
case .floatWithSpacing(let spacing):
step = spacing
case .withoutResizing(let spacing):
step = spacing
default:
break
}
var targetX = touchLocation.x
// Left
var leftView: UIView?
repeat {
targetX -= step
leftView = viewAtLocation(CGPoint(x: targetX, y: touchLocation.y))
} while (leftView == nil)
let leftMargin = touchLocation.x - leftView!.frame.maxX
// Right
var rightView: UIView?
repeat {
targetX += step
rightView = viewAtLocation(CGPoint(x: targetX, y: touchLocation.y))
} while (rightView == nil)
let rightMargin = rightView!.frame.minX - touchLocation.x
if rightMargin < leftMargin {
view = rightView!
} else {
view = leftView!
}
}
// Check if the view is in bounds of scrolling type
if case .max(let maxItems) = scrollType,
let currentRealSelectedIndex = currentRealSelectedIndex,
var newIndex = choices.index (where: { $0 == view }) {
if UInt(abs(newIndex - currentRealSelectedIndex)) > maxItems {
if newIndex > currentRealSelectedIndex {
newIndex = currentRealSelectedIndex + Int(maxItems)
} else {
newIndex = currentRealSelectedIndex - Int(maxItems)
}
}
while newIndex < 0 {
newIndex += originalChoicesNumber
}
while newIndex > choices.count {
newIndex -= originalChoicesNumber
}
view = choices[newIndex]
}
return view
}
/**
Select item in the Carousel.
- parameter choice: Item index to select. If it contains number > than originalChoicesNumber,
you need to set `force` flag to true.
- parameter animated: If the method should try to animate the selection.
- parameter force: Force should be set to true if choice index is out of items bounds.
*/
fileprivate func selectItem(_ choice: Int, animated: Bool, force: Bool) {
var index = choice
if !force {
// allow scroll only in the range of original items
guard choice < choices.count / 3 else {
return
}
// move to same item in middle segment
index = index + originalChoicesNumber
}
let choiceView = choices[index]
let x = choiceView.center.x - scrollView.frame.width / 2.0
let newPosition = CGPoint(x: x, y: scrollView.contentOffset.y)
let animationIsNotNeeded = newPosition.equalTo(scrollView.contentOffset)
scrollView.setContentOffset(newPosition, animated: animated)
if !animated || animationIsNotNeeded {
didSelectItem()
}
}
/**
Select item in the Carousel.
- parameter choice: Item index to select.
- parameter animated: Bool to tell if the selection should be animated.
*/
open func selectItem(_ choice: Int, animated: Bool) {
selectItem(choice, animated: animated, force: false)
}
}
|
f8297719a2168bf943dda608e1e52f08
| 37.382022 | 220 | 0.598946 | false | false | false | false |
alexth/Balkania-iPad
|
refs/heads/master
|
BalkaniaiPad/ViewControllers/MainViewController.swift
|
mit
|
1
|
//
// MainViewController.swift
// BalkaniaiPad
//
// Created by Alex Golub on 9/6/17.
// Copyright © 2017 Alex Golub. All rights reserved.
//
import UIKit
final class MainViewController: UIViewController {
@IBOutlet weak var rsContainerView: UIView!
@IBOutlet weak var srContainerView: UIView!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
fileprivate var selectedPlist: String!
fileprivate var savedSelectedPlist = "savedSelectedPlist"
fileprivate let russianSerbianPlist = "DICT_R-S"
fileprivate let serbianRussianPlist = "DICT_S-R"
fileprivate let rsSegueIdentifier = "rsSegue"
fileprivate let srSegueIdentifier = "srSegue"
fileprivate let animationDuration: TimeInterval = 0.3
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(keyboardWillHide(notification:)),
name:NSNotification.Name.UIKeyboardWillHide,
object: nil)
notificationCenter.addObserver(self,
selector: #selector(keyboardWillShow(notification:)),
name:NSNotification.Name.UIKeyboardWillShow,
object: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == rsSegueIdentifier {
let dictionaryViewController = segue.destination as! DictionaryViewController
dictionaryViewController.dictionaryName = russianSerbianPlist
} else if segue.identifier == srSegueIdentifier {
let dictionaryViewController = segue.destination as! DictionaryViewController
dictionaryViewController.dictionaryName = serbianRussianPlist
}
}
}
extension MainViewController {
@objc fileprivate func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: animationDuration) {
self.bottomConstraint.constant = 0
}
}
@objc fileprivate func keyboardWillShow(notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
UIView.animate(withDuration: animationDuration) {
self.bottomConstraint.constant = keyboardSize.height
}
}
}
|
eb71eb240ad0f2ff6f0155bcacf2118b
| 38.153846 | 120 | 0.658939 | false | false | false | false |
Yuanjihua1/SwiftyORM
|
refs/heads/master
|
SwiftyORM/StORMDataSourceCredentials.swift
|
mit
|
1
|
//
// DataSourceCredentials.swift
// StORM
//
// Created by Jonathan Guthrie on 2016-09-23.
//
//
/// Storage for current datasource connection properties.
public struct StORMDataSourceCredentials {
/// Host, which is either a URL or an IP address.
public var host: String = "localhost"
/// Port at which the client will access the server.
public var port: Int = 0
/// Username for authentication.
public var username: String = ""
/// Password for accessing the datasource.
public var password: String = ""
public init() {}
/// Initializer to set properties at instantiation.
public init(host: String, port: Int = 0, user: String = "", pass: String = "") {
self.host = host
self.port = port
self.username = user
self.password = pass
}
}
|
986481af90198fb5119172b12ecc62ed
| 22.575758 | 81 | 0.677378 | false | false | false | false |
nevyn/CoreDragon
|
refs/heads/master
|
Examples/DragonFrame/DragonFrame/PhotoFrameViewController.swift
|
apache-2.0
|
2
|
//
// FirstViewController.swift
// DragonFrame
//
// Created by Nevyn Bengtsson on 2015-12-20.
// Copyright © 2015 ThirdCog. All rights reserved.
//
import UIKit
class PhotoFrameViewController: UIViewController, DragonDropDelegate {
@IBOutlet var imageView : UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Load image from last run.
imageView.image = self.image
// The user may drop things on the image view.
// This view controller will be the delegate to determine if and how
// drop operations will be handled.
DragonController.sharedController().registerDropTarget(self.imageView, delegate: self)
}
// When a dragging operation starts, this method is called for each drop target
// that this view controller is responsible for, to see if the drop target
// is potentially able to accept the contents of that drag'n'drop.
func dropTarget(droppable: UIView, canAcceptDrag drag: DragonInfo) -> Bool {
// Is there something image-like on the pasteboard? Then accept it.
if drag.pasteboard.pasteboardTypes().contains({ (str) -> Bool in
return UIPasteboardTypeListImage.containsObject(str)
}) {
return true
}
return false
}
// Once the user drops the item on a drop target view, this method is responsible
// for accepting the data and handling it.
func dropTarget(droppable: UIView, acceptDrag drag: DragonInfo, atPoint p: CGPoint) {
if let image = drag.pasteboard.image {
// We handle it by setting the main image view's image to the one
// that the user dropped, and ...
self.imageView.image = image
// ... also saving it to disk for next time.
self.image = image
}
}
// Helpers for loading/saving images from disk
var imageURL : NSURL {
get {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
return NSURL.fileURLWithPath(documentsPath).URLByAppendingPathComponent("image.jpg")
}
}
var image : UIImage? {
get {
return UIImage(contentsOfFile: self.imageURL.path!)
}
set {
if let image = newValue {
UIImageJPEGRepresentation(image, 0.8)?.writeToURL(self.imageURL, atomically: false)
}
}
}
}
|
d1118dbf16f110394baacf2ff2834b4e
| 29.873239 | 108 | 0.722958 | false | false | false | false |
Integreat/app-ios
|
refs/heads/master
|
Integreat/Integreat/RootNavigationController.swift
|
lgpl-3.0
|
2
|
import UIKit
class RootNavigationController: UINavigationController {
var apiService: IGApiService?
var languagePickedObserver: NSObjectProtocol?
override func viewDidLoad() {
super.viewDidLoad()
updateRootVC()
languagePickedObserver = NSNotificationCenter.defaultCenter().addObserverForName(IGLanguagePickedNotification,
object: nil,
queue: NSOperationQueue.mainQueue(),
usingBlock: { [weak self] _ in self?.updateRootVC(animated: true) }
)
}
deinit {
if let observer = languagePickedObserver {
NSNotificationCenter.defaultCenter().removeObserver(observer,
name: IGLanguagePickedNotification,
object: nil
)
}
}
@IBAction func showCityPicker(_: AnyObject?) {
let cityPickerVC = instantiateCityPickerVC()
setViewControllers([ cityPickerVC ], animated: true)
}
private func updateRootVC(animated animated: Bool = false) {
let selection = getSelectedLocationAndLanguage()
// Show pages
if let location = selection.0, language = selection.1 {
let pagesListVC = instantiatePagesListVCWithLocation(location, language: language)
setViewControllers([ pagesListVC ], animated: animated)
}
// Pick city + language
else {
let cityPickerVC = instantiateCityPickerVC()
setViewControllers([ cityPickerVC ], animated: animated)
}
}
private func instantiateCityPickerVC() -> IGCityPickerVCCollectionViewController {
let cityPickerVC = self.storyboard?.instantiateViewControllerWithIdentifier("CityPickerVC")
as! IGCityPickerVCCollectionViewController
cityPickerVC.apiService = apiService
return cityPickerVC
}
private func instantiatePagesListVCWithLocation(location: Location, language: Language) -> IGPagesListVC {
let pagesListVC = self.storyboard?.instantiateViewControllerWithIdentifier("PagesListVC")
as! IGPagesListVC
pagesListVC.apiService = apiService
pagesListVC.selectedLocation = location
pagesListVC.selectedLanguage = language
return pagesListVC
}
private func getSelectedLocationAndLanguage() -> (Location?, Language?) {
let location = NSUserDefaults.standardUserDefaults().stringForKey("location").flatMap { locationId in
(self.apiService?.context).flatMap { context in
Location.findLocationWithIdentifier(locationId, inContext: context)
}
}
let language = NSUserDefaults.standardUserDefaults().stringForKey("language").flatMap { languageId in
(self.apiService?.context).flatMap { context in
Language.findLanguageWithIdentifier(languageId, inContext: context)
}
}
return (location, language)
}
}
|
f221548e067f64b129119cd1247165fb
| 36.525 | 118 | 0.654231 | false | false | false | false |
matrix-org/matrix-ios-sdk
|
refs/heads/develop
|
MatrixSDK/Contrib/Swift/MXRestClient.swift
|
apache-2.0
|
1
|
/*
Copyright 2017 Avery Pierce
Copyright 2017 Vector Creations Ltd
Copyright 2019 The Matrix.org Foundation C.I.C
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/// Represents account data type
public enum MXAccountDataType: Equatable, Hashable {
case direct
case pushRules
case ignoredUserList
case other(String)
var rawValue: String {
switch self {
case .direct: return kMXAccountDataTypeDirect
case .pushRules: return kMXAccountDataTypePushRules
case .ignoredUserList: return kMXAccountDataKeyIgnoredUser
case .other(let value): return value
}
}
}
/// Method of inviting a user to a room
public enum MXRoomInvitee: Equatable, Hashable {
/// Invite a user by username
case userId(String)
/// Invite a user by email
case email(String)
/// Invite a user using a third-party mechanism.
/// `method` is the method to use, eg. "email".
/// `address` is the address of the user.
case thirdPartyId(MX3PID)
}
public extension MXRestClient {
// MARK: - Initialization
/**
Create an instance based on homeserver url.
- parameters:
- homeServer: The homeserver address.
- handler: the block called to handle unrecognized certificate (`nil` if unrecognized certificates are ignored).
- returns: a `MXRestClient` instance.
*/
@nonobjc required convenience init(homeServer: URL, unrecognizedCertificateHandler handler: MXHTTPClientOnUnrecognizedCertificate?) {
self.init(__homeServer: homeServer.absoluteString, andOnUnrecognizedCertificateBlock: handler)
}
/**
Create an instance based on existing user credentials.
- parameters:
- credentials: A set of existing user credentials.
- handler: the block called to handle unrecognized certificate (`nil` if unrecognized certificates are ignored).
- returns: a `MXRestClient` instance.
*/
@nonobjc convenience init(credentials: MXCredentials, unrecognizedCertificateHandler handler: MXHTTPClientOnUnrecognizedCertificate? = nil, persistentTokenDataHandler: MXRestClientPersistTokenDataHandler? = nil, unauthenticatedHandler: MXRestClientUnauthenticatedHandler? = nil) {
self.init(__credentials: credentials, andOnUnrecognizedCertificateBlock: handler, andPersistentTokenDataHandler: persistentTokenDataHandler, andUnauthenticatedHandler: unauthenticatedHandler)
}
// MARK: - Registration Operations
/**
Check whether a username is already in use.
- parameters:
- username: The user name to test.
- completion: A block object called when the operation is completed.
- inUse: Whether the username is in use
- returns: a `MXHTTPOperation` instance.
*/
@available(*, deprecated, message: "Use isUsernameAvailable instead which calls the dedicated API and provides more information.")
@nonobjc @discardableResult func isUserNameInUse(_ username: String, completion: @escaping (_ inUse: Bool) -> Void) -> MXHTTPOperation {
return __isUserName(inUse: username, callback: completion)
}
/**
Checks whether a username is available.
- parameters:
- username: The user name to test.
- completion: A block object called when the operation is completed.
- response: Provides the server response as an `MXUsernameAvailability` instance.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func isUsernameAvailable(_ username: String, completion: @escaping (_ response: MXResponse<MXUsernameAvailability>) -> Void) -> MXHTTPOperation {
return __isUsernameAvailable(username, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the list of register flows supported by the home server.
- parameters:
- completion: A block object called when the operation is completed.
- response: Provides the server response as an `MXAuthenticationSession` instance.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getRegisterSession(completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation {
return __getRegisterSession(currySuccess(completion), failure: curryFailure(completion))
}
/**
Generic registration action request.
As described in [the specification](http://matrix.org/docs/spec/client_server/r0.2.0.html#client-authentication),
some registration flows require to complete several stages in order to complete user registration.
This can lead to make several requests to the home server with different kinds of parameters.
This generic method with open parameters and response exists to handle any kind of registration flow stage.
At the end of the registration process, the SDK user should be able to construct a MXCredentials object
from the response of the last registration action request.
- parameters:
- parameters: the parameters required for the current registration stage
- completion: A block object called when the operation completes.
- response: Provides the raw JSON response from the server.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func register(parameters: [String: Any], completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __register(withParameters: parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/*
TODO: This method accepts a nil username. Maybe this should be called "anonymous registration"? Would it make sense to have a separate API for that case?
We could also create an enum called "MXRegistrationType" with associated values, e.g. `.username(String)` and `.anonymous`
*/
/**
Register a user.
This method manages the full flow for simple login types and returns the credentials of the newly created matrix user.
- parameters:
- loginType: the login type. Only `MXLoginFlowType.password` and `MXLoginFlowType.dummy` (m.login.password and m.login.dummy) are supported.
- username: the user id (ex: "@bob:matrix.org") or the user id localpart (ex: "bob") of the user to register. Can be nil.
- password: the user's password.
- completion: A block object called when the operation completes.
- response: Provides credentials to use to create a `MXRestClient`.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func register(loginType: MXLoginFlowType = .password, username: String?, password: String, completion: @escaping (_ response: MXResponse<MXCredentials>) -> Void) -> MXHTTPOperation {
return __register(withLoginType: loginType.identifier, username: username, password: password, success: currySuccess(completion), failure: curryFailure(completion))
}
/// The register fallback page to make registration via a web browser or a web view.
var registerFallbackURL: URL {
let fallbackString = __registerFallback()!
return URL(string: fallbackString)!
}
// MARK: - Login Operation
/**
Get the list of login flows supported by the home server.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides the server response as an MXAuthenticationSession instance.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getLoginSession(completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation {
return __getLoginSession(currySuccess(completion), failure: curryFailure(completion))
}
/**
Generic login action request.
As described in [the specification](http://matrix.org/docs/spec/client_server/r0.2.0.html#client-authentication),
some login flows require to complete several stages in order to complete authentication.
This can lead to make several requests to the home server with different kinds of parameters.
This generic method with open parameters and response exists to handle any kind of authentication flow stage.
At the end of the registration process, the SDK user should be able to construct a MXCredentials object
from the response of the last authentication action request.
- parameters:
- parameters: the parameters required for the current login stage
- completion: A block object called when the operation completes.
- response: Provides the raw JSON response from the server.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func login(parameters: [String: Any], completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __login(parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Log a user in.
This method manages the full flow for simple login types and returns the credentials of the logged matrix user.
- parameters:
- type: the login type. Only `MXLoginFlowType.password` (m.login.password) is supported.
- username: the user id (ex: "@bob:matrix.org") or the user id localpart (ex: "bob") of the user to authenticate.
- password: the user's password.
- completion: A block object called when the operation succeeds.
- response: Provides credentials for this user on `success`
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func login(type loginType: MXLoginFlowType = .password, username: String, password: String, completion: @escaping (_ response: MXResponse<MXCredentials>) -> Void) -> MXHTTPOperation {
return __login(withLoginType: loginType.identifier, username: username, password: password, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the login fallback page to make login via a web browser or a web view.
Presently only server auth v1 is supported.
- returns: the fallback page URL.
*/
var loginFallbackURL: URL {
let fallbackString = __loginFallback()!
return URL(string: fallbackString)!
}
@nonobjc func generateLoginToken(withCompletion completion: @escaping (_ response: MXResponse<MXLoginToken>) -> Void) -> MXHTTPOperation {
return __generateLoginToken(success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Reset the account password.
- parameters:
- parameters: a set of parameters containing a threepid credentials and the new password.
- completion: A block object called when the operation completes.
- response: indicates whether the operation succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func resetPassword(parameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __resetPassword(withParameters: parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Replace the account password.
- parameters:
- old: the current password to update.
- new: the new password.
- logoutDevices flag to log out all devices
- completion: A block object called when the operation completes
- response: indicates whether the operation succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func changePassword(from old: String, to new: String, logoutDevices: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __changePassword(old, with: new, logoutDevices: logoutDevices, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Invalidate the access token, so that it can no longer be used for authorization.
- parameters:
- completion: A block object called when the operation completes.
- response: Indicates whether the operation succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func logout(completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __logout(currySuccess(completion), failure: curryFailure(completion))
}
/**
Deactivate the user's account, removing all ability for the user to login again.
This API endpoint uses the User-Interactive Authentication API.
An access token should be submitted to this endpoint if the client has an active session.
The homeserver may change the flows available depending on whether a valid access token is provided.
- parameters:
- authParameters The additional authentication information for the user-interactive authentication API.
- eraseAccount Indicating whether the account should be erased.
- completion: A block object called when the operation completes.
- response: indicates whether the request succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func deactivateAccount(withAuthParameters authParameters: [String: Any], eraseAccount: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __deactivateAccount(withAuthParameters: authParameters, eraseAccount: eraseAccount, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Account data
/**
Set some account_data for the client.
- parameters:
- data: the new data to set for this event type.
- type: The event type of the account_data to set. Custom types should be namespaced to avoid clashes.
- completion: A block object called when the operation completes
- response: indicates whether the request succeeded or not
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setAccountData(_ data: [String: Any], for type: MXAccountDataType, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setAccountData(data, forType: type.rawValue, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Push Notifications
/**
Update the pusher for this device on the Home Server.
- parameters:
- pushkey: The pushkey for this pusher. This should be the APNS token formatted as required for your push gateway (base64 is the recommended formatting).
- kind: The kind of pusher your push gateway requires. Generally `.http`. Specify `.none` to disable the pusher.
- appId: The app ID of this application as required by your push gateway.
- appDisplayName: A human readable display name for this app.
- deviceDisplayName: A human readable display name for this device.
- profileTag: The profile tag for this device. Identifies this device in push rules.
- lang: The user's preferred language for push, eg. 'en' or 'en-US'
- data: Dictionary of data as required by your push gateway (generally the notification URI and aps-environment for APNS).
- append: If `true`, the homeserver should add another pusher with the given pushkey and App ID in addition to any others with different user IDs.
- enabled: Whether the pusher should actively create push notifications
- completion: A block object called when the operation succeeds.
- response: indicates whether the request succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setPusher(pushKey: String, kind: MXPusherKind, appId: String, appDisplayName: String, deviceDisplayName: String, profileTag: String, lang: String, data: [String: Any], append: Bool, enabled: Bool = true, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setPusherWithPushkey(pushKey, kind: kind.objectValue, appId: appId, appDisplayName: appDisplayName, deviceDisplayName: deviceDisplayName, profileTag: profileTag, lang: lang, data: data, append: append, enabled: enabled, success: currySuccess(completion), failure: curryFailure(completion))
}
// TODO: setPusherWithPushKey - futher refinement
/*
This method is very long. Some of the parameters seem related,
specifically: appId, appDisplayName, deviceDisplayName, and profileTag.
Perhaps these parameters can be lifted out into a sparate struct?
Something like "MXPusherDescriptor"?
*/
/**
Gets all currently active pushers for the authenticated user.
- parameters:
- response: indicates whether the request succeeded or not.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func pushers(completion: @escaping (_ response: MXResponse<[MXPusher]>) -> Void) -> MXHTTPOperation {
return __pushers(currySuccess(completion), failure: curryFailure(completion))
}
/**
Get all push notifications rules.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides the push rules on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func pushRules(completion: @escaping (_ response: MXResponse<MXPushRulesResponse>) -> Void) -> MXHTTPOperation {
return __pushRules(currySuccess(completion), failure: curryFailure(completion))
}
/*
TODO: Consider refactoring. The following three methods all contain (ruleId:, scope:, kind:).
Option 1: Encapsulate those parameters as a tuple or struct called `MXPushRuleDescriptor`
This would be appropriate if these three parameters typically get passed around as a set,
or if the rule is uniquely identified by this combination of parameters. (eg. one `ruleId`
can have different settings for varying scopes and kinds).
Option 2: Refactor all of these to a single function that takes a "MXPushRuleAction"
as the fourth paramerer. This approach might look like this:
enum MXPushRuleAction {
case enable
case disable
case add(actions: [Any], pattern: String, conditions: [[String: Any]])
case remove
}
func pushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, action: MXPushRuleAction, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation ? {
switch action {
case .enable:
// ... Call the `enablePushRule` method
case .disable:
// ... Call the `enablePushRule` method
case let .add(actions, pattern, conditions):
// ... Call the `addPushRule` method
case let .remove:
// ... Call the `removePushRule` method
}
}
Option 3: Leave these APIs as-is.
*/
/**
Enable/Disable a push notification rule.
- parameters:
- ruleId: The identifier for the rule.
- scope: Either 'global' or 'device/<profile_tag>' to specify global rules or device rules for the given profile_tag.
- kind: The kind of rule, ie. 'override', 'underride', 'sender', 'room', 'content' (see MXPushRuleKind).
- enabled: YES to enable
- completion: A block object called when the operation completes
- response: Indiciates whether the operation was successful
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setPushRuleEnabled(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, enabled: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __enablePushRule(ruleId, scope: scope.identifier, kind: kind.identifier, enable: enabled, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a push notification rule.
- parameters:
- ruleId: The identifier for the rule.
- scope: Either `.global` or `.device(profileTag:)` to specify global rules or device rules for the given profile_tag.
- kind: The kind of rule, ie. `.override`, `.underride`, `.sender`, `.room`, `.content`.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func removePushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __removePushRule(ruleId, scope: scope.identifier, kind: kind.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Create a new push rule.
- parameters:
- ruleId: The identifier for the rule (it depends on rule kind: user id for sender rule, room id for room rule...).
- scope: Either `.global` or `.device(profileTag:)` to specify global rules or device rules for the given profile_tag.
- kind: The kind of rule, ie. `.override`, `.underride`, `.sender`, `.room`, `.content`.
- actions: The rule actions: notify, don't notify, set tweak...
- pattern: The pattern relevant for content rule.
- conditions: The conditions relevant for override and underride rule.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addPushRule(ruleId: String, scope: MXPushRuleScope, kind: MXPushRuleKind, actions: [Any], pattern: String, conditions: [[String: Any]], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __addPushRule(ruleId, scope: scope.identifier, kind: kind.identifier, actions: actions, pattern: pattern, conditions: conditions, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Room operations
/**
Send a generic non state event to a room.
- parameters:
- roomId: the id of the room.
- threadId: the id of the thread to send the message. nil by default.
- eventType: the type of the event.
- content: the content that will be sent to the server as a JSON object.
- txnId: the transaction id to use. If nil, one will be generated
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendEvent(toRoom roomId: String, threadId: String? = nil, eventType: MXEventType, content: [String: Any], txnId: String?, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendEvent(toRoom: roomId, threadId: threadId, eventType: eventType.identifier, content: content, txnId: txnId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Send a generic state event to a room.
- paramters:
- roomId: the id of the room.
- eventType: the type of the event.
- content: the content that will be sent to the server as a JSON object.
- stateKey: the optional state key.
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendStateEvent(toRoom roomId: String, eventType: MXEventType, content: [String: Any], stateKey: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendStateEvent(toRoom: roomId, eventType: eventType.identifier, content: content, stateKey: stateKey, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Send a message to a room
- parameters:
- roomId: the id of the room.
- threadId: the id of the thread to send the message. nil by default.
- messageType: the type of the message.
- content: the message content that will be sent to the server as a JSON object.
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
-returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendMessage(toRoom roomId: String, threadId: String? = nil, messageType: MXMessageType, content: [String: Any], completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendMessage(toRoom: roomId, threadId: threadId, msgType: messageType.identifier, content: content, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Send a text message to a room
- parameters:
- roomId: the id of the room.
- threadId: the id of the thread to send the message. nil by default.
- text: the text to send.
- completion: A block object called when the operation completes.
- response: Provides the event id of the event generated on the home server on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendTextMessage(toRoom roomId: String, threadId: String? = nil, text: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __sendTextMessage(toRoom: roomId, threadId: threadId, text: text, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the topic of a room.
- parameters:
- roomId: the id of the room.
- topic: the topic to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setTopic(ofRoom roomId: String, topic: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomTopic(roomId, topic: topic, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the topic of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the topic of the room on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func topic(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __topic(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the avatar of a room.
- parameters:
- roomId: the id of the room.
- avatar: the avatar url to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setAvatar(ofRoom roomId: String, avatarUrl: URL, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomAvatar(roomId, avatar: avatarUrl.absoluteString, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the avatar of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room avatar url on success.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func avatar(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<URL>) -> Void) -> MXHTTPOperation {
return __avatar(ofRoom: roomId, success: currySuccess(transform: {return URL(string: $0 ?? "")}, completion), failure: curryFailure(completion))
}
/**
Set the name of a room.
- parameters:
- roomId: the id of the room.
- name: the name to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setName(ofRoom roomId: String, name: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomName(roomId, name: name, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the name of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room name on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func name(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __name(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the history visibility of a room.
- parameters:
- roomId: the id of the room
- historyVisibility: the visibily to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setHistoryVisibility(ofRoom roomId: String, historyVisibility: MXRoomHistoryVisibility, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomHistoryVisibility(roomId, historyVisibility: historyVisibility.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the history visibility of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room history visibility on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func historyVisibility(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomHistoryVisibility>) -> Void) -> MXHTTPOperation {
return __historyVisibility(ofRoom: roomId, success: currySuccess(transform: MXRoomHistoryVisibility.init, completion), failure: curryFailure(completion))
}
/**
Set the join rule of a room.
- parameters:
- joinRule: the rule to set.
- roomId: the id of the room.
- allowedParentIds: Optional: list of allowedParentIds (required only for `restricted` join rule as per [MSC3083](https://github.com/matrix-org/matrix-doc/pull/3083) )
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setRoomJoinRule(_ joinRule: MXRoomJoinRule, forRoomWithId roomId: String, allowedParentIds: [String]?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomJoinRule(joinRule.identifier, forRoomWithId: roomId, allowedParentIds: allowedParentIds, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the enhanced join rule of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes. It provides the room enhanced join rule as per [MSC3083](https://github.com/matrix-org/matrix-doc/pull/3083.
- response: Provides the room join rule on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func joinRule(ofRoomWithId roomId: String, completion: @escaping (_ response: MXResponse<MXRoomJoinRuleResponse>) -> Void) -> MXHTTPOperation {
return __joinRuleOfRoom(withId: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the guest access of a room.
- parameters:
- roomId: the id of the room.
- guestAccess: the guest access to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setGuestAccess(forRoom roomId: String, guestAccess: MXRoomGuestAccess, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomGuestAccess(roomId, guestAccess: guestAccess.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the guest access of a room.
- parameters:
- roomId the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room guest access on success.
- return: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func guestAccess(forRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomGuestAccess>) -> Void) -> MXHTTPOperation {
return __guestAccess(ofRoom: roomId, success: currySuccess(transform: MXRoomGuestAccess.init, completion), failure: curryFailure(completion))
}
/**
Set the directory visibility of a room on the current homeserver.
- parameters:
- roomId: the id of the room.
- directoryVisibility: the directory visibility to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func setDirectoryVisibility(ofRoom roomId: String, directoryVisibility: MXRoomDirectoryVisibility, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomDirectoryVisibility(roomId, directoryVisibility: directoryVisibility.identifier, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the visibility of a room in the current HS's room directory.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the room directory visibility on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func directoryVisibility(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<MXRoomDirectoryVisibility>) -> Void) -> MXHTTPOperation {
return __directoryVisibility(ofRoom: roomId, success: currySuccess(transform: MXRoomDirectoryVisibility.init, completion), failure: curryFailure(completion))
}
/**
Create a new mapping from room alias to room ID.
- parameters:
- roomId: the id of the room.
- roomAlias: the alias to add.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addAlias(forRoom roomId: String, alias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __addRoomAlias(roomId, alias: alias, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a mapping of room alias to room ID.
- parameters:
- roomAlias: the alias to remove.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func removeRoomAlias(_ roomAlias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __removeRoomAlias(roomAlias, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the canonical alias of the room.
- parameters:
- roomId: the id of the room.
- canonicalAlias: the canonical alias to set.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setCanonicalAlias(forRoom roomId: String, canonicalAlias: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomCanonicalAlias(roomId, canonicalAlias: canonicalAlias, success: currySuccess(completion), failure: curryFailure(completion));
}
/**
Get the canonical alias.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the canonical alias on success
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func canonicalAlias(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __canonicalAlias(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Join a room, optionally where the user has been invited by a 3PID invitation.
- parameters:
- roomIdOrAlias: The id or an alias of the room to join.
- viaServers The server names to try and join through in addition to those that are automatically chosen.
- thirdPartySigned: The signed data obtained by the validation of the 3PID invitation, if 3PID validation is used. The validation is made by `self.signUrl()`.
- completion: A block object called when the operation completes.
- response: Provides the room id on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func joinRoom(_ roomIdOrAlias: String, viaServers: [String]? = nil, withThirdPartySigned dictionary: [String: Any]? = nil, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __joinRoom(roomIdOrAlias, viaServers: viaServers, withThirdPartySigned: dictionary, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Leave a room.
- parameters:
- roomId: the id of the room to leave.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func leaveRoom(_ roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __leaveRoom(roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Invite a user to a room.
A user can be invited one of three ways:
1. By their user ID
2. By their email address
3. By a third party
The `invitation` parameter specifies how this user should be reached.
- parameters:
- invitation: the way to reach the user.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func invite(_ invitation: MXRoomInvitee, toRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
switch invitation {
case .userId(let userId):
return __inviteUser(userId, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
case .email(let emailAddress):
return __inviteUser(byEmail: emailAddress, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
case .thirdPartyId(let descriptor):
return __invite(byThreePid: descriptor.medium.identifier, address: descriptor.address, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
}
/**
Kick a user from a room.
- parameters:
- userId: the user id.
- roomId: the id of the room.
- reason: the reason for being kicked
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func kickUser(_ userId: String, fromRoom roomId: String, reason: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __kickUser(userId, fromRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Ban a user in a room.
- parameters:
- userId: the user id.
- roomId: the id of the room.
- reason: the reason for being banned
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func banUser(_ userId: String, fromRoom roomId: String, reason: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __banUser(userId, inRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Unban a user in a room.
- parameters:
- userId: the user id.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func unbanUser(_ userId: String, fromRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __unbanUser(userId, inRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Create a room.
- parameters:
- parameters: The parameters for room creation.
- completion: A block object called when the operation completes.
- response: Provides a MXCreateRoomResponse object on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func createRoom(parameters: MXRoomCreationParameters, completion: @escaping (_ response: MXResponse<MXCreateRoomResponse>) -> Void) -> MXHTTPOperation {
return __createRoom(with: parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Create a room.
- parameters:
- parameters: The parameters. Refer to the matrix specification for details.
- completion: A block object called when the operation completes.
- response: Provides a MXCreateRoomResponse object on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func createRoom(parameters: [String: Any], completion: @escaping (_ response: MXResponse<MXCreateRoomResponse>) -> Void) -> MXHTTPOperation {
return __createRoom(parameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get a list of messages for this room.
- parameters:
- roomId: the id of the room.
- from: the token to start getting results from.
- direction: `MXTimelineDirectionForwards` or `MXTimelineDirectionBackwards`
- limit: (optional, use -1 to not defined this value) the maximum nuber of messages to return.
- filter: to filter returned events with.
- completion: A block object called when the operation completes.
- response: Provides a `MXPaginationResponse` object on success.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func messages(forRoom roomId: String, from: String, direction: MXTimelineDirection, limit: UInt?, filter: MXRoomEventFilter, completion: @escaping (_ response: MXResponse<MXPaginationResponse>) -> Void) -> MXHTTPOperation {
// The `limit` variable should be set to -1 if it's not provided.
let _limit: Int
if let limit = limit {
_limit = Int(limit)
} else {
_limit = -1;
}
return __messages(forRoom: roomId, from: from, direction: direction, limit: _limit, filter: filter, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get a list of members for this room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXEvent` objects that are the type `m.room.member` on success.
- returns: a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func members(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[MXEvent]>) -> Void) -> MXHTTPOperation {
return __members(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get a list of all the current state events for this room.
This is equivalent to the events returned under the 'state' key for this room in initialSyncOfRoom.
See [the matrix documentation on state events](http://matrix.org/docs/api/client-server/#!/-rooms/get_state_events)
for more detail.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides the raw home server JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func state(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __state(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Inform the home server that the user is typing (or not) in this room.
- parameters:
- roomId: the id of the room.
- typing: Use `true` if the user is currently typing.
- timeout: the length of time until the user should be treated as no longer typing. Can be set to `nil` if they are no longer typing.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendTypingNotification(inRoom roomId: String, typing: Bool, timeout: TimeInterval?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
// The `timeout` variable should be set to -1 if it's not provided.
let _timeout: Int
if let timeout = timeout {
// The `TimeInterval` type is a double value specified in seconds. Multiply by 1000 to get milliseconds.
_timeout = Int(timeout * 1000 /* milliseconds */)
} else {
_timeout = -1;
}
return __sendTypingNotification(inRoom: roomId, typing: typing, timeout: UInt(_timeout), success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Redact an event in a room.
- parameters:
- eventId: the id of the redacted event.
- roomId: the id of the room.
- reason: the redaction reason.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func redactEvent(_ eventId: String, inRoom roomId: String, reason: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __redactEvent(eventId, inRoom: roomId, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Report an event.
- parameters:
- eventId: the id of the event event.
- roomId: the id of the room.
- score: the metric to let the user rate the severity of the abuse. It ranges from -100 “most offensive” to 0 “inoffensive”.
- reason: the redaction reason.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func reportEvent(_ eventId: String, inRoom roomId: String, score: Int, reason: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __reportEvent(eventId, inRoom: roomId, score: score, reason: reason, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get all the current information for this room, including messages and state events.
See [the matrix documentation](http://matrix.org/docs/api/client-server/#!/-rooms/get_room_sync_data)
for more detail.
- parameters:
- roomId: the id of the room.
- limit: the maximum number of messages to return.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func intialSync(ofRoom roomId: String, limit: UInt, completion: @escaping (_ response: MXResponse<MXRoomInitialSync>) -> Void) -> MXHTTPOperation {
return __initialSync(ofRoom: roomId, withLimit: Int(limit), success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Retrieve an event from its event id.
- parameters:
- eventId: the id of the event to get context around.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
*/
@nonobjc @discardableResult func event(withEventId eventId: String, completion: @escaping (_ response: MXResponse<MXEvent>) -> Void) -> MXHTTPOperation {
return __event(withEventId: eventId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Retrieve an event from its room id and event id.
- parameters:
- eventId: the id of the event to get context around.
- roomId: the id of the room to get events from.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
*/
@nonobjc @discardableResult func event(withEventId eventId: String, inRoom roomId: String, completion: @escaping (_ response: MXResponse<MXEvent>) -> Void) -> MXHTTPOperation {
return __event(withEventId: eventId, inRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the context surrounding an event.
This API returns a number of events that happened just before and after the specified event.
- parameters:
- eventId: the id of the event to get context around.
- roomId: the id of the room to get events from.
- limit: the maximum number of messages to return.
- filter the filter to pass in the request. Can be nil.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func context(ofEvent eventId: String, inRoom roomId: String, limit: UInt, filter: MXRoomEventFilter? = nil, completion: @escaping (_ response: MXResponse<MXEventContext>) -> Void) -> MXHTTPOperation {
return __context(ofEvent: eventId, inRoom: roomId, limit: limit, filter:filter, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the summary of a room
- parameters:
- roomIdOrAlias: the id of the room or its alias
- via: servers, that should be tried to request a summary from, if it can't be generated locally. These can be from a matrix URI, matrix.to link or a `m.space.child` event for example.
- completion: A block object called when the operation completes.
- response: Provides the model created from the homeserver JSON response on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func roomSummary(with roomIdOrAlias: String, via: [String], completion: @escaping (_ response: MXResponse<MXPublicRoom>) -> Void) -> MXHTTPOperation {
return __roomSummary(with: roomIdOrAlias, via: via, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Upgrade a room to a new version
- parameters:
- roomId: the id of the room.
- roomVersion: the new room version
- completion: A block object called when the operation completes.
- response: Provides the ID of the replacement room on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func upgradeRoom(withId roomId: String, to roomVersion: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __upgradeRoom(withId: roomId, to: roomVersion, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Room tags operations
/**
List the tags of a room.
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXRoomTag` objects on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func tags(ofRoom roomId: String, completion: @escaping (_ response: MXResponse<[MXRoomTag]>) -> Void) -> MXHTTPOperation {
return __tags(ofRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Add a tag to a room.
Use this method to update the order of an existing tag.
- parameters:
- tag: the new tag to add to the room.
- order: the order. @see MXRoomTag.order.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXRoomTag` objects on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addTag(_ tag: String, withOrder order: String, toRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __addTag(tag, withOrder: order, toRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a tag from a room.
- parameters:
- tag: the tag to remove.
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides an array of `MXRoomTag` objects on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func removeTag(_ tag: String, fromRoom roomId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __removeTag(tag, fromRoom: roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Room account data operations
/**
Update the tagged events
- parameters:
- roomId: the id of the room.
- content: the new tagged events content.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func updateTaggedEvents(_ roomId: String, withContent content: MXTaggedEvents, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __updateTaggedEvents(roomId, withContent: content, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the tagged events of a room
- parameters:
- roomId: the id of the room.
- completion: A block object called when the operation completes.
- response: Provides a `MXTaggedEvents` object on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getTaggedEvents(_ roomId: String, completion: @escaping (_ response: MXResponse<MXTaggedEvents>) -> Void) -> MXHTTPOperation {
return __getTaggedEvents(roomId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set a dedicated room account data field
- parameters:
- roomId: the id of the room.
- eventTypeString: the type of the event. @see MXEventType.
- content: the event content.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setRoomAccountData(_ roomId: String, eventType eventTypeString: String, withParameters content: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setRoomAccountData(roomId, eventType: eventTypeString, withParameters: content, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the room account data field
- parameters:
- roomId: the id of the room.
- eventTypeString: the type of the event. @see MXEventType.
- completion: A block object called when the operation completes.
- response: Provides the raw JSON response from the server.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getRoomAccountData(_ roomId: String, eventType eventTypeString: String, completion: @escaping (_ response: MXResponse<[String: Any]>) -> Void) -> MXHTTPOperation {
return __getRoomAccountData(roomId, eventType: eventTypeString, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Profile operations
/**
Set the logged-in user display name.
- parameters:
- displayname: the new display name.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setDisplayName(_ displayName: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setDisplayName(displayName, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the display name of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the display name on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func displayName(forUser userId: String, completion: @escaping (_ response: MXResponse<String>) -> Void) -> MXHTTPOperation {
return __displayName(forUser: userId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Set the logged-in user avatar url.
- parameters:
- urlString: The new avatar url.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setAvatarUrl(_ url: URL, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setAvatarUrl(url.absoluteString, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get the avatar url of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the avatar url on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func avatarUrl(forUser userId: String, completion: @escaping (_ response: MXResponse<URL>) -> Void) -> MXHTTPOperation {
return __avatarUrl(forUser: userId, success: currySuccess(transform: { return URL(string: $0 ?? "") }, completion), failure: curryFailure(completion))
}
/**
Get the profile information of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the display name and avatar url if they are defined on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func profile(forUser userId: String, completion: @escaping (_ response: MXResponse<(String?, String?)>) -> Void) -> MXHTTPOperation {
return __profile(forUser: userId, success: { (displayName, avatarUrl) -> Void in
let profileInformation = (displayName, avatarUrl)
completion(MXResponse.success(profileInformation))
}, failure: curryFailure(completion))
}
/**
Link an authenticated 3rd party id to the Matrix user.
This API is deprecated, and you should instead use `addThirdPartyIdentifierOnly`
for homeservers that support it.
- parameters:
- sid: the id provided during the 3PID validation session (MXRestClient.requestEmailValidation).
- clientSecret: the same secret key used in the validation session.
- bind: whether the homeserver should also bind this third party identifier to the account's Matrix ID with the identity server.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addThirdPartyIdentifier(_ sid: String, clientSecret: String, bind: Bool, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __add3PID(sid, clientSecret: clientSecret, bind: bind, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Add a 3PID to your homeserver account.
This API does not use an identity server, as the homeserver is expected to
handle 3PID ownership validation.
You can check whether a homeserver supports this API via
`doesServerSupportSeparateAddAndBind`.
- parameters:
- sid: the session id provided during the 3PID validation session.
- clientSecret: the same secret key used in the validation session.
- authParameters: The additional authentication information for the user-interactive authentication API.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func addThirdPartyIdentifierOnly(withSessionId sid: String, clientSecret: String, authParameters: [String: Any]?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __add3PIDOnly(withSessionId: sid, clientSecret: clientSecret, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Remove a 3rd party id from the Matrix user information.
- parameters:
- address: the 3rd party id.
- medium: medium the type of the 3rd party id.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func remove3PID(address: String, medium: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __remove3PID(address, medium: medium, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
List all 3PIDs linked to the Matrix user account.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides the third-party identifiers on success
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func thirdPartyIdentifiers(_ completion: @escaping (_ response: MXResponse<[MXThirdPartyIdentifier]?>) -> Void) -> MXHTTPOperation {
return __threePIDs(currySuccess(completion), failure: curryFailure(completion))
}
/**
Bind a 3PID for discovery onto an identity server via the homeserver.
The identity server handles 3PID ownership validation and the homeserver records
the new binding to track where all 3PIDs for the account are bound.
You can check whether a homeserver supports this API via
`doesServerSupportSeparateAddAndBind`.
- parameters:
- sid: the session id provided during the 3PID validation session.
- clientSecret: the same secret key used in the validation session.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func bind3Pid(withSessionId sid: String, clientSecret: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __bind3Pid(withSessionId: sid, clientSecret: clientSecret, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Unbind a 3PID for discovery on an identity server via the homeserver.
- parameters:
- address: the 3rd party id.
- medium: medium the type of the 3rd party id.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func unbind3Pid(withAddress address: String, medium: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __unbind3Pid(withAddress: address, medium: medium, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Presence operations
// TODO: MXPresence could be refined to a Swift enum. presence+message could be combined in a struct, since they're closely related.
/**
Set the current user presence status.
- parameters:
- presence: the new presence status.
- statusMessage: the new message status.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setPresence(_ presence: MXPresence, statusMessage: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setPresence(presence, andStatusMessage: statusMessage, success: currySuccess(completion), failure: curryFailure(completion))
}
// TODO: MXPresenceResponse smells like a tuple (_ presence: MXPresence, timeActiveAgo: NSTimeInterval). Consider refining further.
/**
Get the presence status of a user.
- parameters:
- userId: the user id to look up.
- completion: A block object called when the operation completes.
- response: Provides the `MXPresenceResponse` on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func presence(forUser userId: String, completion: @escaping (_ response: MXResponse<MXPresenceResponse>) -> Void) -> MXHTTPOperation {
return __presence(userId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Sync
/*
TODO: This API could be further refined.
`token` is an optional string, with nil meaning "initial sync".
This could be expressed better as an enum: .initial or .fromToken(String)
`presence` appears to support only two possible values: nil or "offline".
This could be expressed better as an enum: .online, or .offline
(are there any other valid values for this field? why would it be typed as a string?)
*/
/**
Synchronise the client's state and receive new messages.
Synchronise the client's state with the latest state on the server.
Client's use this API when they first log in to get an initial snapshot
of the state on the server, and then continue to call this API to get
incremental deltas to the state, and to receive new messages.
- parameters:
- token: the token to stream from (nil in case of initial sync).
- serverTimeout: the maximum time in ms to wait for an event.
- clientTimeout: the maximum time in ms the SDK must wait for the server response.
- presence: the optional parameter which controls whether the client is automatically marked as online by polling this API. If this parameter is omitted then the client is automatically marked as online when it uses this API. Otherwise if the parameter is set to "offline" then the client is not marked as being online when it uses this API.
- filterId: the ID of a filter created using the filter API (optinal).
- completion: A block object called when the operation completes.
- response: Provides the `MXSyncResponse` on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sync(fromToken token: String?, serverTimeout: UInt, clientTimeout: UInt, setPresence presence: String?, filterId: String? = nil, completion: @escaping (_ response: MXResponse<MXSyncResponse>) -> Void) -> MXHTTPOperation {
return __sync(fromToken: token, serverTimeout: serverTimeout, clientTimeout: clientTimeout, setPresence: presence, filter: filterId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Directory operations
/**
Get the list of public rooms hosted by the home server.
Pagination parameters (`limit` and `since`) should be used in order to limit
homeserver resources usage.
- parameters:
- server: (optional) the remote server to query for the room list. If nil, get the user homeserver's public room list.
- limit: (optional, use -1 to not defined this value) the maximum number of entries to return.
- since: (optional) token to paginate from.
- filter: (optional) the string to search for.
- thirdPartyInstanceId: (optional) returns rooms published to specific lists on a third party instance (like an IRC bridge).
- includeAllNetworks: if YES, returns all rooms that have been published to any list. NO to return rooms on the main, default list.
- completion: A block object called when the operation is complete.
- response: Provides an publicRoomsResponse instance on `success`
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func publicRooms(onServer server: String?, limit: UInt?, since: String? = nil, filter: String? = nil, thirdPartyInstanceId: String? = nil, includeAllNetworks: Bool = false, completion: @escaping (_ response: MXResponse<MXPublicRoomsResponse>) -> Void) -> MXHTTPOperation {
// The `limit` variable should be set to -1 if it's not provided.
let _limit: Int
if let limit = limit {
_limit = Int(limit)
} else {
_limit = -1;
}
return __publicRooms(onServer: server, limit: _limit, since: since, filter: filter, thirdPartyInstanceId: thirdPartyInstanceId, includeAllNetworks: includeAllNetworks, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Resolve given room alias to a room identifier and a list of servers aware of this identifier
- parameters:
- roomAlias: the alias of the room to look for.
- completion: A block object called when the operation completes.
- response: Provides a resolution object containing the room ID and a list of servers
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func resolveRoomAlias(_ roomAlias: String, completion: @escaping (_ response: MXResponse<MXRoomAliasResolution>) -> Void) -> MXHTTPOperation {
return __resolveRoomAlias(roomAlias, success: currySuccess(completion), failure: curryFailure(completion))
}
// Mark: - Media Repository API
/**
Upload content to HomeServer
- parameters:
- data: the content to upload.
- filename: optional filename
- mimetype: the content type (image/jpeg, audio/aac...)
- timeout: the maximum time the SDK must wait for the server response.
- uploadProgress: A block object called multiple times as the upload progresses. It's also called once the upload is complete
- progress: Provides the progress of the upload until it completes. This will provide the URL of the resource on successful completion, or an error message on unsuccessful completion.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func uploadContent(_ data: Data, filename: String? = nil, mimeType: String, timeout: TimeInterval, uploadProgress: @escaping (_ progress: MXProgress<URL>) -> Void) -> MXHTTPOperation {
return __uploadContent(data, filename: filename, mimeType: mimeType, timeout: timeout, success: { (urlString) in
if let urlString = urlString, let url = URL(string: urlString) {
uploadProgress(.success(url))
} else {
uploadProgress(.failure(_MXUnknownError()))
}
}, failure: { (error) in
uploadProgress(.failure(error ?? _MXUnknownError()))
}, uploadProgress: { (progress) in
uploadProgress(.progress(progress!))
})
}
// MARK: - VoIP API
/**
Get the TURN server configuration advised by the homeserver.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides a `MXTurnServerResponse` object (or nil if the HS has TURN config) on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func turnServer(_ completion: @escaping (_ response: MXResponse<MXTurnServerResponse?>) -> Void) -> MXHTTPOperation {
return __turnServer(currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - read receipt
/**
Send a read receipt.
- parameters:
- roomId: the id of the room.
- eventId: the id of the event.
- threadId: the id of the thread (`nil` for unthreaded RR)
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendReadReceipt(toRoom roomId: String, forEvent eventId: String, threadId: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __sendReadReceipt(roomId, eventId: eventId, threadId: threadId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Search
/**
Search a text in room messages.
- parameters:
- textPattern: the text to search for in message body.
- roomEventFilter: a nullable dictionary which defines the room event filtering during the search request.
- beforeLimit: the number of events to get before the matching results.
- afterLimit: the number of events to get after the matching results.
- nextBatch: the token to pass for doing pagination from a previous response.
- completion: A block object called when the operation completes.
- response: Provides the search results on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func searchMessages(withPattern textPattern: String, roomEventFilter: MXRoomEventFilter? = nil, beforeLimit: UInt = 0, afterLimit: UInt = 0, nextBatch: String, completion: @escaping (_ response: MXResponse<MXSearchRoomEventResults>) -> Void) -> MXHTTPOperation {
return __searchMessages(withText: textPattern, roomEventFilter: roomEventFilter, beforeLimit: beforeLimit, afterLimit: afterLimit, nextBatch: nextBatch, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Make a search.
- parameters:
- parameters: the search parameters as defined by the Matrix search spec (http://matrix.org/docs/api/client-server/#!/Search/post_search ).
- nextBatch: the token to pass for doing pagination from a previous response.
- completion: A block object called when the operation completes.
- response: Provides the search results on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func search(withParameters parameters: [String: Any], nextBatch: String, completion: @escaping (_ response: MXResponse<MXSearchRoomEventResults>) -> Void) -> MXHTTPOperation {
return __search(parameters, nextBatch: nextBatch, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Crypto
/**
Upload device and/or one-time keys.
- parameters:
- deviceKeys: the device keys to send.
- oneTimeKeys: the one-time keys to send.
- fallbackKeys: the fallback keys to send
- completion: A block object called when the operation completes.
- response: Provides information about the keys on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func uploadKeys(_ deviceKeys: [String: Any]?, oneTimeKeys: [String: Any]?, fallbackKeys: [String: Any]?, forDevice deviceId: String? = nil, completion: @escaping (_ response: MXResponse<MXKeysUploadResponse>) -> Void) -> MXHTTPOperation {
return __uploadKeys(deviceKeys, oneTimeKeys: oneTimeKeys, fallbackKeys: fallbackKeys, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Download device keys.
- parameters:
- userIds: list of users to get keys for.
- token: sync token to pass in the query request, to help the HS give the most recent results. It can be nil.
- completion: A block object called when the operation completes.
- response: Provides information about the keys on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func downloadKeys(forUsers userIds: [String], token: String? = nil, completion: @escaping (_ response: MXResponse<MXKeysQueryResponse>) -> Void) -> MXHTTPOperation {
return __downloadKeys(forUsers: userIds, token: token, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Claim one-time keys.
- parameters:
- usersDevices: a list of users, devices and key types to retrieve keys for.
- completion: A block object called when the operation completes.
- response: Provides information about the keys on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func claimOneTimeKeys(for usersDevices: MXUsersDevicesMap<NSString>, completion: @escaping (_ response: MXResponse<MXKeysClaimResponse>) -> Void) -> MXHTTPOperation {
return __claimOneTimeKeys(forUsersDevices: usersDevices, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Direct-to-device messaging
/**
Send an event to a specific list of devices
- paramaeters:
- eventType: the type of event to send
- contentMap: content to send. Map from user_id to device_id to content dictionary.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func sendDirectToDevice(eventType: String, contentMap: MXUsersDevicesMap<NSDictionary>, txnId: String?, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __send(toDevice: eventType, contentMap: contentMap, txnId: txnId, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Device Management
/**
Get information about all devices for the current user.
- parameters:
- completion: A block object called when the operation completes.
- response: Provides a list of devices on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func devices(completion: @escaping (_ response: MXResponse<[MXDevice]>) -> Void) -> MXHTTPOperation {
return __devices(currySuccess(completion), failure: curryFailure(completion))
}
/**
Get information on a single device, by device id.
- parameters:
- deviceId: The device identifier.
- completion: A block object called when the operation completes.
- response: Provides the requested device on success.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func device(withId deviceId: String, completion: @escaping (_ response: MXResponse<MXDevice>) -> Void) -> MXHTTPOperation {
return __device(byDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Update the display name of a given device.
- parameters:
- deviceName: The new device name. If not given, the display name is unchanged.
- deviceId: The device identifier.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func setDeviceName(_ deviceName: String, forDevice deviceId: String, completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __setDeviceName(deviceName, forDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Get an authentication session to delete a device.
- parameters:
- deviceId: The device identifier.
- completion: A block object called when the operation completes.
- response: Provides the server response.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func getSession(toDeleteDevice deviceId: String, completion: @escaping (_ response: MXResponse<MXAuthenticationSession>) -> Void) -> MXHTTPOperation {
return __getSessionToDeleteDevice(byDeviceId: deviceId, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Delete the given device, and invalidates any access token associated with it.
This API endpoint uses the User-Interactive Authentication API.
- parameters:
- deviceId: The device identifier.
- authParameters: The additional authentication information for the user-interactive authentication API.
- completion: A block object called when the operation completes.
- response: Indicates whether the operation was successful.
- returns: a `MXHTTPOperation` instance.
*/
@nonobjc @discardableResult func deleteDevice(_ deviceId: String, authParameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __deleteDevice(byDeviceId: deviceId, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion))
}
/**
Deletes the given devices, and invalidates any access token associated with them.
@discussion This API endpoint uses the User-Interactive Authentication API.
@param deviceIds The identifiers for devices.
@param authParameters The additional authentication information for the user-interactive authentication API.
@param success A block object called when the operation succeeds.
@param failure A block object called when the operation fails.
@return a MXHTTPOperation instance.
*/
@nonobjc @discardableResult func deleteDevices(_ deviceIds: [String], authParameters: [String: Any], completion: @escaping (_ response: MXResponse<Void>) -> Void) -> MXHTTPOperation {
return __deleteDevices(byDeviceIds: deviceIds, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Spaces
/// Get the space children of a given space.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - maxDepth: Optional. The maximum depth in the tree (from the root room) to return. `-1` for no limit
/// - paginationToken: Optional. Pagination token given to retrieve the next set of rooms.
/// - parameters: Space children request parameters.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@nonobjc @discardableResult func getSpaceChildrenForSpace(withId spaceId: String, suggestedOnly: Bool, limit: Int?, maxDepth: Int?, paginationToken: String?, completion: @escaping (_ response: MXResponse<MXSpaceChildrenResponse>) -> Void) -> MXHTTPOperation {
return __getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit ?? -1, maxDepth: maxDepth ?? -1, paginationToken: paginationToken, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Home server capabilities
/// Get the capabilities of the homeserver
/// - Parameters:
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@nonobjc @discardableResult func homeServerCapabilities(completion: @escaping (_ response: MXResponse<MXHomeserverCapabilities>) -> Void) -> MXHTTPOperation {
return __homeServerCapabilities(success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Aggregations
/// Get relations for a given event.
/// - Parameters:
/// - eventId: the id of the event
/// - roomId: the id of the room
/// - relationType: Optional. The type of relation
/// - eventType: Optional. Event type to filter by
/// - from: Optional. The token to start getting results from
/// - direction: direction from the token
/// - limit: Optional. The maximum number of messages to return
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@nonobjc @discardableResult func relations(forEvent eventId: String,
inRoom roomId: String,
relationType: String?,
eventType: String?,
from: String?,
direction: MXTimelineDirection,
limit: UInt?,
completion: @escaping (_ response: MXResponse<MXAggregationPaginatedResponse>) -> Void) -> MXHTTPOperation {
let _limit: Int
if let limit = limit {
_limit = Int(limit)
} else {
_limit = -1
}
return __relations(forEvent: eventId, inRoom: roomId, relationType: relationType, eventType: eventType, from: from, direction: direction, limit: _limit, success: currySuccess(completion), failure: curryFailure(completion))
}
// MARK: - Versions
/// Get the supported versions of the homeserver
/// - Parameters:
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@nonobjc @discardableResult func supportedMatrixVersions(completion: @escaping (_ response: MXResponse<MXMatrixVersions>) -> Void) -> MXHTTPOperation {
return __supportedMatrixVersions(currySuccess(completion), failure: curryFailure(completion))
}
}
|
bb341ea35c81c93a8a2780bdb9e0e285
| 45.430424 | 350 | 0.674208 | false | false | false | false |
AboutObjectsTraining/swift-comp-reston-2017-02
|
refs/heads/master
|
labs/SwiftProgramming/SwiftBasics.playground/Contents.swift
|
mit
|
1
|
// Copyright (C) 2015 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
print("Have a nice day.")
let message = "Have a nice day"
print(message)
let temperature = 72
print("It's currently \(temperature) degrees")
var width: Int // defines variable 'width' of type Int
// width++ // Illegal because width uninitialized
var x, y, z: Int
var i = 0, j = 0
let pi = 3.14159
// pi += 2.0 // illegal because pi is a constant
|
2dae2d3fbc9f7d4a95bc1105080b71a9
| 23.3 | 62 | 0.68107 | false | false | false | false |
exchangegroup/paged-scroll-view-with-images
|
refs/heads/master
|
paged-scroll-view-with-images/TegPagedImagesCellView.swift
|
mit
|
2
|
//
// PagesImagesCell.swift
// paged-scroll-view-with-images
//
import UIKit
class TegPagedImagesCellView: UIView {
var url: String?
weak var delegate: TegPagedImagesCellViewDelegate?
private let imageView = UIImageView()
private var downloadManager: TegSingleImageDownloadManager?
private let settings: TegPagedImagesSettings
init(frame: CGRect, settings: TegPagedImagesSettings) {
self.settings = settings
super.init(frame: frame)
TegPagedImagesCellView.setupImageView(imageView, size: frame.size, contentMode: settings.contentMode)
addSubview(imageView)
clipsToBounds = true
setupTap()
}
private func setupTap() {
let tapGesture = UITapGestureRecognizer(target: self, action: "respondToTap:")
addGestureRecognizer(tapGesture)
}
func respondToTap(gesture: UITapGestureRecognizer) {
if downloadManager != nil { return } // downloading
if let image = imageView.image {
delegate?.tegPagedImagesCellViewDelegate_onImageTapped(image, gesture: gesture)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showImage(image: UIImage) {
imageView.alpha = 1
imageView.image = image
}
private class func setupImageView(imageView: UIImageView, size: CGSize,
contentMode: UIViewContentMode) {
imageView.frame = CGRect(origin: CGPoint(), size: size)
imageView.contentMode = contentMode
}
// Called each time the cell is visible on screen when scrolling.
// Note: called frequently on each scroll event.
func cellIsVisible() {
downloadImage()
}
// Called when cell is not visible on screen. Opposite of cellIsVisible method
func cellIsInvisible() {
cancelImageDownload()
}
func cancelImageDownload() {
downloadManager = nil
}
private func downloadImage() {
if downloadManager != nil { return } // already downloading
if let url = url {
downloadManager = settings.singleImageDownloadImageFactory.create()
downloadManager?.download(fromUrl: url) { [weak self] image in
self?.imagedDownloadComplete(image)
}
}
}
private func imagedDownloadComplete(image: UIImage) {
url = nil
downloadManager = nil
fadeInImage(image)
}
func fadeInImage(image: UIImage, showOnlyIfNoImageShown: Bool = false) {
let tempImageView = UIImageView(image: image)
addSubview(tempImageView)
TegPagedImagesCellView.setupImageView(tempImageView, size: frame.size,
contentMode: settings.contentMode)
tempImageView.alpha = 0
UIView.animateWithDuration(settings.fadeInAnimationDuration, animations: { [weak self] in
tempImageView.alpha = 1
self?.imageView.alpha = 0
},
completion: { [weak self] finished in
if !showOnlyIfNoImageShown || self?.imageView.image == nil {
self?.showImage(image)
}
tempImageView.removeFromSuperview()
}
)
}
}
|
fb2d1a841460fe5801b2ac59b6bb980a
| 26.423423 | 105 | 0.687911 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.