repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lucaslouca/parallax-table-view-header | ParallaxTableViewHeader/ParallaxTableViewHeader/ParallaxTableHeaderView.swift | 1 | 1731 | //
// ViewParallaxTableHeader.swift
// ParallaxTableViewHeader
//
// Created by Lucas Louca on 11/06/15.
// Copyright (c) 2015 Lucas Louca. All rights reserved.
//
import UIKit
class ParallaxTableHeaderView: UIView {
let parallaxDeltaFactor: CGFloat = 0.5
var defaultHeaderFrame: CGRect!
var scrollView: UIScrollView!
var subView: UIView!
convenience init(size: CGSize, subView:UIView) {
self.init(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
self.scrollView = UIScrollView(frame: self.bounds)
self.subView = subView
self.subView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin, .flexibleHeight, .flexibleWidth]
self.scrollView.addSubview(self.subView)
self.addSubview(self.scrollView)
}
/**
Layout the content of the header view to give the parallax feeling.
- parameter contentOffset: scroll views content offset
*/
func layoutForContentOffset(_ contentOffset: CGPoint) {
var frame = self.scrollView.frame
defaultHeaderFrame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
if (contentOffset.y > 0) {
frame.origin.y = contentOffset.y * parallaxDeltaFactor
self.scrollView.frame = frame
self.clipsToBounds = true
} else {
var delta: CGFloat = 0.0
var rect: CGRect = defaultHeaderFrame
delta = fabs(contentOffset.y)
rect.origin.y -= delta
rect.size.height += delta
self.scrollView.frame = rect
self.clipsToBounds = false
}
}
}
| mit | 51b9d15c8426bcb263accac475623488 | 33.62 | 159 | 0.644714 | 4.496104 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Pedestrians.xcplaygroundpage/Contents.swift | 1 | 884 | //: ## Pedestrians
//: A British crossing signal implemented with AudioKit, an example from
//: Andy Farnell's excellent book "Designing Sound"
import AudioKitPlaygrounds
import AudioKit
let generator = AKOperationGenerator { _ in
// Generate a sine wave at the right frequency
let crossingSignalTone = AKOperation.sineWave(frequency: 2_500)
// Periodically trigger an envelope around that signal
let crossingSignalTrigger = AKOperation.periodicTrigger(period: 0.2)
let crossingSignal = crossingSignalTone.triggeredWithEnvelope(
trigger: crossingSignalTrigger,
attack: 0.01,
hold: 0.1,
release: 0.01)
// scale the volume
return crossingSignal * 0.2
}
AudioKit.output = generator
AudioKit.start()
//: Activate the signal
generator.start()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
| mit | ed2c9c6dff9574f2e605bef42dd59da8 | 28.466667 | 72 | 0.743213 | 4.35468 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Lint/QuickDiscouragedCallRule.swift | 1 | 4448 | import SourceKittenFramework
struct QuickDiscouragedCallRule: OptInRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "quick_discouraged_call",
name: "Quick Discouraged Call",
description: "Discouraged call inside 'describe' and/or 'context' block.",
kind: .lint,
nonTriggeringExamples: QuickDiscouragedCallRuleExamples.nonTriggeringExamples,
triggeringExamples: QuickDiscouragedCallRuleExamples.triggeringExamples
)
func validate(file: SwiftLintFile) -> [StyleViolation] {
let dict = file.structureDictionary
let testClasses = dict.substructure.filter {
return $0.inheritedTypes.isNotEmpty &&
$0.declarationKind == .class
}
let specDeclarations = testClasses.flatMap { classDict in
return classDict.substructure.filter {
return $0.name == "spec()" && $0.enclosedVarParameters.isEmpty &&
$0.declarationKind == .functionMethodInstance &&
$0.enclosedSwiftAttributes.contains(.override)
}
}
return specDeclarations.flatMap {
validate(file: file, dictionary: $0)
}
}
private func validate(file: SwiftLintFile, dictionary: SourceKittenDictionary) -> [StyleViolation] {
return dictionary.traverseDepthFirst { subDict in
guard let kind = subDict.expressionKind else { return nil }
return validate(file: file, kind: kind, dictionary: subDict)
}
}
private func validate(file: SwiftLintFile,
kind: SwiftExpressionKind,
dictionary: SourceKittenDictionary) -> [StyleViolation] {
// is it a call to a restricted method?
guard
kind == .call,
let name = dictionary.name,
let kindName = QuickCallKind(rawValue: name),
QuickCallKind.restrictiveKinds.contains(kindName)
else { return [] }
return violationOffsets(in: dictionary.enclosedArguments).map {
StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0),
reason: "Discouraged call inside a '\(name)' block.")
}
}
private func violationOffsets(in substructure: [SourceKittenDictionary]) -> [ByteCount] {
return substructure.flatMap { dictionary -> [ByteCount] in
let substructure = dictionary.substructure.flatMap { dict -> [SourceKittenDictionary] in
if dict.expressionKind == .closure {
return dict.substructure
} else {
return [dict]
}
}
return substructure.flatMap(toViolationOffsets)
}
}
private func toViolationOffsets(dictionary: SourceKittenDictionary) -> [ByteCount] {
guard
dictionary.kind != nil,
let offset = dictionary.offset
else { return [] }
if dictionary.expressionKind == .call,
let name = dictionary.name, QuickCallKind(rawValue: name) == nil {
return [offset]
}
guard dictionary.expressionKind != .call else { return [] }
return dictionary.substructure.compactMap(toViolationOffset)
}
private func toViolationOffset(dictionary: SourceKittenDictionary) -> ByteCount? {
guard
let name = dictionary.name,
let offset = dictionary.offset,
dictionary.expressionKind == .call,
QuickCallKind(rawValue: name) == nil
else { return nil }
return offset
}
}
private enum QuickCallKind: String {
case describe
case context
case sharedExamples
case itBehavesLike
case beforeEach
case beforeSuite
case afterEach
case afterSuite
case it // swiftlint:disable:this identifier_name
case pending
case xdescribe
case xcontext
case xit
case xitBehavesLike
case fdescribe
case fcontext
case fit
case fitBehavesLike
static let restrictiveKinds: Set<QuickCallKind> = [
.describe, .fdescribe, .xdescribe, .context, .fcontext, .xcontext, .sharedExamples
]
}
| mit | df0ab97de6cf2a9e35c254b49a2a2c57 | 33.75 | 104 | 0.616457 | 5.276394 | false | false | false | false |
shorlander/firefox-ios | Client/Frontend/Browser/TabScrollController.swift | 7 | 11834 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
private let ToolbarBaseAnimationDuration: CGFloat = 0.2
class TabScrollingController: NSObject {
enum ScrollDirection {
case up
case down
}
enum ToolbarState {
case collapsed
case visible
case animating
}
weak var tab: Tab? {
willSet {
self.scrollView?.delegate = nil
self.scrollView?.removeGestureRecognizer(panGesture)
}
didSet {
self.scrollView?.addGestureRecognizer(panGesture)
scrollView?.delegate = self
}
}
weak var header: UIView?
weak var footer: UIView?
weak var urlBar: URLBarView?
weak var snackBars: UIView?
weak var webViewContainerToolbar: UIView?
var footerBottomConstraint: Constraint?
var headerTopConstraint: Constraint?
var toolbarsShowing: Bool { return headerTopOffset == 0 }
fileprivate var suppressToolbarHiding: Bool = false
fileprivate var isZoomedOut: Bool = false
fileprivate var lastZoomedScale: CGFloat = 0
fileprivate var isUserZoom: Bool = false
fileprivate var headerTopOffset: CGFloat = 0 {
didSet {
headerTopConstraint?.update(offset: headerTopOffset)
header?.superview?.setNeedsLayout()
}
}
fileprivate var footerBottomOffset: CGFloat = 0 {
didSet {
footerBottomConstraint?.update(offset: footerBottomOffset)
footer?.superview?.setNeedsLayout()
}
}
fileprivate lazy var panGesture: UIPanGestureRecognizer = {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(TabScrollingController.handlePan(_:)))
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
return panGesture
}()
fileprivate var scrollView: UIScrollView? { return tab?.webView?.scrollView }
fileprivate var contentOffset: CGPoint { return scrollView?.contentOffset ?? CGPoint.zero }
fileprivate var contentSize: CGSize { return scrollView?.contentSize ?? CGSize.zero }
fileprivate var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 }
fileprivate var topScrollHeight: CGFloat { return header?.frame.height ?? 0 }
fileprivate var bottomScrollHeight: CGFloat { return urlBar?.frame.height ?? 0 }
fileprivate var snackBarsFrame: CGRect { return snackBars?.frame ?? CGRect.zero }
fileprivate var lastContentOffset: CGFloat = 0
fileprivate var scrollDirection: ScrollDirection = .down
fileprivate var toolbarState: ToolbarState = .visible
override init() {
super.init()
}
func showToolbars(animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) {
if toolbarState == .visible {
completion?(true)
return
}
toolbarState = .visible
let durationRatio = abs(headerTopOffset / topScrollHeight)
let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated,
duration: actualDuration,
headerOffset: 0,
footerOffset: 0,
alpha: 1,
completion: completion)
}
func hideToolbars(animated: Bool, completion: ((_ finished: Bool) -> Void)? = nil) {
if toolbarState == .collapsed {
completion?(true)
return
}
toolbarState = .collapsed
let durationRatio = abs((topScrollHeight + headerTopOffset) / topScrollHeight)
let actualDuration = TimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated,
duration: actualDuration,
headerOffset: -topScrollHeight,
footerOffset: bottomScrollHeight,
alpha: 0,
completion: completion)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "contentSize" {
if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing {
showToolbars(animated: true, completion: nil)
}
}
}
func updateMinimumZoom() {
guard let scrollView = scrollView else {
return
}
self.isZoomedOut = roundNum(scrollView.zoomScale) == roundNum(scrollView.minimumZoomScale)
self.lastZoomedScale = self.isZoomedOut ? 0 : scrollView.zoomScale
}
func setMinimumZoom() {
guard let scrollView = scrollView else {
return
}
if self.isZoomedOut && roundNum(scrollView.zoomScale) != roundNum(scrollView.minimumZoomScale) {
scrollView.zoomScale = scrollView.minimumZoomScale
}
}
func resetZoomState() {
self.isZoomedOut = false
self.lastZoomedScale = 0
}
fileprivate func roundNum(_ num: CGFloat) -> CGFloat {
return round(100 * num) / 100
}
}
private extension TabScrollingController {
func tabIsLoading() -> Bool {
return tab?.loading ?? true
}
@objc func handlePan(_ gesture: UIPanGestureRecognizer) {
if tabIsLoading() {
return
}
if let containerView = scrollView?.superview {
let translation = gesture.translation(in: containerView)
let delta = lastContentOffset - translation.y
if delta > 0 {
scrollDirection = .down
} else if delta < 0 {
scrollDirection = .up
}
lastContentOffset = translation.y
if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() {
if (toolbarState != .collapsed || contentOffset.y <= 0) && contentOffset.y + scrollViewHeight < contentSize.height {
scrollWithDelta(delta)
}
if headerTopOffset == -topScrollHeight {
toolbarState = .collapsed
} else if headerTopOffset == 0 {
toolbarState = .visible
} else {
toolbarState = .animating
}
}
if gesture.state == .ended || gesture.state == .cancelled {
lastContentOffset = 0
}
showOrHideWebViewContainerToolbar()
}
}
func checkRubberbandingForDelta(_ delta: CGFloat) -> Bool {
return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height &&
scrollViewHeight < contentSize.height) ||
contentOffset.y < delta)
}
func scrollWithDelta(_ delta: CGFloat) {
if scrollViewHeight >= contentSize.height {
return
}
var updatedOffset = headerTopOffset - delta
headerTopOffset = clamp(updatedOffset, min: -topScrollHeight, max: 0)
if isHeaderDisplayedForGivenOffset(updatedOffset) {
scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta)
}
updatedOffset = footerBottomOffset + delta
footerBottomOffset = clamp(updatedOffset, min: 0, max: bottomScrollHeight)
let alpha = 1 - abs(headerTopOffset / topScrollHeight)
urlBar?.updateAlphaForSubviews(alpha)
}
func isHeaderDisplayedForGivenOffset(_ offset: CGFloat) -> Bool {
return offset > -topScrollHeight && offset < 0
}
func clamp(_ y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
if y >= max {
return max
} else if y <= min {
return min
}
return y
}
func animateToolbarsWithOffsets(_ animated: Bool, duration: TimeInterval, headerOffset: CGFloat, footerOffset: CGFloat, alpha: CGFloat, completion: ((_ finished: Bool) -> Void)?) {
let animation: () -> Void = {
self.headerTopOffset = headerOffset
self.footerBottomOffset = footerOffset
self.urlBar?.updateAlphaForSubviews(alpha)
self.header?.superview?.layoutIfNeeded()
}
if animated {
UIView.animate(withDuration: duration, delay: 0, options: .allowUserInteraction, animations: animation, completion: completion)
} else {
animation()
completion?(true)
}
}
func checkScrollHeightIsLargeEnoughForScrolling() -> Bool {
return (UIScreen.main.bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height ?? 0
}
func showOrHideWebViewContainerToolbar() {
if contentOffset.y >= webViewContainerToolbar?.frame.height ?? 0 {
webViewContainerToolbar?.isHidden = true
} else {
webViewContainerToolbar?.isHidden = false
}
}
}
extension TabScrollingController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension TabScrollingController: UIScrollViewDelegate {
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if targetContentOffset.pointee.y + scrollView.frame.size.height >= scrollView.contentSize.height {
suppressToolbarHiding = true
showToolbars(animated: true)
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if tabIsLoading() {
return
}
if (decelerate || (toolbarState == .animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() {
if scrollDirection == .up {
showToolbars(animated: true)
} else if scrollDirection == .down && !suppressToolbarHiding {
hideToolbars(animated: true)
}
}
suppressToolbarHiding = false
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
// Only mess with the zoom level if the user did not initate the zoom via a zoom gesture
if self.isUserZoom {
return
}
//scrollViewDidZoom will be called multiple times when a rotation happens.
// In that case ALWAYS reset to the minimum zoom level if the previous state was zoomed out (isZoomedOut=true)
if isZoomedOut {
scrollView.zoomScale = scrollView.minimumZoomScale
} else if roundNum(scrollView.zoomScale) > roundNum(self.lastZoomedScale) && self.lastZoomedScale != 0 {
//When we have manually zoomed in we want to preserve that scale.
//But sometimes when we rotate a larger zoomScale is appled. In that case apply the lastZoomedScale
scrollView.zoomScale = self.lastZoomedScale
}
}
func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
self.isUserZoom = true
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
self.isUserZoom = false
showOrHideWebViewContainerToolbar()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
showOrHideWebViewContainerToolbar()
}
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
showToolbars(animated: true)
webViewContainerToolbar?.isHidden = false
return true
}
}
| mpl-2.0 | 154af32414969d1a23f5d1e5b1dc0703 | 34.752266 | 184 | 0.63419 | 5.478704 | false | false | false | false |
LYM-mg/MGDYZB | MGDYZB简单封装版/MGDYZB/Class/Home/View/CollectionNormalCell.swift | 1 | 1903 | //
// CollectionNormalCell.swift
// MGDYZB
//
// Created by ming on 16/10/26.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
//
import UIKit
import Kingfisher
class CollectionNormalCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nickNameBtn: UIButton!
@IBOutlet weak var roomNameLabel: UILabel!
// MARK:- 定义模型
var anchor : AnchorModel? {
didSet {
// 0.校验模型是否有值
guard let anchor = anchor else { return }
// 1.取出在线人数显示的文字
var onlineStr : String = ""
if let online = anchor.online {
if online >= 10000.0 {
onlineStr = "\(String(describing: online/10000))万人在线"
} else {
onlineStr = "\(String(describing: online))人在线"
}
}else {
onlineStr = "无人在线"
}
onlineBtn.setTitle(onlineStr, for: UIControl.State())
onlineBtn.sizeToFit()
// 2.昵称的显示
nickNameBtn.setTitle(anchor.nickname, for: UIControl.State())
// 3.设置房间名称
roomNameLabel.text = anchor.room_name
// 4.设置封面图片
guard let iconURL = URL(string: anchor.vertical_src) else { return }
iconImageView.kf.setImage(with: iconURL, placeholder: #imageLiteral(resourceName: "placehoderImage"))
}
}
override func awakeFromNib() {
super.awakeFromNib()
iconImageView.layer.cornerRadius = 6
iconImageView.clipsToBounds = true
}
}
| mit | c71738ec39ecbca44c20220f71db2e42 | 29.372881 | 113 | 0.5625 | 4.536709 | false | false | false | false |
JoeLago/MHGDB-iOS | MHGDB/Common/TableAbstraction/HeaderView.swift | 1 | 1481 | //
// MIT License
// Copyright (c) Gathering Hall Studios
//
import UIKit
class HeaderView: UIView {
var section: Int?
var text: String? {
didSet {
label.text = text
}
}
var isCollapsed = false {
didSet {
updateIndicator()
}
}
private var label = UILabel()
private var indicator = UILabel()
private var seperator = UIView()
init() {
super.init(frame: CGRect.zero)
setupViews()
updateIndicator()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews() {
backgroundColor = Color.Background.header
label.font = Font.header
indicator.textAlignment = .right
indicator.font = Font.header
seperator.backgroundColor = Color.Background.seperator
addSubview(label)
addSubview(indicator)
addSubview(seperator)
label.matchParent(top: 8, left: 15, bottom: 5, right: 15, priority: UILayoutPriority.defaultHigh)
indicator.matchParent(top: 8, left: nil, bottom: 5, right: 15, priority: UILayoutPriority.defaultHigh)
seperator.matchParent(top: nil, left: 0, bottom: 0, right: 0, priority: UILayoutPriority.defaultHigh)
seperator.heightConstraint(1)
}
func updateIndicator() {
indicator.text = isCollapsed ? "+" : "-"
}
}
| mit | 318997b0229b7dfdc8e8d63c6b21f4d9 | 24.101695 | 110 | 0.592843 | 4.716561 | false | false | false | false |
mingxianzyh/D3View | D3View/D3View/D3View.swift | 1 | 1942 | // Created by mozhenhau on 14/11/21.
// Copyright (c) 2014年 mozhenhau. All rights reserved.
// 初始化话是基于tag的,比如D3Button默认tag为0时是圆角
// 使用方法1:在mainstoryboard继承D3__ ,然后tag设置为对应样式。(tag被占用的时候不可用)
// 2: 在viewcontroller实例化后在viewdiload进行初始化initstyle,可以传多个样式
//
import UIKit
//MARK: OTHER widget
public class D3View: UIView {
//对应enum ViewStyle
@IBInspectable var viewStyle: Int = 0
//对应enum ViewStyle,可写多个用逗号隔开
@IBInspectable var viewStyles: String = ""{
didSet{
let styles = viewStyles.componentsSeparatedByString(",")
for style in styles{
if let style:ViewStyle = ViewStyle(rawValue: Int(style)!){
initStyle(style)
}
}
}
}
@IBInspectable var isShadowDown: Bool = false {
didSet {
if isShadowDown{
initStyle(ViewStyle.ShadowDown)
}
}
}
@IBInspectable var isShadow: Bool = false {
didSet {
if isShadow{
initStyle(ViewStyle.Shadow)
}
}
}
@IBInspectable var isGrayBorder: Bool = false {
didSet {
if isGrayBorder{
initStyle(ViewStyle.Border,ViewStyle.GrayBorder)
}
}
}
//是否圆形
@IBInspectable var isRound: Bool = false {
didSet {
if isRound{
initStyle(ViewStyle.Round)
}
}
}
@IBInspectable var borderColor: UIColor = UIColor.clearColor(){
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
} | mit | 909b9fe6fb3d7851be90a14b4366fefb | 24.385714 | 74 | 0.543356 | 4.363636 | false | false | false | false |
3aaap/DZHandleDB | DZHandleDB/DZHandleDB/Person.swift | 1 | 2130 | //
// Person.swift
// DZHandleDB
//
// Created by 宋得中 on 15/10/30.
// Copyright © 2015年 song_dzhong. All rights reserved.
//
import UIKit
/// 演示并测试数据库管理函数编写的正确性
class Person: NSObject {
var id = 0
var name: String?
var age = 0
var height: Double = 0
init(dict: [String : AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
// 方便调试
override var description: String {
let keys = ["id", "name", "age", "height"]
return dictionaryWithValuesForKeys(keys).description
}
}
extension Person {
// 根据数据库中数据创建模型数组
class func persons() -> [Person]? {
let sql = "SELECT id, name, age, height FROM T_Person;"
guard let dataDictArr = DZSQLiteManager.sharedManager.queryExec(sql) else {
return nil
}
var modelArr: [Person] = [Person]()
for dict in dataDictArr {
modelArr.append(Person(dict: dict))
}
return modelArr
}
// 根据数据模型向数据表中插入一条模型数据
func insertPerson() -> Bool {
let sql = "INSERT INTO T_Person\n" +
"(name, age, height) VALUES\n" +
"('\(name!)', \(age), \(height));"
print(sql)
id = DZSQLiteManager.sharedManager.insertExec(sql)
return id > 0
}
// 修改当前对象 id 对应的数据
func updatePerson() -> Bool {
let sql = "UPDATE T_Person SET name = '\(name!)', age = \(age), height = \(height) \n" +
"WHERE id = \(id);"
print(sql)
let rows = DZSQLiteManager.sharedManager.updateOrDelExec(sql)
return rows > 0
}
// 删除当前对象 id 对应的数据
func deletePerson() -> Bool {
let sql = "DELETE FROM T_Person WHERE id = \(id)"
print(sql)
let rows = DZSQLiteManager.sharedManager.updateOrDelExec(sql)
return rows > 0
}
}
| mit | ab6c001eb65fc43789dcca02f3bcfe42 | 23.5875 | 96 | 0.529741 | 3.965726 | false | false | false | false |
cweatureapps/SwiftScraper | Sources/Steps/ScriptStep.swift | 1 | 2906 | //
// ScriptStep.swift
// SwiftScraper
//
// Created by Ken Ko on 21/04/2017.
// Copyright © 2017 Ken Ko. All rights reserved.
//
import Foundation
// MARK: - Types
/// Callback invoked when a `ScriptStep` or `AsyncScriptStep` is finished.
///
/// - parameter response: Data returned from JavaScript.
/// - parameter model: The model JSON dictionary which can be modified by the step.
/// - returns: The `StepFlowResult` which allows control flow of the steps.
public typealias ScriptStepHandler = (_ response: Any?, _ model: inout JSON) -> StepFlowResult
// MARK: - ScriptStep
/// Step that runs some JavaScript which will return a result immediately from the JavaScript function.
///
/// The `StepFlowResult` returned by the `handler` can be used to drive control flow of the steps.
public class ScriptStep: Step {
private var functionName: String
var params: [Any]
private var paramsKeys: [String]
private var handler: ScriptStepHandler
/// Initializer.
///
/// - parameter functionName: The name of the JavaScript function to call. The module namespace is automatically added.
/// - parameter params: Parameters which will be passed to the JavaScript function.
/// - parameter paramsKeys: Look up the values from the JSON model dictionary using these keys,
/// and pass them as the parameters to the JavaScript function. If provided, these are used instead of `params`.
/// - parameter handler: Callback function which returns data from JavaScript, and passes the model JSON dictionary for modification.
public init(
functionName: String,
params: Any...,
paramsKeys: [String] = [],
handler: @escaping ScriptStepHandler) {
self.functionName = functionName
self.params = params
self.paramsKeys = paramsKeys
self.handler = handler
}
public func run(with browser: Browser, model: JSON, completion: @escaping StepCompletionCallback) {
let params: [Any]
if paramsKeys.isEmpty {
params = self.params
} else {
params = paramsKeys.map { model[$0] ?? NSNull() }
}
runScript(browser: browser, functionName: functionName, params: params) { [weak self] result in
guard let this = self else { return }
switch result {
case .failure(let error):
completion(.failure(error, model))
case .success(let response):
var modelCopy = model
let result = this.handler(response, &modelCopy)
completion(result.convertToStepCompletionResult(with: modelCopy))
}
}
}
func runScript(browser: Browser, functionName: String, params: [Any], completion: @escaping ScriptResponseResultCallback) {
browser.runScript(functionName: functionName, params: params, completion: completion)
}
}
| mit | ddb2a60ff9e1fcfefe8a12e5acd36225 | 38.794521 | 137 | 0.666093 | 4.603803 | false | false | false | false |
Hovo-Infinity/radio | Radio/RadioStation.swift | 1 | 1022 | //
// RadioStation.swift
// Radio
//
// Created by Hovhannes Stepanyan on 7/25/17.
// Copyright © 2017 Hovhannes Stepanyan. All rights reserved.
//
import UIKit
class RadioStationStream {
var stream:String = "";
var bitrate:Int = 32;
var content_type:String = "";
var status:Int = 0;
var listeners:Int = 0;
}
class RadioStationCategory {
var categoryId:Int = 0;
var title:String = "";
var description:String = "";
var slug:String = "";
var ancestry:(Any)? = nil;
}
class RadioStation: NSObject {
var uid:Int = 0;
var name:String = "";
var desc:String = "";
var country:String = "";
var website:String = "";
var imageUrl:String = "";
var thumbUrl:String = "";
var created_at:String = "";
var updated_at:String = "";
var slug:String = "";
var twitter:String = "";
var facebook:String = "";
var total_listeners:Int = 0;
var streams:Array = [RadioStationStream]();
var categories:Array = [RadioStationCategory]();
}
| gpl-3.0 | 68f99a32625c6d5bee1d1e3d53f17a26 | 22.744186 | 62 | 0.611166 | 3.59507 | false | false | false | false |
ngageoint/geopackage-mapcache-ios | mapcache-ios/layer/MCCreateLayerFieldViewController.swift | 1 | 6396 | //
// MCLayerDetailsViewController.swift
// mapcache-ios
//
// Created by Tyler Burgett on 5/19/20.
// Copyright © 2020 NGA. All rights reserved.
//
import UIKit
protocol MCCreateLayerFieldDelegate: AnyObject {
func createField(name:String, type:GPKGDataType)
func checkFieldNameCollision(name: String) -> Bool
}
class MCCreateLayerFieldViewController: NGADrawerViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, MCDualButtonCellDelegate, MCSegmentedControlCellDelegate {
var cellArray: Array<UITableViewCell> = []
var featureTable: MCFeatureTable = MCFeatureTable()
var tableView: UITableView = UITableView()
var haveScrolled: Bool = false
var contentOffset: CGFloat = 0.0
var fieldName: MCFieldWithTitleCell?
var dualButtons: MCDualButtonCell?
var segmentedControl: MCSegmentedControlCell?
weak var createLayerFieldDelegate:MCCreateLayerFieldDelegate?
let typeDictionary: NSDictionary = ["Checkbox": GPKG_DT_BOOLEAN, "Number": GPKG_DT_DOUBLE, "Text": GPKG_DT_TEXT]
var selectedType: GPKGDataType = GPKG_DT_TEXT
override func viewDidLoad() {
super.viewDidLoad()
let bounds: CGRect = self.view.bounds
let insetBounds: CGRect = CGRect.init(x: bounds.origin.x, y: bounds.origin.y + 32, width: bounds.size.width, height: bounds.size.height)
self.tableView = UITableView.init(frame: insetBounds, style: UITableView.Style.plain)
self.tableView.autoresizingMask.insert(.flexibleWidth)
self.tableView.autoresizingMask.insert(.flexibleHeight)
self.tableView.separatorStyle = .none
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.estimatedRowHeight = 140
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.backgroundColor = UIColor.init(named:"ngaBackgroundColor")
self.extendedLayoutIncludesOpaqueBars = false
addAndConstrainSubview(self.tableView)
registerCellTypes()
initCellArray()
addDragHandle()
addCloseButton()
}
func registerCellTypes() {
self.tableView.register(UINib.init(nibName: "MCTitleCell", bundle: nil), forCellReuseIdentifier: "title")
self.tableView.register(UINib.init(nibName: "MCFieldWithTitleCell", bundle: nil), forCellReuseIdentifier: "fieldWithTitle")
self.tableView.register(UINib.init(nibName: "MCSegmentedControlCell", bundle: nil), forCellReuseIdentifier: "segmentedControl")
self.tableView.register(UINib.init(nibName: "MCDualButtonCell", bundle: nil), forCellReuseIdentifier: "dualButtons")
}
func initCellArray() {
self.cellArray.removeAll()
let titleCell:MCTitleCell = self.tableView.dequeueReusableCell(withIdentifier: "title") as! MCTitleCell
titleCell.setLabelText("New Field")
cellArray.append(titleCell)
self.fieldName = (self.tableView.dequeueReusableCell(withIdentifier: "fieldWithTitle") as! MCFieldWithTitleCell)
self.fieldName?.setTitleText("Name")
self.fieldName?.useReturnKeyDone()
self.fieldName?.setTextFieldDelegate(self)
self.cellArray.append(self.fieldName!)
self.segmentedControl = (self.tableView.dequeueReusableCell(withIdentifier: "segmentedControl") as! MCSegmentedControlCell)
self.segmentedControl?.setLabelText("Type")
self.segmentedControl?.updateItems(typeDictionary.allKeys)
self.segmentedControl?.delegate = self
self.cellArray.append(self.segmentedControl!)
self.dualButtons = (self.tableView.dequeueReusableCell(withIdentifier: "dualButtons") as! MCDualButtonCell)
self.dualButtons?.setLeftButtonLabel("Cancel")
self.dualButtons?.leftButtonAction = "cancel"
self.dualButtons?.setRightButtonLabel("Save")
self.dualButtons?.rightButtonAction = "save"
self.dualButtons?.disableRightButton() //TODO: until we have a valid field name, don't enable the button
self.dualButtons?.dualButtonDelegate = self
self.cellArray.append(dualButtons!)
}
override func closeDrawer() {
self.drawerViewDelegate.popDrawer()
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.trimWhiteSpace()
if let isValidFieldName = self.createLayerFieldDelegate?.checkFieldNameCollision(name: textField.text!) {
if (!isValidFieldName || textField.text == "") {
self.fieldName?.useErrorAppearance()
} else {
self.fieldName?.useNormalAppearance()
}
}
textField.resignFirstResponder()
self.dualButtons?.enableRightButton()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
self.dualButtons?.enableRightButton()
return true
}
// MARK: UITableViewDataSource and UITableViewDelegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cellArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return cellArray[indexPath.row]
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (self.haveScrolled) {
rollUpPanGesture(scrollView.panGestureRecognizer, with: scrollView)
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.haveScrolled = true
if (!self.isFullView) {
scrollView.isScrollEnabled = false
scrollView.isScrollEnabled = true
} else {
scrollView.isScrollEnabled = true
}
}
func performDualButtonAction(_ action: String) {
if (action == "save") {
self.createLayerFieldDelegate?.createField(name: (self.fieldName?.fieldValue())!, type: self.selectedType)
} else if (action == "cancel") {
self.closeDrawer()
}
}
// MARK: MCSegmentedControlCellDelegate methods
func selectionChanged(_ selection: String!) {
self.selectedType = self.typeDictionary.value(forKey: selection) as! GPKGDataType
}
}
| mit | 4e833e685fb77fce3a252e74ad143ec3 | 38.475309 | 188 | 0.683815 | 4.919231 | false | false | false | false |
slavapestov/swift | test/Interpreter/generic_class.swift | 4 | 5211 | // RUN: rm -rf %t && mkdir %t
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %target-run %t/a.out | FileCheck %s
// REQUIRES: executable_test
protocol MyPrintable {
func myPrint()
}
extension Int : MyPrintable {
func myPrint() {
print(self.description, terminator: "")
}
}
extension Double : MyPrintable {
func myPrint() {
print(self.description, terminator: "")
}
}
extension String : MyPrintable {
func myPrint() {
print(self.debugDescription, terminator: "")
}
}
class BufferedPair<T, U> {
var front: UInt8
var first: T
var second: U
var back: UInt8
init(_ front: UInt8, _ first: T, _ second: U, _ back: UInt8) {
self.front = front
self.first = first
self.second = second
self.back = back
}
}
enum State : MyPrintable {
case CA, OR, WA
func myPrint() {
switch self {
case .CA:
print("California", terminator: "")
case .OR:
print("Oregon", terminator: "")
case .WA:
print("Washington", terminator: "")
}
}
}
func printPair<A: MyPrintable, B: MyPrintable>(p: BufferedPair<A,B>) {
print("\(p.front) ", terminator: "")
p.first.myPrint()
print(" ", terminator: "")
p.second.myPrint()
print(" \(p.back)")
}
var p = BufferedPair(99, State.OR, "Washington's Mexico", 84)
// CHECK: 99 Oregon "Washington\'s Mexico" 84
printPair(p)
class AwkwardTriple<V, W, X> : BufferedPair<V, W> {
var third: X
init(_ front: UInt8, _ first: V, _ second: W, _ back: UInt8, _ third: X) {
self.third = third
super.init(front, first, second, back)
self.third = third
}
}
func printTriple
<D: MyPrintable, E: MyPrintable, F: MyPrintable>
(p: AwkwardTriple<D, E, F>)
{
print("\(p.front) ", terminator: "")
p.first.myPrint()
print(" ", terminator: "")
p.second.myPrint()
print(" \(p.back) ", terminator: "")
p.third.myPrint()
print("")
}
var q = AwkwardTriple(123, State.CA, "Foo", 234, State.WA)
// CHECK: 123 California "Foo" 234
printPair(q)
// CHECK: 123 California "Foo" 234 Washington
printTriple(q)
class FourthWheel<P, Q, R, S> : AwkwardTriple<P, Q, R> {
var fourth: S
init(_ front: UInt8, _ first: P, _ second: Q, _ back: UInt8, _ third: R,
_ fourth: S) {
self.fourth = fourth
super.init(front, first, second, back, third)
self.fourth = fourth
}
}
func printQuad
<G: MyPrintable, H: MyPrintable, I: MyPrintable, J: MyPrintable>
(p: FourthWheel<G, H, I, J>)
{
print("\(p.front) ", terminator: "")
p.first.myPrint()
print(" ", terminator: "")
p.second.myPrint()
print(" \(p.back) ", terminator: "")
p.third.myPrint()
print(" ", terminator: "")
p.fourth.myPrint()
print("")
}
var r = FourthWheel(21, State.WA, "Bar", 31, State.OR, 3.125)
// CHECK: 21 Washington "Bar" 31
printPair(r)
// CHECK: 21 Washington "Bar" 31 Oregon
printTriple(r)
var rAsPair: BufferedPair<State, String> = r
// CHECK: 21 Washington "Bar" 31 Oregon
printTriple(rAsPair as! AwkwardTriple<State, String, State>)
// CHECK: 21 Washington "Bar" 31 Oregon 3.125
printQuad(r)
// CHECK: 21 Washington "Bar" 31 Oregon 3.125
printQuad(rAsPair as! FourthWheel<State, String, State, Double>)
class ConcretePair {
var first, second: UInt8
init(_ first: UInt8, _ second: UInt8) {
self.first = first
self.second = second
}
}
class SemiConcreteTriple<O> : ConcretePair {
var third: O
init(_ first: UInt8, _ second: UInt8, _ third: O) {
self.third = third
super.init(first, second)
self.third = third
}
}
func printConcretePair(p: ConcretePair) {
print("\(p.first) \(p.second)")
}
func printSemiTriple<O : MyPrintable>(p: SemiConcreteTriple<O>) {
print("\(p.first) \(p.second) ", terminator: "")
p.third.myPrint()
print("")
}
var s = SemiConcreteTriple(120, 230, State.CA)
// CHECK: 120 230
printConcretePair(s)
// CHECK: 120 230 California
printSemiTriple(s)
var t = SemiConcreteTriple(121, 231, "California's Canada")
// CHECK: 121 231
printConcretePair(t)
// CHECK: 121 231 "California\'s Canada"
printSemiTriple(t)
class MoreConcreteQuadruple : SemiConcreteTriple<State> {
var fourth: String
init(_ first: UInt8, _ second: UInt8, _ third: State, _ fourth: String) {
self.fourth = fourth
super.init(first, second, third)
}
}
var u = MoreConcreteQuadruple(10, 17, State.CA, "Hella")
// CHECK: 10 17
printConcretePair(u)
class RootGenericFixedLayout<T> {
let a: [T]
let b: Int
init(a: [T], b: Int) {
self.a = a
self.b = b
}
}
func checkRootGenericFixedLayout<T>(r: RootGenericFixedLayout<T>) {
print(r.a)
print(r.b)
}
let rg = RootGenericFixedLayout<Int>(a: [1, 2, 3], b: 4)
// CHECK: [1, 2, 3]
// CHECK: 4
checkRootGenericFixedLayout(rg)
class GenericInheritsGenericFixedLayout<T> : RootGenericFixedLayout<T> {
let c: Int
init(a: [T], b: Int, c: Int) {
self.c = c
super.init(a: a, b: b)
}
}
let gg = GenericInheritsGenericFixedLayout<Int>(a: [1, 2, 3], b: 4, c: 5)
func checkGenericInheritsGenericFixedLayout<T>(g: GenericInheritsGenericFixedLayout<T>) {
print(g.a)
print(g.b)
print(g.c)
}
// CHECK: [1, 2, 3]
// CHECK: 4
checkRootGenericFixedLayout(gg)
// CHECK: [1, 2, 3]
// CHECK: 4
// CHECK: 5
checkGenericInheritsGenericFixedLayout(gg)
| apache-2.0 | 3f4f77f3109e1cd9c17c9465b4aaae9f | 21.080508 | 89 | 0.641528 | 2.949066 | false | false | false | false |
insidegui/WWDC | PlayerUI/Views/PUIAnnotationLayer.swift | 2 | 1469 | //
// PUIAnnotationLayer.swift
// PlayerUI
//
// Created by Guilherme Rambo on 01/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
class PUIAnnotationLayer: PUIBoringLayer {
private var attachmentSpacing: CGFloat = 0
private var attachmentAttribute: NSLayoutConstraint.Attribute = .notAnAttribute
private(set) var attachedLayer: PUIBoringTextLayer = PUIBoringTextLayer()
func attach(layer: PUIBoringTextLayer, attribute: NSLayoutConstraint.Attribute, spacing: CGFloat) {
guard attribute == .top else {
fatalError("Only .top is implemented for now")
}
attachmentSpacing = spacing
attachmentAttribute = attribute
addSublayer(layer)
attachedLayer = layer
layoutAttached(layer: layer)
}
private func layoutAttached(layer: PUIBoringTextLayer) {
layer.layoutIfNeeded()
var f = layer.frame
if let textLayerContents = layer.string as? NSAttributedString {
let s = textLayerContents.size()
f.size.width = ceil(s.width)
f.size.height = ceil(s.height)
}
let y: CGFloat = -f.height - attachmentSpacing
let x: CGFloat = -f.width / 2 + bounds.width / 2
f.origin.x = x
f.origin.y = y
layer.frame = f
}
override func layoutSublayers() {
super.layoutSublayers()
layoutAttached(layer: attachedLayer)
}
}
| bsd-2-clause | abb0642f6e9eae94bb1a2c7463edac52 | 23.881356 | 103 | 0.643733 | 4.516923 | false | false | false | false |
trvslhlt/CalcLater | CalcLater/CalcLater.swift | 1 | 2864 | //
// CalcLaterAlt.swift
// CalcLater
//
// Created by trvslhlt on 11/1/15.
// Copyright © 2015 travis holt. All rights reserved.
//
import Foundation
// 4 + 2 * 2 + 10 / 10 * 5 = =
// interpret as...
// 4 + 2 * 2 + 10 / 10 * 5 * 5
// 4 + 4 + 10 / 10 * 5 * 5
// 4 + 4 + 1 * 5 * 5
// 4 + 4 + 5 * 5
// 4 + 4 + 25
// 8 + 25
// 33
// 4 + 3 = * 5 =
// 7 * 5 =
// 35
// 4 + 3 * 5 =
//
class CalcLater {
//MARK: State
static let sharedInstance = CalcLater()
private var inputSequence = [CalcLaterSymbol]()
private var expressionEngine = CalcLaterEngine()
var computedOutput: String?
var clearIsValidInput: Bool {
return CalcLaterSymbol.lastIsDecimal(inputSequence) || CalcLaterSymbol.lastIsDigit(inputSequence)
}
//MARK: Input
func input(symbol: CalcLaterSymbol) {
// this function should only route input
switch symbol {
case .EqualsSign: inputEquals()
case .ClearAllSign: inputClearAll()
case .ClearSign: inputClear()
case .PlusSign: inputPlus()
case .MinusSign: inputMinus()
case .MultiplySign: inputMultiply()
case .DivideSign: inputDivide()
case .DecimalSign: inputDecimal()
default: inputDigit(symbol)
}
print(inputSequence.reduce("") { $0 + "\($1)"})
}
//MARK: Input validators + mutation
private func inputEquals() {
guard let lastSymbol = inputSequence.last else { return }
if (lastSymbol.isDigit() ||
CalcLaterSymbol.lastIsEquals(inputSequence) ||
CalcLaterSymbol.lastIsDecimal(inputSequence)) &&
CalcLaterSymbol.containsArithmeticOperator(inputSequence) {
if CalcLaterSymbol.lastIsDecimal(inputSequence) { inputSequence.removeLast() }
inputSequence.append(.EqualsSign)
}
}
private func inputClearAll() {
inputSequence = []
}
private func inputClear() {
if CalcLaterSymbol.lastIsDigit(inputSequence) || CalcLaterSymbol.lastIsDecimal(inputSequence) {
inputSequence.removeLast()
inputClear()
}
}
func inputPlus() {
inputSequence.append(.PlusSign)
}
func inputMinus() {
inputSequence.append(.MinusSign)
}
func inputMultiply() {
inputSequence.append(.MultiplySign)
}
func inputDivide() {
inputSequence.append(.DivideSign)
}
private func inputDecimal() {
if CalcLaterSymbol.tailDigitSequenceContainsDecimal(inputSequence) {
return
} else if !CalcLaterSymbol.lastIsDigit(inputSequence) {
inputSequence.append(.Zero)
}
inputSequence.append(.DecimalSign)
}
private func inputDigit(symbol: CalcLaterSymbol) {
inputSequence.append(symbol)
}
} | mit | 4a9411df229971b1a4d157e9c3068bd0 | 24.801802 | 105 | 0.599721 | 4.078348 | false | false | false | false |
zxwWei/SWiftWeiBlog | XWWeibo/XWWeibo/Classes/Tool(工具)/XWAFNTool.swift | 1 | 2565 | //
// XWAFNTool.swift
// XWWeibo
//
// Created by apple on 15/10/28.
// Copyright © 2015年 ZXW. All rights reserved.
//
// MARK : - ios9中的网络请求需配key
import Foundation
import AFNetworking
class XWNetworkTool: AFHTTPSessionManager {
// MARK: - 1.创建单例 继续自本类
static let shareInstance: XWNetworkTool = {
let urlStr = "https://api.weibo.com/"
let tool = XWNetworkTool(baseURL: NSURL(string: urlStr))
tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tool
}()
// MARK: - 2 Oauth授权url 注意参数不要复制出错
// 2.参数
// 申请时应用时分配的APPKey
private let client_id = "1369851949"
// 回调地址
let redirect_uri = "http://www.baidu.com/"
/// 请求的类型,填写authorization_code
private let grant_type = "authorization_code"
// 应用的secert
private let client_secret = "abc9cd7b14e70a7b26ad4e1cfa147e0e"
// MARK: - 3.OAthURL地址 Oauth授权url
func oauthURL() -> NSURL {
// 拼接
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
return NSURL(string: urlString)!
}
// MARK: - 4.加载AssesToken
func loadAssesToken(code: String , finished: (result: [String: AnyObject]? ,error: NSError?) -> ()){
let urlString = "https://api.weibo.com/oauth2/access_token"
// 参数
let parameters = [
//"code" : code
"client_id" : client_id ,
"client_secret": client_secret,
"grant_type": grant_type,
"code": code,
"redirect_uri": redirect_uri
]
// 错误的
// let parameters = {
// "client_id": client_id,
// "client_secret": client_secret,
// "grant_type": grant_type,
// "code": code,
// "redirect_uri": redirect_uri
// }
// 网络请求
POST(urlString, parameters: parameters, success: { (_, result) -> Void in
// 成功时告诉调用闭包者得到result
finished(result: result as? [String: AnyObject] , error: nil)
}) { (_, error) -> Void in
// 失败时告诉调用闭包者得到error
finished(result: nil, error: error)
}
}
}
| apache-2.0 | 748862aa331f0960511366e86c6f8064 | 24.212766 | 116 | 0.52827 | 3.878887 | false | false | false | false |
brennanMKE/StravaKit | StravaKitTests/JSONRequestor.swift | 2 | 1386 | //
// JSONRequestor.swift
// StravaKit
//
// Created by Brennan Stehling on 8/22/16.
// Copyright © 2016 SmallSharpTools LLC. All rights reserved.
//
import Foundation
import StravaKit
open class JSONRequestor : Requestor {
open var response: Any?
open var responses: [Any]?
open var error: NSError?
open var callback: (() -> ())?
open var baseUrl: String
init() {
baseUrl = StravaBaseURL
}
open func request(_ method: HTTPMethod, authenticated: Bool, path: String, params: ParamsDictionary?, completionHandler: ((_ response: Any?, _ error: NSError?) -> ())?) -> URLSessionTask? {
DispatchQueue.main.async { [weak self] in
guard let s = self else {
return
}
if s.response == nil {
if let responses = s.responses,
let firstResponse = responses.first {
s.response = firstResponse
var responses = responses
responses.removeFirst()
s.responses = responses
}
}
completionHandler?(s.response, s.error)
s.callback?()
// advance to the next response if there are responses defined
if s.responses != nil {
s.response = nil
}
}
return nil
}
}
| mit | 1143070f5da98c9f4ca1e024395c1458 | 26.7 | 193 | 0.540794 | 4.911348 | false | false | false | false |
chenqihui/QHAwemeDemo | QHAwemeDemo/QHRootScrollViewController.swift | 1 | 2469 | //
// QHRootScrollViewController.swift
// QHAwemeDemo
//
// Created by Anakin chen on 2017/10/25.
// Copyright © 2017年 AnakinChen Network Technology. All rights reserved.
//
import UIKit
class QHRootScrollViewController: QHBaseViewController, QHNavigationControllerProtocol {
@IBOutlet weak var mainScrollV: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// if let navigationC = self.navigationController as? QHNavigationController {
// navigationC.addGesturePush()
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
mainScrollV.contentOffset = CGPoint(x: UIScreen.main.bounds.width, y: 0)
}
//MARK: QHNavigationControllerProtocol
func navigationControllerShouldPush(_ vc: QHNavigationController) -> Bool {
let v = self.childViewControllers[1] as! QHTabBarViewController
//条件1
var bScrollBegin = v.navigationControllerShouldPush()
//条件2
if bScrollBegin == true {
if mainScrollV.contentOffset.x == mainScrollV.frame.size.width {
//手势push触发前关闭scrollView滑动
mainScrollV.isScrollEnabled = false
bScrollBegin = true
}
else {
bScrollBegin = false
}
}
return bScrollBegin
}
func navigationControllerDidPushBegin(_ vc: QHNavigationController) -> Bool {
let v = self.childViewControllers[1] as! QHTabBarViewController
return v.navigationControllerDidPushBegin()
}
func navigationControllerDidPushEnd(_ vc: QHNavigationController) {
//手势push触发后重新开启scrollView滑动
let v = self.childViewControllers[1] as! QHTabBarViewController
if v.selectedIndex == 0 {
mainScrollV.isScrollEnabled = true
}
}
func doNavigationControllerGesturePush(_ vc: QHNavigationController) -> Bool {
//当root scrollview不在tabView时忽略导航push手势
if mainScrollV.contentOffset.x < mainScrollV.frame.size.width {
return false
}
return true
}
}
| mit | 0a5abe1ad7eaba0ea6fa2f14a09766a1 | 30.142857 | 88 | 0.640534 | 4.854251 | false | false | false | false |
practicalswift/swift | stdlib/public/core/DictionaryStorage.swift | 10 | 13968 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// An instance of this class has all `Dictionary` data tail-allocated.
/// Enough bytes are allocated to hold the bitmap for marking valid entries,
/// keys, and values. The data layout starts with the bitmap, followed by the
/// keys, followed by the values.
// NOTE: older runtimes called this class _RawDictionaryStorage. The two
// must coexist without a conflicting ObjC class name, so it was
// renamed. The old name must not be used in the new runtime.
@_fixed_layout
@usableFromInline
@_objc_non_lazy_realization
internal class __RawDictionaryStorage: __SwiftNativeNSDictionary {
// NOTE: The precise layout of this type is relied on in the runtime to
// provide a statically allocated empty singleton. See
// stdlib/public/stubs/GlobalObjects.cpp for details.
/// The current number of occupied entries in this dictionary.
@usableFromInline
@nonobjc
internal final var _count: Int
/// The maximum number of elements that can be inserted into this set without
/// exceeding the hash table's maximum load factor.
@usableFromInline
@nonobjc
internal final var _capacity: Int
/// The scale of this dictionary. The number of buckets is 2 raised to the
/// power of `scale`.
@usableFromInline
@nonobjc
internal final var _scale: Int8
/// The scale corresponding to the highest `reserveCapacity(_:)` call so far,
/// or 0 if there were none. This may be used later to allow removals to
/// resize storage.
///
/// FIXME: <rdar://problem/18114559> Shrink storage on deletion
@usableFromInline
@nonobjc
internal final var _reservedScale: Int8
// Currently unused, set to zero.
@nonobjc
internal final var _extra: Int16
/// A mutation count, enabling stricter index validation.
@usableFromInline
@nonobjc
internal final var _age: Int32
/// The hash seed used to hash elements in this dictionary instance.
@usableFromInline
internal final var _seed: Int
/// A raw pointer to the start of the tail-allocated hash buffer holding keys.
@usableFromInline
@nonobjc
internal final var _rawKeys: UnsafeMutableRawPointer
/// A raw pointer to the start of the tail-allocated hash buffer holding
/// values.
@usableFromInline
@nonobjc
internal final var _rawValues: UnsafeMutableRawPointer
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@nonobjc
internal init(_doNotCallMe: ()) {
_internalInvariantFailure("This class cannot be directly initialized")
}
@inlinable
@nonobjc
internal final var _bucketCount: Int {
@inline(__always) get { return 1 &<< _scale }
}
@inlinable
@nonobjc
internal final var _metadata: UnsafeMutablePointer<_HashTable.Word> {
@inline(__always) get {
let address = Builtin.projectTailElems(self, _HashTable.Word.self)
return UnsafeMutablePointer(address)
}
}
// The _HashTable struct contains pointers into tail-allocated storage, so
// this is unsafe and needs `_fixLifetime` calls in the caller.
@inlinable
@nonobjc
internal final var _hashTable: _HashTable {
@inline(__always) get {
return _HashTable(words: _metadata, bucketCount: _bucketCount)
}
}
}
/// The storage class for the singleton empty set.
/// The single instance of this class is created by the runtime.
// NOTE: older runtimes called this class _EmptyDictionarySingleton.
// The two must coexist without a conflicting ObjC class name, so it was
// renamed. The old name must not be used in the new runtime.
@_fixed_layout
@usableFromInline
internal class __EmptyDictionarySingleton: __RawDictionaryStorage {
@nonobjc
internal override init(_doNotCallMe: ()) {
_internalInvariantFailure("This class cannot be directly initialized")
}
#if _runtime(_ObjC)
@objc
internal required init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer,
count: Int
) {
_internalInvariantFailure("This class cannot be directly initialized")
}
#endif
}
#if _runtime(_ObjC)
extension __EmptyDictionarySingleton: _NSDictionaryCore {
@objc(copyWithZone:)
internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
return self
}
@objc
internal var count: Int {
return 0
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
// Even though we never do anything in here, we need to update the
// state so that callers know we actually ran.
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
}
state.pointee = theState
return 0
}
@objc(objectForKey:)
internal func object(forKey aKey: AnyObject) -> AnyObject? {
return nil
}
@objc(keyEnumerator)
internal func keyEnumerator() -> _NSEnumerator {
return __SwiftEmptyNSEnumerator()
}
@objc(getObjects:andKeys:count:)
internal func getObjects(
_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?,
count: Int) {
// Do nothing, we're empty
}
}
#endif
extension __RawDictionaryStorage {
/// The empty singleton that is used for every single Dictionary that is
/// created without any elements. The contents of the storage should never
/// be mutated.
@inlinable
@nonobjc
internal static var empty: __EmptyDictionarySingleton {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyDictionarySingleton))
}
}
@usableFromInline
final internal class _DictionaryStorage<Key: Hashable, Value>
: __RawDictionaryStorage, _NSDictionaryCore {
// This type is made with allocWithTailElems, so no init is ever called.
// But we still need to have an init to satisfy the compiler.
@nonobjc
override internal init(_doNotCallMe: ()) {
_internalInvariantFailure("This class cannot be directly initialized")
}
deinit {
guard _count > 0 else { return }
if !_isPOD(Key.self) {
let keys = self._keys
for bucket in _hashTable {
(keys + bucket.offset).deinitialize(count: 1)
}
}
if !_isPOD(Value.self) {
let values = self._values
for bucket in _hashTable {
(values + bucket.offset).deinitialize(count: 1)
}
}
_count = 0
_fixLifetime(self)
}
@inlinable
final internal var _keys: UnsafeMutablePointer<Key> {
@inline(__always)
get {
return self._rawKeys.assumingMemoryBound(to: Key.self)
}
}
@inlinable
final internal var _values: UnsafeMutablePointer<Value> {
@inline(__always)
get {
return self._rawValues.assumingMemoryBound(to: Value.self)
}
}
internal var asNative: _NativeDictionary<Key, Value> {
return _NativeDictionary(self)
}
#if _runtime(_ObjC)
@objc
internal required init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafeRawPointer,
count: Int
) {
_internalInvariantFailure("This class cannot be directly initialized")
}
@objc(copyWithZone:)
internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
return self
}
@objc
internal var count: Int {
return _count
}
@objc(keyEnumerator)
internal func keyEnumerator() -> _NSEnumerator {
return _SwiftDictionaryNSEnumerator<Key, Value>(asNative)
}
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
defer { _fixLifetime(self) }
let hashTable = _hashTable
var theState = state.pointee
if theState.state == 0 {
theState.state = 1 // Arbitrary non-zero value.
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
theState.extra.0 = CUnsignedLong(hashTable.startBucket.offset)
}
// Test 'objects' rather than 'count' because (a) this is very rare anyway,
// and (b) the optimizer should then be able to optimize away the
// unwrapping check below.
if _slowPath(objects == nil) {
return 0
}
let unmanagedObjects = _UnmanagedAnyObjectArray(objects!)
var bucket = _HashTable.Bucket(offset: Int(theState.extra.0))
let endBucket = hashTable.endBucket
_precondition(bucket == endBucket || hashTable.isOccupied(bucket),
"Invalid fast enumeration state")
var stored = 0
for i in 0..<count {
if bucket == endBucket { break }
let key = _keys[bucket.offset]
unmanagedObjects[i] = _bridgeAnythingToObjectiveC(key)
stored += 1
bucket = hashTable.occupiedBucket(after: bucket)
}
theState.extra.0 = CUnsignedLong(bucket.offset)
state.pointee = theState
return stored
}
@objc(objectForKey:)
internal func object(forKey aKey: AnyObject) -> AnyObject? {
guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self)
else { return nil }
let (bucket, found) = asNative.find(nativeKey)
guard found else { return nil }
let value = asNative.uncheckedValue(at: bucket)
return _bridgeAnythingToObjectiveC(value)
}
@objc(getObjects:andKeys:count:)
internal func getObjects(
_ objects: UnsafeMutablePointer<AnyObject>?,
andKeys keys: UnsafeMutablePointer<AnyObject>?,
count: Int) {
_precondition(count >= 0, "Invalid count")
guard count > 0 else { return }
var i = 0 // Current position in the output buffers
switch (_UnmanagedAnyObjectArray(keys), _UnmanagedAnyObjectArray(objects)) {
case (let unmanagedKeys?, let unmanagedObjects?):
for (key, value) in asNative {
unmanagedObjects[i] = _bridgeAnythingToObjectiveC(value)
unmanagedKeys[i] = _bridgeAnythingToObjectiveC(key)
i += 1
guard i < count else { break }
}
case (let unmanagedKeys?, nil):
for (key, _) in asNative {
unmanagedKeys[i] = _bridgeAnythingToObjectiveC(key)
i += 1
guard i < count else { break }
}
case (nil, let unmanagedObjects?):
for (_, value) in asNative {
unmanagedObjects[i] = _bridgeAnythingToObjectiveC(value)
i += 1
guard i < count else { break }
}
case (nil, nil):
// Do nothing.
break
}
}
#endif
}
extension _DictionaryStorage {
@usableFromInline
@_effects(releasenone)
internal static func copy(
original: __RawDictionaryStorage
) -> _DictionaryStorage {
return allocate(
scale: original._scale,
age: original._age,
seed: original._seed)
}
@usableFromInline
@_effects(releasenone)
static internal func resize(
original: __RawDictionaryStorage,
capacity: Int,
move: Bool
) -> _DictionaryStorage {
let scale = _HashTable.scale(forCapacity: capacity)
return allocate(scale: scale, age: nil, seed: nil)
}
@usableFromInline
@_effects(releasenone)
static internal func allocate(capacity: Int) -> _DictionaryStorage {
let scale = _HashTable.scale(forCapacity: capacity)
return allocate(scale: scale, age: nil, seed: nil)
}
#if _runtime(_ObjC)
@usableFromInline
@_effects(releasenone)
static internal func convert(
_ cocoa: __CocoaDictionary,
capacity: Int
) -> _DictionaryStorage {
let scale = _HashTable.scale(forCapacity: capacity)
let age = _HashTable.age(for: cocoa.object)
return allocate(scale: scale, age: age, seed: nil)
}
#endif
static internal func allocate(
scale: Int8,
age: Int32?,
seed: Int?
) -> _DictionaryStorage {
// The entry count must be representable by an Int value; hence the scale's
// peculiar upper bound.
_internalInvariant(scale >= 0 && scale < Int.bitWidth - 1)
let bucketCount = (1 as Int) &<< scale
let wordCount = _UnsafeBitset.wordCount(forCapacity: bucketCount)
let storage = Builtin.allocWithTailElems_3(
_DictionaryStorage<Key, Value>.self,
wordCount._builtinWordValue, _HashTable.Word.self,
bucketCount._builtinWordValue, Key.self,
bucketCount._builtinWordValue, Value.self)
let metadataAddr = Builtin.projectTailElems(storage, _HashTable.Word.self)
let keysAddr = Builtin.getTailAddr_Word(
metadataAddr, wordCount._builtinWordValue, _HashTable.Word.self,
Key.self)
let valuesAddr = Builtin.getTailAddr_Word(
keysAddr, bucketCount._builtinWordValue, Key.self,
Value.self)
storage._count = 0
storage._capacity = _HashTable.capacity(forScale: scale)
storage._scale = scale
storage._reservedScale = 0
storage._extra = 0
if let age = age {
storage._age = age
} else {
// The default mutation count is simply a scrambled version of the storage
// address.
storage._age = Int32(
truncatingIfNeeded: ObjectIdentifier(storage).hashValue)
}
storage._seed = seed ?? _HashTable.hashSeed(for: storage, scale: scale)
storage._rawKeys = UnsafeMutableRawPointer(keysAddr)
storage._rawValues = UnsafeMutableRawPointer(valuesAddr)
// Initialize hash table metadata.
storage._hashTable.clear()
return storage
}
}
| apache-2.0 | 5386ef655a053c118e1d571b58bfd07c | 29.76652 | 80 | 0.6875 | 4.48699 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Publish-发布/View/XMGPlaceholderTextView.swift | 1 | 3932 | //
// XMGPlaceholderTextView.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/3/4.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
class XMGPlaceholderTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
// 垂直方向上永远有弹簧效果
self.alwaysBounceVertical = true
// 默认字体
self.font = UIFont.systemFontOfSize(15)
// 默认的占位文字颜色
self.placeholderColor = UIColor.grayColor()
// 监听文字改变
XMGNoteCenter.addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
/// 绘制占位文字(每次drawRect:之前, 会自动清除掉之前绘制的内容)
override func drawRect(rect: CGRect) {
// Drawing code
// 如果有文字, 直接返回, 不绘制占位文字
// if (self.text.length || self.attributedText.length) return;
if (self.hasText()) {return}
var rect: CGRect = rect
// 处理rect
rect.origin.x = 4;
rect.origin.y = 7;
rect.size.width -= 2 * rect.origin.x;
// 文字属性
var attrs=[String:AnyObject]()
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
self.placeholder?.drawInRect(rect, withAttributes: attrs)
}
*/
private lazy var placeholderLabel: UILabel = {
// 添加一个用来显示占位文字的label
let label = UILabel()
label.numberOfLines = 0;
label.x = 4;
label.y = 7;
self.addSubview(label)
return label
}()
deinit{
XMGNoteCenter.removeObserver(self)
}
override func layoutSubviews() {
super.layoutSubviews()
self.placeholderLabel.width = self.width - 2 * self.placeholderLabel.x;
self.placeholderLabel.sizeToFit()
}
/*
/// 更新占位文字的尺寸
func updatePlaceholderLabelSize(){
if self.placeholder == nil{
return
}
// 文字的最大尺寸
let maxSize:CGSize = CGSizeMake(XMGScreenW - 2 * self.placeholderLabel.x, CGFloat(MAXFLOAT))
self.placeholderLabel.size = (self.placeholder! as NSString).boundingRectWithSize(maxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:self.font!], context: nil).size
self.placeholderLabel.backgroundColor = UIColor.redColor()
}
*/
///: 监听文字改变
func textDidChange(){
// 只要有文字, 就隐藏占位文字label
self.placeholderLabel.hidden = self.hasText()
}
//MARK: 重写setter
var placeholderColor:UIColor?{
didSet{
self.placeholderLabel.textColor = placeholderColor;
setNeedsDisplay()
}
}
var placeholder:String?{
didSet{
self.placeholderLabel.text = placeholder
setNeedsLayout()
}
}
override var font:UIFont?{
didSet{
super.font = font
self.placeholderLabel.font = font
setNeedsLayout()
}
}
override var text:String?{
didSet{
super.text = text
textDidChange()
}
}
override var attributedText: NSAttributedString?{
didSet{
super.attributedText = attributedText
textDidChange()
}
}
/**
* setNeedsDisplay方法 : 会在恰当的时刻自动调用drawRect:方法
* setNeedsLayout方法 : 会在恰当的时刻调用layoutSubviews方法
*/
}
| apache-2.0 | c36b935657d63496682f473aceb414c8 | 24.457746 | 215 | 0.597234 | 4.593393 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift | 27 | 2849 | //
// RxScrollViewDelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import RxSwift
import UIKit
extension UIScrollView: HasDelegate {
public typealias Delegate = UIScrollViewDelegate
}
/// For more information take a look at `DelegateProxyType`.
open class RxScrollViewDelegateProxy
: DelegateProxy<UIScrollView, UIScrollViewDelegate>
, DelegateProxyType
, UIScrollViewDelegate {
/// Typed parent object.
public weak private(set) var scrollView: UIScrollView?
/// - parameter scrollView: Parent object for delegate proxy.
public init(scrollView: ParentObject) {
self.scrollView = scrollView
super.init(parentObject: scrollView, delegateProxy: RxScrollViewDelegateProxy.self)
}
// Register known implementations
public static func registerKnownImplementations() {
self.register { RxScrollViewDelegateProxy(scrollView: $0) }
self.register { RxTableViewDelegateProxy(tableView: $0) }
self.register { RxCollectionViewDelegateProxy(collectionView: $0) }
self.register { RxTextViewDelegateProxy(textView: $0) }
}
fileprivate var _contentOffsetBehaviorSubject: BehaviorSubject<CGPoint>?
fileprivate var _contentOffsetPublishSubject: PublishSubject<()>?
/// Optimized version used for observing content offset changes.
internal var contentOffsetBehaviorSubject: BehaviorSubject<CGPoint> {
if let subject = _contentOffsetBehaviorSubject {
return subject
}
let subject = BehaviorSubject<CGPoint>(value: self.scrollView?.contentOffset ?? CGPoint.zero)
_contentOffsetBehaviorSubject = subject
return subject
}
/// Optimized version used for observing content offset changes.
internal var contentOffsetPublishSubject: PublishSubject<()> {
if let subject = _contentOffsetPublishSubject {
return subject
}
let subject = PublishSubject<()>()
_contentOffsetPublishSubject = subject
return subject
}
// MARK: delegate methods
/// For more information take a look at `DelegateProxyType`.
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let subject = _contentOffsetBehaviorSubject {
subject.on(.next(scrollView.contentOffset))
}
if let subject = _contentOffsetPublishSubject {
subject.on(.next(()))
}
self._forwardToDelegate?.scrollViewDidScroll?(scrollView)
}
deinit {
if let subject = _contentOffsetBehaviorSubject {
subject.on(.completed)
}
if let subject = _contentOffsetPublishSubject {
subject.on(.completed)
}
}
}
#endif
| mit | c30042822eee585f106f49c336246799 | 29.956522 | 101 | 0.682584 | 5.639604 | false | false | false | false |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Common Models/Mappable/LOL.swift | 1 | 644 | //
// LOL.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/16/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
import Genome
/// Model for LOL tag.
///
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451658
public struct LOL {
public var tag: LolTag = .Unknown
public var count: Int = 0
public init() {}
}
extension LOL: CommonMappableModel {
public mutating func sequence(map: Map) throws {
var tagString = ""
try tagString <~ map["tag"]
if let tag = LolTag(rawValue: tagString) {
self.tag = tag
}
try count <~ map["count"]
}
}
| mit | 485fc97c685ff6f98f33c7829707e49a | 17.371429 | 59 | 0.597201 | 3.532967 | false | false | false | false |
rmnblm/Mapbox-iOS-Examples | src/Examples/OfflineViewController.swift | 1 | 1893 | //
// OfflineViewController.swift
// Mapbox-iOS-Examples
//
// Created by Roman Blum on 04.10.16.
// Copyright © 2016 rmnblm. All rights reserved.
//
import UIKit
import Mapbox
class OfflineViewController: UIViewController, MGLMapViewDelegate, OfflineDownloadDelegate {
@IBOutlet var mapView: MGLMapView!
var downloadView: OfflineDownloadProgressView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.setCenter(CLLocationCoordinate2DMake(22.27933, 114.16281), animated: false)
mapView.zoomLevel = 13
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Download", style: .plain, target: self, action: #selector(startOfflinePackDownload))
}
func startOfflinePackDownload() {
navigationItem.rightBarButtonItem?.isEnabled = false
setupDownloadView()
downloadView.startDownload(mapView: mapView)
}
func setupDownloadView() {
downloadView = OfflineDownloadProgressView(frame: view.frame)
downloadView.delegate = self
view.addSubview(downloadView)
downloadView.translatesAutoresizingMaskIntoConstraints = false
downloadView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
downloadView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
downloadView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
downloadView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
downloadView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
downloadView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func didFinishDownload() {
navigationItem.rightBarButtonItem?.isEnabled = true
downloadView.removeFromSuperview()
}
}
| mit | bf16d5bd68a76fc760a584b0aece9aff | 36.098039 | 152 | 0.718288 | 5.183562 | false | false | false | false |
RevenueCat/purchases-ios | Sources/SubscriberAttributes/ReservedSubscriberAttributes.swift | 1 | 1341 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// ReservedSubscriberAttributes.swift
//
// Created by César de la Vega on 6/17/21.
//
import Foundation
// swiftlint:disable identifier_name
enum ReservedSubscriberAttribute: String {
var key: String { rawValue }
case email = "$email"
case phoneNumber = "$phoneNumber"
case displayName = "$displayName"
case pushToken = "$apnsTokens"
case idfa = "$idfa"
case idfv = "$idfv"
case gpsAdId = "$gpsAdId"
case consentStatus = "$attConsentStatus"
case ip = "$ip"
case adjustID = "$adjustId"
case appsFlyerID = "$appsflyerId"
case fBAnonID = "$fbAnonId"
case mpParticleID = "$mparticleId"
case oneSignalID = "$onesignalId"
case airshipChannelID = "$airshipChannelId"
case cleverTapID = "$clevertapId"
case mixpanelDistinctID = "$mixpanelDistinctId"
case firebaseAppInstanceID = "$firebaseAppInstanceId"
case mediaSource = "$mediaSource"
case campaign = "$campaign"
case adGroup = "$adGroup"
case ad = "$ad"
case keyword = "$keyword"
case creative = "$creative"
}
| mit | d0cb6da673a57e28b3ea432e0a076077 | 25.27451 | 68 | 0.672388 | 3.806818 | false | false | false | false |
hliberato/curso-ios | Signos/Signos/ViewController.swift | 1 | 2531 | //
// ViewController.swift
// Signos
//
// Created by Henrique Liberato on 23/12/16.
// Copyright © 2016 Henrique Liberato. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var data: [String] = []
var message: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
data.append("Aquário")
data.append("Peixes")
data.append("Câncer")
data.append("Leão")
data.append("Sagitário")
data.append("Escorpião")
data.append("Capricórnio")
data.append("Virgem")
data.append("Libra")
data.append("Touro")
data.append("Gêmeos")
data.append("Áries")
message.append("Não acredite nessa merda.")
message.append("Te enganaram!")
message.append("Signos não existem.")
message.append("Você será feliz, ou não.")
message.append("Não acredite nessa merda.")
message.append("Te enganaram!")
message.append("Signos não existem.")
message.append("Você será feliz, ou não.")
message.append("Não acredite nessa merda.")
message.append("Te enganaram!")
message.append("Signos não existem.")
message.append("Você será feliz, ou não.")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellReusable = "cellReusable"
let cell = tableView.dequeueReusableCell(withIdentifier: cellReusable, for: indexPath)
cell.textLabel?.text = data[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let alertController = UIAlertController(title: "Significado", message: message[indexPath.row], preferredStyle: .alert)
let actionConfirm = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(actionConfirm)
present(alertController, animated: true, completion: nil)
}
}
| apache-2.0 | 3af53936d2b4e900354116841e27ff73 | 32.426667 | 126 | 0.642601 | 4.249153 | false | false | false | false |
sclark01/Swift_VIPER_Demo | VIPER_Demo/VIPER_Demo/Modules/PeopleList/View/PeopleListViewController.swift | 1 | 1681 | import UIKit
class PeopleListViewController : UIViewController {
@IBOutlet weak var tableView: UITableView!
var eventHandler: PeopleListPresenterType?
fileprivate var peopleList: PeopleListDataModel?
override func viewDidLoad() {
eventHandler?.updateView()
navigationItem.title = "Contacts"
}
}
extension PeopleListViewController : PeopleListViewType {
func set(_ people: PeopleListDataModel) {
self.peopleList = people
tableView.reloadData()
}
}
extension PeopleListViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return peopleList?.sections ?? 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peopleList?.rows ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellID = "person"
let cell = tableView.dequeueReusableCell(withIdentifier: cellID) ?? UITableViewCell(style: .subtitle, reuseIdentifier: cellID)
if let person = peopleList?.personAt(index: (indexPath as NSIndexPath).row) {
cell.textLabel?.text = person.name
cell.detailTextLabel?.text = person.phone
}
return cell
}
}
extension PeopleListViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let person = peopleList?.personAt(index: (indexPath as NSIndexPath).row) {
eventHandler?.detailsForPerson(withId: person.id)
}
}
}
| mit | d31701a845e778b6b6908c2c5184f3b5 | 32.62 | 134 | 0.693635 | 5.172308 | false | false | false | false |
kingloveyy/SwiftBlog | SwiftNetWorking/Sources/SwiftNetWorking.swift | 1 | 3440 | //
// SwiftNetWorking.swift
// SwiftNetWorking
//
// Created by King on 15/3/9.
// Copyright (c) 2015年 king. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
}
public class SwiftNetWorking {
/// 定义闭包
public typealias Completion = ((resule: AnyObject?, error: NSError?)->())
/// 请求JSON
public func requestJSON(method: HTTPMethod, _ urlString: String, _ params: [String: String]?, completion: Completion) {
if let request = request(method, urlString, params) {
session?.dataTaskWithRequest(request, completionHandler: { (data, _, error) -> Void in
if error != nil {
completion(resule: nil, error: error)
return
}
// 反序列化 -> 字典或者数组
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil)
if json == nil {
let error = NSError(domain: SwiftNetWorking.errorDomain, code: -1, userInfo: ["error": "反序列化失败"])
}else {
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
completion(resule: json, error: nil)
})
}
}).resume()
return
}
let error = NSError(domain: SwiftNetWorking.errorDomain, code: -1, userInfo: ["error": "请求建立失败"])
completion(resule: nil, error: error)
}
static let errorDomain = "com.king.error"
/// 获取网络请求
///
/// :param: method 请求方法
/// :param: urlString urlString
/// :param: params 可选字典参数
///
/// :returns: 返回网络请求
func request(method: HTTPMethod, _ urlString: String, _ params: [String: String]?) -> NSURLRequest? {
if urlString.isEmpty {
return nil
}
var urlstr = urlString
var req: NSMutableURLRequest?
if method == .GET {
if let query = queryString(params) {
urlstr += "?" + query
}
req = NSMutableURLRequest(URL: NSURL(string: urlstr)!)
}else {
if let query = queryString(params) {
req = NSMutableURLRequest(URL: NSURL(string: urlString)!)
req?.HTTPMethod = method.rawValue
req?.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
}
}
return req
}
/// 生成查询字符串
///
/// :param: params 可选字典参数
///
/// :returns: 拼接字符串
func queryString(params: [String: String]?)->String? {
if params == nil {
return nil
}
var array = [String]()
for (k, v) in params! {
let str = k + "=" + v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
array.append(str)
}
return join("&", array)
}
public init() {}
/// 全局网络会话
lazy var session: NSURLSession? = {
return NSURLSession.sharedSession()
}()
} | mit | 6fa9f481dbbaf826f8bf708f30d82d56 | 28.123894 | 135 | 0.509119 | 4.838235 | false | false | false | false |
oceanfive/swift | swift_two/swift_two/Classes/View(controller)/Home/HYStatusContentView.swift | 1 | 1553 | //
// HYStatusContentView.swift
// swift_two
//
// Created by ocean on 16/6/20.
// Copyright © 2016年 ocean. All rights reserved.
//
import UIKit
class HYStatusContentView: UIView {
let originalView = HYOriginalStatusView()
let retweetedView = HYRetweetedStatusView()
var contentViewFrame = HYStatusContentFrame(){
willSet(newValue){
self.frame = newValue.frame!
originalView.originalStatusFrame = newValue.originalStatusFrame!
//MARK: - 这种方法会崩溃
// retweetedView.retweetedStatusFrame = newValue.retweetedStatusFrame!
//MARK: - 这里可以不需要再次进行判断,因为在frame模型中已经判断过了
if newValue.status.retweeted_status != nil {
retweetedView.retweetedStatusFrame = newValue.retweetedStatusFrame!
//MARK: - 在frame模型里面已经说明
retweetedView.hidden = false
}else {
retweetedView.hidden = true
}
// setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(originalView)
addSubview(retweetedView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | ee1e7188d8a45926b62addbc7e9ead90 | 19.942857 | 83 | 0.531378 | 5.055172 | false | false | false | false |
kumabook/MusicFav | MusicFav/YouTubePlaylistItemTableViewController.swift | 1 | 3073 | //
// YouTubePlaylistItemTableViewController.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 8/18/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import UIKit
import MusicFeeder
import ReactiveSwift
import YouTubeKit
class YouTubePlaylistItemTableViewController: TrackTableViewController {
var youtubePlaylist: YouTubeKit.Playlist!
var youtubePlaylistLoader: YouTubePlaylistLoader!
var observer: Disposable?
override var playlistType: PlaylistType {
return .thirdParty
}
init(playlist: YouTubeKit.Playlist, playlistLoader: YouTubePlaylistLoader) {
youtubePlaylist = playlist
youtubePlaylistLoader = playlistLoader
super.init(playlist: Playlist(id: youtubePlaylist.id, title: youtubePlaylist.title, tracks: []))
updateTracks()
}
override init(style: UITableViewStyle) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {}
override func viewDidLoad() {
observePlaylistLoader()
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observePlaylistLoader()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func observePlaylistLoader() {
observer?.dispose()
observer = youtubePlaylistLoader.signal.observeResult({ result in
guard let event = result.value else { return }
switch event {
case .startLoading:
self.showIndicator()
case .completeLoading:
self.hideIndicator()
self.updateTracks()
self.playlistQueue.enqueue(self.playlist)
self.tableView.reloadData()
self.fetchTrackDetails()
case .failToLoad:
break
}
})
tableView.reloadData()
}
func updateTracks() {
let tracks = youtubePlaylistLoader.itemsOfPlaylist[youtubePlaylist]?.map { $0.track } ?? []
_playlist = Playlist(id: youtubePlaylist.id, title: youtubePlaylist.title, tracks: tracks)
}
override func fetchTracks() {
youtubePlaylistLoader.fetchPlaylistItems(youtubePlaylist)
}
override func fetchTrackDetails() {
for track in tracks {
track.fetchPropertiesFromProviderIfNeed().on(
failed: { error in
self.tableView.reloadData()
}, completed: {
self.tableView.reloadData()
}, value: { (track: Track?) in
if let t = track {
if let index = self.tracks.index(of: t) {
self.tableView?.reloadRows(at: [IndexPath(item: index, section: 0)],
with: UITableViewRowAnimation.none)
}
}
return
}).start()
}
}
}
| mit | df16f4eec5df4f099c3c01d1349924ca | 29.425743 | 104 | 0.592255 | 5.130217 | false | false | false | false |
azfx/Sapporo | Sapporo/Sapporo+DelegateFlowLayout.swift | 1 | 2501 | //
// Sapporo+DelegateFlowLayout.swift
// Example
//
// Created by Le VanNghia on 6/29/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
import UIKit
extension Sapporo: UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if let cellmodel = self[indexPath], flowLayout = collectionViewLayout as? SAFlowLayout {
return flowLayout.collectionView(collectionView, sizeForCellModel: cellmodel)
}
return CGSize.zeroSize
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
if let sec = getSection(section), flowLayout = collectionViewLayout as? SAFlowLayout {
return flowLayout.collectionView(collectionView, insetForSection: sec)
}
return UIEdgeInsets()
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
if let sec = getSection(section), flowLayout = collectionViewLayout as? SAFlowLayout {
return flowLayout.collectionView(collectionView, minimumInteritemSpacingForSection: sec)
}
return 0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
if let sec = getSection(section), flowLayout = collectionViewLayout as? SAFlowLayout {
return flowLayout.collectionView(collectionView, minimumLineSpacingForSection: sec)
}
return 0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if let sec = getSection(section), flowLayout = collectionViewLayout as? SAFlowLayout {
return flowLayout.collectionView(collectionView, referenceSizeForFooterInSection: sec)
}
return CGSize.zeroSize
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if let sec = getSection(section), flowLayout = collectionViewLayout as? SAFlowLayout {
return flowLayout.collectionView(collectionView, referenceSizeForHeaderInSection: sec)
}
return CGSize.zeroSize
}
} | mit | bbba48b45232e38cc78f5330a6a13bf8 | 46.207547 | 182 | 0.808477 | 5.35546 | false | false | false | false |
MidnightPulse/Tabman | Example/Tabman-Example/SettingsItem.swift | 1 | 1413 | //
// SettingsItem.swift
// Tabman-Example
//
// Created by Merrick Sapsford on 27/02/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import Foundation
class SettingsItem: Any {
// MARK: Types
typealias SelectedValueLoad = () -> String?
enum CellType {
case toggle
case options(values: [String], selectedValue: SelectedValueLoad)
}
typealias ItemUpdateClosure = (_ value: Any) -> Void
// MARK: Properties
let type: CellType
let title: String
let description: String?
let update: ItemUpdateClosure
var value: Any?
// MARK: Init
init(type: CellType,
title: String,
description: String?,
value: Any?,
update: @escaping ItemUpdateClosure) {
self.type = type
self.title = title
self.description = description
self.value = value
self.update = update
}
}
extension SettingsItem.CellType {
var reuseIdentifier: String {
switch self {
case .toggle:
return "SettingsToggleCell"
case .options:
return "SettingsOptionCell"
}
}
}
extension SettingsItem: SettingsToggleCellDelegate {
func settingsToggleCell(_ cell: SettingsToggleCell, didUpdateValue value: Bool) {
self.value = value
update(value)
}
}
| mit | 8871ee379486440243123fc3840478d1 | 20.393939 | 85 | 0.597025 | 4.644737 | false | false | false | false |
nameghino/swift-algorithm-club | Hash Table/HashTable.swift | 2 | 4409 | /*
Hash table
Allows you to store and retrieve objects by a "key".
The key must be Hashable, which means it can be converted into a fairly
unique Int that represents the key as a number. The more unique the hash
value, the better.
The hashed version of the key is used to calculate an index into the array
of "buckets". The capacity of the hash table is how many of these buckets
it has. Ideally, the number of buckets is the same as the maximum number of
items you'll be storing in the HashTable, and each hash value maps to its
own bucket. In practice that is hard to achieve.
When there is more than one hash value that maps to the same bucket index
-- a "collision" -- they are chained together, using an array. (Note that
more clever ways exist for dealing with the chaining issue.)
While there are free buckets, inserting/retrieving/removing are O(1).
But when the buckets are full and the chains are long, using the hash table
becomes an O(n) operation.
Counting the size of the hash table is O(1) because we're caching the count.
The order of the elements in the hash table is undefined.
This implementation has a fixed capacity; it does not resize when the table
gets too full. (To do that, you'd allocate a larger array of buckets and then
insert each of the elements into that new array; this is necessary because
the hash values will now map to different bucket indexes.)
*/
public struct HashTable<Key: Hashable, Value> {
private typealias Element = (key: Key, value: Value)
private typealias Bucket = [Element]
private var buckets: [Bucket]
private(set) var count = 0
public init(capacity: Int) {
assert(capacity > 0)
buckets = .init(count: capacity, repeatedValue: [])
}
public var isEmpty: Bool {
return count == 0
}
private func indexForKey(key: Key) -> Int {
return abs(key.hashValue) % buckets.count
}
}
// MARK: - Basic operations
extension HashTable {
public subscript(key: Key) -> Value? {
get {
return valueForKey(key)
}
set {
if let value = newValue {
updateValue(value, forKey: key)
} else {
removeValueForKey(key)
}
}
}
public func valueForKey(key: Key) -> Value? {
let index = indexForKey(key)
for element in buckets[index] {
if element.key == key {
return element.value
}
}
return nil // key not in hash table
}
public mutating func updateValue(value: Value, forKey key: Key) -> Value? {
let index = indexForKey(key)
// Do we already have this key in the bucket?
for (i, element) in buckets[index].enumerate() {
if element.key == key {
let oldValue = element.value
buckets[index][i].value = value
return oldValue
}
}
// This key isn't in the bucket yet; add it to the chain.
buckets[index].append((key: key, value: value))
count += 1
return nil
}
public mutating func removeValueForKey(key: Key) -> Value? {
let index = indexForKey(key)
// Find the element in the bucket's chain and remove it.
for (i, element) in buckets[index].enumerate() {
if element.key == key {
buckets[index].removeAtIndex(i)
count -= 1
return element.value
}
}
return nil // key not in hash table
}
public mutating func removeAll() {
buckets = .init(count: buckets.count, repeatedValue: [])
count = 0
}
}
// MARK: - Helper methods for inspecting the hash table
extension HashTable {
public var keys: [Key] {
var a = [Key]()
for bucket in buckets {
for element in bucket {
a.append(element.key)
}
}
return a
}
public var values: [Value] {
var a = [Value]()
for bucket in buckets {
for element in bucket {
a.append(element.value)
}
}
return a
}
}
// MARK: - For debugging
extension HashTable: CustomStringConvertible {
public var description: String {
return buckets.flatMap { b in b.map { e in "\(e.key) = \(e.value)" } }.joinWithSeparator(", ")
}
}
extension HashTable: CustomDebugStringConvertible {
public var debugDescription: String {
var s = ""
for (i, bucket) in buckets.enumerate() {
s += "bucket \(i): " + bucket.map { e in "\(e.key) = \(e.value)" }.joinWithSeparator(", ") + "\n"
}
return s
}
}
| mit | 50e322b95b396c36b13c5131725b5e51 | 26.72956 | 103 | 0.645271 | 4.071099 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/Utilities/SynchronisedDictionary.swift | 1 | 3236 | //
// SynchronisedDictionary.swift
// Pelican
//
import Foundation
import Dispatch // Linux thing.
/**
A dictionary that allows for thread-safe concurrent access.
- warning: This is not yet feature complete, and only supports a small number
of the in-built methods and properties that a normal dictionary supports.
*/
public class SynchronisedDictionary<KeyType: Hashable, ValueType> {
typealias Key = KeyType
typealias Value = ValueType
/// The name of the dictionary, used when making the queue to identify it for debugging purposes.
public private(set) var name: String?
/// The internal dictionary that this class gates access to across threads.
private var internalDictionary: [KeyType: ValueType] = [:]
/// The queue used to order and execute read/write operations on the dictionary.
private let queue: DispatchQueue
init(name: String? = nil) {
self.name = name
var queueLabel = ""
if name != nil {
queueLabel = "com.Pelican.SynthronizedDictionary.\(name!)"
} else {
queueLabel = "com.Pelican.SynthronizedDictionary"
}
self.queue = DispatchQueue(label: queueLabel, attributes: .concurrent)
}
}
// MARK: - Properties
public extension SynchronisedDictionary {
/// The first element of the collection.
var first: (key: KeyType, value: ValueType)? {
var result: (key: KeyType, value: ValueType)?
queue.sync { result = self.internalDictionary.first }
return result
}
/// The number of elements in the dictionary.
var count: Int {
var result = 0
queue.sync { result = self.internalDictionary.count }
return result
}
/// A Boolean value indicating whether the collection is empty.
var isEmpty: Bool {
var result = false
queue.sync { result = self.internalDictionary.isEmpty }
return result
}
/// A textual representation of the dictionary and its elements.
var description: String {
var result = ""
queue.sync { result = self.internalDictionary.description }
return result
}
}
extension SynchronisedDictionary {
////////////////
// SUBSCRIPT
subscript(key: KeyType) -> ValueType? {
get {
var result: ValueType?
queue.sync {
result = internalDictionary[key]
}
return result
}
set {
guard let newValue = newValue else { return }
queue.async(flags: .barrier) {
self.internalDictionary[key] = newValue
}
}
}
}
// MARK: - Immutable
public extension SynchronisedDictionary {
/// Calls the given closure on each element in the sequence in the same order as a for-in loop.
///
/// - Parameter body: A closure that takes a key-value pair of the sequence as a parameter.
func forEach(_ body: ((key: KeyType, value: ValueType)) throws -> Void) rethrows {
try queue.sync { try self.internalDictionary.forEach(body) }
}
}
// MARK: - Mutable
public extension SynchronisedDictionary {
func removeValue(forKey key: KeyType, completion: ((ValueType?) -> Void)? = nil) {
queue.async(flags: .barrier) {
let value = self.internalDictionary.removeValue(forKey: key)
DispatchQueue.main.async {
completion?(value)
}
}
}
/// Removes all elements from the array.
///
func removeAll() {
queue.async(flags: .barrier) {
self.internalDictionary.removeAll()
}
}
}
| mit | 077c3c17d4a90b1d4a5e6b58a0da89ed | 23.515152 | 98 | 0.699011 | 3.767171 | false | false | false | false |
ajeferson/AJImageViewController | Pod/Classes/AJImageViewController.swift | 1 | 9410 | //
// ViewController.swift
// AJImageViewController
//
// Created by Alan Jeferson on 21/08/15.
// Copyright (c) 2015 AJWorks. All rights reserved.
//
import UIKit
public class AJImageViewController: UIViewController, UIScrollViewDelegate, UIViewControllerTransitioningDelegate {
var scrollView: UIScrollView!
public var dismissButton: UIButton!
var images = [UIImage]()
var urls = [NSURL]()
//Indicates where the images will be loaded from
private var loadType = AJImageViewControllerLoadType.LoadFromLocalImages
private var itensCount = 0
var pages = [AJScrollView?]()
var currentPage = 0
private var firstPage: Int!
var loadedPagesOffset = 1
let sideOffset: CGFloat = 10.0
var imageWidth: CGFloat!
var originalImageCenter: CGPoint!
public var enableSingleTapToDismiss: Bool = false {
didSet {
for scroll in self.pages {
scroll?.enableSingleTapGesture(self.enableSingleTapToDismiss)
}
}
}
private var transition = AJAwesomeTransition()
//MARK:- Init
public init(imageView: UIImageView, images: UIImage ...) {
super.init(nibName: nil, bundle: nil)
self.images = images
self.setupTransitionWith(imageView: imageView)
}
public init(imageView: UIImageView, urls: NSURL ...) {
super.init(nibName: nil, bundle: nil)
self.urls = urls
self.setupTransitionWith(imageView: imageView)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- View methods
override public func viewDidLoad() {
super.viewDidLoad()
self.firstPage = self.currentPage
self.transitioningDelegate = self
self.modalPresentationStyle = UIModalPresentationStyle.OverFullScreen
self.view.backgroundColor = UIColor.blackColor()
self.setupSuperSCrollView()
self.setupPagging()
self.addDismissButton()
}
func setupSuperSCrollView() -> Void {
self.scrollView = UIScrollView(frame: self.view.frame)
self.view.addSubview(self.scrollView)
self.scrollView.pagingEnabled = true
//Setup the side offset to give a blank space between each image
self.scrollView.frame.size.width += 2*self.sideOffset
self.scrollView.frame.origin.x -= self.sideOffset
}
//MARK:- Page Methods
/** Inits the arrays, the scroll view and the load type (local or from urls) */
func setupPagging() -> Void {
self.scrollView.delegate = self
//Setup load type
if self.images.count == 0 {
self.loadType = AJImageViewControllerLoadType.LoadFromUrls
}
//Counting the number of itens
self.setupItemCount()
//Create page holders
for _ in 0..<self.itensCount {
self.pages.append(nil)
}
//Setup scroll view
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width * CGFloat(self.itensCount), height: self.scrollView.frame.size.height)
self.scrollView.contentOffset.x = CGFloat(self.currentPage) * self.scrollView.frame.width
//Creates the current page and the - and + page offset
self.loadVisiblePages()
}
/** Loads a page */
func load(#page: Int) -> Void {
if page>=0 && page<self.itensCount {
if self.pages[page] == nil {
//Init inside image and scroll
var frame = self.scrollView.frame
frame.origin.x = CGFloat(page) * self.scrollView.frame.width
frame.origin.x += self.sideOffset
frame.size.width -= 2*self.sideOffset
var insideScroll: AJScrollView!
var imageForZooming: UIImageView
if self.loadType == AJImageViewControllerLoadType.LoadFromLocalImages {
insideScroll = AJScrollView(frame: frame, image: self.images[page])
} else {
insideScroll = AJScrollView(frame: frame, url: self.urls[page])
}
insideScroll.dismissBlock = self.dismissViewController
insideScroll.showDissmissButtonBlock = self.showDismissButton
insideScroll.superScroll = self.scrollView
insideScroll.tag = page
//Adding subviews
self.scrollView.addSubview(insideScroll)
self.pages[page] = insideScroll
}
}
}
/** Deallocates a page */
func purge(#page: Int) -> Void {
if page>=0 && page<self.itensCount {
if let pageView = self.pages[page] {
pageView.removeFromSuperview()
self.pages[page] = nil
}
}
}
/** Load the current and the offset pages. Purge the other ones */
func loadVisiblePages() -> Void {
let firstPage = self.currentPage - self.loadedPagesOffset
let lastPage = self.currentPage + self.loadedPagesOffset
//Dealocating pages
for var index = 0; index<firstPage; ++index {
self.purge(page: index)
}
//Allocating pages
for i in firstPage...lastPage {
self.load(page: i)
}
//Dealocating pages
for var index = lastPage+1; index<self.itensCount; ++index {
self.purge(page: index)
}
}
//MARK:- Dismiss button methods
/** Inits and adds the 'X' dismiss button */
private func addDismissButton() -> Void {
let buttonSize: CGFloat = 44.0
let buttonOffset: CGFloat = 5.0
let buttonInset: CGFloat = 12.0
self.dismissButton = UIButton(frame: CGRect(x: buttonOffset, y: buttonOffset, width: buttonSize, height: buttonSize))
self.dismissButton.contentEdgeInsets = UIEdgeInsets(top: buttonInset, left: buttonInset, bottom: buttonInset, right: buttonInset)
let podBundle = NSBundle(forClass: self.classForCoder)
if let bundlePath = podBundle.URLForResource("AJImageViewController", withExtension: "bundle"), bundle = NSBundle(URL: bundlePath), image = UIImage(named: "delete", inBundle: bundle, compatibleWithTraitCollection: nil) {
self.dismissButton.setImage(image, forState: UIControlState.Normal)
self.dismissButton.addTarget(self, action: Selector("dismissViewController"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(self.dismissButton)
}
}
/** Dismisses this view controller */
func dismissViewController() -> Void {
self.transition.referenceImageView = self.pages[self.currentPage]!.imageView
self.transition.imageWidth = self.imageWidth
if self.currentPage != self.firstPage {
self.transition.dismissalType = AJImageViewDismissalType.DisappearBottom
}
self.dismissViewControllerAnimated(true, completion: nil)
}
/** Hides/Shows the dismiss button */
func showDismissButton(show: Bool) -> Void {
if self.dismissButton.hidden != !show && !self.enableSingleTapToDismiss {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.dismissButton.alpha = show ? 1.0 : 0.0
}) { (_) -> Void in
self.dismissButton.hidden = !show
}
}
}
//MARK:- ScrollView delegate
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
var page = Int(self.scrollView.contentOffset.x / self.scrollView.frame.width)
if page != self.currentPage {
self.currentPage = page
self.loadVisiblePages()
}
self.transition.showOriginalImage(self.currentPage != self.firstPage)
}
//MARK:- Transition Delegate
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.transition
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.transition
}
//MARK:- Transition methods
/** Inits the transition */
private func setupTransitionWith(#imageView: UIImageView) -> Void {
self.imageWidth = imageView.frame.size.width //Original image width
self.originalImageCenter = imageView.center
self.transition.referenceImageView = imageView
self.transition.imageWidth = self.view.frame.size.width
}
//MARK:- Other
/** Counts the itens based on the load type */
private func setupItemCount() -> Void {
if self.loadType == AJImageViewControllerLoadType.LoadFromLocalImages {
self.itensCount = self.images.count
} else {
self.itensCount = self.urls.count
}
}
override public func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 04bf9c2b36c3795707a9add0c2296af6 | 35.614786 | 228 | 0.619129 | 5.070043 | false | false | false | false |
andreamazz/AMPopTip | Source/PopTip.swift | 1 | 41682 | //
// PopTip.swift
// AMPopTip
//
// Created by Andrea Mazzini on 01/05/2017.
// Copyright © 2017 Andrea Mazzini. All rights reserved.
//
import UIKit
// NOTE: workaround for an Xcode 13 compile issue
// #if canImport(SwiftUI) && canImport(Combine)
#if !(os(iOS) && (arch(i386) || arch(arm)))
import SwiftUI
#endif
//public enum PopTipAxis {
// case
//}
/// Enum that specifies the direction of the poptip
public enum PopTipDirection {
/// Up, the poptip will appear above the element, arrow pointing down
case up
/// Down, the poptip will appear below the element, arrow pointing up
case down
/// Left, the poptip will appear on the left of the element, arrow pointing right
case left
/// Right, the poptip will appear on the right of the element, arrow pointing left
case right
/// Automatic, the poptip will decide where to pop by checking the available space
case auto
/// Automatic in the horizontal axis, the poptip will decide where to pop by checking the available space left and right
case autoHorizontal
/// Automatic in the vertical axis, the poptip will decide where to pop by checking the available space top and bottom
case autoVertical
/// None, the poptip will appear above the element with no arrow
case none
var isAuto: Bool {
return self == .autoVertical || self == .autoHorizontal || self == .auto
}
}
/** Enum that specifies the type of entrance animation. Entrance animations are performed while showing the poptip.
- `scale`: The poptip scales from 0% to 100%
- `transitions`: The poptip moves in position from the edge of the screen
- `fadeIn`: The poptip fade in
- `custom`: The Animation is provided by the user
- `none`: No Animation
*/
public enum PopTipEntranceAnimation {
/// The poptip scales from 0% to 100%
case scale
/// The poptip moves in position from the edge of the screen
case transition
/// The poptip fades in
case fadeIn
/// The Animation is provided by the user
case custom
/// No Animation
case none
}
/** Enum that specifies the type of entrance animation. Entrance animations are performed while showing the poptip.
- `scale`: The poptip scales from 100% to 0%
- `fadeOut`: The poptip fade out
- `custom`: The Animation is provided by the user
- `none`: No Animation
*/
public enum PopTipExitAnimation {
/// The poptip scales from 100% to 0%
case scale
/// The poptip fades out
case fadeOut
/// The Animation is provided by the user
case custom
/// No Animation
case none
}
/** Enum that specifies the type of action animation. Action animations are performed after the poptip is visible and the entrance animation completed.
- `bounce(offset: CGFloat?)`: The poptip bounces following its direction. The bounce offset can be provided optionally
- `float(offset: CGFloat?)`: The poptip floats in place. The float offset can be provided optionally
- `pulse(offset: CGFloat?)`: The poptip pulsates by changing its size. The maximum amount of pulse increase can be provided optionally
- `none`: No animation
*/
public enum PopTipActionAnimation {
/// The poptip bounces following its direction. The bounce offset can be provided optionally
case bounce(CGFloat?)
/// The poptip floats in place. The float offset can be provided optionally. Defaults to 8 points
case float(offsetX: CGFloat?, offsetY: CGFloat?)
/// The poptip pulsates by changing its size. The maximum amount of pulse increase can be provided optionally. Defaults to 1.1 (110% of the original size)
case pulse(CGFloat?)
/// No animation
case none
}
private let DefaultBounceOffset = CGFloat(8)
private let DefaultFloatOffset = CGFloat(8)
private let DefaultPulseOffset = CGFloat(1.1)
open class PopTip: UIView {
/// The text displayed by the poptip. Can be updated once the poptip is visible
open var text: String? {
didSet {
accessibilityLabel = text
setNeedsLayout()
}
}
/// The `UIFont` used in the poptip's text
open var font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
/// The `UIColor` of the text
@objc open dynamic var textColor = UIColor.white
/// The `NSTextAlignment` of the text
@objc open dynamic var textAlignment = NSTextAlignment.center
/// The `UIColor` for the poptip's background. If `bubbleLayer` is specificed, this will be ignored
@objc open dynamic var bubbleColor = UIColor.red
/// The `CALayer` generator closure for poptip's sublayer 0. If nil, the bubbleColor will be used as solid fill
@objc open dynamic var bubbleLayerGenerator: ((_ path: UIBezierPath) -> CALayer?)?
/// The `UIColor` for the poptip's border
@objc open dynamic var borderColor = UIColor.clear
/// The width for the poptip's border
@objc open dynamic var borderWidth = CGFloat(0.0)
/// The `Double` with the poptip's border radius
@objc open dynamic var cornerRadius = CGFloat(4.0)
/// The `BOOL` that determines wether the poptip is rounded. If set to `true` the radius will equal `frame.height / 2`
@objc open dynamic var isRounded = false
/// The `UIColor` with the poptip's shadow color
@objc open dynamic var shadowColor: UIColor = .clear
/// The `CGSize` with the poptip's shadow offset
@objc open dynamic var shadowOffset: CGSize = .zero
/// The `Float` with the poptip's shadow radius
@objc open dynamic var shadowRadius: Float = 0
/// The `Float` with the poptip's shadow opacity
@objc open dynamic var shadowOpacity: Float = 0
/// Holds the offset between the poptip and origin
@objc open dynamic var offset = CGFloat(0.0)
/// Holds the CGFloat with the padding used for the inner text
@objc open dynamic var padding = CGFloat(6.0)
/// Holds the insets setting for padding different direction
@objc open dynamic var edgeInsets = UIEdgeInsets.zero
/// Holds the CGSize with the width and height of the arrow
@objc open dynamic var arrowSize = CGSize(width: 8, height: 8)
/// CGfloat value that determines the radius of the vertex for the pointing arrow
@objc open dynamic var arrowRadius = CGFloat(0.0)
/// Holds the NSTimeInterval with the duration of the revealing animation
@objc open dynamic var animationIn: TimeInterval = 0.4
/// Holds the NSTimeInterval with the duration of the disappearing animation
@objc open dynamic var animationOut: TimeInterval = 0.2
/// Holds the NSTimeInterval with the delay of the revealing animation
@objc open dynamic var delayIn: TimeInterval = 0
/// Holds the NSTimeInterval with the delay of the disappearing animation
@objc open dynamic var delayOut: TimeInterval = 0
/// Holds the enum with the type of entrance animation (triggered once the poptip is shown)
open var entranceAnimation = PopTipEntranceAnimation.scale
/// Holds the enum with the type of exit animation (triggered once the poptip is dismissed)
open var exitAnimation = PopTipExitAnimation.scale
/// Holds the enum with the type of action animation (triggered once the poptip is shown)
open var actionAnimation = PopTipActionAnimation.none
/// Holds the NSTimeInterval with the duration of the action animation
@objc open dynamic var actionAnimationIn: TimeInterval = 1.2
/// Holds the NSTimeInterval with the duration of the action stop animation
@objc open dynamic var actionAnimationOut: TimeInterval = 1.0
/// Holds the NSTimeInterval with the delay of the action animation
@objc open dynamic var actionDelayIn: TimeInterval = 0
/// Holds the NSTimeInterval with the delay of the action animation stop
@objc open dynamic var actionDelayOut: TimeInterval = 0
/// CGfloat value that determines the leftmost margin from the screen
@objc open dynamic var edgeMargin = CGFloat(0.0)
/// Holds the offset between the bubble and origin
@objc open dynamic var bubbleOffset = CGFloat(0.0)
/// Holds the offset between the center of the bubble and the arrow
@objc open dynamic var arrowOffset = CGFloat(0.0)
/// Color of the mask that is going to dim the background when the pop up is visible
@objc open dynamic var maskColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
/// Flag to enable or disable background mask
@objc open dynamic var shouldShowMask = false
/// Flag to enable or disable cutout mask
@objc open dynamic var shouldCutoutMask = false
/// The path to use for the cutout path when the the pop up is visible
@objc open dynamic var cutoutPathGenerator: (_ from: CGRect) -> UIBezierPath = { from in
UIBezierPath(roundedRect: from.insetBy(dx: -8, dy: -8), byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 8, height: 8))
}
/// Flag to enable or disable the checks that make sure that the tip does not extend over the container
@objc open dynamic var constrainInContainerView = true
/// Holds the CGrect with the rect the tip is pointing to
open var from = CGRect.zero {
didSet {
setup()
}
}
/// Holds the readonly BOOL with the poptip visiblity. The poptip is considered visible as soon as
/// the animation is complete, and invisible when the subview is removed from its parent.
open var isVisible: Bool { get { return self.superview != nil } }
/// A boolean value that determines whether the poptip is dismissed on tap.
@objc open dynamic var shouldDismissOnTap = true
/// A boolean value that determines whether to dismiss when tapping outside the poptip.
@objc open dynamic var shouldDismissOnTapOutside = true
/// A boolean value that determines whether to consider the originating frame as part of the poptip,
/// i.e wether to call the `tapHandler` or the `tapOutsideHandler` when the tap occurs in the `from` frame.
@objc open dynamic var shouldConsiderOriginatingFrameAsPopTip = false
/// A boolean value that determines whether to consider the cutout area as separately to outside,
/// i.e wether to call the `tapOutsideHandler` or the `tapCutoutHandler` when the tap occurs in the `from` frame.
@objc open dynamic var shouldConsiderCutoutTapSeparately = false
/// A boolean value that determines whether to dismiss when swiping outside the poptip.
@objc open dynamic var shouldDismissOnSwipeOutside = false
/// A boolean value that determines if the action animation should start automatically when the poptip is shown
@objc open dynamic var startActionAnimationOnShow = true
/// A direction that determines what swipe direction to dismiss when swiping outside the poptip.
/// The default direction is `right`
open var swipeRemoveGestureDirection = UISwipeGestureRecognizer.Direction.right {
didSet {
swipeGestureRecognizer?.direction = swipeRemoveGestureDirection
}
}
/// A block that will be fired when the user taps the poptip.
open var tapHandler: ((PopTip) -> Void)?
/// A block that will be fired when the user taps outside the poptip.
open var tapOutsideHandler: ((PopTip) -> Void)?
/// A block that will be fired when the user taps the cutout area, only applicable is shouldShowMask and shouldCutoutMask are true.
open var tapCutoutHandler: ((PopTip) -> Void)?
/// A block that will be fired when the user swipes outside the poptip.
open var swipeOutsideHandler: ((PopTip) -> Void)?
/// A block that will be fired when the poptip appears.
open var appearHandler: ((PopTip) -> Void)?
/// A block that will be fired when the poptip is dismissed.
open var dismissHandler: ((PopTip) -> Void)?
/// A block that handles the entrance animation of the poptip. Should be provided
/// when using a `PopTipActionAnimationCustom` entrance animation type.
/// Please note that the poptip will be automatically added as a subview before firing the block
/// Remember to call the completion block provided
open var entranceAnimationHandler: ((@escaping () -> Void) -> Void)?
/// A block block that handles the exit animation of the poptip. Should be provided
/// when using a `AMPopTipActionAnimationCustom` exit animation type.
/// Remember to call the completion block provided
open var exitAnimationHandler: ((@escaping () -> Void) -> Void)?
/// The CGPoint originating the arrow. Read only.
open private(set) var arrowPosition = CGPoint.zero
/// A read only reference to the view containing the poptip
open private(set) weak var containerView: UIView?
/// The direction from which the poptip is shown. Read only.
open private(set) var direction = PopTipDirection.none
/// Holds the readonly BOOL with the poptip animation state.
open private(set) var isAnimating: Bool = false
/// The view that dims the background (including the button that triggered PopTip.
/// The mask by appears with fade in effect only.
open private(set) var backgroundMask: UIView?
/// The tap gesture recognizer. Read-only.
open private(set) var tapGestureRecognizer: UITapGestureRecognizer?
/// The tap remove gesture recognizer. Read-only.
open private(set) var tapToRemoveGestureRecognizer: UITapGestureRecognizer?
fileprivate var attributedText: NSAttributedString?
fileprivate var paragraphStyle = NSMutableParagraphStyle()
fileprivate var swipeGestureRecognizer: UISwipeGestureRecognizer?
fileprivate var dismissTimer: Timer?
fileprivate var textBounds = CGRect.zero
fileprivate var maxWidth = CGFloat(0)
fileprivate var customView: UIView?
fileprivate var hostingController: UIViewController?
fileprivate var isApplicationInBackground: Bool?
fileprivate var bubbleLayer: CALayer? {
willSet {
bubbleLayer?.removeFromSuperlayer()
}
}
fileprivate var label: UILabel = {
let label = UILabel()
label.numberOfLines = 0
return label
}()
private var shouldBounce = false
/// Setup a poptip oriented vertically (direction .up or .down). Returns the bubble frame and the arrow position
///
/// - Returns: a tuple with the bubble frame and the arrow position
internal func setupVertically() -> (CGRect, CGPoint) {
guard let containerView = containerView else { return (CGRect.zero, CGPoint.zero) }
var frame = CGRect.zero
let offset = self.offset * (direction == .up ? -1 : 1)
frame.size = CGSize(width: textBounds.width + padding * 2 + edgeInsets.horizontal, height: textBounds.height + padding * 2 + edgeInsets.vertical + arrowSize.height)
var x = from.origin.x + from.width / 2 - frame.width / 2
if x < 0 { x = edgeMargin }
if constrainInContainerView && (x + frame.width > containerView.bounds.width) {
x = containerView.bounds.width - frame.width - edgeMargin
}
if direction == .down {
frame.origin = CGPoint(x: x, y: from.origin.y + from.height + offset)
} else {
frame.origin = CGPoint(x: x, y: from.origin.y - frame.height + offset)
}
// Constraint the offset in the boundaries of the bubble, maintaining the sign (hence the arrowOffset / arrowOffset)
let constrainedArrowOffset = abs(arrowOffset) > (frame.size.width / 2) ? ((arrowOffset / arrowOffset) * (frame.size.width / 2 - cornerRadius * 2)) : arrowOffset
// Make sure that the bubble doesn't leave the boundaries of the view
var arrowPosition = CGPoint(
x: from.origin.x + from.width / 2 - frame.origin.x - constrainedArrowOffset,
y: (direction == .up) ? frame.height : from.origin.y + from.height - frame.origin.y + offset
)
if bubbleOffset > 0 && arrowPosition.x < bubbleOffset {
bubbleOffset = arrowPosition.x - arrowSize.width
} else if bubbleOffset < 0 && frame.width < abs(bubbleOffset) {
bubbleOffset = -(arrowPosition.x - arrowSize.width)
} else if bubbleOffset < 0 && (frame.origin.x - arrowPosition.x) < abs(bubbleOffset) {
bubbleOffset = -(arrowSize.width + edgeMargin)
}
if constrainInContainerView {
// Make sure that the bubble doesn't leave the boundaries of the view
let leftSpace = frame.origin.x - containerView.frame.origin.x
let rightSpace = containerView.frame.width - leftSpace - frame.width
if bubbleOffset < 0 && leftSpace < abs(bubbleOffset) {
bubbleOffset = -leftSpace + edgeMargin
} else if bubbleOffset > 0 && rightSpace < bubbleOffset {
bubbleOffset = rightSpace - edgeMargin
}
}
frame.origin.x += bubbleOffset
frame.size = CGSize(width: frame.width + borderWidth * 2, height: frame.height + borderWidth * 2)
// Only when the tip is not constrained, make sure to center the frame if the containerView is smaller than the tip
if containerView.frame.width < frame.width, !constrainInContainerView {
frame.origin.x = -frame.width / 2 + containerView.frame.width / 2
arrowPosition.x += frame.width / 2 - containerView.frame.width / 2
}
return (frame, arrowPosition)
}
/// Setup a poptip oriented horizontally (direction .left or .right). Returns the bubble frame and the arrow position
///
/// - Returns: a tuple with the bubble frame and the arrow position
internal func setupHorizontally() -> (CGRect, CGPoint) {
guard let containerView = containerView else { return (CGRect.zero, CGPoint.zero) }
var frame = CGRect.zero
let offset = self.offset * (direction == .left ? -1 : 1)
frame.size = CGSize(width: textBounds.width + padding * 2 + edgeInsets.horizontal + arrowSize.height, height: textBounds.height + padding * 2 + edgeInsets.vertical)
let x = direction == .left ? from.origin.x - frame.width + offset : from.origin.x + from.width + offset
var y = from.origin.y + from.height / 2 - frame.height / 2
if y < 0 { y = edgeMargin }
// Make sure we stay in the view limits except if it has scroll then it must be inside contentview limits not the view
if let containerScrollView = containerView as? UIScrollView {
if y + frame.height > containerScrollView.contentSize.height {
y = containerScrollView.contentSize.height - frame.height - edgeMargin
}
} else {
if y + frame.height > containerView.bounds.height && constrainInContainerView {
y = containerView.bounds.height - frame.height - edgeMargin
}
}
frame.origin = CGPoint(x: x, y: y)
// Constraint the offset in the boundaries of the bubble, maintaining the sign (hence the arrowOffset / arrowOffset)
let constrainedArrowOffset = abs(arrowOffset) > (frame.size.height / 2) ? ((arrowOffset / arrowOffset) * (frame.size.height / 2 - cornerRadius * 2)) : arrowOffset
// Make sure that the bubble doesn't leave the boundaries of the view
let arrowPosition = CGPoint(
x: direction == .left ? from.origin.x - frame.origin.x + offset : from.origin.x + from.width - frame.origin.x + offset,
y: from.origin.y + from.height / 2 - frame.origin.y - constrainedArrowOffset
)
if bubbleOffset > 0 && arrowPosition.y < bubbleOffset {
bubbleOffset = arrowPosition.y - arrowSize.width
} else if bubbleOffset < 0 && frame.height < abs(bubbleOffset) {
bubbleOffset = -(arrowPosition.y - arrowSize.height)
}
if constrainInContainerView {
let topSpace = frame.origin.y - containerView.frame.origin.y
let bottomSpace = containerView.frame.height - topSpace - frame.height
if bubbleOffset < 0 && topSpace < abs(bubbleOffset) {
bubbleOffset = -topSpace + edgeMargin
} else if bubbleOffset > 0 && bottomSpace < bubbleOffset {
bubbleOffset = bottomSpace - edgeMargin
}
}
frame.origin.y += bubbleOffset
frame.size = CGSize(width: frame.width + borderWidth * 2, height: frame.height + borderWidth * 2)
return (frame, arrowPosition)
}
/// Checks if the rect with positioning `.none` is inside the container
internal func rectContained(rect: CGRect) -> CGRect {
guard let containerView = containerView, constrainInContainerView else { return rect }
var finalRect = rect
// The `.none` positioning implies a rect with the origin in the middle of the poptip
if (rect.origin.x) < containerView.frame.origin.x {
finalRect.origin.x = edgeMargin
}
if (rect.origin.y) < containerView.frame.origin.y {
finalRect.origin.y = edgeMargin
}
if (rect.origin.x + rect.width) > (containerView.frame.origin.x + containerView.frame.width) {
finalRect.origin.x = containerView.frame.origin.x + containerView.frame.width - rect.width - edgeMargin
}
if (rect.origin.y + rect.height) > (containerView.frame.origin.y + containerView.frame.height) {
finalRect.origin.y = containerView.frame.origin.y + containerView.frame.height - rect.height - edgeMargin
}
return finalRect
}
fileprivate func textBounds(for text: String?, attributedText: NSAttributedString?, view: UIView?, with font: UIFont, padding: CGFloat, edges: UIEdgeInsets, in maxWidth: CGFloat) -> CGRect {
var bounds = CGRect.zero
if let text = text {
bounds = NSString(string: text).boundingRect(with: CGSize(width: maxWidth, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
}
if let attributedText = attributedText {
bounds = attributedText.boundingRect(with: CGSize(width: maxWidth, height: CGFloat.infinity), options: .usesLineFragmentOrigin, context: nil)
}
if let view = view {
bounds = view.frame
}
bounds.origin = CGPoint(x: padding + edges.left, y: padding + edges.top)
return bounds.integral
}
fileprivate func setup() {
guard let containerView = containerView else { return }
var rect = CGRect.zero
backgroundColor = .clear
// Decide the direction if not specified
if direction.isAuto {
var spaces: [PopTipDirection: CGFloat] = [:]
if direction == .autoHorizontal || direction == .auto {
spaces[.left] = from.minX - containerView.frame.minX
spaces[.right] = containerView.frame.maxX - from.maxX
}
if direction == .autoVertical || direction == .auto {
spaces[.up] = from.minY - containerView.frame.minY
spaces[.down] = containerView.frame.maxY - from.maxY
}
direction = spaces.sorted(by: { $0.1 > $1.1 }).first!.key
}
if direction == .left {
maxWidth = CGFloat.minimum(maxWidth, from.origin.x - padding * 2 - edgeInsets.horizontal - arrowSize.width)
}
if direction == .right {
maxWidth = CGFloat.minimum(maxWidth, containerView.bounds.width - from.origin.x - from.width - padding * 2 - edgeInsets.horizontal - arrowSize.width)
}
textBounds = textBounds(for: text, attributedText: attributedText, view: customView, with: font, padding: padding, edges: edgeInsets, in: maxWidth)
switch direction {
case .auto, .autoHorizontal, .autoVertical: break // The decision will be made at this point
case .up:
let dimensions = setupVertically()
rect = dimensions.0
arrowPosition = dimensions.1
let anchor = arrowPosition.x / rect.size.width
layer.anchorPoint = CGPoint(x: anchor, y: 1)
layer.position = CGPoint(x: layer.position.x + rect.width * anchor, y: layer.position.y + rect.height / 2)
case .down:
let dimensions = setupVertically()
rect = dimensions.0
arrowPosition = dimensions.1
let anchor = arrowPosition.x / rect.size.width
textBounds.origin = CGPoint(x: textBounds.origin.x, y: textBounds.origin.y + arrowSize.height)
layer.anchorPoint = CGPoint(x: anchor, y: 0)
layer.position = CGPoint(x: layer.position.x + rect.width * anchor, y: layer.position.y - rect.height / 2)
case .left:
let dimensions = setupHorizontally()
rect = dimensions.0
arrowPosition = dimensions.1
let anchor = arrowPosition.y / rect.height
layer.anchorPoint = CGPoint(x: 1, y: anchor)
layer.position = CGPoint(x: layer.position.x - rect.width / 2, y: layer.position.y + rect.height * anchor)
case .right:
let dimensions = setupHorizontally()
rect = dimensions.0
arrowPosition = dimensions.1
textBounds.origin = CGPoint(x: textBounds.origin.x + arrowSize.height, y: textBounds.origin.y)
let anchor = arrowPosition.y / rect.height
layer.anchorPoint = CGPoint(x: 0, y: anchor)
layer.position = CGPoint(x: layer.position.x + rect.width / 2, y: layer.position.y + rect.height * anchor)
case .none:
rect.size = CGSize(width: textBounds.width + padding * 2.0 + edgeInsets.horizontal + borderWidth * 2, height: textBounds.height + padding * 2.0 + edgeInsets.vertical + borderWidth * 2)
rect.origin = CGPoint(x: from.midX - rect.size.width / 2, y: from.midY - rect.height / 2)
rect = rectContained(rect: rect)
arrowPosition = CGPoint.zero
layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
layer.position = CGPoint(x: from.midX, y: from.midY)
}
label.frame = textBounds
if label.superview == nil {
addSubview(label)
}
frame = rect
if let customView = customView {
customView.frame = textBounds
}
if !shouldShowMask {
backgroundMask?.removeFromSuperview()
} else {
if backgroundMask == nil {
backgroundMask = UIView()
}
backgroundMask?.frame = containerView.bounds
}
setNeedsDisplay()
if tapGestureRecognizer == nil {
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PopTip.handleTap(_:)))
tapGestureRecognizer?.cancelsTouchesInView = false
self.addGestureRecognizer(tapGestureRecognizer!)
}
if shouldDismissOnTapOutside && tapToRemoveGestureRecognizer == nil {
tapToRemoveGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PopTip.handleTapOutside(_:)))
}
if shouldDismissOnSwipeOutside && swipeGestureRecognizer == nil {
swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(PopTip.handleSwipeOutside(_:)))
swipeGestureRecognizer?.direction = swipeRemoveGestureDirection
}
if isApplicationInBackground == nil {
NotificationCenter.default.addObserver(self, selector: #selector(PopTip.handleApplicationActive), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(PopTip.handleApplicationResignActive), name: UIApplication.willResignActiveNotification, object: nil)
}
}
/// Custom draw override
///
/// - Parameter rect: the rect occupied by the view
open override func draw(_ rect: CGRect) {
if isRounded {
let showHorizontally = direction == .left || direction == .right
cornerRadius = (frame.size.height - (showHorizontally ? 0 : arrowSize.height)) / 2
}
let path = PopTip.pathWith(rect: rect, frame: frame, direction: direction, arrowSize: arrowSize, arrowPosition: arrowPosition, arrowRadius: arrowRadius, borderWidth: borderWidth, radius: cornerRadius)
layer.shadowOpacity = shadowOpacity
layer.shadowRadius = CGFloat(shadowRadius)
layer.shadowOffset = shadowOffset
layer.shadowColor = shadowColor.cgColor
if let bubbleLayerGenerator = self.bubbleLayerGenerator, let bubbleLayer = bubbleLayerGenerator(path) {
self.bubbleLayer = bubbleLayer
layer.insertSublayer(bubbleLayer, at: 0)
} else {
bubbleLayer = nil
bubbleColor.setFill()
path.fill()
}
borderColor.setStroke()
path.lineWidth = borderWidth
path.stroke()
paragraphStyle.alignment = textAlignment
let titleAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: textColor
]
if let text = text {
label.attributedText = NSAttributedString(string: text, attributes: titleAttributes)
} else if let text = attributedText {
label.attributedText = text
} else {
label.attributedText = nil
}
}
/// Shows an animated poptip in a given view, from a given rectangle. The property `isVisible` will be `true` as soon as the poptip is added to the given view.
///
/// - Parameters:
/// - text: The text to display
/// - direction: The direction of the poptip in relation to the element that generates it
/// - maxWidth: The maximum width of the poptip. If the poptip won't fit in the given space, this will be overridden.
/// - view: The view that will hold the poptip as a subview.
/// - frame: The originating frame. The poptip's arrow will point to the center of this frame.
/// - duration: Optional time interval that determines when the poptip will self-dismiss.
open func show(text: String, direction: PopTipDirection, maxWidth: CGFloat, in view: UIView, from frame: CGRect, duration: TimeInterval? = nil) {
resetView()
attributedText = nil
self.text = text
accessibilityLabel = text
self.direction = direction
containerView = view
self.maxWidth = maxWidth
customView?.removeFromSuperview()
customView = nil
label.isHidden = false
from = frame
show(duration: duration)
}
/// Shows an animated poptip in a given view, from a given rectangle. The property `isVisible` will be `true` as soon as the poptip is added to the given view.
///
/// - Parameters:
/// - attributedText: The attributed string to display
/// - direction: The direction of the poptip in relation to the element that generates it
/// - maxWidth: The maximum width of the poptip. If the poptip won't fit in the given space, this will be overridden.
/// - view: The view that will hold the poptip as a subview.
/// - frame: The originating frame. The poptip's arrow will point to the center of this frame.
/// - duration: Optional time interval that determines when the poptip will self-dismiss.
open func show(attributedText: NSAttributedString, direction: PopTipDirection, maxWidth: CGFloat, in view: UIView, from frame: CGRect, duration: TimeInterval? = nil) {
resetView()
text = nil
self.attributedText = attributedText
accessibilityLabel = attributedText.string
self.direction = direction
containerView = view
self.maxWidth = maxWidth
customView?.removeFromSuperview()
customView = nil
label.isHidden = false
from = frame
show(duration: duration)
}
/// Shows an animated poptip in a given view, from a given rectangle. The property `isVisible` will be `true` as soon as the poptip is added to the given view.
///
/// - Parameters:
/// - customView: A custom view
/// - direction: The direction of the poptip in relation to the element that generates it
/// - view: The view that will hold the poptip as a subview.
/// - frame: The originating frame. The poptip's arrow will point to the center of this frame.
/// - duration: Optional time interval that determines when the poptip will self-dismiss.
open func show(customView: UIView, direction: PopTipDirection, in view: UIView, from frame: CGRect, duration: TimeInterval? = nil) {
resetView()
text = nil
attributedText = nil
self.direction = direction
containerView = view
maxWidth = customView.frame.size.width
self.customView?.removeFromSuperview()
self.customView = customView
label.isHidden = true
addSubview(customView)
from = frame
show(duration: duration)
}
// #if canImport(SwiftUI) && canImport(Combine)
#if !(os(iOS) && (arch(i386) || arch(arm)))
/// Shows an animated poptip in a given view, from a given rectangle. The property `isVisible` will be `true` as soon as the poptip is added to the given view.
///
/// - Parameters:
/// - rootView: A SwiftUI view
/// - direction: The direction of the poptip in relation to the element that generates it
/// - view: The view that will hold the poptip as a subview.
/// - frame: The originating frame. The poptip's arrow will point to the center of this frame.
/// - parent: The controller that holds the view that will hold the poptip. Needed as SwiftUI views have to be embed in a child UIHostingController.
/// - duration: Optional time interval that determines when the poptip will self-dismiss.
@available(iOS 13.0, *)
open func show<V: View>(rootView: V, direction: PopTipDirection, in view: UIView, from frame: CGRect, parent: UIViewController, duration: TimeInterval? = nil) {
resetView()
text = nil
attributedText = nil
self.direction = direction
containerView = view
let controller = UIHostingController(rootView: rootView)
controller.view.backgroundColor = .clear
let maxContentWidth = UIScreen.main.bounds.width - (self.edgeMargin * 2) - self.edgeInsets.horizontal - (self.padding * 2)
let sizeThatFits = controller.view.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.greatestFiniteMagnitude))
controller.view.frame.size = CGSize(width: min(sizeThatFits.width, maxContentWidth), height: sizeThatFits.height)
maxWidth = controller.view.frame.size.width
self.customView?.removeFromSuperview()
self.customView = controller.view
parent.addChild(controller)
addSubview(controller.view)
controller.didMove(toParent: parent)
controller.view.layoutIfNeeded()
from = frame
hostingController = controller
show(duration: duration)
}
#endif
/// Update the current text
///
/// - Parameter text: the new text
open func update(text: String) {
self.text = text
updateBubble()
}
/// Update the current text
///
/// - Parameter attributedText: the new attributs string
open func update(attributedText: NSAttributedString) {
self.attributedText = attributedText
updateBubble()
}
/// Update the current text
///
/// - Parameter customView: the new custom view
open func update(customView: UIView) {
self.customView = customView
updateBubble()
}
/// Hides the poptip and removes it from the view. The property `isVisible` will be set to `false` when the animation is complete and the poptip is removed from the parent view.
///
/// - Parameter forced: Force the removal, ignoring running animations
@objc open func hide(forced: Bool = false) {
if !forced && isAnimating {
return
}
resetView()
isAnimating = true
dismissTimer?.invalidate()
dismissTimer = nil
if let gestureRecognizer = tapToRemoveGestureRecognizer {
containerView?.removeGestureRecognizer(gestureRecognizer)
}
if let gestureRecognizer = swipeGestureRecognizer {
containerView?.removeGestureRecognizer(gestureRecognizer)
}
let completion = {
self.hostingController?.willMove(toParent: nil)
self.customView?.removeFromSuperview()
self.hostingController?.removeFromParent()
self.customView = nil
self.dismissActionAnimation()
self.bubbleLayer = nil
self.backgroundMask?.removeFromSuperview()
self.backgroundMask?.subviews.forEach { $0.removeFromSuperview() }
self.removeFromSuperview()
self.layer.removeAllAnimations()
self.transform = .identity
self.isAnimating = false
self.dismissHandler?(self)
}
if isApplicationInBackground ?? false {
completion()
} else {
performExitAnimation(completion: completion)
}
}
/// Makes the poptip perform the action indefinitely. The action animation calls for the user's attention after the poptip is shown
open func startActionAnimation() {
performActionAnimation()
}
/// Stops the poptip action animation. Does nothing if the poptip wasn't animating in the first place.
///
/// - Parameter completion: Optional completion block clled once the animation is completed
open func stopActionAnimation(_ completion: (() -> Void)? = nil) {
dismissActionAnimation(completion)
}
fileprivate func resetView() {
CATransaction.begin()
layer.removeAllAnimations()
CATransaction.commit()
transform = .identity
shouldBounce = false
}
fileprivate func updateBubble() {
stopActionAnimation {
UIView.animate(withDuration: 0.2, delay: 0, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: {
self.setup()
let path = PopTip.pathWith(rect: self.frame, frame: self.frame, direction: self.direction, arrowSize: self.arrowSize, arrowPosition: self.arrowPosition, arrowRadius: self.arrowRadius, borderWidth: self.borderWidth, radius: self.cornerRadius)
let shadowAnimation = CABasicAnimation(keyPath: "shadowPath")
shadowAnimation.duration = 0.2
shadowAnimation.toValue = path.cgPath
shadowAnimation.isRemovedOnCompletion = true
self.layer.add(shadowAnimation, forKey: "shadowAnimation")
}) { (_) in
self.startActionAnimation()
}
}
}
fileprivate func show(duration: TimeInterval? = nil) {
isAnimating = true
dismissTimer?.invalidate()
setNeedsLayout()
performEntranceAnimation {
self.customView?.layoutIfNeeded()
if let tapRemoveGesture = self.tapToRemoveGestureRecognizer {
self.containerView?.addGestureRecognizer(tapRemoveGesture)
}
if let swipeGesture = self.swipeGestureRecognizer {
self.containerView?.addGestureRecognizer(swipeGesture)
}
self.appearHandler?(self)
if self.startActionAnimationOnShow {
self.performActionAnimation()
}
self.isAnimating = false
if let duration = duration {
self.dismissTimer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(PopTip.hide), userInfo: nil, repeats: false)
}
}
}
@objc fileprivate func handleTap(_ gesture: UITapGestureRecognizer) {
if shouldDismissOnTap {
hide()
}
tapHandler?(self)
}
@objc fileprivate func handleTapOutside(_ gesture: UITapGestureRecognizer) {
if !isVisible {
return
}
if shouldDismissOnTapOutside {
hide()
}
let gestureLocationInContainer = gesture.location(in: containerView)
if shouldConsiderOriginatingFrameAsPopTip && from.contains(gestureLocationInContainer) {
tapHandler?(self)
} else if shouldConsiderCutoutTapSeparately && shouldShowMask && shouldCutoutMask && cutoutPathGenerator(from).contains(gestureLocationInContainer) {
tapCutoutHandler?(self)
} else {
tapOutsideHandler?(self)
}
}
@objc fileprivate func handleSwipeOutside(_ gesture: UITapGestureRecognizer) {
if shouldDismissOnSwipeOutside {
hide()
}
swipeOutsideHandler?(self)
}
@objc fileprivate func handleApplicationActive() {
isApplicationInBackground = false
}
@objc fileprivate func handleApplicationResignActive() {
isApplicationInBackground = true
}
fileprivate func performActionAnimation() {
switch actionAnimation {
case .bounce(let offset):
shouldBounce = true
bounceAnimation(offset: offset ?? DefaultBounceOffset)
case .float(let offsetX, let offsetY):
floatAnimation(offsetX: offsetX ?? DefaultFloatOffset, offsetY: offsetY ?? DefaultFloatOffset)
case .pulse(let offset):
pulseAnimation(offset: offset ?? DefaultPulseOffset)
case .none:
return
}
}
fileprivate func dismissActionAnimation(_ completion: (() -> Void)? = nil) {
shouldBounce = false
UIView.animate(withDuration: actionAnimationOut / 2, delay: actionDelayOut, options: .beginFromCurrentState, animations: {
self.transform = .identity
}) { (_) in
self.layer.removeAllAnimations()
completion?()
}
}
fileprivate func bounceAnimation(offset: CGFloat) {
var offsetX = CGFloat(0)
var offsetY = CGFloat(0)
switch direction {
case .auto, .autoHorizontal, .autoVertical: break // The decision will be made at this point
case .up, .none:
offsetY = -offset
case .left:
offsetX = -offset
case .right:
offsetX = offset
case .down:
offsetY = offset
}
UIView.animate(withDuration: actionAnimationIn / 10, delay: actionDelayIn, options: [.curveEaseIn, .allowUserInteraction, .beginFromCurrentState], animations: {
self.transform = CGAffineTransform(translationX: offsetX, y: offsetY)
}) { (completed) in
if completed {
UIView.animate(withDuration: self.actionAnimationIn - self.actionAnimationIn / 10, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 1, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.transform = .identity
}, completion: { (done) in
if self.shouldBounce && done {
self.bounceAnimation(offset: offset)
}
})
}
}
}
fileprivate func floatAnimation(offsetX: CGFloat, offsetY: CGFloat) {
var offsetX = offsetX
var offsetY = offsetY
switch direction {
case .up, .none:
offsetY = -offsetY
case .left:
offsetX = -offsetX
default: break
}
UIView.animate(withDuration: actionAnimationIn / 2, delay: actionDelayIn, options: [.curveEaseInOut, .repeat, .autoreverse, .beginFromCurrentState, .allowUserInteraction], animations: {
self.transform = CGAffineTransform(translationX: offsetX, y: offsetY)
}, completion: nil)
}
fileprivate func pulseAnimation(offset: CGFloat) {
UIView.animate(withDuration: actionAnimationIn / 2, delay: actionDelayIn, options: [.curveEaseInOut, .allowUserInteraction, .beginFromCurrentState, .autoreverse, .repeat], animations: {
self.transform = CGAffineTransform(scaleX: offset, y: offset)
}, completion: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
fileprivate extension UIEdgeInsets {
var horizontal: CGFloat {
return self.left + self.right
}
var vertical: CGFloat {
return self.top + self.bottom
}
}
| mit | ad5e29bfe61fbd3cec7405670ee700fb | 41.92585 | 249 | 0.708188 | 4.41536 | false | false | false | false |
davidvuong/ddfa-app | ios/Pods/GooglePlacePicker/Example/GooglePlacePickerDemos/ViewControllers/PickAPlace/PickAPlaceViewController.swift | 2 | 4412 | /*
* Copyright 2016 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import GooglePlacePicker
/// A view controller which displays a UI for opening the Place Picker. Once a place is selected
/// it navigates to the place details screen for the selected location.
class PickAPlaceViewController: UIViewController {
@IBOutlet private weak var pickAPlaceButton: UIButton!
@IBOutlet weak var buildNumberLabel: UILabel!
@IBOutlet var containerView: UIView!
var mapViewController: BackgroundMapViewController?
init() {
super.init(nibName: String(describing: type(of: self)), bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// This is the size we would prefer to be.
self.preferredContentSize = CGSize(width: 330, height: 600)
// Configure our view.
view.backgroundColor = Colors.blue1
containerView.backgroundColor = Colors.blue1
view.clipsToBounds = true
// Set the build number.
buildNumberLabel.text = "Places API Build: \(GMSPlacesClient.sdkVersion())"
// Setup the constraint between the container and the layout guides to be consistant with
// LaunchScreen.storyboard. Because this view controller uses XIB rather than storyboard files
// this cannot be done in interface builder.
NSLayoutConstraint(item: containerView,
attribute: .top,
relatedBy: .equal,
toItem: topLayoutGuide,
attribute: .bottom,
multiplier: 1,
constant: 0)
.isActive = true
NSLayoutConstraint(item: bottomLayoutGuide,
attribute: .top,
relatedBy: .equal,
toItem: containerView,
attribute: .bottom,
multiplier: 1,
constant: 0)
.isActive = true
}
@IBAction func buttonTapped() {
// Create a place picker. Attempt to display it as a popover if we are on a device which
// supports popovers.
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
placePicker.modalPresentationStyle = .popover
placePicker.popoverPresentationController?.sourceView = pickAPlaceButton
placePicker.popoverPresentationController?.sourceRect = pickAPlaceButton.bounds
// Display the place picker. This will call the delegate methods defined below when the user
// has made a selection.
self.present(placePicker, animated: true, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension PickAPlaceViewController : GMSPlacePickerViewControllerDelegate {
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
// Create the next view controller we are going to display and present it.
let nextScreen = PlaceDetailViewController(place: place)
self.splitPaneViewController?.push(viewController: nextScreen, animated: false)
self.mapViewController?.coordinate = place.coordinate
// Dismiss the place picker.
viewController.dismiss(animated: true, completion: nil)
}
func placePicker(_ viewController: GMSPlacePickerViewController, didFailWithError error: Error) {
// In your own app you should handle this better, but for the demo we are just going to log
// a message.
NSLog("An error occurred while picking a place: \(error)")
}
func placePickerDidCancel(_ viewController: GMSPlacePickerViewController) {
NSLog("The place picker was canceled by the user")
// Dismiss the place picker.
viewController.dismiss(animated: true, completion: nil)
}
}
| mit | 878e3516b01af382be054be7e68f55e6 | 38.044248 | 99 | 0.701269 | 5.053837 | false | false | false | false |
anpavlov/swiftperl | Sources/Perl/UnsafeSV.swift | 1 | 6259 | import CPerl
public enum SvType {
case scalar, array, hash, code, format, io
init(_ t: svtype) {
switch t {
case SVt_PVAV:
self = .array
case SVt_PVHV:
self = .hash
case SVt_PVCV:
self = .code
case SVt_PVFM:
self = .format
case SVt_PVIO:
self = .io
default:
self = .scalar
}
}
}
public typealias UnsafeSV = CPerl.SV
public typealias UnsafeSvPointer = UnsafeMutablePointer<UnsafeSV>
extension UnsafeSV {
@discardableResult
mutating func refcntInc() -> UnsafeSvPointer {
return SvREFCNT_inc(&self)
}
mutating func refcntDec(perl: UnsafeInterpreterPointer) {
SvREFCNT_dec(perl, &self)
}
var type: SvType { mutating get { return SvType(SvTYPE(&self)) } }
var defined: Bool { mutating get { return SvOK(&self) } }
var isInt: Bool { mutating get { return SvIOK(&self) } }
var isDouble: Bool { mutating get { return SvNOK(&self) } }
var isString: Bool { mutating get { return SvPOK(&self) } }
var isRef: Bool { mutating get { return SvROK(&self) } }
var referent: UnsafeSvPointer? {
mutating get { return SvROK(&self) ? SvRV(&self) : nil }
}
mutating func isObject(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool {
return perl.pointee.sv_isobject(&self)
}
mutating func isDerived(from: String, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool {
return from.withCString { perl.pointee.sv_derived_from(&self, $0) }
}
mutating func classname(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> String? {
guard isObject(perl: perl) else { return nil }
return String(cString: perl.pointee.sv_reftype(SvRV(&self), true))
}
mutating func hasSwiftObjectMagic(perl: UnsafeInterpreterPointer) -> Bool {
return SvTYPE(&self) == SVt_PVMG && perl.pointee.mg_findext(&self, PERL_MAGIC_ext, &objectMgvtbl) != nil
}
mutating func swiftObject(perl: UnsafeInterpreterPointer) -> PerlBridgedObject? {
guard isObject(perl: perl) else { return nil }
let sv = SvRV(&self)!
guard sv.pointee.hasSwiftObjectMagic(perl: perl) else { return nil }
let iv = perl.pointee.SvIV(sv)
let u = Unmanaged<AnyObject>.fromOpaque(UnsafeRawPointer(bitPattern: iv)!)
return (u.takeUnretainedValue() as! PerlBridgedObject)
}
}
extension UnsafeInterpreter {
mutating func newSV(_ v: Bool) -> UnsafeSvPointer {
return newSV(boolSV(v))
}
mutating func newSV(_ v: String, mortal: Bool = false) -> UnsafeSvPointer {
let flags = mortal ? SVf_UTF8|SVs_TEMP : SVf_UTF8
return v.withCStringWithLength { newSVpvn_flags($0, $1, UInt32(flags)) }
}
mutating func newSV(_ v: UnsafeRawBufferPointer, utf8: Bool = false, mortal: Bool = false) -> UnsafeSvPointer {
let flags = (utf8 ? SVf_UTF8 : 0) | (mortal ? SVs_TEMP : 0)
return newSVpvn_flags(v.baseAddress?.assumingMemoryBound(to: CChar.self), v.count, UInt32(flags))
}
mutating func newRV<T: UnsafeSvCastable>(inc v: UnsafeMutablePointer<T>) -> UnsafeSvPointer {
return v.withMemoryRebound(to: UnsafeSV.self, capacity: 1) { newRV(inc: $0) }
}
mutating func newRV<T: UnsafeSvCastable>(noinc v: UnsafeMutablePointer<T>) -> UnsafeSvPointer {
return v.withMemoryRebound(to: UnsafeSV.self, capacity: 1) { newRV(noinc: $0) }
}
mutating func newSV(_ v: AnyObject, isa: String) -> UnsafeSvPointer {
let u = Unmanaged<AnyObject>.passRetained(v)
let iv = unsafeBitCast(u, to: Int.self)
let sv = sv_setref_iv(newSV(), isa, iv)
sv_magicext(SvRV(sv), nil, PERL_MAGIC_ext, &objectMgvtbl, nil, 0)
return sv
}
mutating func newSV(_ v: PerlBridgedObject) -> UnsafeSvPointer {
return newSV(v, isa: type(of: v).perlClassName)
}
}
private var objectMgvtbl = MGVTBL(
svt_get: nil,
svt_set: nil,
svt_len: nil,
svt_clear: nil,
svt_free: {
(perl, sv, magic) in
let iv = perl.unsafelyUnwrapped.pointee.SvIV(sv.unsafelyUnwrapped)
let u = Unmanaged<AnyObject>.fromOpaque(UnsafeRawPointer(bitPattern: iv)!)
u.release()
return 0
},
svt_copy: nil,
svt_dup: nil,
svt_local: nil
)
extension Bool {
public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) {
self = perl.pointee.SvTRUE(sv)
}
public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) {
guard SvOK(sv) else { return nil }
self = perl.pointee.SvTRUE(sv)
}
}
extension Int {
public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
guard SvNIOK(sv) || perl.pointee.looks_like_number(sv) else {
throw PerlError.notNumber(fromUnsafeSvPointer(inc: sv, perl: perl))
}
self.init(unchecked: sv, perl: perl)
}
public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
guard SvOK(sv) else { return nil }
try self.init(sv, perl: perl)
}
public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) {
self = perl.pointee.SvIV(sv)
}
}
extension Double {
public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
guard SvNIOK(sv) || perl.pointee.looks_like_number(sv) else {
throw PerlError.notNumber(fromUnsafeSvPointer(inc: sv, perl: perl))
}
self.init(unchecked: sv, perl: perl)
}
public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
guard SvOK(sv) else { return nil }
try self.init(sv, perl: perl)
}
public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) {
self = perl.pointee.SvNV(sv)
}
}
extension String {
public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
guard SvPOK(sv) || SvNIOK(sv) else {
throw PerlError.notStringOrNumber(fromUnsafeSvPointer(inc: sv, perl: perl))
}
self.init(unchecked: sv, perl: perl)
}
public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws {
guard SvOK(sv) else { return nil }
try self.init(sv, perl: perl)
}
public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) {
var clen = 0
let cstr = perl.pointee.SvPV(sv, &clen)!
self = String(cString: cstr, withLength: clen)
}
}
| mit | b6adca4fe73dd8323f82ed1764ccb748 | 31.430052 | 112 | 0.717846 | 3.016386 | false | false | false | false |
eligreg/ExhibitionSwift | ExhibitionSwift/Classes/ExhibitionActivityIndicatorView.swift | 1 | 2306 | //
// ExhibitionActivityIndicatorView.swift
// Exhibition
//
// Created by Eli Gregory on 12/27/16.
// Copyright © 2016 Eli Gregory. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
public typealias XActivityView = ExhibitionActivityIndicatorView
public class ExhibitionActivityIndicatorView: UIView {
let activity: UIActivityIndicatorView
public init(sized: CGFloat = 30.0, config: ExhibitionConfig) {
// Scaling
let minSize = CGFloat(30.0)
let size = max(sized, minSize)
let scale = ((size / 1.5) / 20.0)
// Scale Activity Indicator
self.activity = UIActivityIndicatorView(activityIndicatorStyle: .white)
self.activity.transform = CGAffineTransform(scaleX: scale, y: scale)
self.activity.sizeToFit()
self.activity.clipsToBounds = false
self.activity.layer.masksToBounds = false
// Init
super.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: size, height: size)))
// Visuals
self.layer.cornerRadius = sized / 2.0
self.backgroundColor = config.activityTheme.backgroundColor
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowRadius = 5.0
self.activity.color = config.activityTheme.foregroundColor
// Subview
self.addSubview(self.activity)
self.activity.center = self.center
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
activity.removeFromSuperview()
}
}
extension ExhibitionActivityIndicatorView: ExhibititionActivityIndicatorViewProtocol {
public func startAnimating() {
self.alpha = 1.0
self.activity.startAnimating()
}
public func stopAnimating() {
self.activity.stopAnimating()
self.hide()
}
public func hide() {
self.alpha = 0.0
}
}
public typealias XActivityProtocol = ExhibititionActivityIndicatorViewProtocol
public protocol ExhibititionActivityIndicatorViewProtocol {
func startAnimating()
func stopAnimating()
var center: CGPoint { get set }
}
| mit | f7321cf3da2721c5d54df0d805882f96 | 27.109756 | 96 | 0.658134 | 4.772257 | false | false | false | false |
richardpiazza/XCServerCoreData | Example/Pods/CodeQuickKit/Sources/UIAlertController.swift | 2 | 13846 | #if os(iOS)
import UIKit
public typealias DefaultAlertCompletion = (_ selectedAction: String?, _ wasCanceled: Bool) -> Void
public typealias TextAlertCompletion = (_ selectedAction: String?, _ wasCanceled: Bool, _ enteredText: String?) -> Void
public typealias CredentialAlertCompletion = (_ selectedAction: String?, _ wasCanceled: Bool, _ enteredCredentials: URLCredential?) -> Void
/// Extension allowing for a single callback.
public extension UIAlertController {
fileprivate struct Manager {
var alertController: UIAlertController?
var cancelAction: String?
var defaultCompletion: DefaultAlertCompletion?
var textCompletion: TextAlertCompletion?
var credentialCompletion: CredentialAlertCompletion?
fileprivate mutating func dismiss() {
guard let alert = alertController else {
return
}
alert.dismiss(animated: true, completion: nil)
if let completion = defaultCompletion {
completion(cancelAction, true)
} else if let completion = textCompletion {
completion(cancelAction, true, nil)
} else if let completion = credentialCompletion {
completion(cancelAction, true, nil)
}
reset()
}
fileprivate mutating func reset() {
defaultCompletion = nil
textCompletion = nil
credentialCompletion = nil
cancelAction = nil
alertController = nil
}
}
fileprivate static var manager = Manager()
public static func reset() {
manager.reset()
}
/// A basic message and single button `.Default` alert
public static func prompt(presentedFrom vc: UIViewController?, withMessage message: String?, action: String = "OK") {
manager.dismiss()
var vc = vc
if vc == nil {
vc = UIApplication.shared.delegate?.window??.rootViewController
}
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
manager.cancelAction = action
let cancelAlertAction = UIAlertAction(title: action, style: .default) { (alertAction: UIAlertAction) -> Void in
manager.reset()
}
alertController.addAction(cancelAlertAction)
manager.alertController = alertController
if let viewController = vc {
viewController.present(alertController, animated: true, completion: nil)
} else {
manager.dismiss()
}
}
/// A configurable `.Default` alert
public static func alert(presentedFrom vc: UIViewController?, withTitle title: String?, message: String?, cancelAction: String?, destructiveAction: String?, otherActions: [String]?, completion: @escaping DefaultAlertCompletion) {
manager.dismiss()
var vc = vc
if vc == nil {
vc = UIApplication.shared.delegate?.window??.rootViewController
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
if cancelAction != nil {
manager.cancelAction = cancelAction
manager.defaultCompletion = completion
let cancelAlertAction = UIAlertAction(title: cancelAction, style: .default, handler: { (UIAlertAction) -> Void in
completion(cancelAction, true)
manager.reset()
})
alertController.addAction(cancelAlertAction)
}
if destructiveAction != nil {
let destroyAlertAction = UIAlertAction(title: destructiveAction, style: .destructive, handler: { (UIAlertAction) -> Void in
completion(destructiveAction, false)
manager.reset()
})
alertController.addAction(destroyAlertAction)
}
if let otherActions = otherActions {
for action in otherActions {
let alertAction = UIAlertAction(title: action, style: .default, handler: { (UIAlertAction) -> Void in
completion(action, false)
manager.reset()
})
alertController.addAction(alertAction)
}
}
manager.alertController = alertController
if let viewController = vc {
viewController.present(alertController, animated: true, completion: nil)
} else {
manager.dismiss()
}
}
/// A configurable `.Default` style alert with a single `UITextField`
public static func textAlert(presentedFrom vc: UIViewController?, withTitle title: String?, message: String?, initialText: String?, cancelAction: String?, otherActions: [String]?, completion: @escaping TextAlertCompletion) {
manager.dismiss()
var vc = vc
if vc == nil {
vc = UIApplication.shared.delegate?.window??.rootViewController
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
if cancelAction != nil {
manager.cancelAction = cancelAction
manager.textCompletion = completion
let cancelAlertAction = UIAlertAction(title: cancelAction, style: .default, handler: { (UIAlertAction) -> Void in
completion(cancelAction, true, nil)
manager.reset()
})
alertController.addAction(cancelAlertAction)
}
if let otherActions = otherActions {
for action in otherActions {
let alertAction = UIAlertAction(title: action, style: .default, handler: { (UIAlertAction) -> Void in
let enteredText = alertController.textFields?.first?.text
completion(action, false, enteredText)
manager.reset()
})
alertController.addAction(alertAction)
}
}
alertController.addTextField { (textField: UITextField) -> Void in
textField.text = initialText
}
manager.alertController = alertController
if let viewController = vc {
viewController.present(alertController, animated: true, completion: nil)
} else {
manager.dismiss()
}
}
/// A configurable `.Default` style alert with a single secure `UITextField`
public static func secureAlert(presentedFrom vc: UIViewController?, withTitle title: String?, message: String?, initialText: String?, cancelAction: String?, otherActions: [String]?, completion: @escaping TextAlertCompletion) {
manager.dismiss()
var vc = vc
if vc == nil {
vc = UIApplication.shared.delegate?.window??.rootViewController
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
if cancelAction != nil {
manager.cancelAction = cancelAction
manager.textCompletion = completion
let cancelAlertAction = UIAlertAction(title: cancelAction, style: .default, handler: { (UIAlertAction) -> Void in
completion(cancelAction, true, nil)
manager.reset()
})
alertController.addAction(cancelAlertAction)
}
if let otherActions = otherActions {
for action in otherActions {
let alertAction = UIAlertAction(title: action, style: .default, handler: { (UIAlertAction) -> Void in
let enteredText = alertController.textFields?.first?.text
completion(action, false, enteredText)
manager.reset()
})
alertController.addAction(alertAction)
}
}
alertController.addTextField { (textField: UITextField) -> Void in
textField.text = initialText
textField.isSecureTextEntry = true
}
manager.alertController = alertController
if let viewController = vc {
viewController.present(alertController, animated: true, completion: nil)
} else {
manager.dismiss()
}
}
/// A configurable `.Default` style alert with two `UITextField`s, the
/// second of which is secure
public static func credentialAlert(presentedFrom vc: UIViewController?, withTitle title: String?, message: String?, initialCredentials: URLCredential?, cancelAction: String?, otherActions: [String]?, completion: @escaping CredentialAlertCompletion) {
manager.dismiss()
var vc = vc
if vc == nil {
vc = UIApplication.shared.delegate?.window??.rootViewController
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
if cancelAction != nil {
manager.cancelAction = cancelAction
manager.credentialCompletion = completion
let cancelAlertAction = UIAlertAction(title: cancelAction, style: .default, handler: { (UIAlertAction) -> Void in
completion(cancelAction, true, nil)
manager.reset()
})
alertController.addAction(cancelAlertAction)
}
if let otherActions = otherActions {
for action in otherActions {
let alertAction = UIAlertAction(title: action, style: .default, handler: { (UIAlertAction) -> Void in
var enteredUsername = ""
if let text = alertController.textFields?.first?.text {
enteredUsername = text
}
var enteredPassword = ""
if let text = alertController.textFields?.last?.text {
enteredPassword = text
}
let enteredCredentials = URLCredential(user: enteredUsername, password: enteredPassword, persistence: .none)
completion(action, false, enteredCredentials)
manager.reset()
})
alertController.addAction(alertAction)
}
}
alertController.addTextField { (textField: UITextField) -> Void in
textField.text = initialCredentials?.user
}
alertController.addTextField { (textField: UITextField) -> Void in
textField.text = initialCredentials?.password
textField.isSecureTextEntry = true
}
manager.alertController = alertController
if let viewController = vc {
viewController.present(alertController, animated: true, completion: nil)
} else {
manager.dismiss()
}
}
/// A configurable `.ActionSheet` style alert presented from the
/// `viewController` or `sourceView` on Regular horizontal size classes
public static func sheet(presentedFrom vc: UIViewController?, withBarButtonItem barButtonItem: UIBarButtonItem?, orSourceView sourceView: UIView?, title: String?, message: String?, cancelAction: String?, destructiveAction: String?, otherActions: [String]?, completion: @escaping DefaultAlertCompletion) {
manager.dismiss()
var vc = vc
if vc == nil {
vc = UIApplication.shared.delegate?.window??.rootViewController
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
if cancelAction != nil {
manager.cancelAction = cancelAction
manager.defaultCompletion = completion
let cancelAlertAction = UIAlertAction(title: cancelAction, style: .default, handler: { (UIAlertAction) -> Void in
completion(cancelAction, true)
manager.reset()
})
alertController.addAction(cancelAlertAction)
}
if destructiveAction != nil {
let destroyAlertAction = UIAlertAction(title: destructiveAction, style: .destructive, handler: { (UIAlertAction) -> Void in
completion(destructiveAction, false)
manager.reset()
})
alertController.addAction(destroyAlertAction)
}
if let otherActions = otherActions {
for action in otherActions {
let alertAction = UIAlertAction(title: action, style: .default, handler: { (UIAlertAction) -> Void in
completion(action, false)
manager.reset()
})
alertController.addAction(alertAction)
}
}
manager.alertController = alertController
if let viewController = vc {
viewController.present(alertController, animated: true, completion: nil)
if let ppc = alertController.popoverPresentationController {
ppc.barButtonItem = barButtonItem
ppc.sourceView = sourceView
if sourceView != nil {
ppc.sourceRect = sourceView!.frame
}
}
} else {
manager.dismiss()
}
}
}
#endif
| mit | dd73891bd7ded1381a0390968266480f | 38.335227 | 308 | 0.578795 | 6.070145 | false | false | false | false |
MakiZz/30DaysToLearnSwift3.0 | project 13 - animationTable/project 13 - animationTable/TableViewController.swift | 1 | 5298 | //
// TableViewController.swift
// project 13 - animationTable
//
// Created by mk on 17/3/17.
// Copyright © 2017年 maki. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var tableData = ["Read 3 article on Medium", "Cleanup bedroom", "Go for a run", "Hit the gym", "Build another swift project", "Movement training", "Fix the layout problem of a client project", "Write the experience of #30daysSwift", "Inbox Zero", "Booking the ticket to Chengdu", "Test the Adobe Project Comet", "Hop on a call to mom"]
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.view.backgroundColor = UIColor.black
self.tableView.separatorStyle = .none
self.tableView.tableFooterView = UIView()
self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func animtation() {
self.tableView.reloadData()
// 获得可见Cells
let cells = tableView.visibleCells
let tableHeight: CGFloat = tableView.bounds.size.height
for (index,cell) in cells.enumerated() {
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
UIView.animate(withDuration: 1.0, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
cell.transform = CGAffineTransform.init(translationX: 0, y: tableHeight)
}, completion: nil)
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tableData.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = tableData[indexPath.row]
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.backgroundColor = UIColor.clear
cell.textLabel?.font = UIFont(name: "Avenir Next", size: 18)
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
func colorforIndex(index: Int) -> UIColor {
let itemCount = tableData.count - 1
let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
return UIColor.init(red: color, green: 0.0, blue: 1.0, alpha: 1.0)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = colorforIndex(index: indexPath.row)
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 1eb280056bb5b5300a85f394b9cee4cd | 34.246667 | 339 | 0.650274 | 5.168133 | false | false | false | false |
Restofire/Restofire-Gloss | Tests/ServiceSpec/PersonArrayService+GETSpec.swift | 1 | 1873 | // _____ ____ __.
// / _ \ _____ _______ | |/ _|____ ___.__.
// / /_\ \\__ \\_ __ \ | < \__ \< | |
// / | \/ __ \| | \/ | | \ / __ \\___ |
// \____|__ (____ /__| |____|__ (____ / ____|
// \/ \/ \/ \/\/
//
// Copyright (c) 2016 RahulKatariya. All rights reserved.
//
import Quick
import Nimble
import Alamofire
class PersonArrayGETServiceSpec: ServiceSpec {
override func spec() {
describe("PersonArrayGETService") {
it("executeTask") {
let actual: [Person] = [
Person(id: 12345, name: "Rahul Katariya"),
Person(id: 12346, name: "Aar Kay")
]
var expected: [Person]!
PersonArrayGETService().executeTask() {
if let value = $0.result.value {
expected = value
}
}
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
it("executeRequestOperation") {
let actual: [Person] = [
Person(id: 12345, name: "Rahul Katariya"),
Person(id: 12346, name: "Aar Kay")
]
var expected: [Person]!
let requestOperation = PersonArrayGETService().requestOperation() {
if let value = $0.result.value {
expected = value
}
}
requestOperation.start()
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
}
}
}
| mit | 6effe98956c26a97eb888398272e2a2a | 30.216667 | 116 | 0.384944 | 4.557178 | false | false | false | false |
matsprea/omim | iphone/Maps/Bookmarks/Catalog/Subscription/AllPassSubscriptionViewController.swift | 1 | 5550 | class AllPassSubscriptionViewController: BaseSubscriptionViewController {
// MARK: outlets
@IBOutlet private var backgroundImageView: ImageViewCrossDisolve!
@IBOutlet private var annualSubscriptionButton: BookmarksSubscriptionButton!
@IBOutlet private var annualDiscountLabel: InsetsLabel!
@IBOutlet private var monthlySubscriptionButton: BookmarksSubscriptionButton!
@IBOutlet private var descriptionPageScrollView: UIScrollView!
@IBOutlet private var contentView: UIView!
@IBOutlet private var statusBarBackgroundView: UIVisualEffectView!
@IBOutlet private var descriptionSubtitles: [UILabel]!
//MARK: locals
private var pageWidth: CGFloat {
return descriptionPageScrollView.frame.width
}
private let maxPages = 3
private var currentPage: Int {
return Int(descriptionPageScrollView.contentOffset.x / pageWidth) + 1
}
private var animatingTask: DispatchWorkItem?
private let animationDelay: TimeInterval = 2
private let animationDuration: TimeInterval = 0.75
private let animationBackDuration: TimeInterval = 0.3
private let statusBarBackVisibleThreshold: CGFloat = 60
override var subscriptionManager: ISubscriptionManager? { return InAppPurchase.allPassSubscriptionManager }
override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
backgroundImageView.images = [
UIImage(named: "AllPassSubscriptionBg1"),
UIImage(named: "AllPassSubscriptionBg2"),
UIImage(named: "AllPassSubscriptionBg3")
]
startAnimating()
annualSubscriptionButton.config(title: L("annual_subscription_title"),
price: "...",
enabled: false)
monthlySubscriptionButton.config(title: L("montly_subscription_title"),
price: "...",
enabled: false)
annualDiscountLabel.isHidden = true
let fontSize: CGFloat = UIScreen.main.bounds.width > 320 ? 17.0 : 14.0
let fontFamily = UIFont.systemFont(ofSize: fontSize).familyName
let css = "<style type=\"text/css\">b{font-weight: 900;}body{font-weight: 300; font-size: \(fontSize); font-family: '-apple-system','\(fontFamily)';}</style>"
zip(descriptionSubtitles, ["all_pass_subscription_message_subtitle",
"all_pass_subscription_message_subtitle_3",
"all_pass_subscription_message_subtitle_2"]).forEach { title, loc in
title.attributedText = NSAttributedString.string(withHtml: css + L(loc), defaultAttributes: [:])
}
configure(buttons: [
.year: annualSubscriptionButton,
.month: monthlySubscriptionButton],
discountLabels:[
.year: annualDiscountLabel])
preferredContentSize = CGSize(width: 414, height: contentView.frame.height)
}
@IBAction func onAnnualButtonTap(_ sender: UIButton) {
purchase(sender: sender, period: .year)
}
@IBAction func onMonthlyButtonTap(_ sender: UIButton) {
purchase(sender: sender, period: .month)
}
}
//MARK: Animation
extension AllPassSubscriptionViewController {
private func perform(withDelay: TimeInterval, execute: DispatchWorkItem?) {
if let execute = execute {
DispatchQueue.main.asyncAfter(deadline: .now() + withDelay, execute: execute)
}
}
private func startAnimating() {
if animatingTask != nil {
animatingTask?.cancel()
}
animatingTask = DispatchWorkItem.init { [weak self, animationDelay] in
self?.scrollToWithAnimation(page: (self?.currentPage ?? 0) + 1, completion: {
self?.perform(withDelay: animationDelay, execute: self?.animatingTask)
})
}
perform(withDelay: animationDelay, execute: animatingTask)
}
private func stopAnimating() {
animatingTask?.cancel()
animatingTask = nil
view.layer.removeAllAnimations()
}
private func scrollToWithAnimation(page: Int, completion: @escaping () -> Void) {
var nextPage = page
var duration = animationDuration
if nextPage < 1 || nextPage > maxPages {
nextPage = 1
duration = animationBackDuration
}
let xOffset = CGFloat(nextPage - 1) * pageWidth
UIView.animate(withDuration: duration,
delay: 0,
options: [.curveEaseInOut, .allowUserInteraction],
animations: { [weak self] in
self?.descriptionPageScrollView.contentOffset.x = xOffset
}, completion: { complete in
completion()
})
}
}
extension AllPassSubscriptionViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == descriptionPageScrollView {
let pageProgress = scrollView.contentOffset.x / pageWidth
backgroundImageView.currentPage = pageProgress
} else {
let statusBarAlpha = min(scrollView.contentOffset.y / statusBarBackVisibleThreshold, 1)
statusBarBackgroundView.alpha = statusBarAlpha
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopAnimating()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
startAnimating()
}
}
| apache-2.0 | ceea6910ada0f3b02a6e5dd47f662685 | 35.754967 | 162 | 0.68973 | 5.157993 | false | false | false | false |
code-h/MapDemo | BaiduMapDemo/ViewController.swift | 1 | 6249 | //
// ViewController.swift
// BaiduDemo
//
// Created by marquis on 16/4/22.
// Copyright © 2016年 marquis. All rights reserved.
//
import UIKit
import SwiftyJSON
class ViewController: UIViewController, BMKMapViewDelegate, BMKLocationServiceDelegate {
var _mapView: BMKMapView?
var pointAnnotation: BMKPointAnnotation!
//离线地图
var offlineMap: BMKOfflineMap!
//本地下载的离线地图
var localDownloadMapInfo: [BMKOLUpdateElement]!
//定位服务
var locationService: BMKLocationService!
//当前用户位置
var userLocation: BMKUserLocation!
override func viewDidLoad() {
super.viewDidLoad()
//初始化离线地图服务
offlineMap = BMKOfflineMap()
//将Macau数据copy到App的Documents/vmp
let fileManager = NSFileManager.defaultManager()
let exsit = fileManager.fileExistsAtPath(mapDataPath)
if exsit == false {
let mapPath = NSBundle.mainBundle().pathForResource("map_data", ofType: "zip")!
//将地图数据包解压到App的Documents/vmp
SSZipArchive.unzipFileAtPath(mapPath, toDestination: documentPath.last!)
}
//初始化地图
_mapView = BMKMapView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
_mapView!.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(_mapView!)
//获取在本地的离线数据包
let localMapInfo = offlineMap.getUpdateInfo(macaoCode)
_mapView?.setCenterCoordinate(localMapInfo.pt, animated: true)
//澳門的經緯度
let coor = CLLocationCoordinate2DMake(macaoCenter["lat"]!, macaoCenter["lng"]!)
_mapView!.removeOverlays(_mapView!.overlays)
self.addPointAnnotation()
//設置顯示範圍
self.mapDisplayRange(coor, latitudeDelta: rangeDelta["lat"]!, longitudeDelta: rangeDelta["lng"]!)
//添加定位
//定位功能初始化
locationService = BMKLocationService()
//設置定位精度
locationService.desiredAccuracy = kCLLocationAccuracyBest
//指定最小距離更新(米)
locationService.distanceFilter = 10
locationService.startUserLocationService()
self.followLocation()
}
//添加标注
func addPointAnnotation(){
var coor: CLLocationCoordinate2D = CLLocationCoordinate2D.init()
let data = self.changeData()
for i in 0..<data.count {
pointAnnotation = BMKPointAnnotation.init()
coor.longitude = data[i]["lng"].doubleValue
coor.latitude = data[i]["lat"].doubleValue
pointAnnotation.coordinate = coor
pointAnnotation.title = data[i]["title"].stringValue
pointAnnotation.subtitle = data[i]["subtitle"].stringValue
_mapView?.addAnnotation(pointAnnotation)
}
}
//数据转换
func changeData() -> JSON {
let path = NSBundle.mainBundle().pathForResource("Locations", ofType: "json")
let jsonData = NSData(contentsOfFile: path!)
let json = JSON(data: jsonData!)
return json
}
//根据anntation生成对应的View
func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! {
//普通标注
if annotation as! BMKPointAnnotation == pointAnnotation {
let AnnotationViewID = "renameMark"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(AnnotationViewID) as! BMKPinAnnotationView?
if annotationView == nil {
annotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
//设置颜色
annotationView!.pinColor = UInt(BMKPinAnnotationColorPurple)
//从天上掉下的动画
annotationView!.animatesDrop = true
//设置可拖曳
annotationView!.draggable = false
}
return annotationView
}
return nil
}
//设置地图显示范围(其他地方不会显示)
func mapDisplayRange(center:CLLocationCoordinate2D, latitudeDelta:Double, longitudeDelta:Double) {
let span = BMKCoordinateSpanMake(latitudeDelta, longitudeDelta)
_mapView?.rotateEnabled = false//禁用旋转手势
_mapView?.limitMapRegion = BMKCoordinateRegionMake(center, span)
}
func followLocation() {
//进入普通定位
_mapView!.showsUserLocation = false
_mapView!.userTrackingMode = locationModel["None"]!
_mapView!.showsUserLocation = true
_mapView!.scrollEnabled = true //允許用户移动地图
_mapView!.updateLocationData(userLocation)
}
//用户位置更新后,会调用此函数
func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) {
_mapView!.updateLocationData(userLocation)
print("目前位置:\(userLocation.location.coordinate.longitude), \(userLocation.location.coordinate.latitude)")
}
//用户方向更新后,会调用此函数
func didUpdateUserHeading(userLocation: BMKUserLocation!) {
_mapView!.updateLocationData(userLocation)
print("目前朝向:\(userLocation.heading)")
}
func didFailToLocateUserWithError(error: NSError!) {
NSLog("定位失敗")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
_mapView?.viewWillAppear()
_mapView?.delegate = self //此处记得不用的时候需要置nil,否则影响内存的释放
locationService.delegate = self
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
_mapView?.viewWillDisappear()
_mapView?.delegate = nil //不用时,置nil
locationService.delegate = nil
}
}
| mit | 8ed2e48a71e5e05e7eb523c9b71dc6c3 | 34.325153 | 128 | 0.644668 | 4.704248 | false | false | false | false |
sublimter/Meijiabang | KickYourAss/KickYourAss/ZXY_Start/ZXY_ArtistVCS/ZXY_NailArtistListVC.swift | 3 | 12245 | //
// ZXY_NailArtistListVC.swift
// KickYourAss
//
// Created by 宇周 on 15/1/28.
// Copyright (c) 2015年 宇周. All rights reserved.
//
import UIKit
enum ZXY_OrderStatus : Int
{
case OrderStatusFasion = 1
case OrderStatusNearBy = 2
case OrderStatusRateRank = 3
case OrderStatusArts = 4
func titleForOrderStatus(var status : ZXY_OrderStatus) -> String
{
switch status
{
case .OrderStatusNearBy :
return "附近"
case .OrderStatusFasion :
return "热门"
case .OrderStatusArts :
return "作品"
case .OrderStatusRateRank:
return "评价"
default :
return "热门"
}
}
}
class ZXY_NailArtistListVC: UIViewController {
@IBOutlet weak var currentTable: UITableView!
private var locationService : BMKLocationService = BMKLocationService()
private var cityNameSearch : BMKGeoCodeSearch = BMKGeoCodeSearch()
private var userListData : NSMutableArray = NSMutableArray()
private var isDown = false
private var userCityForFail = "大连市"
private var currentPage : Int = 1
private var currentOrderStatus : ZXY_OrderStatus = .OrderStatusNearBy
@IBOutlet var changeStatusBtn: [UIButton]!
@IBOutlet weak var rightBtn : UIButton!
@IBOutlet weak var controlView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.currentTable.tableFooterView = UIView(frame: CGRectZero)
currentTable.addFooterWithCallback {[weak self] () -> Void in
self?.currentTable.footerPullToRefreshText = "上拉加载更多"
self?.currentTable.footerReleaseToRefreshText = "松开加载"
self?.currentTable.footerRefreshingText = "正在加载"
self?.currentPage++
self?.startGetArtistListData()
}
currentTable.addHeaderWithCallback { [weak self] () -> Void in
self?.currentPage = 1
self?.currentTable.headerPullToRefreshText = "下拉刷新"
self?.currentTable.headerReleaseToRefreshText = "松开刷新"
self?.currentTable.headerRefreshingText = "正在刷新"
self?.startGetArtistListData()
}
startGetArtistListData()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.rightBtn)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
locationService.delegate = nil
cityNameSearch.delegate = nil
locationService.stopUserLocationService()
}
private func startGetArtistListData()
{
var cityNameTemp = ZXY_UserInfoDetail.sharedInstance.getUserCityName()
if(cityNameTemp == nil)
{
locationService.delegate = self
cityNameSearch.delegate = self
locationService.startUserLocationService()
}
else
{
if(isDown)
{
currentTable.footerEndRefreshing()
currentTable.headerEndRefreshing()
return
}
isDown = true
var urlString = ZXY_ALLApi.ZXY_MainAPI + ZXY_ALLApi.ZXY_UserListAPI
var coor : Dictionary<String , String?>? = ZXY_UserInfoDetail.sharedInstance.getUserCoordinate()
var lat = coor!["latitude"]!
var log = coor!["longitude"]!
var parameter : Dictionary<String , String> = ["city" : cityNameTemp! ,
"user_id" : "" ,
"lng" : log! ,
"lat" : lat! ,
"control" : "\(currentOrderStatus.rawValue)" ,
"p" : "\(currentPage)"
]
ZXY_NetHelperOperate().startGetDataPost(urlString, parameter: parameter, successBlock: {[weak self] (returnDic) -> Void in
if(self?.currentPage == 1)
{
self?.userListData.removeAllObjects()
self?.userListData.addObjectsFromArray(ZXYArtistListBase(dictionary: returnDic).data)
}
else
{
self?.userListData.addObjectsFromArray(ZXYArtistListBase(dictionary: returnDic).data)
}
self?.reloadTableView()
self?.currentTable.footerEndRefreshing()
self?.currentTable.headerEndRefreshing()
self?.isDown = false
}, failBlock: { [weak self](error) -> Void in
self?.currentTable.footerEndRefreshing()
self?.currentTable.headerEndRefreshing()
self?.isDown = false
println(error)
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ZXY_NailArtistListVC : BMKLocationServiceDelegate , BMKGeoCodeSearchDelegate
{
func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) {
var lastLocation : CLLocation = userLocation.location
var optionO : BMKReverseGeoCodeOption = BMKReverseGeoCodeOption()
optionO.reverseGeoPoint = userLocation.location.coordinate
ZXY_UserInfoDetail.sharedInstance.setUserCoordinate("\(lastLocation.coordinate.latitude)", longitude: "\(lastLocation.coordinate.longitude)")
self.cityNameSearch.reverseGeoCode(optionO)
}
func onGetReverseGeoCodeResult(searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeResult!, errorCode error: BMKSearchErrorCode) {
if(error.value == BMK_SEARCH_NO_ERROR.value)
{
ZXY_UserInfoDetail.sharedInstance.setUserCityName(result.addressDetail.city)
startGetArtistListData()
searcher.delegate = nil
locationService.stopUserLocationService()
}
else
{
ZXY_UserInfoDetail.sharedInstance.setUserCityName(userCityForFail)
startGetArtistListData()
searcher.delegate = nil
locationService.stopUserLocationService()
}
}
}
extension ZXY_NailArtistListVC: UITableViewDelegate , UITableViewDataSource
{
func reloadTableView()
{
self.currentTable.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var currentRow = indexPath.row
var currentSection = indexPath.section
var cell = tableView.dequeueReusableCellWithIdentifier(ZXY_ArtistListCellID) as ZXY_ArtistListCell
var currentArtist : ZXYArtistListData = userListData[currentRow] as ZXYArtistListData
cell.nameLbl.text = currentArtist.nickName
cell.numOfArt.text = "作品:\(currentArtist.albumCount)"
cell.likeNumLbl.text = currentArtist.byAttention
var headImg = ZXY_ALLApi.ZXY_MainAPIImage + currentArtist.headImage
if(currentArtist.headImage.hasPrefix("http"))
{
headImg = currentArtist.headImage
}
var coor : Dictionary<String , String?>? = ZXY_UserInfoDetail.sharedInstance.getUserCoordinate()
var lat = coor!["latitude"]!
var log = coor!["longitude"]!
var currentUserL = self.xYStringToCoor(log, latitude: lat)
var artistL = self.xYStringToCoor(currentArtist.longitude, latitude: currentArtist.latitude)
var distance = self.distanceCompareCoor(artistL, userPosition: currentUserL)
cell.distanceLbl.text = "\(Double(round(100 * distance)/100)) km"
cell.setHeadImageURL(NSURL(string: headImg))
cell.setRateValue((currentArtist.score as NSString).integerValue)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 99
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userListData.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var story = UIStoryboard(name: "ArtistDetailStoryBoard", bundle: nil)
var currentArtist : ZXYArtistListData = userListData[indexPath.row] as ZXYArtistListData
var vc = story.instantiateViewControllerWithIdentifier(ZXY_ArtistDetailVCID) as ZXY_ArtistDetailVC
vc.setUserID(currentArtist.userId)
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension ZXY_NailArtistListVC
{
func distanceCompareCoor(artistPosition : CLLocationCoordinate2D? , userPosition : CLLocationCoordinate2D?) -> Double
{
if(artistPosition != nil && userPosition != nil)
{
var artistPot = BMKMapPointForCoordinate(artistPosition!)
var userPot = BMKMapPointForCoordinate(userPosition!)
var distance = BMKMetersBetweenMapPoints(artistPot, userPot)
return distance/1000
}
else
{
return 0
}
}
func xYStringToCoor(longitude : String? , latitude: String?) -> CLLocationCoordinate2D?
{
if(longitude == nil || latitude == nil)
{
return nil
}
else
{
var logFloat = (longitude! as NSString).doubleValue
var latFloat = (latitude! as NSString).doubleValue
return CLLocationCoordinate2DMake(latFloat, logFloat)
}
}
@IBAction func ClickRightBtnAction(sender: AnyObject)
{
var btn : UIButton = sender as UIButton
if(btn.selected)
{
btn.selected = false
hideControlView()
}
else
{
btn.selected = true
showControlView()
}
}
func showControlView()
{
UIView.animateWithDuration(0.2, animations: {[weak self] () -> Void in
self?.controlView.alpha = 1
return
})
}
func hideControlView()
{
UIView.animateWithDuration(0.2, animations: {[weak self] () -> Void in
self?.controlView.alpha = 0
return
})
}
@IBAction func changeOrderStatusAction(sender: AnyObject) {
var currentBtn : UIButton = sender as UIButton
for (index , value) in enumerate(changeStatusBtn)
{
if(value == currentBtn)
{
switch index
{
case 0 :
currentOrderStatus = ZXY_OrderStatus.OrderStatusFasion
case 1 :
currentOrderStatus = ZXY_OrderStatus.OrderStatusNearBy
case 2 :
currentOrderStatus = ZXY_OrderStatus.OrderStatusRateRank
case 3 :
currentOrderStatus = ZXY_OrderStatus.OrderStatusArts
default:
currentOrderStatus = ZXY_OrderStatus.OrderStatusFasion
}
currentPage = 1
self.startGetArtistListData()
self.hideControlView()
self.startReloadRightBtn()
self.rightBtn.selected = false
return
}
}
}
func startReloadRightBtn()
{
switch currentOrderStatus
{
case ZXY_OrderStatus.OrderStatusFasion :
rightBtn.setTitle("热门", forState: UIControlState.Normal)
case ZXY_OrderStatus.OrderStatusNearBy :
rightBtn.setTitle("附近", forState: UIControlState.Normal)
case ZXY_OrderStatus.OrderStatusRateRank :
rightBtn.setTitle("评价", forState: UIControlState.Normal)
case ZXY_OrderStatus.OrderStatusArts :
rightBtn.setTitle("作品", forState: UIControlState.Normal)
default :
rightBtn.setTitle("热门", forState: UIControlState.Normal)
}
}
}
| mit | a629cce4e47a5261cf377bb9cf116470 | 34.162319 | 149 | 0.606793 | 5.071488 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDKTests/Crypto/KeySharing/MXSharedHistoryKeyManagerUnitTests.swift | 1 | 8625 | //
// Copyright 2022 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
import XCTest
@testable import MatrixSDK
class MXSharedHistoryKeyManagerUnitTests: XCTestCase {
class CryptoStub: MXLegacyCrypto {
var devices = MXUsersDevicesMap<MXDeviceInfo>()
override func downloadKeys(_ userIds: [String], forceDownload: Bool, success: ((MXUsersDevicesMap<MXDeviceInfo>, [String : MXCrossSigningInfo]) -> Void)?, failure: ((Error) -> Void)? = nil) -> MXHTTPOperation? {
success?(devices, [:])
return MXHTTPOperation()
}
}
class SpyService: NSObject, MXSharedHistoryKeyService {
struct SessionStub: Hashable {
let roomId: String
let sessionId: String
let senderKey: String
}
var sharedHistory: Set<SessionStub>?
func hasSharedHistory(forRoomId roomId: String!, sessionId: String!, senderKey: String!) -> Bool {
guard let sharedHistory = sharedHistory else {
return true
}
let session = SessionStub(roomId: roomId, sessionId: sessionId, senderKey: senderKey)
return sharedHistory.contains(session)
}
var requests = [MXSharedHistoryKeyRequest]()
func shareKeys(for request: MXSharedHistoryKeyRequest!, success: (() -> Void)!, failure: ((Error?) -> Void)!) {
requests.append(request)
success?()
}
}
class EnumeratorStub: NSObject, MXEventsEnumerator {
var messages: [MXEvent] = []
func nextEventsBatch(_ eventsCount: UInt, threadId: String!) -> [MXEvent]! {
return nil
}
var nextEvent: MXEvent? {
if messages.isEmpty {
return nil
}
return messages.removeFirst()
}
var remaining: UInt {
return UInt(messages.count)
}
}
var enumerator: EnumeratorStub!
var crypto: CryptoStub!
var service: SpyService!
var manager: MXSharedHistoryKeyManager!
override func setUp() {
super.setUp()
enumerator = EnumeratorStub()
crypto = CryptoStub()
crypto.devices.setObject(MXDeviceInfo(deviceId: "1"), forUser: "user1", andDevice: "1")
service = SpyService()
}
private func makeEvent(
sessionId: String = "123",
senderKey: String = "456"
) -> MXEvent {
MXEvent(fromJSON: [
"room_id": "ABC",
"type": kMXEventTypeStringRoomEncrypted,
"content": [
"session_id": sessionId,
"sender_key": senderKey,
]
])
}
private func makeInboundSession(
roomId: String = "ABC",
sessionId: String = "123",
senderKey: String = "456"
) -> SpyService.SessionStub {
return .init(roomId: roomId, sessionId: sessionId, senderKey: senderKey)
}
private func shareKeys(
userId: String = "user1",
roomId: String = "ABC",
enumerator: MXEventsEnumerator? = nil,
limit: Int = .max
) {
manager = MXSharedHistoryKeyManager(roomId: roomId, crypto: crypto, service: service)
manager.shareMessageKeys(
withUserId: userId,
messageEnumerator: enumerator ?? self.enumerator,
limit: limit
)
}
func testDoesNotCreateRequestIfNoKnownDevices() {
enumerator.messages = [
makeEvent(sessionId: "A", senderKey: "B")
]
crypto.devices = MXUsersDevicesMap<MXDeviceInfo>()
shareKeys()
XCTAssertEqual(service.requests.count, 0)
}
func testCreateRequestForSingleMessage() {
enumerator.messages = [
makeEvent(sessionId: "A", senderKey: "B")
]
crypto.devices.setObject(MXDeviceInfo(deviceId: "1"), forUser: "user1", andDevice: "1")
crypto.devices.setObject(MXDeviceInfo(deviceId: "2"), forUser: "user1", andDevice: "2")
crypto.devices.setObject(MXDeviceInfo(deviceId: "3"), forUser: "user2", andDevice: "3")
shareKeys()
XCTAssertEqual(service.requests.count, 1)
XCTAssertEqual(
service.requests.first,
MXSharedHistoryKeyRequest(
userId: "user1",
devices: [
MXDeviceInfo(deviceId: "1"),
MXDeviceInfo(deviceId: "2")
],
roomId: "ABC",
sessionId: "A",
senderKey: "B"
)
)
}
func testCreateOneRequestPerSessionIdAndSenderKey() {
enumerator.messages = [
makeEvent(sessionId: "1", senderKey: "A"),
makeEvent(sessionId: "1", senderKey: "B"),
makeEvent(sessionId: "1", senderKey: "A"),
makeEvent(sessionId: "2", senderKey: "A"),
makeEvent(sessionId: "3", senderKey: "A"),
makeEvent(sessionId: "2", senderKey: "A"),
makeEvent(sessionId: "3", senderKey: "B"),
]
shareKeys()
let identifiers = service.requests.map { [$0.sessionId, $0.senderKey] }
XCTAssertEqual(service.requests.count, 5)
XCTAssertTrue(identifiers.contains(["1", "A"]))
XCTAssertTrue(identifiers.contains(["1", "B"]))
XCTAssertTrue(identifiers.contains(["2", "A"]))
XCTAssertTrue(identifiers.contains(["3", "A"]))
XCTAssertTrue(identifiers.contains(["3", "B"]))
}
func testCreateRequestsWithinLimit() {
enumerator.messages = [
makeEvent(sessionId: "5"),
makeEvent(sessionId: "4"),
makeEvent(sessionId: "3"),
makeEvent(sessionId: "2"),
makeEvent(sessionId: "1"),
]
shareKeys(limit: 3)
let identifiers = service.requests.map { $0.sessionId }
XCTAssertEqual(service.requests.count, 3)
XCTAssertEqual(Set(identifiers), ["5", "4", "3"])
}
func testCreateRequestsOnlyForSessionsWithSharedHistory() {
enumerator.messages = [
makeEvent(sessionId: "1"),
makeEvent(sessionId: "2"),
makeEvent(sessionId: "3"),
makeEvent(sessionId: "4"),
makeEvent(sessionId: "5"),
]
service.sharedHistory = [
makeInboundSession(sessionId: "1"),
makeInboundSession(sessionId: "2"),
makeInboundSession(sessionId: "4"),
]
shareKeys()
let identifiers = service.requests.map { $0.sessionId }
XCTAssertEqual(service.requests.count, 3)
XCTAssertEqual(Set(identifiers), ["1", "2", "4"])
}
func testIgnoresEventsWithMismatchedRoomId() {
enumerator.messages = [
makeEvent(sessionId: "1"),
makeEvent(sessionId: "2"),
makeEvent(sessionId: "3"),
]
service.sharedHistory = [
makeInboundSession(
roomId: "XYZ",
sessionId: "1"
),
makeInboundSession(
roomId: "ABC",
sessionId: "2"
),
makeInboundSession(
roomId: "XYZ",
sessionId: "3"
),
]
shareKeys(roomId: "ABC")
XCTAssertEqual(service.requests.count, 1)
XCTAssertEqual(service.requests.first?.sessionId, "2")
}
}
extension MXSharedHistoryKeyRequest {
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MXSharedHistoryKeyRequest else {
return false
}
return object.userId == userId
&& object.devices.map { $0.deviceId } == devices.map { $0.deviceId }
&& object.roomId == roomId
&& object.sessionId == sessionId
&& object.senderKey == senderKey
}
}
| apache-2.0 | 2171f30e4c0a7845f519849eb6495485 | 32.173077 | 219 | 0.561623 | 4.813058 | false | false | false | false |
mssun/passforios | pass/Controllers/AboutTableViewController.swift | 2 | 1997 | //
// AboutTableViewController.swift
// pass
//
// Created by Mingshen Sun on 8/2/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import UIKit
class AboutTableViewController: BasicStaticTableViewController {
override func viewDidLoad() {
tableData = [
// section 0
[
[.title: "Website".localize(), .action: "link", .link: "https://github.com/mssun/pass-ios.git"],
[.title: "Help".localize(), .action: "link", .link: "https://github.com/mssun/passforios/wiki"],
[.title: "ContactDeveloper".localize(), .action: "link", .link: "mailto:[email protected]?subject=Pass%20for%20iOS"],
],
// section 1,
[
[.title: "OpenSourceComponents".localize(), .action: "segue", .link: "showOpenSourceComponentsSegue"],
[.title: "SpecialThanks".localize(), .action: "segue", .link: "showSpecialThanksSegue"],
],
]
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == tableData.count - 1 {
let view = UIView()
let footerLabel = UILabel(frame: CGRect(x: 8, y: 15, width: tableView.frame.width, height: 60))
footerLabel.numberOfLines = 0
footerLabel.text = "PassForIos".localize() + " \(Bundle.main.releaseVersionNumber!) (\(Bundle.main.buildVersionNumber!))"
footerLabel.font = UIFont.preferredFont(forTextStyle: .footnote)
footerLabel.textColor = UIColor.lightGray
footerLabel.textAlignment = .center
view.addSubview(footerLabel)
return view
}
return nil
}
override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 1 {
return "Acknowledgements".localize().uppercased()
}
return nil
}
}
| mit | 68b15522b121d14e3335b18c74b0a561 | 38.137255 | 145 | 0.595691 | 4.406181 | false | false | false | false |
tecgirl/firefox-ios | Client/Frontend/Settings/SettingsTableViewController.swift | 1 | 27206 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Account
import Shared
import UIKit
struct SettingsUX {
static let TableViewHeaderFooterHeight = CGFloat(44)
}
extension UILabel {
// iOS bug: NSAttributed string color is ignored without setting font/color to nil
func assign(attributed: NSAttributedString?) {
guard let attributed = attributed else { return }
let attribs = attributed.attributes(at: 0, effectiveRange: nil)
if attribs[NSAttributedStringKey.foregroundColor] == nil {
// If the text color attribute isn't set, use the table view row text color.
textColor = UIColor.theme.tableView.rowText
} else {
textColor = nil
font = nil
}
attributedText = attributed
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting: NSObject {
fileprivate var _title: NSAttributedString?
fileprivate var _footerTitle: NSAttributedString?
fileprivate var _cellHeight: CGFloat?
fileprivate var _image: UIImage?
weak var delegate: SettingsDelegate?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: URL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
var footerTitle: NSAttributedString? { return _footerTitle }
var cellHeight: CGFloat? { return _cellHeight}
fileprivate(set) var accessibilityIdentifier: String?
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .subtitle }
var accessoryType: UITableViewCellAccessoryType { return .none }
var textAlignment: NSTextAlignment { return .natural }
var image: UIImage? { return _image }
fileprivate(set) var enabled: Bool = true
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(_ cell: UITableViewCell) {
cell.detailTextLabel?.assign(attributed: status)
cell.detailTextLabel?.attributedText = status
cell.detailTextLabel?.numberOfLines = 0
cell.textLabel?.assign(attributed: title)
cell.textLabel?.textAlignment = textAlignment
cell.textLabel?.numberOfLines = 1
cell.textLabel?.lineBreakMode = .byTruncatingTail
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.selectionStyle = enabled ? .default : .none
cell.accessibilityIdentifier = accessibilityIdentifier
cell.imageView?.image = _image
if let title = title?.string {
if let detailText = cell.detailTextLabel?.text {
cell.accessibilityLabel = "\(title), \(detailText)"
} else if let status = status?.string {
cell.accessibilityLabel = "\(title), \(status)"
} else {
cell.accessibilityLabel = title
}
}
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.indentationWidth = 0
cell.layoutMargins = .zero
// So that the separator line goes all the way to the left edge.
cell.separatorInset = .zero
}
// Called when the pref is tapped.
func onClick(_ navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(_ navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self._title = title
self._footerTitle = footerTitle
self._cellHeight = cellHeight
self.delegate = delegate
self.enabled = enabled ?? true
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection: Setting {
fileprivate let children: [Setting]
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, children: [Setting]) {
self.children = children
super.init(title: title, footerTitle: footerTitle, cellHeight: cellHeight)
}
var count: Int {
var count = 0
for setting in children where !setting.hidden {
count += 1
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children where !setting.hidden {
if i == val {
return setting
}
i += 1
}
return nil
}
}
private class PaddedSwitch: UIView {
fileprivate static let Padding: CGFloat = 8
init(switchView: UISwitch) {
super.init(frame: .zero)
addSubview(switchView)
frame.size = CGSize(width: switchView.frame.width + PaddedSwitch.Padding, height: switchView.frame.height)
switchView.frame.origin = CGPoint(x: PaddedSwitch.Padding, y: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
let prefKey: String? // Sometimes a subclass will manage its own pref setting. In that case the prefkey will be nil
fileprivate let prefs: Prefs
fileprivate let defaultValue: Bool
fileprivate let settingDidChange: ((Bool) -> Void)?
fileprivate let statusText: NSAttributedString?
init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = attributedStatusText
super.init(title: attributedTitleText)
}
convenience init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
var statusTextAttributedString: NSAttributedString?
if let statusTextString = statusText {
statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])
}
self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange)
}
override var status: NSAttributedString? {
return statusText
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.SystemBlueColor
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.accessibilityIdentifier = prefKey
displayBool(control)
if let title = title {
if let status = status {
control.accessibilityLabel = "\(title.string), \(status.string)"
} else {
control.accessibilityLabel = title.string
}
cell.accessibilityLabel = nil
}
cell.accessoryView = PaddedSwitch(switchView: control)
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ control: UISwitch) {
writeBool(control)
settingDidChange?(control.isOn)
UnifiedTelemetry.recordEvent(category: .action, method: .change, object: .setting, value: self.prefKey, extras: ["to": control.isOn])
}
// These methods allow a subclass to control how the pref is saved
func displayBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
control.isOn = prefs.boolForKey(key) ?? defaultValue
}
func writeBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
prefs.setBool(control.isOn, forKey: key)
}
}
class PrefPersister: SettingValuePersister {
fileprivate let prefs: Prefs
let prefKey: String
init(prefs: Prefs, prefKey: String) {
self.prefs = prefs
self.prefKey = prefKey
}
func readPersistedValue() -> String? {
return prefs.stringForKey(prefKey)
}
func writePersistedValue(value: String?) {
if let value = value {
prefs.setString(value, forKey: prefKey)
} else {
prefs.removeObjectForKey(prefKey)
}
}
}
class StringPrefSetting: StringSetting {
init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
super.init(defaultValue: defaultValue, placeholder: placeholder, accessibilityIdentifier: accessibilityIdentifier, persister: PrefPersister(prefs: prefs, prefKey: prefKey), settingIsValid: isValueValid, settingDidChange: settingDidChange)
}
}
protocol SettingValuePersister {
func readPersistedValue() -> String?
func writePersistedValue(value: String?)
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional settingIsValid and settingDidChange callback
/// If settingIsValid returns false, the Setting will not change and the text remains red.
class StringSetting: Setting, UITextFieldDelegate {
var Padding: CGFloat = 8
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
fileprivate let persister: SettingValuePersister
let textField = UITextField()
init(defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, persister: SettingValuePersister, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
self.persister = persister
super.init()
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
if let placeholderColor = UIColor.theme.general.settingsTextPlaceholder {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedStringKey.foregroundColor: placeholderColor])
} else {
textField.placeholder = placeholder
}
textField.textAlignment = .center
textField.delegate = self
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
textField.snp.makeConstraints { make in
make.height.equalTo(44)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
}
textField.text = self.persister.readPersistedValue() ?? defaultValue
textFieldDidChange(textField)
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
/// This gives subclasses an opportunity to treat the user input string
/// before it is saved or tested.
/// Default implementation does nothing.
func prepareValidValue(userInput value: String?) -> String? {
return value
}
@objc func textFieldDidChange(_ textField: UITextField) {
let color = isValid(textField.text) ? UIColor.theme.tableView.rowText : UIColor.theme.general.destructiveRed
textField.textColor = color
}
@objc func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return isValid(textField.text)
}
@objc func textFieldDidEndEditing(_ textField: UITextField) {
let text = textField.text
if !isValid(text) {
return
}
self.persister.writePersistedValue(value: prepareValidValue(userInput: text))
// Call settingDidChange with text or nil.
settingDidChange?(text)
}
}
class CheckmarkSetting: Setting {
let onChanged: () -> Void
let isEnabled: () -> Bool
private let subtitle: NSAttributedString?
override var status: NSAttributedString? {
return subtitle
}
init(title: NSAttributedString, subtitle: NSAttributedString?, accessibilityIdentifier: String? = nil, isEnabled: @escaping () -> Bool, onChanged: @escaping () -> Void) {
self.subtitle = subtitle
self.onChanged = onChanged
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.accessoryType = .checkmark
cell.tintColor = isEnabled() ? UIColor.theme.tableView.rowActionAccessory : UIColor.clear
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if !isEnabled() {
onChanged()
}
}
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional isEnabled and mandatory onClick callback
/// isEnabled is called on each tableview.reloadData. If it returns
/// false then the 'button' appears disabled.
class ButtonSetting: Setting {
let onButtonClick: (UINavigationController?) -> Void
let destructive: Bool
let isEnabled: (() -> Bool)?
init(title: NSAttributedString?, destructive: Bool = false, accessibilityIdentifier: String, isEnabled: (() -> Bool)? = nil, onClick: @escaping (UINavigationController?) -> Void) {
self.onButtonClick = onClick
self.destructive = destructive
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if isEnabled?() ?? true {
cell.textLabel?.textColor = destructive ? UIColor.theme.general.destructiveRed : UIColor.theme.general.highlightBlue
} else {
cell.textLabel?.textColor = UIColor.theme.tableView.disabledRowText
}
cell.textLabel?.textAlignment = .center
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.selectionStyle = .none
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if isEnabled?() ?? true {
onButtonClick(navigationController)
}
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .none
}
}
override var accessoryType: UITableViewCellAccessoryType { return .none }
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) {
// This method will get called twice: once when the user signs in, and once
// when the account is verified by email – on this device or another.
// If the user hasn't dismissed the fxa content view controller,
// then we should only do that (thus finishing the sign in/verification process)
// once the account is verified.
// By the time we get to here, we should be syncing or just about to sync in the
// background, most likely from FxALoginHelper.
if flags.verified {
_ = settings.navigationController?.popToRootViewController(animated: true)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.refresh()
}
}
func contentViewControllerDidCancel(_ viewController: FxAContentViewController) {
NSLog("didCancel")
_ = settings.navigationController?.popToRootViewController(animated: true)
}
}
class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
@objc
protocol SettingsDelegate: AnyObject {
func settingsOpenURLInNewTab(_ url: URL)
}
// The base settings view controller.
class SettingsTableViewController: ThemedTableViewController {
typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection]
fileprivate let Identifier = "CellIdentifier"
fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var settings = [SettingSection]()
weak var settingsDelegate: SettingsDelegate?
var profile: Profile!
var tabManager: TabManager!
var hasSectionSeparatorLine = true
/// Used to calculate cell heights.
fileprivate lazy var dummyToggleCell: UITableViewCell = {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell")
cell.accessoryView = UISwitch()
return cell
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.register(ThemedTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = UIView(frame: CGRect(width: view.frame.width, height: 30))
tableView.estimatedRowHeight = 44
tableView.estimatedSectionHeaderHeight = 44
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
settings = generateSettings()
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidStartSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidFinishSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(firefoxAccountDidChange), name: .FirefoxAccountChanged, object: nil)
applyTheme()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
[Notification.Name.ProfileDidStartSyncing, Notification.Name.ProfileDidFinishSyncing, Notification.Name.FirefoxAccountChanged].forEach { name in
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
}
// Override to provide settings in subclasses
func generateSettings() -> [SettingSection] {
return []
}
@objc fileprivate func syncDidChangeState() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
@objc fileprivate func refresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { state in
DispatchQueue.main.async { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
@objc func firefoxAccountDidChange() {
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let _ = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = UITableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
}
setting.onConfigureCell(cell)
cell.backgroundColor = UIColor.theme.tableView.rowBackground
return cell
}
return tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return settings.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! ThemedTableSectionHeaderFooterView
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle.uppercased()
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 || !hasSectionSeparatorLine {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
headerView.applyTheme()
return headerView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let sectionSetting = settings[section]
guard let sectionFooter = sectionSetting.footerTitle?.string else {
return nil
}
let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! ThemedTableSectionHeaderFooterView
footerView.titleLabel.text = sectionFooter
footerView.titleAlignment = .top
footerView.showBottomBorder = false
footerView.applyTheme()
return footerView
}
// To hide a footer dynamically requires returning nil from viewForFooterInSection
// and setting the height to zero.
// However, we also want the height dynamically calculated, there is a magic constant
// for that: `UITableViewAutomaticDimension`.
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let sectionSetting = settings[section]
if let _ = sectionSetting.footerTitle?.string {
return UITableViewAutomaticDimension
}
return 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = settings[indexPath.section]
// Workaround for calculating the height of default UITableViewCell cells with a subtitle under
// the title text label.
if let setting = section[indexPath.row], setting is BoolSetting && setting.status != nil {
return calculateStatusCellHeightForSetting(setting)
}
if let setting = section[indexPath.row], let height = setting.cellHeight {
return height
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = settings[indexPath.section]
if let setting = section[indexPath.row], setting.enabled {
setting.onClick(navigationController)
}
}
fileprivate func calculateStatusCellHeightForSetting(_ setting: Setting) -> CGFloat {
dummyToggleCell.layoutSubviews()
let topBottomMargin: CGFloat = 10
let width = dummyToggleCell.contentView.frame.width - 2 * dummyToggleCell.separatorInset.left
return
heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) +
heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) +
2 * topBottomMargin
}
fileprivate func heightForLabel(_ label: UILabel, width: CGFloat, text: String?) -> CGFloat {
guard let text = text else { return 0 }
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let attrs = [NSAttributedStringKey.font: label.font as Any]
let boundingRect = NSString(string: text).boundingRect(with: size,
options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
return boundingRect.height
}
}
| mpl-2.0 | 791ae91215b694cfa4f9e198b90597ac | 38.480406 | 309 | 0.679987 | 5.33896 | false | false | false | false |
EstebanVallejo/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/MercadoPagoService.swift | 1 | 1786 | //
// MercadoPagoService.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 5/2/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import Foundation
import UIKit
public class MercadoPagoService : NSObject {
var baseURL : String!
init (baseURL : String) {
super.init()
self.baseURL = baseURL
}
public func request(uri: String, params: String?, body: AnyObject?, method: String, success: (jsonResult: AnyObject?) -> Void, failure: ((error: NSError) -> Void)?) {
var url = baseURL + uri
if params != nil {
url += "?" + params!
}
var finalURL: NSURL = NSURL(string: url)!
var request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = finalURL
request.HTTPMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if body != nil {
request.HTTPBody = (body as! NSString).dataUsingEncoding(NSUTF8StringEncoding)
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
NSURLConnection.sendAsynchronousRequest(request, queue:
NSOperationQueue.mainQueue(), completionHandler: {(response:
NSURLResponse!,data: NSData!,error: NSError!) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error == nil {
success(jsonResult: NSJSONSerialization.JSONObjectWithData(data,
options:NSJSONReadingOptions.MutableContainers, error: nil))
}
else {
if failure != nil {
failure!(error: error)
}
}
})
}
} | mit | 4c0e436ba47550289d956af529c3e2ee | 31.490909 | 170 | 0.595745 | 5.299703 | false | false | false | false |
Altece/Reggie | Source/Lexer.swift | 1 | 2017 | import Foundation
/// A generator which emits values that belong to a given automata's language.
public struct Lexer<Input> {
/// - note: This is `internal` for testing only.
internal var iterator: AnyIterator<Input>
/// Create a new lexer which reads from the given iterator.
public init<Iterator: IteratorProtocol>(reading iterator: Iterator)
where Input == Iterator.Element {
self.iterator = AnyIterator(iterator)
}
/// Create a new lexer which reads from the given sequence.
public init<S: Sequence>(reading sequence: S)
where Input == S.Iterator.Element {
self.iterator = AnyIterator(sequence.makeIterator())
}
/// Generate the next match for the given automata.
/// - parameter automata: The automata against which this lexer's input should match.
/// - returns: `nil` if no match is found. Otherwise, the matching subsequence is returned.
/// - note: If a match isn't found for an automata, it might match another. The internal iterator
/// will only advance when a match is found.
public mutating func next<Meta>(matching automata: Automata<Input, Meta>) -> [Input]? {
var automata = automata,
consumed: [Input] = [],
passingInput: [Input]? = nil
outerLoop: while let unit = iterator.next() {
guard let advanced = automata.advance(with: unit) else {
guard let passing = passingInput else {
consumed.append(unit)
break outerLoop
}
self.iterator = AnyIterator(emitting: [unit], before: iterator)
return passing
}
consumed.append(unit)
if advanced.isPassing { passingInput = consumed }
automata = advanced
}
guard let passing = passingInput else {
iterator = AnyIterator(emitting: consumed, before: iterator)
return nil
}
let unread = consumed[passing.endIndex..<consumed.endIndex]
iterator = AnyIterator(emitting: unread, before: iterator)
return passing
}
}
| mit | 2ed4e22c2c44d48b7066d7214bc01748 | 37.788462 | 99 | 0.66237 | 4.532584 | false | false | false | false |
Eonil/EditorLegacy | Modules/EditorToolComponents/EditorToolComponents/ShellTaskExecutionController.swift | 1 | 4060 | //
// ShellTaskExecutionController.swift
// Precompilation
//
// Created by Hoon H. on 2015/01/17.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import EditorCommon
public protocol ShellTaskExecutionControllerDelegate: class {
func shellTaskExecutableControllerDidReadFromStandardOutput(String)
func shellTaskExecutableControllerDidReadFromStandardError(String)
func shellTaskExecutableControllerRemoteProcessDidTerminate(#exitCode:Int32, reason:NSTaskTerminationReason)
}
/// Runs a non-interactive shell.
/// Non-interactive shell (so non-`pty`) can provide seaprated error output.
///
/// Collection of utility functions to run `sh` in remote child process.
/// This spawns a new background thread to manage the remote process.
/// The background thread will not finish until the remote process finishes.
///
/// Any execution request will return an `Shell.ExecutionController` to control the
/// background thread. You can control the execution using this object. You have to
/// keep this even you don't want to control it, because killing this object will
/// send `SIGNKILL` to the remote process if the process is not finished yet.
///
/// This internally uses `sh` to execute the command.
/// On OS X, it is likely to be `bash`.
///
/// You can use a shell command `exec` to run a desired command to be executed by
/// replacing the shell process itself.
///
public class ShellTaskExecutionController {
public weak var delegate:ShellTaskExecutionControllerDelegate?
public init() {
_remoteTask.standardInput = _stdinPipe
_remoteTask.standardOutput = _stdoutPipe
_remoteTask.standardError = _stderrPipe
_stdoutPipe.fileHandleForReading.readabilityHandler = { [weak self](f:NSFileHandle!)->() in
self?._stdoutReader.push(f.availableData)
()
}
_stderrPipe.fileHandleForReading.readabilityHandler = { [weak self](f:NSFileHandle!)->() in
self?._stderrReader.push(f.availableData)
()
}
_stdoutReader.onString = { [weak self] s in
self?.delegate?.shellTaskExecutableControllerDidReadFromStandardOutput(s)
()
}
_stderrReader.onString = { [weak self] s in
self?.delegate?.shellTaskExecutableControllerDidReadFromStandardError(s)
()
}
_remoteTask.terminationHandler = { [weak self] t in
self?.delegate?.shellTaskExecutableControllerRemoteProcessDidTerminate(exitCode: t.terminationStatus, reason: t.terminationReason)
()
}
}
deinit {
precondition(_remoteTask.running == false, "You must quit the remote process before this object deinitialises.")
}
public var exitCode:Int32 {
get {
return _remoteTask.terminationStatus
}
}
public var exitReason:NSTaskTerminationReason {
get {
return _remoteTask.terminationReason
}
}
public func launch(#workingDirectoryURL:NSURL) {
assert(workingDirectoryURL.existingAsDirectoryFile)
let p1 = workingDirectoryURL.path!
_remoteTask.currentDirectoryPath = p1
_remoteTask.launchPath = "/bin/bash" // TODO: Need to use `sh` for regularity. But `sh` doesn't work for `cargo`, so temporarily fallback to `bash`.
_remoteTask.arguments = ["--login", "-s"]
_remoteTask.launch()
}
public func writeToStandardInput(s:String) {
_stdinPipe.fileHandleForWriting.writeUTF8String(s)
}
public func waitUntilExit() -> Int32 {
_remoteTask.waitUntilExit()
assert(_remoteTask.running == false)
return _remoteTask.terminationStatus
}
/// Sends `SIGTERM` to notify remote process to quit as soon as possible.
public func terminate() {
_remoteTask.terminate()
}
/// Sends `SIGKILL` to forces remote process to quit immediately.
/// Remote process will be killed by kernel and cannot perform any cleanup.
public func kill() {
Darwin.kill(_remoteTask.processIdentifier, SIGKILL)
}
////
private let _remoteTask = NSTask()
private let _stdinPipe = NSPipe()
private let _stdoutPipe = NSPipe()
private let _stderrPipe = NSPipe()
private var _stdoutReader = UTF8StringDispatcher()
private var _stderrReader = UTF8StringDispatcher()
}
| mit | 8aec697fc1d3bae06746c5db94e06a11 | 28.42029 | 154 | 0.741379 | 3.690909 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Settings/HomepageSettings/HomePageSettingViewController.swift | 2 | 13089 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
class HomePageSettingViewController: SettingsTableViewController, FeatureFlaggable {
// MARK: - Variables
/* variables for checkmark settings */
let prefs: Prefs
var currentNewTabChoice: NewTabPage!
var currentStartAtHomeSetting: StartAtHomeSetting!
var hasHomePage = false
var wallpaperManager: WallpaperManagerInterface
var isJumpBackInSectionEnabled: Bool {
return featureFlags.isFeatureEnabled(.jumpBackIn, checking: .buildOnly)
}
var isRecentlySavedSectionEnabled: Bool {
return featureFlags.isFeatureEnabled(.recentlySaved, checking: .buildOnly)
}
var isWallpaperSectionEnabled: Bool {
return wallpaperManager.canSettingsBeShown &&
featureFlags.isFeatureEnabled(.wallpapers, checking: .buildOnly)
}
var isPocketSectionEnabled: Bool {
return featureFlags.isFeatureEnabled(.pocket, checking: .buildOnly)
}
var isPocketSponsoredStoriesEnabled: Bool {
return featureFlags.isFeatureEnabled(.sponsoredPocket, checking: .buildOnly)
}
var isHistoryHighlightsSectionEnabled: Bool {
return featureFlags.isFeatureEnabled(.historyHighlights, checking: .buildOnly)
}
// MARK: - Initializers
init(prefs: Prefs,
wallpaperManager: WallpaperManagerInterface = WallpaperManager()) {
self.prefs = prefs
self.wallpaperManager = wallpaperManager
super.init(style: .grouped)
title = .SettingsHomePageSectionName
navigationController?.navigationBar.accessibilityIdentifier = AccessibilityIdentifiers.Settings.Homepage.homePageNavigationBar
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.keyboardDismissMode = .onDrag
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.post(name: .HomePanelPrefsChanged, object: nil)
}
// MARK: - Methods
override func generateSettings() -> [SettingSection] {
let customizeFirefoxHomeSection = customizeFirefoxSettingSection()
let customizeHomePageSection = customizeHomeSettingSection()
guard let startAtHomeSection = setupStartAtHomeSection() else {
return [customizeFirefoxHomeSection, customizeHomePageSection]
}
return [startAtHomeSection, customizeFirefoxHomeSection, customizeHomePageSection]
}
private func customizeHomeSettingSection() -> SettingSection {
// The Home button and the New Tab page can be set independently
self.currentNewTabChoice = NewTabAccessors.getHomePage(self.prefs)
self.hasHomePage = HomeButtonHomePageAccessors.getHomePage(self.prefs) != nil
let onFinished = {
self.prefs.setString(self.currentNewTabChoice.rawValue, forKey: NewTabAccessors.HomePrefKey)
self.tableView.reloadData()
}
let showTopSites = CheckmarkSetting(
title: NSAttributedString(string: .SettingsNewTabTopSites),
subtitle: nil,
accessibilityIdentifier: "HomeAsFirefoxHome",
isChecked: { return self.currentNewTabChoice == NewTabPage.topSites },
onChecked: {
self.currentNewTabChoice = NewTabPage.topSites
onFinished()
})
let showWebPage = WebPageSetting(
prefs: prefs,
prefKey: PrefsKeys.HomeButtonHomePageURL,
defaultValue: nil,
placeholder: .CustomNewPageURL,
accessibilityIdentifier: "HomeAsCustomURL",
isChecked: { return !showTopSites.isChecked() },
settingDidChange: { (string) in
self.currentNewTabChoice = NewTabPage.homePage
self.prefs.setString(self.currentNewTabChoice.rawValue, forKey: NewTabAccessors.HomePrefKey)
self.tableView.reloadData()
})
showWebPage.textField.textAlignment = .natural
return SettingSection(title: NSAttributedString(string: .SettingsHomePageURLSectionTitle),
footerTitle: NSAttributedString(string: .Settings.Homepage.Current.Description),
children: [showTopSites, showWebPage])
}
private func customizeFirefoxSettingSection() -> SettingSection {
// Setup
var sectionItems = [Setting]()
let pocketSponsoredSetting = BoolSetting(with: .sponsoredPocket,
titleText: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.SponsoredPocket))
// This sets whether the cell is enabled or not, and not the setting itself.
pocketSponsoredSetting.enabled = featureFlags.isFeatureEnabled(
.pocket,
checking: .buildAndUser)
let pocketSetting = BoolSetting(
with: .pocket,
titleText: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.Pocket)) { [weak self] in
// Disable sponsored option if pocket stories are disabled
pocketSponsoredSetting.enabled = $0
self?.tableView.reloadData()
}
let jumpBackInSetting = BoolSetting(with: .jumpBackIn,
titleText: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.JumpBackIn))
let recentlySavedSetting = BoolSetting(with: .recentlySaved,
titleText: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.RecentlySaved))
let historyHighlightsSetting = BoolSetting(with: .historyHighlights,
titleText: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.RecentlyVisited))
let wallpaperSetting = WallpaperSettings(settings: self, wallpaperManager: wallpaperManager)
// Section ordering
sectionItems.append(TopSitesSettings(settings: self))
if isJumpBackInSectionEnabled {
sectionItems.append(jumpBackInSetting)
}
if isRecentlySavedSectionEnabled {
sectionItems.append(recentlySavedSetting)
}
if isHistoryHighlightsSectionEnabled {
sectionItems.append(historyHighlightsSetting)
}
if isPocketSectionEnabled {
sectionItems.append(pocketSetting)
// Only show the sponsored stories setting if the Pocket setting is showing
if isPocketSponsoredStoriesEnabled {
sectionItems.append(pocketSponsoredSetting)
}
}
if isWallpaperSectionEnabled {
sectionItems.append(wallpaperSetting)
}
return SettingSection(title: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.Title),
footerTitle: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.Description),
children: sectionItems)
}
private func setupStartAtHomeSection() -> SettingSection? {
guard featureFlags.isFeatureEnabled(.startAtHome, checking: .buildOnly) else { return nil }
guard let startAtHomeSetting: StartAtHomeSetting = featureFlags.getCustomState(for: .startAtHome) else { return nil }
currentStartAtHomeSetting = startAtHomeSetting
typealias a11y = AccessibilityIdentifiers.Settings.Homepage.StartAtHome
let onOptionSelected: (Bool, StartAtHomeSetting) -> Void = { state, option in
self.featureFlags.set(feature: .startAtHome, to: option)
self.tableView.reloadData()
let extras = [TelemetryWrapper.EventExtraKey.preference.rawValue: PrefsKeys.FeatureFlags.StartAtHome,
TelemetryWrapper.EventExtraKey.preferenceChanged.rawValue: option.rawValue]
TelemetryWrapper.recordEvent(category: .action, method: .change, object: .setting, extras: extras)
}
let afterFourHoursOption = CheckmarkSetting(
title: NSAttributedString(string: .Settings.Homepage.StartAtHome.AfterFourHours),
subtitle: nil,
accessibilityIdentifier: a11y.afterFourHours,
isChecked: { return self.currentStartAtHomeSetting == .afterFourHours },
onChecked: {
self.currentStartAtHomeSetting = .afterFourHours
onOptionSelected(true, .afterFourHours)
})
let alwaysOption = CheckmarkSetting(
title: NSAttributedString(string: .Settings.Homepage.StartAtHome.Always),
subtitle: nil,
accessibilityIdentifier: a11y.always,
isChecked: { return self.currentStartAtHomeSetting == .always },
onChecked: {
self.currentStartAtHomeSetting = .always
onOptionSelected(true, .always)
})
let neverOption = CheckmarkSetting(
title: NSAttributedString(string: .Settings.Homepage.StartAtHome.Never),
subtitle: nil,
accessibilityIdentifier: a11y.disabled,
isChecked: { return self.currentStartAtHomeSetting == .disabled },
onChecked: {
self.currentStartAtHomeSetting = .disabled
onOptionSelected(false, .disabled)
})
let section = SettingSection(title: NSAttributedString(string: .Settings.Homepage.StartAtHome.SectionTitle),
footerTitle: NSAttributedString(string: .Settings.Homepage.StartAtHome.SectionDescription),
children: [alwaysOption, neverOption, afterFourHoursOption])
return section
}
}
// MARK: - TopSitesSettings
extension HomePageSettingViewController {
class TopSitesSettings: Setting, FeatureFlaggable {
var profile: Profile
override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return AccessibilityIdentifiers.Settings.Homepage.CustomizeFirefox.Shortcuts.settingsPage }
override var style: UITableViewCell.CellStyle { return .value1 }
override var status: NSAttributedString {
let areShortcutsOn = featureFlags.isFeatureEnabled(.topSites, checking: .userOnly)
let status: String = areShortcutsOn ? .Settings.Homepage.Shortcuts.ToggleOn : .Settings.Homepage.Shortcuts.ToggleOff
return NSAttributedString(string: String(format: status))
}
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: .Settings.Homepage.Shortcuts.ShortcutsPageTitle))
}
override func onClick(_ navigationController: UINavigationController?) {
let topSitesVC = TopSitesSettingsViewController()
topSitesVC.profile = profile
navigationController?.pushViewController(topSitesVC, animated: true)
}
}
}
// MARK: - WallpaperSettings
extension HomePageSettingViewController {
class WallpaperSettings: Setting, FeatureFlaggable {
var settings: SettingsTableViewController
var tabManager: TabManager
var wallpaperManager: WallpaperManagerInterface
override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator }
override var accessibilityIdentifier: String? { return AccessibilityIdentifiers.Settings.Homepage.CustomizeFirefox.wallpaper }
override var style: UITableViewCell.CellStyle { return .value1 }
init(settings: SettingsTableViewController,
and tabManager: TabManager = BrowserViewController.foregroundBVC().tabManager,
wallpaperManager: WallpaperManagerInterface = WallpaperManager()
) {
self.settings = settings
self.tabManager = tabManager
self.wallpaperManager = wallpaperManager
super.init(title: NSAttributedString(string: .Settings.Homepage.CustomizeFirefoxHome.Wallpaper))
}
override func onClick(_ navigationController: UINavigationController?) {
if wallpaperManager.canSettingsBeShown {
let viewModel = WallpaperSettingsViewModel(wallpaperManager: wallpaperManager,
tabManager: tabManager,
theme: settings.themeManager.currentTheme)
let wallpaperVC = WallpaperSettingsViewController(viewModel: viewModel)
navigationController?.pushViewController(wallpaperVC, animated: true)
}
}
}
}
| mpl-2.0 | ed1bac2d6d66201db5c685c01f3a6888 | 43.070707 | 147 | 0.671556 | 5.636951 | false | false | false | false |
lojals/semanasanta | Semana Santa/Semana Santa/Classes/SQLiteDB/SQLiteDB.swift | 1 | 15926 | //
// SQLiteDB.swift
// TasksGalore
//
// Created by Fahim Farook on 12/6/14.
// Copyright (c) 2014 RookSoft Pte. Ltd. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#else
import AppKit
#endif
let SQLITE_DATE = SQLITE_NULL + 1
private let SQLITE_STATIC = sqlite3_destructor_type(COpaquePointer(bitPattern:0))
private let SQLITE_TRANSIENT = sqlite3_destructor_type(COpaquePointer(bitPattern:-1))
// MARK:- SQLColumn Class - Column Definition
@objc class SQLColumn {
var value:AnyObject? = nil
var type:CInt = -1
init(value:AnyObject, type:CInt) {
// println("SQLiteDB - Initialize column with type: \(type), value: \(value)")
self.value = value
self.type = type
}
// New conversion functions
func asString()->String {
switch (type) {
case SQLITE_INTEGER, SQLITE_FLOAT:
return "\(value!)"
case SQLITE_TEXT:
return value as String
case SQLITE_BLOB:
if let str = NSString(data:value as NSData, encoding:NSUTF8StringEncoding) {
return str
} else {
return ""
}
case SQLITE_NULL:
return ""
case SQLITE_DATE:
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
return fmt.stringFromDate(value as NSDate)
default:
return ""
}
}
func asInt()->Int {
switch (type) {
case SQLITE_INTEGER, SQLITE_FLOAT:
return value as Int
case SQLITE_TEXT:
let str = value as NSString
return str.integerValue
case SQLITE_BLOB:
if let str = NSString(data:value as NSData, encoding:NSUTF8StringEncoding) {
return str.integerValue
} else {
return 0
}
case SQLITE_NULL:
return 0
case SQLITE_DATE:
return Int((value as NSDate).timeIntervalSince1970)
default:
return 0
}
}
func asDouble()->Double {
switch (type) {
case SQLITE_INTEGER, SQLITE_FLOAT:
return value as Double
case SQLITE_TEXT:
let str = value as NSString
return str.doubleValue
case SQLITE_BLOB:
if let str = NSString(data:value as NSData, encoding:NSUTF8StringEncoding) {
return str.doubleValue
} else {
return 0.0
}
case SQLITE_NULL:
return 0.0
case SQLITE_DATE:
return (value as NSDate).timeIntervalSince1970
default:
return 0.0
}
}
func asData()->NSData? {
switch (type) {
case SQLITE_INTEGER, SQLITE_FLOAT:
let str = "\(value)" as NSString
return str.dataUsingEncoding(NSUTF8StringEncoding)
case SQLITE_TEXT:
let str = value as NSString
return str.dataUsingEncoding(NSUTF8StringEncoding)
case SQLITE_BLOB:
return value as? NSData
case SQLITE_NULL:
return nil
case SQLITE_DATE:
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
let str = fmt.stringFromDate(value as NSDate)
return str.dataUsingEncoding(NSUTF8StringEncoding)
default:
return nil
}
}
func asDate()->NSDate? {
switch (type) {
case SQLITE_INTEGER, SQLITE_FLOAT:
let tm = value as Double
return NSDate(timeIntervalSince1970:tm)
case SQLITE_TEXT:
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
return fmt.dateFromString(value as String)
case SQLITE_BLOB:
if let str = NSString(data:value as NSData, encoding:NSUTF8StringEncoding) {
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
return fmt.dateFromString(str)
} else {
return nil
}
case SQLITE_NULL:
return nil
case SQLITE_DATE:
return value as? NSDate
default:
return nil
}
}
func description()->String {
return "Type: \(type), Value: \(value)"
}
}
// MARK:- SQLRow Class - Row Definition
@objc class SQLRow {
var data = Dictionary<String, SQLColumn>()
subscript(key: String) -> SQLColumn? {
get {
return data[key]
}
set(newVal) {
data[key] = newVal
}
}
func description()->String {
return data.description
}
}
// MARK:- SQLiteDB Class - Does all the work
@objc class SQLiteDB {
let DB_NAME = "data.db"
let QUEUE_LABLE = "SQLiteDB"
private var db:COpaquePointer = nil
private var queue:dispatch_queue_t
private var fmt = NSDateFormatter()
private var GROUP = ""
struct Static {
static var instance:SQLiteDB? = nil
static var token:dispatch_once_t = 0
}
class func sharedInstance() -> SQLiteDB! {
dispatch_once(&Static.token) {
Static.instance = self(gid:"")
}
return Static.instance!
}
class func sharedInstance(gid:String) -> SQLiteDB! {
dispatch_once(&Static.token) {
Static.instance = self(gid:gid)
}
return Static.instance!
}
required init(gid:String) {
assert(Static.instance == nil, "Singleton already initialized!")
GROUP = gid
// Set queue
queue = dispatch_queue_create(QUEUE_LABLE, nil)
// Set up for file operations
let fm = NSFileManager.defaultManager()
let dbName:String = String.fromCString(DB_NAME)!
var docDir = ""
// Is this for an app group?
if GROUP.isEmpty {
// Get path to DB in Documents directory
docDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
} else {
// Get path to shared group folder
if let url = fm.containerURLForSecurityApplicationGroupIdentifier(GROUP) {
docDir = url.path!
} else {
assert(false, "Error getting container URL for group: \(GROUP)")
}
}
let path = docDir.stringByAppendingPathComponent(dbName)
println("Database path: \(path)")
// Check if copy of DB is there in Documents directory
if !(fm.fileExistsAtPath(path)) {
// The database does not exist, so copy to Documents directory
if let from = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent(dbName) {
var error:NSError?
if !fm.copyItemAtPath(from, toPath: path, error: &error) {
println("SQLiteDB - failed to copy writable version of DB!")
println("Error - \(error!.localizedDescription)")
return
}
}
}
// Open the DB
let cpath = path.cStringUsingEncoding(NSUTF8StringEncoding)
let error = sqlite3_open(cpath!, &db)
if error != SQLITE_OK {
// Open failed, close DB and fail
println("SQLiteDB - failed to open DB!")
sqlite3_close(db)
}
fmt.dateFormat = "YYYY-MM-dd HH:mm:ss"
}
deinit {
closeDatabase()
}
private func closeDatabase() {
if db != nil {
// Get launch count value
let ud = NSUserDefaults.standardUserDefaults()
var launchCount = ud.integerForKey("LaunchCount")
launchCount--
println("SQLiteDB - Launch count \(launchCount)")
var clean = false
if launchCount < 0 {
clean = true
launchCount = 500
}
ud.setInteger(launchCount, forKey: "LaunchCount")
ud.synchronize()
// Do we clean DB?
if !clean {
sqlite3_close(db)
return
}
// Clean DB
println("SQLiteDB - Optimize DB")
let sql = "VACUUM; ANALYZE"
if execute(sql) != SQLITE_OK {
println("SQLiteDB - Error cleaning DB")
}
sqlite3_close(db)
}
}
// Execute SQL with parameters and return result code
func execute(sql:String, parameters:[AnyObject]?=nil)->CInt {
var result:CInt = 0
dispatch_sync(queue) {
let stmt = self.prepare(sql, params:parameters)
if stmt != nil {
result = self.execute(stmt, sql:sql)
}
}
return result
}
// Run SQL query with parameters
func query(sql:String, parameters:[AnyObject]?=nil)->[SQLRow] {
var rows = [SQLRow]()
dispatch_sync(queue) {
let stmt = self.prepare(sql, params:parameters)
if stmt != nil {
rows = self.query(stmt, sql:sql)
}
}
return rows
}
// Show alert with either supplied message or last error
func alert(msg:String) {
dispatch_async(dispatch_get_main_queue()) {
#if os(iOS)
let alert = UIAlertView(title: "SQLiteDB", message:msg, delegate: nil, cancelButtonTitle: "OK")
alert.show()
#else
let alert = NSAlert()
alert.addButtonWithTitle("OK")
alert.messageText = "SQLiteDB"
alert.informativeText = msg
alert.alertStyle = NSAlertStyle.WarningAlertStyle
alert.runModal()
#endif
}
}
// Private method which prepares the SQL
private func prepare(sql:String, params:[AnyObject]?)->COpaquePointer {
var stmt:COpaquePointer = nil
var cSql = sql.cStringUsingEncoding(NSUTF8StringEncoding)
// Prepare
let result = sqlite3_prepare_v2(self.db, cSql!, -1, &stmt, nil)
if result != SQLITE_OK {
sqlite3_finalize(stmt)
if let error = String.fromCString(sqlite3_errmsg(self.db)) {
let msg = "SQLiteDB - failed to prepare SQL: \(sql), Error: \(error)"
println(msg)
}
return nil
}
// Bind parameters, if any
if params != nil {
// Validate parameters
let cntParams = sqlite3_bind_parameter_count(stmt)
let cnt = CInt(params!.count)
if cntParams != cnt {
let msg = "SQLiteDB - failed to bind parameters, counts did not match. SQL: \(sql), Parameters: \(params)"
println(msg)
return nil
}
var flag:CInt = 0
// Text & BLOB values passed to a C-API do not work correctly if they are not marked as transient.
for ndx in 1...cnt {
// println("Binding: \(params![ndx-1]) at Index: \(ndx)")
// Check for data types
if let txt = params![ndx-1] as? String {
flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT)
} else if let data = params![ndx-1] as? NSData {
flag = sqlite3_bind_blob(stmt, CInt(ndx), data.bytes, CInt(data.length), SQLITE_TRANSIENT)
} else if let date = params![ndx-1] as? NSDate {
let txt = fmt.stringFromDate(date)
flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT)
} else if let val = params![ndx-1] as? Double {
flag = sqlite3_bind_double(stmt, CInt(ndx), CDouble(val))
} else if let val = params![ndx-1] as? Int {
flag = sqlite3_bind_int(stmt, CInt(ndx), CInt(val))
} else {
flag = sqlite3_bind_null(stmt, CInt(ndx))
}
// Check for errors
if flag != SQLITE_OK {
sqlite3_finalize(stmt)
if let error = String.fromCString(sqlite3_errmsg(self.db)) {
let msg = "SQLiteDB - failed to bind for SQL: \(sql), Parameters: \(params), Index: \(ndx) Error: \(error)"
println(msg)
}
return nil
}
}
}
return stmt
}
// Private method which handles the actual execution of an SQL statement
private func execute(stmt:COpaquePointer, sql:String)->CInt {
// Step
var result = sqlite3_step(stmt)
if result != SQLITE_OK && result != SQLITE_DONE {
sqlite3_finalize(stmt)
if let err = String.fromCString(sqlite3_errmsg(self.db)) {
let msg = "SQLiteDB - failed to execute SQL: \(sql), Error: \(err)"
println(msg)
}
return 0
}
// Is this an insert
let upp = sql.uppercaseString
if upp.hasPrefix("INSERT ") {
// Known limitations: http://www.sqlite.org/c3ref/last_insert_rowid.html
let rid = sqlite3_last_insert_rowid(self.db)
result = CInt(rid)
} else if upp.hasPrefix("DELETE") || upp.hasPrefix("UPDATE") {
var cnt = sqlite3_changes(self.db)
if cnt == 0 {
cnt++
}
result = CInt(cnt)
} else {
result = 1
}
// Finalize
sqlite3_finalize(stmt)
return result
}
// Private method which handles the actual execution of an SQL query
private func query(stmt:COpaquePointer, sql:String)->[SQLRow] {
var rows = [SQLRow]()
var fetchColumnInfo = true
var columnCount:CInt = 0
var columnNames = [String]()
var columnTypes = [CInt]()
var result = sqlite3_step(stmt)
while result == SQLITE_ROW {
// Should we get column info?
if fetchColumnInfo {
columnCount = sqlite3_column_count(stmt)
for index in 0..<columnCount {
// Get column name
let name = sqlite3_column_name(stmt, index)
columnNames.append(String.fromCString(name)!)
// Get column type
columnTypes.append(self.getColumnType(index, stmt:stmt))
}
fetchColumnInfo = false
}
// Get row data for each column
var row = SQLRow()
for index in 0..<columnCount {
let key = columnNames[Int(index)]
let type = columnTypes[Int(index)]
if let val:AnyObject = self.getColumnValue(index, type:type, stmt:stmt) {
// println("Column type:\(type) with value:\(val)")
let col = SQLColumn(value: val, type: type)
row[key] = col
}
}
rows.append(row)
// Next row
result = sqlite3_step(stmt)
}
sqlite3_finalize(stmt)
return rows
}
// Get column type
private func getColumnType(index:CInt, stmt:COpaquePointer)->CInt {
var type:CInt = 0
// Column types - http://www.sqlite.org/datatype3.html (section 2.2 table column 1)
let blobTypes = ["BINARY", "BLOB", "VARBINARY"]
let charTypes = ["CHAR", "CHARACTER", "CLOB", "NATIONAL VARYING CHARACTER", "NATIVE CHARACTER", "NCHAR", "NVARCHAR", "TEXT", "VARCHAR", "VARIANT", "VARYING CHARACTER"]
let dateTypes = ["DATE", "DATETIME", "TIME", "TIMESTAMP"]
let intTypes = ["BIGINT", "BIT", "BOOL", "BOOLEAN", "INT", "INT2", "INT8", "INTEGER", "MEDIUMINT", "SMALLINT", "TINYINT"]
let nullTypes = ["NULL"]
let realTypes = ["DECIMAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT", "NUMERIC", "REAL"]
// Determine type of column - http://www.sqlite.org/c3ref/c_blob.html
let buf = sqlite3_column_decltype(stmt, index)
// println("SQLiteDB - Got column type: \(buf)")
if buf != nil {
var tmp = String.fromCString(buf)!.uppercaseString
// Remove brackets
let pos = tmp.positionOf("(")
if pos > 0 {
tmp = tmp.subStringTo(pos)
}
// Remove unsigned?
// Remove spaces
// Is the data type in any of the pre-set values?
// println("SQLiteDB - Cleaned up column type: \(tmp)")
if contains(intTypes, tmp) {
return SQLITE_INTEGER
}
if contains(realTypes, tmp) {
return SQLITE_FLOAT
}
if contains(charTypes, tmp) {
return SQLITE_TEXT
}
if contains(blobTypes, tmp) {
return SQLITE_BLOB
}
if contains(nullTypes, tmp) {
return SQLITE_NULL
}
if contains(dateTypes, tmp) {
return SQLITE_DATE
}
return SQLITE_TEXT
} else {
// For expressions and sub-queries
type = sqlite3_column_type(stmt, index)
}
return type
}
// Get column value
private func getColumnValue(index:CInt, type:CInt, stmt:COpaquePointer)->AnyObject? {
// Integer
if type == SQLITE_INTEGER {
let val = sqlite3_column_int(stmt, index)
return Int(val)
}
// Float
if type == SQLITE_FLOAT {
let val = sqlite3_column_double(stmt, index)
return Double(val)
}
// Text - handled by default handler at end
// Blob
if type == SQLITE_BLOB {
let data = sqlite3_column_blob(stmt, index)
let size = sqlite3_column_bytes(stmt, index)
let val = NSData(bytes:data, length: Int(size))
return val
}
// Null
if type == SQLITE_NULL {
return nil
}
// Date
if type == SQLITE_DATE {
// Is this a text date
let txt = UnsafePointer<Int8>(sqlite3_column_text(stmt, index))
if txt != nil {
if let buf = NSString(CString:txt, encoding:NSUTF8StringEncoding) {
let set = NSCharacterSet(charactersInString: "-:")
let range = buf.rangeOfCharacterFromSet(set)
if range.location != NSNotFound {
// Convert to time
var time:tm = tm(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0, tm_gmtoff: 0, tm_zone:nil)
strptime(txt, "%Y-%m-%d %H:%M:%S", &time)
time.tm_isdst = -1
let diff = NSTimeZone.localTimeZone().secondsFromGMT
let t = mktime(&time) + diff
let ti = NSTimeInterval(t)
let val = NSDate(timeIntervalSince1970:ti)
return val
}
}
}
// If not a text date, then it's a time interval
let val = sqlite3_column_double(stmt, index)
let dt = NSDate(timeIntervalSince1970: val)
return dt
}
// If nothing works, return a string representation
let buf = UnsafePointer<Int8>(sqlite3_column_text(stmt, index))
let val = String.fromCString(buf)
// println("SQLiteDB - Got value: \(val)")
return val
}
}
| gpl-2.0 | b2300258be8067bdabcbd84b616f9a4d | 26.458621 | 169 | 0.653334 | 3.276955 | false | false | false | false |
codepgq/LearningSwift | ScrollView/ScrollView/ViewController.swift | 1 | 1752 | //
// ViewController.swift
// ScrollView
//
// Created by ios on 16/9/8.
// Copyright © 2016年 ios. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let leftVC :LeftViewController = LeftViewController(nibName: "LeftViewController", bundle: nil)
let centerVC :CenterViewController = CenterViewController(nibName: "CenterViewController", bundle: nil)
let rightVC :RightViewController = RightViewController(nibName: "RightViewController", bundle: nil)
self.addChildViewController(leftVC)
self.scrollView.addSubview(leftVC.view)
leftVC.didMoveToParentViewController(self)
self.addChildViewController(centerVC)
self.scrollView.addSubview(centerVC.view)
centerVC.didMoveToParentViewController(self)
self.addChildViewController(rightVC)
self.scrollView.addSubview(rightVC.view)
rightVC.didMoveToParentViewController(self)
var centerFrame : CGRect = centerVC.view.frame
centerFrame.origin.x = self.view.frame.width
centerVC.view.frame = centerFrame
var rightFrame : CGRect = rightVC.view.frame
rightFrame.origin.x = self.view.frame.width * 2
rightVC.view.frame = rightFrame
self.scrollView.contentSize = CGSize(width: self.view.frame.width * 3, height: 0)
self.scrollView.pagingEnabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | c851eb285aa8b47eec8dbe547b24a4c1 | 30.232143 | 111 | 0.668382 | 5.129032 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Services/Models/PXInstruction.swift | 1 | 4960 | import Foundation
/// :nodoc:
open class PXInstruction: NSObject, Codable {
open var title: String = ""
open var subtitle: String?
open var accreditationMessage: String?
open var accreditationComments: [String] = []
open var actions: [PXInstructionAction]?
open var type: String?
open var references: [PXInstructionReference]?
open var interactions: [PXInstructionInteraction]?
open var secondaryInfo: [String]?
open var tertiaryInfo: [String]?
open var info: [String] = []
public init(title: String, subtitle: String?, accreditationMessage: String?, accreditationComments: [String], actions: [PXInstructionAction]?, type: String?, references: [PXInstructionReference]?, interactions: [PXInstructionInteraction]?, secondaryInfo: [String]?, tertiaryInfo: [String]?, info: [String]) {
self.title = title
self.subtitle = subtitle
self.accreditationMessage = accreditationMessage
self.accreditationComments = accreditationComments
self.actions = actions
self.type = type
self.references = references
self.interactions = interactions
self.secondaryInfo = secondaryInfo
self.tertiaryInfo = tertiaryInfo
self.info = info
}
public enum PXInstructionKeys: String, CodingKey {
case title
case subtitle
case accreditationMessage = "accreditation_message"
case accreditationComments = "accreditation_comments"
case actions
case type
case references
case interactions
case secondaryInfo = "secondary_info"
case tertiaryInfo = "tertiary_info"
case info
}
public required convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PXInstructionKeys.self)
let title: String = try container.decodeIfPresent(String.self, forKey: .title) ?? ""
let subtitle: String? = try container.decodeIfPresent(String.self, forKey: .subtitle)
let accreditationMessage: String? = try container.decodeIfPresent(String.self, forKey: .accreditationMessage)
let accreditationComments: [String] = try container.decodeIfPresent([String].self, forKey: .accreditationComments) ?? []
let action: [PXInstructionAction]? = try container.decodeIfPresent([PXInstructionAction].self, forKey: .actions)
let type: String? = try container.decodeIfPresent(String.self, forKey: .type)
let references: [PXInstructionReference]? = try container.decodeIfPresent([PXInstructionReference].self, forKey: .references)
let interactions: [PXInstructionInteraction]? = try container.decodeIfPresent([PXInstructionInteraction].self, forKey: .interactions)
let secondaryInfo: [String]? = try container.decodeIfPresent([String].self, forKey: .secondaryInfo)
let tertiaryInfo: [String]? = try container.decodeIfPresent([String].self, forKey: .tertiaryInfo)
let info: [String] = try container.decodeIfPresent([String].self, forKey: .info) ?? []
self.init(title: title, subtitle: subtitle, accreditationMessage: accreditationMessage, accreditationComments: accreditationComments, actions: action, type: type, references: references, interactions: interactions, secondaryInfo: secondaryInfo, tertiaryInfo: tertiaryInfo, info: info)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: PXInstructionKeys.self)
try container.encodeIfPresent(self.title, forKey: .title)
try container.encodeIfPresent(self.subtitle, forKey: .subtitle)
try container.encodeIfPresent(self.accreditationMessage, forKey: .accreditationMessage)
try container.encodeIfPresent(self.accreditationComments, forKey: .accreditationComments)
try container.encodeIfPresent(self.actions, forKey: .actions)
try container.encodeIfPresent(self.type, forKey: .type)
try container.encodeIfPresent(self.references, forKey: .references)
try container.encodeIfPresent(self.interactions, forKey: .interactions)
try container.encodeIfPresent(self.secondaryInfo, forKey: .secondaryInfo)
try container.encodeIfPresent(self.tertiaryInfo, forKey: .tertiaryInfo)
try container.encodeIfPresent(self.info, forKey: .info)
}
open func toJSONString() throws -> String? {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
return String(data: data, encoding: .utf8)
}
open func toJSON() throws -> Data {
let encoder = JSONEncoder()
return try encoder.encode(self)
}
open class func fromJSONToPXInstruction(data: Data) throws -> PXInstruction {
return try JSONDecoder().decode(PXInstruction.self, from: data)
}
open class func fromJSON(data: Data) throws -> [PXInstruction] {
return try JSONDecoder().decode([PXInstruction].self, from: data)
}
}
| mit | 01a9863d771029f2ed3b3e8106f30aac | 51.765957 | 312 | 0.710484 | 4.601113 | false | false | false | false |
gurhub/ScrollableStackView | Example/ScrollableStackView/VerticalLayoutViewController.swift | 1 | 2071 | // MIT license. Copyright (c) 2017 Gürhan Yerlikaya. All rights reserved.
import UIKit
import ScrollableStackView
class VerticalLayoutViewController: UIViewController {
@IBOutlet weak var scrollable: ScrollableStackView!
override func viewDidLoad() {
super.viewDidLoad()
scrollable.stackView.distribution = .fillProportionally
scrollable.stackView.alignment = .center
scrollable.scrollView.layoutMargins = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
for _ in 1 ..< 23 {
let min:UInt32 = 30
let max:UInt32 = UInt32(view.bounds.width - 10)
let random = CGFloat(arc4random_uniform(max - min) + min) // between 30-130
let rectangle = UIView(frame: CGRect(x: 0, y: 0, width: random, height: random))
rectangle.backgroundColor = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)
rectangle.heightAnchor.constraint(equalToConstant: random).isActive = true
rectangle.widthAnchor.constraint(equalToConstant: random).isActive = true
scrollable.stackView.addArrangedSubview(rectangle)
}
let label = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 45))
label.numberOfLines = 0
label.text = "Here's to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes. The ones who see things differently. They're not fond of rules. And they have no respect for the status quo. You can quote them, disagree with them, glorify or vilify them. About the only thing you can't do is ignore them. Because they change things. They push the human race forward. And while some may see them as the crazy ones, we see genius. Because the people who are crazy enough to think they can change the world, are the ones who do."
label.sizeToFit()
scrollable.stackView.addArrangedSubview(label)
}
@IBAction func jumpToViewAction(_ sender: Any) {
scrollable.scrollToItem(index: 11)
}
}
| mit | 15f61d0d008007df0f63a4b7080b36b5 | 54.945946 | 572 | 0.698551 | 4.207317 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift | 54 | 3777 | //
// PublishSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/11/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed observers.
final public class PublishSubject<Element>
: Observable<Element>
, SubjectType
, Cancelable
, ObserverType
, SynchronizedUnsubscribeType {
public typealias SubjectObserverType = PublishSubject<Element>
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
_lock.lock(); defer { _lock.unlock() }
return _observers.count > 0
}
private var _lock = NSRecursiveLock()
// state
private var _isDisposed = false
private var _observers = Bag<AnyObserver<Element>>()
private var _stopped = false
private var _stoppedEvent = nil as Event<Element>?
/// Indicates whether the subject has been isDisposed.
public var isDisposed: Bool {
return _isDisposed
}
/// Creates a subject.
public override init() {
super.init()
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<Element>) {
_synchronized_on(event).on(event)
}
func _synchronized_on(_ event: Event<E>) -> Bag<AnyObserver<Element>> {
_lock.lock(); defer { _lock.unlock() }
switch event {
case .next(_):
if _isDisposed || _stopped {
return Bag()
}
return _observers
case .completed, .error:
if _stoppedEvent == nil {
_stoppedEvent = event
_stopped = true
let observers = _observers
_observers.removeAll()
return observers
}
return Bag()
}
}
/**
Subscribes an observer to the subject.
- parameter observer: Observer to subscribe to the subject.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock(); defer { _lock.unlock() }
return _synchronized_subscribe(observer)
}
func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
if _isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let key = _observers.insert(observer.asObserver())
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_unsubscribe(disposeKey)
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
_ = _observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> PublishSubject<Element> {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
_lock.lock(); defer { _lock.unlock() }
_synchronized_dispose()
}
final func _synchronized_dispose() {
_isDisposed = true
_observers.removeAll()
_stoppedEvent = nil
}
}
| apache-2.0 | 2ef5bc66da45dfb61013ed63bf738e0c | 28.271318 | 104 | 0.599576 | 4.961892 | false | false | false | false |
juheon0615/GhostHandongSwift | HandongAppSwift/CVCalendar/CVAuxiliaryView.swift | 11 | 4253 | //
// CVAuxiliaryView.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 22/03/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
class CVAuxiliaryView: UIView {
var shape: CVShape!
var strokeColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
var fillColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
let defaultFillColor = UIColor.colorFromCode(0xe74c3c)
private var radius: CGFloat {
get {
return (min(frame.height, frame.width) - 10) / 2
}
}
unowned let dayView: DayView
init(dayView: DayView, rect: CGRect, shape: CVShape) {
self.dayView = dayView
self.shape = shape
super.init(frame: rect)
strokeColor = UIColor.clearColor()
fillColor = UIColor.colorFromCode(0xe74c3c)
layer.cornerRadius = 5
backgroundColor = .clearColor()
}
override func didMoveToSuperview() {
setNeedsDisplay()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
var path: UIBezierPath!
if let shape = shape {
switch shape {
case .RightFlag: path = rightFlagPath()
case .LeftFlag: path = leftFlagPath()
case .Circle: path = circlePath()
case .Rect: path = rectPath()
}
}
strokeColor.setStroke()
fillColor.setFill()
if let path = path {
path.lineWidth = 1
path.stroke()
path.fill()
}
}
deinit {
//println("[CVCalendar Recovery]: AuxiliaryView is deinited.")
}
}
extension CVAuxiliaryView {
func updateFrame(frame: CGRect) {
self.frame = frame
setNeedsDisplay()
}
}
extension CVAuxiliaryView {
func circlePath() -> UIBezierPath {
let arcCenter = CGPointMake(frame.width / 2, frame.height / 2)
let startAngle = CGFloat(0)
let endAngle = CGFloat(M_PI * 2.0)
let clockwise = true
let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
return path
}
func rightFlagPath() -> UIBezierPath {
let appearance = dayView.calendarView.appearance
let offset = appearance.spaceBetweenDayViews!
let flag = UIBezierPath()
flag.moveToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 - radius))
flag.addLineToPoint(CGPointMake(bounds.width, bounds.height / 2 - radius))
flag.addLineToPoint(CGPointMake(bounds.width, bounds.height / 2 + radius ))
flag.addLineToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 + radius))
var path = CGPathCreateMutable()
CGPathAddPath(path, nil, circlePath().CGPath)
CGPathAddPath(path, nil, flag.CGPath)
return UIBezierPath(CGPath: path)
}
func leftFlagPath() -> UIBezierPath {
let flag = UIBezierPath()
flag.moveToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 + radius))
flag.addLineToPoint(CGPointMake(0, bounds.height / 2 + radius))
flag.addLineToPoint(CGPointMake(0, bounds.height / 2 - radius))
flag.addLineToPoint(CGPointMake(bounds.width / 2, bounds.height / 2 - radius))
var path = CGPathCreateMutable()
CGPathAddPath(path, nil, circlePath().CGPath)
CGPathAddPath(path, nil, flag.CGPath)
return UIBezierPath(CGPath: path)
}
func rectPath() -> UIBezierPath {
let midX = bounds.width / 2
let midY = bounds.height / 2
let appearance = dayView.calendarView.appearance
let offset = appearance.spaceBetweenDayViews!
println("offset = \(offset)")
let path = UIBezierPath(rect: CGRectMake(0 - offset, midY - radius, bounds.width + offset / 2, radius * 2))
return path
}
} | mit | 3eff3b390518826f2e202acf46bc2152 | 28.136986 | 135 | 0.58688 | 4.811086 | false | false | false | false |
rain2540/CustomActionSheet | Swift/CustomActionSheet/CustomActionSheet/CustomActionSheet.swift | 1 | 5102 | //
// CustomActionSheet.swift
// CustomActionSheet
//
// Created by RAIN on 15/11/30.
// Copyright © 2015年 Smartech. All rights reserved.
//
import UIKit
private let IntervalWithButtonsX: CGFloat = 30.0
private let IntervalWithButtonsY: CGFloat = 5.0
private let ButtonsPerRow = 3
private let HeaderHeight: CGFloat = 20.0
private let BottomHeight: CGFloat = 20.0
private let CancelButtonHeight: CGFloat = 46.0
@objc protocol CustomActionSheetDelegate: NSObjectProtocol {
optional func customActionSheet(actionSheet: CustomActionSheet, choseAtIndex index: Int)
}
class CustomActionSheet: UIView {
weak var delegate: CustomActionSheetDelegate?
lazy var backgroundImageView = UIImageView()
lazy var cancelButton = UIButton()
lazy var coverView = UIView()
var buttons: [UIView?] = []
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
func setupViews(buttonArray: [UIView?]) {
buttons = buttonArray
backgroundColor = UIColor.grayColor()
coverView = UIView(frame: MainScreen.bounds)
coverView.backgroundColor = UIColor(Red: 51.0, Green: 51.0, Blue: 51.0, Alpha: 0.6)
coverView.hidden = true
backgroundImageView = UIImageView(image: UIImage(named: "actionsheet_bg"))
backgroundImageView.alpha = 0.7
addSubview(backgroundImageView)
for i in 0 ..< buttons.count {
if let button = self.buttons[i] as? CustomActionSheetButton {
button.imageButton.tag = i
button.imageButton.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
addSubview(button)
}
}
cancelButton = UIButton(type: .Custom)
cancelButton.setBackgroundImage(UIImage(named: "actionsheet_button"), forState: .Normal)
cancelButton.setTitle("取消", forState: .Normal)
cancelButton.addTarget(self, action: "dissmiss", forControlEvents: .TouchUpInside)
addSubview(cancelButton)
}
private func setPositionInView(view: UIView) {
if buttons.count == 0 {
return
}
let buttonWidth = (buttons.first as! CustomActionSheetButton).width
let buttonHeight = (buttons.first as! CustomActionSheetButton).height
frame = CGRect(x: 0, y: view.height, width: view.width, height: CancelButtonHeight + BottomHeight + HeaderHeight + (buttonHeight + IntervalWithButtonsY) * (CGFloat(buttons.count - 1) / CGFloat(ButtonsPerRow + 1)))
backgroundImageView.frame = CGRect(x: 0, y: 0, width: width, height: height)
let beginX = (width - (IntervalWithButtonsX * CGFloat(ButtonsPerRow - 1) + buttonWidth * CGFloat(ButtonsPerRow))) / 2
cancelButton.frame = CGRect(x: beginX, y: (IntervalWithButtonsY + buttonHeight) * (CGFloat(buttons.count - 1) / CGFloat(ButtonsPerRow) + 1) + HeaderHeight, width: width - beginX * 2, height: CancelButtonHeight)
if buttons.count > ButtonsPerRow {
for i in 0 ..< buttons.count {
let button = buttons[i] as! CustomActionSheetButton
button.frame = CGRect(x: beginX + CGFloat(i % ButtonsPerRow) * (buttonWidth + IntervalWithButtonsX), y: HeaderHeight + CGFloat(i / ButtonsPerRow) * (buttonHeight + IntervalWithButtonsY), width: buttonWidth, height: buttonHeight)
}
} else {
let intervalX = (width - beginX * 2 - buttonWidth * CGFloat(buttons.count)) / CGFloat(buttons.count - 1)
for i in 0 ..< buttons.count {
let button = buttons[i] as! CustomActionSheetButton
button.frame = CGRect(x: beginX + CGFloat(i % ButtonsPerRow) * (buttonWidth + intervalX), y: HeaderHeight + CGFloat(i / ButtonsPerRow) * (buttonHeight + IntervalWithButtonsY), width: buttonWidth, height: buttonHeight)
}
}
}
func showInView(view: UIView) {
setPositionInView(view)
view.addSubview(coverView)
view.addSubview(self)
UIView.beginAnimations("ShowCustomActionSheet", context: nil)
frame = CGRect(x: 0, y: y - height, width: width, height: height)
coverView.hidden = false
UIView.commitAnimations()
}
func dismiss() {
UIView.beginAnimations("DismissCustomActionSheet", context: nil)
frame = CGRect(x: 0, y: y + height, width: width, height: height)
UIView.setAnimationDelegate(self)
UIView.setAnimationDidStopSelector("sheetDidDismissed")
coverView.hidden = true
UIView.commitAnimations()
}
func sheetDidDismissed() {
coverView.removeFromSuperview()
removeFromSuperview()
}
@objc private func buttonAction(sender: UIButton) {
if (delegate?.respondsToSelector("customActionSheet:choseAtIndex:")) != false {
delegate?.customActionSheet!(self, choseAtIndex: sender.tag)
}
dismiss()
}
}
| mit | ca22c97be3549929247d00b641ba4a68 | 40.422764 | 244 | 0.649853 | 4.553172 | false | false | false | false |
salemoh/GoldenQuraniOS | GoldenQuranSwift/Pods/GRDB.swift/GRDB/Core/Utils.swift | 1 | 8251 | import Foundation
#if SWIFT_PACKAGE
import CSQLite
#endif
// MARK: - Public
extension String {
/// Returns the receiver, quoted for safe insertion as an identifier in an
/// SQL query.
///
/// db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
public var quotedDatabaseIdentifier: String {
// See https://www.sqlite.org/lang_keywords.html
return "\"" + self + "\""
}
}
/// Return as many question marks separated with commas as the *count* argument.
///
/// databaseQuestionMarks(count: 3) // "?,?,?"
public func databaseQuestionMarks(count: Int) -> String {
return Array(repeating: "?", count: count).joined(separator: ",")
}
// MARK: - Internal
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// Custom precondition function which aims at solving
/// https://bugs.swift.org/browse/SR-905 and
/// https://github.com/groue/GRDB.swift/issues/37
///
/// TODO: remove this function when https://bugs.swift.org/browse/SR-905 is solved.
func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) {
if !condition() {
fatalError(message, file: file, line: line)
}
}
// Workaround Swift inconvenience around factory methods of non-final classes
func cast<T, U>(_ value: T) -> U? {
return value as? U
}
extension Array {
/// Removes the first object that matches *predicate*.
mutating func removeFirst(_ predicate: (Element) throws -> Bool) rethrows {
if let index = try index(where: predicate) {
remove(at: index)
}
}
}
extension Dictionary {
/// Create a dictionary with the keys and values in the given sequence.
init<Sequence: Swift.Sequence>(keyValueSequence: Sequence) where Sequence.Iterator.Element == (Key, Value) {
self.init(minimumCapacity: keyValueSequence.underestimatedCount)
for (key, value) in keyValueSequence {
self[key] = value
}
}
/// Create a dictionary from keys and a value builder.
init<Sequence: Swift.Sequence>(keys: Sequence, value: (Key) -> Value) where Sequence.Iterator.Element == Key {
self.init(minimumCapacity: keys.underestimatedCount)
for key in keys {
self[key] = value(key)
}
}
}
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
final class ReadWriteBox<T> {
var value: T {
get { return read { $0 } }
set { write { $0 = newValue } }
}
init(_ value: T) {
self._value = value
self.queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
}
func read<U>(_ block: (T) -> U) -> U {
var result: U? = nil
queue.sync {
result = block(self._value)
}
return result!
}
func write(_ block: (inout T) -> Void) {
queue.sync(flags: [.barrier]) {
block(&self._value)
}
}
private var _value: T
private var queue: DispatchQueue
}
/// A Pool maintains a set of elements that are built them on demand. A pool has
/// a maximum number of elements.
///
/// // A pool of 3 integers
/// var number = 0
/// let pool = Pool<Int>(maximumCount: 3, makeElement: {
/// number = number + 1
/// return number
/// })
///
/// The function get() dequeues an available element and gives this element to
/// the block argument. During the block execution, the element is not
/// available. When the block is ended, the element is available again.
///
/// // got 1
/// pool.get { n in
/// print("got \(n)")
/// }
///
/// If there is no available element, the pool builds a new element, unless the
/// maximum number of elements is reached. In this case, the get() method
/// blocks the current thread, until an element eventually turns available again.
///
/// DispatchQueue.concurrentPerform(iterations: 6) { _ in
/// pool.get { n in
/// print("got \(n)")
/// }
/// }
///
/// got 1
/// got 2
/// got 3
/// got 2
/// got 1
/// got 3
final class Pool<T> {
var makeElement: (() throws -> T)?
private var items: [PoolItem<T>] = []
private let queue: DispatchQueue // protects items
private let semaphore: DispatchSemaphore // limits the number of elements
init(maximumCount: Int, makeElement: (() throws -> T)? = nil) {
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
self.queue = DispatchQueue(label: "GRDB.Pool")
self.semaphore = DispatchSemaphore(value: maximumCount)
}
/// Returns a tuple (element, releaseElement())
/// Client MUST call releaseElement() after the element has been used.
func get() throws -> (T, () -> ()) {
var item: PoolItem<T>! = nil
_ = semaphore.wait(timeout: .distantFuture)
do {
try queue.sync {
if let availableItem = items.first(where: { $0.available }) {
item = availableItem
item.available = false
} else {
item = try PoolItem(element: makeElement!(), available: false)
items.append(item)
}
}
} catch {
semaphore.signal()
throw error
}
let unlock = {
self.queue.sync {
item.available = true
}
self.semaphore.signal()
}
return (item.element, unlock)
}
/// Performs a synchronous block with an element. The element turns
/// available after the block has executed.
func get<U>(block: (T) throws -> U) throws -> U {
let (element, release) = try get()
defer { release() }
return try block(element)
}
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary queue.
func forEach(_ body: (T) throws -> ()) rethrows {
try queue.sync {
for item in items {
try body(item.element)
}
}
}
/// Empty the pool. Currently used items won't be reused.
func clear() {
clear {}
}
/// Empty the pool. Currently used items won't be reused.
/// Eventual block is executed before any other element is dequeued.
func clear(andThen block: () throws -> ()) rethrows {
try queue.sync {
items = []
try block()
}
}
}
private class PoolItem<T> {
let element: T
var available: Bool
init(element: T, available: Bool) {
self.element = element
self.available = available
}
}
enum Result<Value> {
case success(Value)
case failure(Error)
static func wrap(_ value: () throws -> Value) -> Result<Value> {
do {
return try .success(value())
} catch {
return .failure(error)
}
}
/// Evaluates the given closure when this `Result` is a success, passing the
/// unwrapped value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: Result<Data> = .success(Data())
/// let possibleInt = possibleData.map { $0.count }
/// try print(possibleInt.unwrap())
/// // Prints "0"
///
/// let noData: Result<Data> = .failure(error)
/// let noInt = noData.map { $0.count }
/// try print(noInt.unwrap())
/// // Throws error
///
/// - parameter transform: A closure that takes the success value of
/// the instance.
/// - returns: A `Result` containing the result of the given closure. If
/// this instance is a failure, returns the same failure.
func map<T>(_ transform: (Value) -> T) -> Result<T> {
switch self {
case .success(let value):
return .success(transform(value))
case .failure(let error):
return .failure(error)
}
}
}
| mit | f937b5639611b5a078ae90f5523325fc | 30.253788 | 150 | 0.577263 | 4.177722 | false | false | false | false |
ilyathewhite/Euler | EulerSketch/EulerSketch/Commands/Sketch+Combined.playground/Pages/SimsonLine.xcplaygroundpage/Contents.swift | 1 | 1100 | import Cocoa
import PlaygroundSupport
import EulerSketchOSX
let sketch = Sketch()
sketch.addPoint("A", hint: (145, 230))
sketch.addPoint("B", hint: (445, 230))
sketch.addPoint("C", hint: (393, 454))
sketch.addTriangle("ABC")
sketch.addCircumcircle("o", ofTriangle: "ABC")
sketch.addPoint("P", onCircle: "o", hint: (340, 150))
sketch.addPerpendicular("PA1", toSegment: "BC")
sketch.addPerpendicular("PB1", toSegment: "AC")
sketch.addPerpendicular("PC1", toSegment: "AB")
sketch.addSegment("C1A1", style: .emphasized)
sketch.addSegment("C1B1", style: .emphasized)
// result
sketch.assert("A1, B1, C1 are collinear") { [unowned sketch] in
let p1 = try sketch.getPoint("A1")
let p2 = try sketch.getPoint("B1")
let p3 = try sketch.getPoint("C1")
return collinear(points: [p1, p2, p3])
}
sketch.eval()
// sketch adjustments
sketch.point("A", setNameLocation: .bottomLeft)
sketch.point("B", setNameLocation: .bottomRight)
sketch.point("B1", setNameLocation: .topLeft)
sketch.point("A1", setNameLocation: .bottomRight)
// live view
PlaygroundPage.current.liveView = sketch.quickView()
| mit | 663abee130ba39c577d54caac5e12958 | 25.829268 | 63 | 0.717273 | 3.055556 | false | false | false | false |
BelledonneCommunications/linphone-iphone | Classes/Swift/Voip/Views/Fragments/ActiveCall/ActiveCallView.swift | 1 | 10610 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Foundation
import SnapKit
import linphonesw
class ActiveCallView: UIView { // = currentCall
// Layout constants :
static let top_displayname_margin_top = 20.0
let sip_address_margin_top = 4.0
static let remote_recording_margin_top = 10.0
static let remote_recording_height = 30
static let bottom_displayname_margin_bottom = 10.0
static let bottom_displayname_margin_left = 12.0
static let center_view_margin_top = 15.0
static let center_view_corner_radius = 20.0
let record_pause_button_size = 40
let record_pause_button_inset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7)
let record_pause_button_margin = 10.0
static let local_video_width = 150.0
static let local_video_margins = 15.0
let upperSection = UIStackView()
let displayNameTop = StyledLabel(VoipTheme.call_display_name_duration)
let duration = CallTimer(nil, VoipTheme.call_display_name_duration)
let sipAddress = StyledLabel(VoipTheme.call_sip_address)
let remotelyRecordedIndicator = RemotelyRecordingView(height: ActiveCallView.remote_recording_height,text: VoipTexts.call_remote_recording)
let centerSection = UIView()
let avatar = Avatar(color:VoipTheme.voipBackgroundColor, textStyle: VoipTheme.call_generated_avatar_large)
let displayNameBottom = StyledLabel(VoipTheme.call_remote_name)
var recordCallButtons : [CallControlButton] = []
var pauseCallButtons : [CallControlButton] = []
let remoteVideo = UIView()
let localVideo = LocalVideoView(width: local_video_width)
var callData: CallData? = nil {
didSet {
duration.call = callData?.call
callData?.call.remoteAddress.map {
avatar.fillFromAddress(address: $0)
if let displayName = $0.addressBookEnhancedDisplayName() {
displayNameTop.text = displayName+" - "
displayNameBottom.text = displayName
}
sipAddress.text = $0.asStringUriOnly()
}
self.remotelyRecordedIndicator.isRemotelyRecorded = callData?.isRemotelyRecorded
callData?.isRecording.readCurrentAndObserve { (selected) in
self.recordCallButtons.forEach {
$0.isSelected = selected == true
}
}
callData?.isPaused.readCurrentAndObserve { (paused) in
self.pauseCallButtons.forEach {
$0.isSelected = paused == true
}
if (paused == true) {
self.localVideo.isHidden = true
}
}
callData?.isRemotelyRecorded.readCurrentAndObserve { (remotelyRecorded) in
self.centerSection.removeConstraints().matchParentSideBorders().alignUnder(view:remotelyRecorded == true ? self.remotelyRecordedIndicator : self.upperSection ,withMargin: ActiveCallView.center_view_margin_top).alignParentBottom().done()
self.setNeedsLayout()
}
Core.get().nativeVideoWindow = remoteVideo
Core.get().nativePreviewWindowId = UnsafeMutableRawPointer(Unmanaged.passRetained(localVideo).toOpaque())
ControlsViewModel.shared.isVideoEnabled.readCurrentAndObserve{ (video) in
self.remoteVideo.isHidden = video != true
self.localVideo.isHidden = video != true
self.recordCallButtons.first?.isHidden = video != true
self.pauseCallButtons.first?.isHidden = video != true
self.recordCallButtons.last?.isHidden = video == true
self.pauseCallButtons.last?.isHidden = video == true
}
}
}
init() {
super.init(frame: .zero)
let stack = UIStackView()
stack.distribution = .equalSpacing
stack.alignment = .bottom
stack.spacing = record_pause_button_margin
stack.axis = .vertical
let displayNameDurationSipAddress = UIView()
displayNameDurationSipAddress.addSubview(displayNameTop)
displayNameTop.alignParentLeft().done()
displayNameDurationSipAddress.addSubview(duration)
duration.toRightOf(displayNameTop).alignParentRight().done()
duration.accessibilityIdentifier = "active_call_upper_section_duration"
displayNameDurationSipAddress.addSubview(sipAddress)
sipAddress.matchParentSideBorders().alignUnder(view: displayNameTop,withMargin:sip_address_margin_top).done()
upperSection.distribution = .equalSpacing
upperSection.alignment = .center
upperSection.spacing = record_pause_button_margin
upperSection.axis = .horizontal
upperSection.addArrangedSubview(displayNameDurationSipAddress)
displayNameDurationSipAddress.wrapContentY().done()
let recordPauseView = UIStackView()
recordPauseView.spacing = record_pause_button_margin
// Record (with video)
var recordCall = CallControlButton(width: record_pause_button_size, height: record_pause_button_size, imageInset:record_pause_button_inset, buttonTheme: VoipTheme.call_record, onClickAction: {
self.callData.map { $0.toggleRecord() }
})
recordCallButtons.append(recordCall)
recordPauseView.addArrangedSubview(recordCall)
recordCall.accessibilityIdentifier = "active_call_upper_section_record"
recordCall.accessibilityLabel = "Record Call"
// Pause (with video)
var pauseCall = CallControlButton(width: record_pause_button_size, height: record_pause_button_size, imageInset:record_pause_button_inset, buttonTheme: VoipTheme.call_pause, onClickAction: {
self.callData.map { $0.togglePause() }
})
pauseCallButtons.append(pauseCall)
recordPauseView.addArrangedSubview(pauseCall)
upperSection.addArrangedSubview(recordPauseView)
pauseCall.accessibilityIdentifier = "active_call_upper_section_pause"
pauseCall.accessibilityLabel = "Pause Call"
stack.addArrangedSubview(upperSection)
upperSection.matchParentSideBorders().alignParentTop(withMargin:ActiveCallView.top_displayname_margin_top).done()
stack.addArrangedSubview(remotelyRecordedIndicator)
remotelyRecordedIndicator.matchParentSideBorders().height(CGFloat(ActiveCallView.remote_recording_height)).done()
// Center Section : Avatar + video + record/pause buttons + videos
centerSection.layer.cornerRadius = ActiveCallView.center_view_corner_radius
centerSection.clipsToBounds = true
centerSection.backgroundColor = VoipTheme.voipParticipantBackgroundColor.get()
//centerSection.removeConstraints().matchParentSideBorders().alignUnder(view: remotelyRecordedIndicator, withMargin: ActiveCallView.center_view_margin_top).alignParentBottom().done()
// Record (w/o video)
recordCall = CallControlButton(width: record_pause_button_size, height: record_pause_button_size, imageInset:record_pause_button_inset, buttonTheme: VoipTheme.call_record, onClickAction: {
self.callData.map { $0.toggleRecord() }
})
recordCallButtons.append(recordCall)
centerSection.addSubview(recordCall)
recordCall.alignParentLeft(withMargin:record_pause_button_margin).alignParentTop(withMargin:record_pause_button_margin).done()
recordCall.accessibilityIdentifier = "active_call_center_section_record"
recordCall.accessibilityLabel = "Record Call"
// Pause (w/o video)
pauseCall = CallControlButton(width: record_pause_button_size, height: record_pause_button_size, imageInset:record_pause_button_inset, buttonTheme: VoipTheme.call_pause, onClickAction: {
self.callData.map { $0.togglePause() }
})
pauseCallButtons.append(pauseCall)
centerSection.addSubview(pauseCall)
pauseCall.alignParentRight(withMargin:record_pause_button_margin).alignParentTop(withMargin:record_pause_button_margin).done()
pauseCall.accessibilityIdentifier = "active_call_center_section_pause"
pauseCall.accessibilityLabel = "Pause Call"
// Avatar
centerSection.addSubview(avatar)
avatar.square(Avatar.diameter_for_call_views).center().done()
// Remote Video Display
centerSection.addSubview(remoteVideo)
remoteVideo.isHidden = true
remoteVideo.matchParentDimmensions().done()
// Local Video Display
centerSection.addSubview(localVideo)
localVideo.backgroundColor = .black
localVideo.alignParentBottom(withMargin: ActiveCallView.local_video_margins).alignParentRight(withMargin: ActiveCallView.local_video_margins).done()
localVideo.isHidden = true
localVideo.dragZone = centerSection
// Full screen video togggle
remoteVideo.onClick {
ControlsViewModel.shared.toggleFullScreen()
}
ControlsViewModel.shared.fullScreenMode.observe { (fullScreen) in
if (self.isHidden) {
return
}
self.remoteVideo.removeConstraints().done()
self.localVideo.removeConstraints().done()
if (fullScreen == true) {
self.remoteVideo.removeFromSuperview()
self.localVideo.removeFromSuperview()
PhoneMainView.instance().mainViewController.view?.addSubview(self.remoteVideo)
PhoneMainView.instance().mainViewController.view?.addSubview(self.localVideo)
} else {
self.remoteVideo.removeFromSuperview()
self.localVideo.removeFromSuperview()
self.centerSection.addSubview(self.remoteVideo)
self.centerSection.addSubview(self.localVideo)
}
self.remoteVideo.matchParentDimmensions().done()
self.localVideo.alignParentBottom(withMargin: ActiveCallView.local_video_margins).alignParentRight(withMargin: ActiveCallView.local_video_margins).done()
self.localVideo.setSizeConstraint()
}
// Bottom display name
centerSection.addSubview(displayNameBottom)
displayNameBottom.alignParentLeft(withMargin:ActiveCallView.bottom_displayname_margin_left).alignParentRight().alignParentBottom(withMargin:ActiveCallView.bottom_displayname_margin_bottom).done()
stack.addArrangedSubview(centerSection)
addSubview(stack)
stack.matchParentDimmensions().done()
layoutRotatableElements()
}
func layoutRotatableElements() {
avatar.removeConstraints().done()
if ([.landscapeLeft, .landscapeRight].contains( UIDevice.current.orientation)) {
avatar.square(Avatar.diameter_for_call_views_land).center().done()
} else {
avatar.square(Avatar.diameter_for_call_views).center().done()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-3.0 | 92cfed1b4918eef19015c059d72329dd | 40.124031 | 252 | 0.763996 | 3.875091 | false | false | false | false |
ben-ng/swift | stdlib/public/core/StringCharacterView.swift | 1 | 17020 | //===--- StringCharacterView.swift - String's Collection of Characters ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// String is-not-a Sequence or Collection, but it exposes a
// collection of characters.
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#70 : The character string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of characters.
///
/// In Swift, every string provides a view of its contents as characters. In
/// this view, many individual characters---for example, "é", "김", and
/// "🇮🇳"---can be made up of multiple Unicode code points. These code points
/// are combined by Unicode's boundary algorithms into *extended grapheme
/// clusters*, represented by the `Character` type. Each element of a
/// `CharacterView` collection is a `Character` instance.
///
/// let flowers = "Flowers 💐"
/// for c in flowers.characters {
/// print(c)
/// }
/// // F
/// // l
/// // o
/// // w
/// // e
/// // r
/// // s
/// //
/// // 💐
///
/// You can convert a `String.CharacterView` instance back into a string
/// using the `String` type's `init(_:)` initializer.
///
/// let name = "Marie Curie"
/// if let firstSpace = name.characters.index(of: " ") {
/// let firstName = String(name.characters.prefix(upTo: firstSpace))
/// print(firstName)
/// }
/// // Prints "Marie"
public struct CharacterView {
internal var _core: _StringCore
/// The offset of this view's `_core` from an original core. This works
/// around the fact that `_StringCore` is always zero-indexed.
/// `_coreOffset` should be subtracted from `UnicodeScalarIndex._position`
/// before that value is used as a `_core` index.
internal var _coreOffset: Int
/// Creates a view of the given string.
public init(_ text: String) {
self._core = text._core
self._coreOffset = 0
}
public // @testable
init(_ _core: _StringCore, coreOffset: Int = 0) {
self._core = _core
self._coreOffset = coreOffset
}
}
/// A view of the string's contents as a collection of characters.
public var characters: CharacterView {
get {
return CharacterView(self)
}
set {
self = String(newValue)
}
}
/// Applies the given closure to a mutable view of the string's characters.
///
/// Do not use the string that is the target of this method inside the
/// closure passed to `body`, as it may not have its correct value. Instead,
/// use the closure's `CharacterView` argument.
///
/// This example below uses the `withMutableCharacters(_:)` method to
/// truncate the string `str` at the first space and to return the remainder
/// of the string.
///
/// var str = "All this happened, more or less."
/// let afterSpace = str.withMutableCharacters { chars -> String.CharacterView in
/// if let i = chars.index(of: " ") {
/// let result = chars.suffix(from: chars.index(after: i))
/// chars.removeSubrange(i..<chars.endIndex)
/// return result
/// }
/// return String.CharacterView()
/// }
///
/// print(str)
/// // Prints "All"
/// print(String(afterSpace))
/// // Prints "this happened, more or less."
///
/// - Parameter body: A closure that takes a character view as its argument.
/// The `CharacterView` argument is valid only for the duration of the
/// closure's execution.
/// - Returns: The return value of the `body` closure, if any, is the return
/// value of this method.
public mutating func withMutableCharacters<R>(
_ body: (inout CharacterView) -> R
) -> R {
// Naively mutating self.characters forces multiple references to
// exist at the point of mutation. Instead, temporarily move the
// core of this string into a CharacterView.
var tmp = CharacterView("")
swap(&_core, &tmp._core)
let r = body(&tmp)
swap(&_core, &tmp._core)
return r
}
/// Creates a string from the given character view.
///
/// Use this initializer to recover a string after performing a collection
/// slicing operation on a string's character view.
///
/// let poem = "'Twas brillig, and the slithy toves / " +
/// "Did gyre and gimbal in the wabe: / " +
/// "All mimsy were the borogoves / " +
/// "And the mome raths outgrabe."
/// let excerpt = String(poem.characters.prefix(22)) + "..."
/// print(excerpt)
/// // Prints "'Twas brillig, and the..."
///
/// - Parameter characters: A character view to convert to a string.
public init(_ characters: CharacterView) {
self.init(characters._core)
}
}
/// `String.CharacterView` is a collection of `Character`.
extension String.CharacterView : BidirectionalCollection {
internal typealias UnicodeScalarView = String.UnicodeScalarView
internal var unicodeScalars: UnicodeScalarView {
return UnicodeScalarView(_core, coreOffset: _coreOffset)
}
/// A position in a string's `CharacterView` instance.
///
/// You can convert between indices of the different string views by using
/// conversion initializers and the `samePosition(in:)` method overloads.
/// The following example finds the index of the first space in the string's
/// character view and then converts that to the same position in the UTF-8
/// view:
///
/// let hearts = "Hearts <3 ♥︎ 💘"
/// if let i = hearts.characters.index(of: " ") {
/// let j = i.samePosition(in: hearts.utf8)
/// print(Array(hearts.utf8.prefix(upTo: j)))
/// }
/// // Prints "[72, 101, 97, 114, 116, 115]"
public struct Index : Comparable, CustomPlaygroundQuickLookable {
public // SPI(Foundation)
init(_base: String.UnicodeScalarView.Index, in c: String.CharacterView) {
self._base = _base
self._countUTF16 = c._measureExtendedGraphemeClusterForward(from: _base)
}
internal init(_base: UnicodeScalarView.Index, _countUTF16: Int) {
self._base = _base
self._countUTF16 = _countUTF16
}
internal let _base: UnicodeScalarView.Index
/// The count of this extended grapheme cluster in UTF-16 code units.
internal let _countUTF16: Int
/// The integer offset of this index in UTF-16 code units.
public // SPI(Foundation)
var _utf16Index: Int {
return _base._position
}
/// The one past end index for this extended grapheme cluster in Unicode
/// scalars.
internal var _endBase: UnicodeScalarView.Index {
return UnicodeScalarView.Index(_position: _utf16Index + _countUTF16)
}
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .int(Int64(_utf16Index))
}
}
public typealias IndexDistance = Int
/// The position of the first character in a nonempty character view.
///
/// In an empty character view, `startIndex` is equal to `endIndex`.
public var startIndex: Index {
return Index(_base: unicodeScalars.startIndex, in: self)
}
/// A character view's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In an empty character view, `endIndex` is equal to `startIndex`.
public var endIndex: Index {
return Index(_base: unicodeScalars.endIndex, in: self)
}
/// Returns the next consecutive position after `i`.
///
/// - Precondition: The next position is valid.
public func index(after i: Index) -> Index {
_precondition(i._base < unicodeScalars.endIndex,
"cannot increment beyond endIndex")
_precondition(i._base >= unicodeScalars.startIndex,
"cannot increment invalid index")
return Index(_base: i._endBase, in: self)
}
/// Returns the previous consecutive position before `i`.
///
/// - Precondition: The previous position is valid.
public func index(before i: Index) -> Index {
_precondition(i._base > unicodeScalars.startIndex,
"cannot decrement before startIndex")
_precondition(i._base <= unicodeScalars.endIndex,
"cannot decrement invalid index")
let predecessorLengthUTF16 =
_measureExtendedGraphemeClusterBackward(from: i._base)
return Index(
_base: UnicodeScalarView.Index(
_position: i._utf16Index - predecessorLengthUTF16
),
in: self
)
}
// NOTE: don't make this function inlineable. Grapheme cluster
// segmentation uses a completely different algorithm in Unicode 9.0.
//
/// Returns the length of the first extended grapheme cluster in UTF-16
/// code units.
@inline(never) // Don't remove, see above.
internal func _measureExtendedGraphemeClusterForward(
from start: UnicodeScalarView.Index
) -> Int {
var start = start
let end = unicodeScalars.endIndex
if start == end {
return 0
}
let startIndexUTF16 = start._position
let graphemeClusterBreakProperty =
_UnicodeGraphemeClusterBreakPropertyTrie()
let segmenter = _UnicodeExtendedGraphemeClusterSegmenter()
var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue(
unicodeScalars[start].value)
unicodeScalars.formIndex(after: &start)
while start != end {
// FIXME(performance): consider removing this "fast path". A branch
// that is hard to predict could be worse for performance than a few
// loads from cache to fetch the property 'gcb1'.
if segmenter.isBoundaryAfter(gcb0) {
break
}
let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue(
unicodeScalars[start].value)
if segmenter.isBoundary(gcb0, gcb1) {
break
}
gcb0 = gcb1
unicodeScalars.formIndex(after: &start)
}
return start._position - startIndexUTF16
}
// NOTE: don't make this function inlineable. Grapheme cluster
// segmentation uses a completely different algorithm in Unicode 9.0.
//
/// Returns the length of the previous extended grapheme cluster in UTF-16
/// code units.
@inline(never) // Don't remove, see above.
internal func _measureExtendedGraphemeClusterBackward(
from end: UnicodeScalarView.Index
) -> Int {
let start = unicodeScalars.startIndex
if start == end {
return 0
}
let endIndexUTF16 = end._position
let graphemeClusterBreakProperty =
_UnicodeGraphemeClusterBreakPropertyTrie()
let segmenter = _UnicodeExtendedGraphemeClusterSegmenter()
var graphemeClusterStart = end
unicodeScalars.formIndex(before: &graphemeClusterStart)
var gcb0 = graphemeClusterBreakProperty.getPropertyRawValue(
unicodeScalars[graphemeClusterStart].value)
var graphemeClusterStartUTF16 = graphemeClusterStart._position
while graphemeClusterStart != start {
unicodeScalars.formIndex(before: &graphemeClusterStart)
let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue(
unicodeScalars[graphemeClusterStart].value)
if segmenter.isBoundary(gcb1, gcb0) {
break
}
gcb0 = gcb1
graphemeClusterStartUTF16 = graphemeClusterStart._position
}
return endIndexUTF16 - graphemeClusterStartUTF16
}
/// Accesses the character at the given position.
///
/// The following example searches a string's character view for a capital
/// letter and then prints the character at the found index:
///
/// let greeting = "Hello, friend!"
/// if let i = greeting.characters.index(where: { "A"..."Z" ~= $0 }) {
/// print("First capital letter: \(greeting.characters[i])")
/// }
/// // Prints "First capital letter: H"
///
/// - Parameter position: A valid index of the character view. `position`
/// must be less than the view's end index.
public subscript(i: Index) -> Character {
return Character(String(unicodeScalars[i._base..<i._endBase]))
}
}
extension String.CharacterView : RangeReplaceableCollection {
/// Creates an empty character view.
public init() {
self.init("")
}
/// Replaces the characters within the specified bounds with the given
/// characters.
///
/// Invalidates all indices with respect to the string.
///
/// - Parameters:
/// - bounds: The range of characters to replace. The bounds of the range
/// must be valid indices of the character view.
/// - newElements: The new characters to add to the view.
///
/// - Complexity: O(*m*), where *m* is the combined length of the character
/// view and `newElements`. If the call to `replaceSubrange(_:with:)`
/// simply removes characters at the end of the view, the complexity is
/// O(*n*), where *n* is equal to `bounds.count`.
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Iterator.Element == Character {
let rawSubRange: Range<Int> =
bounds.lowerBound._base._position - _coreOffset
..< bounds.upperBound._base._position - _coreOffset
let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 }
_core.replaceSubrange(rawSubRange, with: lazyUTF16)
}
/// Reserves enough space in the character view's underlying storage to store
/// the specified number of ASCII characters.
///
/// Because each element of a character view can require more than a single
/// ASCII character's worth of storage, additional allocation may be
/// necessary when adding characters to the character view after a call to
/// `reserveCapacity(_:)`.
///
/// - Parameter n: The minimum number of ASCII character's worth of storage
/// to allocate.
///
/// - Complexity: O(*n*), where *n* is the capacity being reserved.
public mutating func reserveCapacity(_ n: Int) {
_core.reserveCapacity(n)
}
/// Appends the given character to the character view.
///
/// - Parameter c: The character to append to the character view.
public mutating func append(_ c: Character) {
switch c._representation {
case .small(let _63bits):
let bytes = Character._smallValue(_63bits)
_core.append(contentsOf: Character._SmallUTF16(bytes))
case .large(_):
_core.append(String(c)._core)
}
}
/// Appends the characters in the given sequence to the character view.
///
/// - Parameter newElements: A sequence of characters.
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Iterator.Element == Character {
reserveCapacity(_core.count + newElements.underestimatedCount)
for c in newElements {
self.append(c)
}
}
/// Creates a new character view containing the characters in the given
/// sequence.
///
/// - Parameter characters: A sequence of characters.
public init<S : Sequence>(_ characters: S)
where S.Iterator.Element == Character {
self = String.CharacterView()
self.append(contentsOf: characters)
}
}
// Algorithms
extension String.CharacterView {
/// Accesses the characters in the given range.
///
/// The example below uses this subscript to access the characters up to, but
/// not including, the first comma (`","`) in the string.
///
/// let str = "All this happened, more or less."
/// let i = str.characters.index(of: ",")!
/// let substring = str.characters[str.characters.startIndex ..< i]
/// print(String(substring))
/// // Prints "All this happened"
///
/// - Complexity: O(*n*) if the underlying string is bridged from
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
public subscript(bounds: Range<Index>) -> String.CharacterView {
let unicodeScalarRange = bounds.lowerBound._base..<bounds.upperBound._base
return String.CharacterView(unicodeScalars[unicodeScalarRange]._core,
coreOffset: unicodeScalarRange.lowerBound._position)
}
}
extension String.CharacterView {
@available(*, unavailable, renamed: "replaceSubrange")
public mutating func replaceRange<C>(
_ subRange: Range<Index>,
with newElements: C
) where C : Collection, C.Iterator.Element == Character {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "append(contentsOf:)")
public mutating func appendContentsOf<S : Sequence>(_ newElements: S)
where S.Iterator.Element == Character {
Builtin.unreachable()
}
}
| apache-2.0 | 6d74ced893028210089c7b1a8a8f5ec2 | 35.24307 | 87 | 0.652077 | 4.418508 | false | false | false | false |
curiousurick/BluetoothBackupSensor-iOS | CSS427Bluefruit_Connect/BLE Test/CSS427IntervalView.swift | 1 | 6899 | //
// CSS427IntervalView.swift
// CSS427Bluefruit_Connect
//
// Created by George Urick on 3/7/16.
// Copyright © 2016 Adafruit Industries. All rights reserved.
//
import UIKit
@objc protocol IntervalViewDelegate: Any {
func sendRequest(command: String)
}
class CSS427IntervalView: UIView, UITextFieldDelegate {
weak var delegate: IntervalViewDelegate?
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var accelerometerLabel: UILabel!
@IBOutlet weak var compassLabel: UILabel!
@IBOutlet weak var distanceSampleField: UITextField!
@IBOutlet weak var tempSampleField: UITextField!
@IBOutlet weak var accelerometerSampleField: UITextField!
@IBOutlet weak var compassSampleField: UITextField!
@IBOutlet weak var distanceToggle: UIButton!
@IBOutlet weak var tempToggle: UIButton!
@IBOutlet weak var accelerometerToggle: UIButton!
@IBOutlet weak var compassToggle: UIButton!
func textFieldShouldReturn(textField: UITextField) -> Bool {
return true
}
func updateReading(printValue: String, device: Character) {
// if containsACommand(reading) == false { return }
// let letters = NSCharacterSet.letterCharacterSet()
// let command = reading.substringToIndex(reading.startIndex.advancedBy(2))
// var readString : String?
// if reading.characters.count > 2 {
// readString = reading.substringFromIndex(reading.startIndex.advancedBy(2))
// }
//
// if (readString == nil){
// checkToggle(command)
// return
// }
// var index = 0;
// for var c in readString!.unicodeScalars {
// if letters.longCharacterIsMember(c.value) {
// let newReading = readString!.substringFromIndex(readString!.startIndex.advancedBy(index))
// readString = readString!.substringToIndex(readString!.startIndex.advancedBy(index))
// print(newReading)
// updateReading(newReading)
// break;
// }
// index += 1
// }
// if (readString == nil || readString!.characters.count == 0) {
// checkToggle(command)
// return
// }
switch device {
case "A":
distanceLabel.text = "Distance: \(printValue) cm"
break;
case "B":
tempLabel.text = "Temperature: \(printValue)°"
break;
case "C":
accelerometerLabel.text = "Accelerometer: \(printValue)"
break;
case "D":
compassLabel.text = "Compass: \(printValue)°"
default:
printLog(self, funcName: "updateReading", logString: "Incorrect command passed")
}
}
func checkToggle(command: String) {
switch command {
case CommandEnableDistance:
distanceToggle.setTitle("D", forState: .Normal)
break;
case CommandEnableTemp:
tempToggle.setTitle("D", forState: .Normal)
break;
case CommandEnableAccelerometer:
accelerometerToggle.setTitle("D", forState: .Normal)
break;
case CommandEnableCompass:
compassToggle.setTitle("D", forState: .Normal)
break;
case CommandDisableDistance:
distanceToggle.setTitle("E", forState: .Normal)
break;
case CommandDisableTemp:
tempToggle.setTitle("E", forState: .Normal)
break;
case CommandDisableAccelerometer:
accelerometerToggle.setTitle("E", forState: .Normal)
break;
case CommandDisableCompass:
compassToggle.setTitle("E", forState: .Normal)
break;
default:
break;
}
}
func closeKeyboard() {
self.distanceSampleField.resignFirstResponder()
self.tempSampleField.resignFirstResponder()
self.accelerometerSampleField.resignFirstResponder()
self.compassSampleField.resignFirstResponder()
}
func clear() {
distanceLabel.text = ""
distanceToggle.setTitle("D", forState: .Normal)
tempLabel.text = ""
tempToggle.setTitle("D", forState: .Normal)
accelerometerLabel.text = ""
accelerometerToggle.setTitle("D", forState: .Normal)
compassLabel.text = ""
compassToggle.setTitle("D", forState: .Normal)
}
@IBAction func toggleDistance(sender: UIButton) {
if delegate == nil { return }
let command = distanceToggle.titleForState(.Normal) == "D" ? CommandDisableDistance : CommandEnableDistance
delegate?.sendRequest(command)
}
@IBAction func toggleTemp(sender: UIButton) {
if delegate == nil { return }
let command = tempToggle.titleForState(.Normal) == "D" ? CommandDisableTemp : CommandEnableTemp
delegate?.sendRequest(command)
}
@IBAction func toggleAccelerometer(sender: UIButton) {
if delegate == nil { return }
let command = accelerometerToggle.titleForState(.Normal) == "D" ? CommandDisableAccelerometer : CommandEnableAccelerometer
delegate?.sendRequest(command)
}
@IBAction func toggleCompass(sender: UIButton) {
if delegate == nil { return }
let command = compassToggle.titleForState(.Normal) == "D" ? CommandDisableCompass : CommandEnableCompass
delegate?.sendRequest(command)
}
@IBAction func updateDistanceSample(sender: UIButton) {
closeKeyboard()
if (delegate == nil) { return }
delegate?.sendRequest("\(CommandAlertUpdateDistance)\(distanceSampleField.text!)")
distanceSampleField.text = ""
}
@IBAction func updateTempSample(sender: UIButton) {
closeKeyboard()
if (delegate == nil) { return }
delegate?.sendRequest("\(CommandAlertUpdateTemp)\(tempSampleField.text!)")
tempSampleField.text = ""
}
@IBAction func updateAccelerometerSample(sender: UIButton) {
closeKeyboard()
if (delegate == nil) { return }
delegate?.sendRequest("\(CommandAlertUpdateAccelerometer)\(accelerometerSampleField.text!)")
accelerometerSampleField.text = ""
}
@IBAction func updateCompassSample(sender: UIButton) {
closeKeyboard()
if (delegate == nil) { return }
delegate?.sendRequest("\(CommandAlertUpdateCompass)\(compassSampleField.text!)")
compassSampleField.text = ""
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | a2781fc747e2627fa454d15c3ea79198 | 33.653266 | 130 | 0.618039 | 4.876945 | false | false | false | false |
OpenKitten/Meow | Sources/Meow/WrappedIdentifier.swift | 1 | 1163 | internal class AnyInstanceIdentifier: Hashable {
fileprivate init() {}
var hashValue: Int {
assertionFailure("The HashValue implementation of AnyInstanceIdentifier should not be used")
return 0
}
static func == (lhs: AnyInstanceIdentifier, rhs: AnyInstanceIdentifier) -> Bool {
return lhs.equals(rhs)
}
fileprivate func equals(_ other: AnyInstanceIdentifier) -> Bool {
assertionFailure("The AnyInstanceIdentifier method of equals should not be used")
return false
}
}
internal final class InstanceIdentifier<M: Model> : AnyInstanceIdentifier {
let identifier: M.Identifier
init(_ identifier: M.Identifier) {
self.identifier = identifier
super.init()
}
override var hashValue: Int {
return ObjectIdentifier(M.self).hashValue ^ identifier.hashValue
}
override func equals(_ other: AnyInstanceIdentifier) -> Bool {
guard let other = other as? InstanceIdentifier<M> else {
// Different types
return false
}
return other.identifier == self.identifier
}
}
| mit | 7081de4d717b5d6dd2349b1bcae0c9a4 | 28.075 | 100 | 0.639725 | 5.123348 | false | false | false | false |
google/JacquardSDKiOS | Tests/FakeImplementations/FakeDFUCommands.swift | 1 | 4674 | // 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
@testable import JacquardSDK
struct FakeDFUCommands {
static func prepareDFUStatusRequest(
vid: String,
pid: String
) -> Google_Jacquard_Protocol_Request {
return Google_Jacquard_Protocol_Request.with { request in
request.domain = .dfu
request.opcode = .dfuStatus
request.Google_Jacquard_Protocol_DFUStatusRequest_dfuStatus =
Google_Jacquard_Protocol_DFUStatusRequest.with { statusDFURequest in
statusDFURequest.vendorID = ComponentImplementation.convertToDecimal(vid)
statusDFURequest.productID = ComponentImplementation.convertToDecimal(pid)
}
}
}
static func prepareDFUStatusResponse(
status: Google_Jacquard_Protocol_Status,
dfuStatusResponse: Google_Jacquard_Protocol_DFUStatusResponse?
) -> Data {
let response = Google_Jacquard_Protocol_Response.with { response in
response.status = status
response.id = 1
if let dfuStatusResponse = dfuStatusResponse {
response.Google_Jacquard_Protocol_DFUStatusResponse_dfuStatus = dfuStatusResponse
}
}
return try! response.serializedData()
}
static func prepareDFUPrepareRequest(
componentID: UInt32,
vid: String,
pid: String,
image: Data
) -> Google_Jacquard_Protocol_Request {
return Google_Jacquard_Protocol_Request.with { request in
request.domain = .dfu
request.opcode = .dfuPrepare
return request.Google_Jacquard_Protocol_DFUPrepareRequest_dfuPrepare =
Google_Jacquard_Protocol_DFUPrepareRequest.with { prepareRequest in
prepareRequest.component = componentID
prepareRequest.finalCrc = UInt32(CRC16.compute(in: image, seed: 0))
prepareRequest.finalSize = UInt32(image.count)
prepareRequest.vendorID = ComponentImplementation.convertToDecimal(vid)
prepareRequest.productID = ComponentImplementation.convertToDecimal(pid)
}
}
}
static func prepareDFUPrepareResponse(status: Google_Jacquard_Protocol_Status) -> Data {
let response = Google_Jacquard_Protocol_Response.with { response in
response.status = status
response.id = 1
}
return try! response.serializedData()
}
static func prepareDFUWriteRequest(data: Data, offset: UInt32)
-> Google_Jacquard_Protocol_Request
{
return Google_Jacquard_Protocol_Request.with { request in
request.domain = .dfu
request.opcode = .dfuWrite
request.Google_Jacquard_Protocol_DFUWriteRequest_dfuWrite =
Google_Jacquard_Protocol_DFUWriteRequest.with { writeRequest in
writeRequest.data = data
writeRequest.offset = offset
}
}
}
static func prepareDFUWriteResponse(
status: Google_Jacquard_Protocol_Status,
writeResponse: Google_Jacquard_Protocol_DFUWriteResponse?
) -> Data {
let response = Google_Jacquard_Protocol_Response.with { response in
response.status = status
response.id = 1
if let writeResponse = writeResponse {
response.Google_Jacquard_Protocol_DFUWriteResponse_dfuWrite = writeResponse
}
}
return try! response.serializedData()
}
static func prepareExecuteRequest(vid: String, pid: String) -> Google_Jacquard_Protocol_Request {
return Google_Jacquard_Protocol_Request.with { request in
request.domain = .dfu
request.opcode = .dfuExecute
request.Google_Jacquard_Protocol_DFUExecuteRequest_dfuExecute =
Google_Jacquard_Protocol_DFUExecuteRequest.with { dfuExecuteRequest in
dfuExecuteRequest.vendorID = ComponentImplementation.convertToDecimal(vid)
dfuExecuteRequest.productID = ComponentImplementation.convertToDecimal(pid)
dfuExecuteRequest.updateSched = Google_Jacquard_Protocol_UpdateSchedule.updateNow
}
}
}
static func prepareDFUExecuteResponse(status: Google_Jacquard_Protocol_Status) -> Data {
let response = Google_Jacquard_Protocol_Response.with { response in
response.status = status
response.id = 1
}
return try! response.serializedData()
}
}
| apache-2.0 | 3bb4220b244023afe6eb9e5552b14f8e | 34.679389 | 99 | 0.719726 | 4.442966 | false | false | false | false |
cbadke/SwiftMockGen | src/SwiftMockGen/SwiftMockGenTests/CallVerifierTests.swift | 1 | 3668 | //
// VerifierTests.swift
// SwiftMockGen
//
// Created by Curtis Badke on 2016-06-01.
// Copyright © 2016 DevFacto Technologies. All rights reserved.
//
import XCTest
@testable import SwiftMockGen
private class custom : CustomStringConvertible {
let Property: String
init (prop: String) { Property = prop }
//CustomStringConvertible
var description: String { get { return "Property=\(Property)" } }
}
class CallVerifierTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_RecordingACall_DoesNotThrowError() {
let sut = CallVerifier()
sut.record("someMethod")
}
func test_VerifyWithoutRecordingACall_ReturnsFalse() {
let sut = CallVerifier()
let response = sut.verify("someMethod")
XCTAssertFalse(response)
}
func test_VerifyAfterRecordingACall_ReturnsTrue() {
let sut = CallVerifier()
sut.record("someMethod")
let response = sut.verify("someMethod")
XCTAssertTrue(response)
}
func test_VerifyAfterRecordADifferentCall_ReturnsFalse() {
let sut = CallVerifier()
sut.record("someMethod")
let response = sut.verify("someOtherMethod")
XCTAssertFalse(response)
}
func test_RecordingACallWithArguments_DoesNotThrowError() {
let sut = CallVerifier()
sut.record("someMethodTakesInt", 123)
}
func test_VerifyingWithoutArguments_MatchesAnyRecordedCallWithName() {
let sut = CallVerifier()
sut.record("someMethod", 123)
let response = sut.verify("someMethod")
XCTAssertTrue(response)
}
func test_VerifyingWithArguments_MatchesRecordedCallWithSameNameAndArguments() {
let sut = CallVerifier()
sut.record("someMethod", 123)
let response = sut.verify("someMethod", 123)
XCTAssertTrue(response)
}
func test_VerifyingWithArguments_DoesNotMatchRecordedCallWithDifferentArguments() {
let sut = CallVerifier()
sut.record("someMethod", 123)
let response = sut.verify("someMethod", 789)
XCTAssertFalse(response)
}
func test_VerifyingWithMultipleArguments_FailsIfOrderMismatch() {
let sut = CallVerifier()
sut.record("someMethod", 123, 789)
let response = sut.verify("someMethod", 789, 123)
XCTAssertFalse(response)
}
func test_VerifyingWithMultipleArguments_SucceedsIfOrderMatches() {
let sut = CallVerifier()
sut.record("someMethod", 123, 789)
let response = sut.verify("someMethod", 123, 789)
XCTAssertTrue(response)
}
func test_CanVerifyWithCustomObject() {
let obj = custom(prop: "propVal")
let sut = CallVerifier()
sut.record("call", obj)
let response = sut.verify("call", obj)
XCTAssertTrue(response)
}
func test_VerifyingCallsWithDifferentObjects_Fails() {
let obj1 = custom(prop: "propVal")
let obj2 = custom(prop: "otherVal")
let sut = CallVerifier()
sut.record("call", obj1)
let response = sut.verify("call", obj2)
XCTAssertFalse(response)
}
func test_VerifyingCallsWithEquivalentObjects_Passes() {
let obj1 = custom(prop: "propVal")
let obj2 = custom(prop: "propVal")
let sut = CallVerifier()
sut.record("call", obj1)
let response = sut.verify("call", obj2)
XCTAssertTrue(response)
}
}
| mit | c58686336c114ebb261967e724a36b40 | 24.116438 | 111 | 0.641942 | 4.45565 | false | true | false | false |
mitochrome/complex-gestures-demo | apps/GestureInput/Carthage/Checkouts/RxDataSources/Sources/DataSources/Array+Extensions.swift | 11 | 968 | //
// Array+Extensions.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 4/26/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Array where Element: SectionModelType {
mutating func moveFromSourceIndexPath(_ sourceIndexPath: IndexPath, destinationIndexPath: IndexPath) {
let sourceSection = self[sourceIndexPath.section]
var sourceItems = sourceSection.items
let sourceItem = sourceItems.remove(at: sourceIndexPath.item)
let sourceSectionNew = Element(original: sourceSection, items: sourceItems)
self[sourceIndexPath.section] = sourceSectionNew
let destinationSection = self[destinationIndexPath.section]
var destinationItems = destinationSection.items
destinationItems.insert(sourceItem, at: destinationIndexPath.item)
self[destinationIndexPath.section] = Element(original: destinationSection, items: destinationItems)
}
}
| mit | e6b833ea3aeb0f9cd5e2a9334804bfd3 | 34.814815 | 107 | 0.744571 | 4.883838 | false | false | false | false |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/connect/ConnectUserServer.swift | 1 | 1277 | //
// ConnectUserServer.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 08/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
public struct ConnectUserServer: Codable
{
public let id: String
public let url: String
public let name: String
public let accessKey: String
public let systemId: String
public let localAddress: String
public let userType: String
public let supporterKey: String?
public init?(jSON: JSON_Object) {
if let id = jSON["Id"] as? String,
let url = jSON["Url"] as? String,
let name = jSON["Name"] as? String,
let systemId = jSON["SystemId"] as? String,
let accessKey = jSON["AccessKey"] as? String,
let localAddress = jSON["LocalAddress"] as? String,
let userType = jSON["UserType"] as? String
{
self.id = id
self.url = url
self.name = name
self.accessKey = accessKey
self.systemId = systemId
self.localAddress = localAddress
self.userType = userType
self.supporterKey = jSON["SupporterKey"] as? String
}
else {
return nil
}
}
}
| mit | 0d58e99c721c2f32b34b26af12493bac | 26.73913 | 63 | 0.570533 | 4.461538 | false | false | false | false |
Bouke/HAP | Sources/HAP/Utils/QRCode.swift | 1 | 2964 | import CQRCode
import Foundation
#if os(macOS)
import Cocoa
#endif
public struct QRCode {
let string: String
init(from: String) {
self.string = from
}
public var asBitmap: [[Bool]] {
var qrcode = CQRCode.QRCode()
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CQRCode.qrcode_getBufferSize(1)))
let returnValue = string.withCString { stringPointer in
CQRCode.qrcode_initText(&qrcode, buffer, 1, UInt8(CQRCode.ECC_MEDIUM), stringPointer)
}
precondition(returnValue == 0, "QRCode generation failed")
return (0..<qrcode.size).map { y in
(0..<qrcode.size).map { x in
CQRCode.qrcode_getModule(&qrcode, x, y) == 1
}
}
}
public var asText: String {
let bitmap = asBitmap
return stride(from: 0, to: bitmap.count, by: 2)
.map { y in
let lower = bitmap[y]
let upper = y > 0 ? bitmap[y - 1] : [Bool](repeating: false, count: lower.count)
return zip(upper, lower)
.map { pixel in
switch pixel {
case (false, false): return " "
case (true, false): return "▀"
case (false, true): return "▄"
case (true, true): return "█"
}
}
.joined()
}
.joined(separator: "\n")
}
public var asBigText: String {
let bitmap = asBitmap
return (0..<bitmap.count)
.map { y in
bitmap[y]
.map { $0 ? "██" : " " }
.joined()
}
.joined(separator: "\n")
}
public var asASCII: String {
let bitmap = asBitmap
return (0..<bitmap.count)
.map { y in
bitmap[y]
.map { $0 ? "##" : " " }
.joined()
}
.joined(separator: "\n")
}
#if os(macOS)
public var asCIImage: CIImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.transformed(by: transform) {
// Having this comment here stops swiftlint from generating implicit_return violation
return output
}
}
return nil
}
public var asNSImage: NSImage? {
if let ciImage = asCIImage {
let rep: NSCIImageRep = NSCIImageRep(ciImage: ciImage)
let nsImage: NSImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
return nsImage
}
return nil
}
#endif
}
| mit | 3ccd55b6c27d09437f8d8e84490debd7 | 29.453608 | 105 | 0.492552 | 4.422156 | false | false | false | false |
mateuszfidosBLStream/MFCircleDialPad | MFCircleDialPad/MFDialPadItemView.swift | 1 | 2606 | //
// DialPadButton.swift
// CircleDialPad
//
// Created by Mateusz Fidos on 23.05.2016.
// Copyright © 2016 mateusz.fidos. All rights reserved.
//
import UIKit
import Foundation
let kMenuItemViewBorderSize:CGFloat = 2.0
let kMenuItemViewAlpha:CGFloat = 0.2
let kDefaultShadowOpacity:Float = 0.5
let kDefaultShadowOffset:CGFloat = 2.0
let kDefaulShadowRadius:CGFloat = 2.0
class MFDialPadItemView: UIView
{
var background:UIColor?
var imageView:UIImageView?
convenience init(radius:CGFloat, text:String?)
{
self.init(radius: radius, backgroundColor: MFDialPadColor.random().padColor, text: text, image: nil)
}
convenience init(radius:CGFloat, image:UIImage?, backgroundColor:UIColor?)
{
self.init(radius: radius, backgroundColor: backgroundColor, text: nil, image: image)
}
init(radius: CGFloat, backgroundColor: UIColor?, text:String?, image:UIImage?)
{
self.background = backgroundColor
super.init(frame: CGRectMake(-radius, -radius, radius, radius))
construct(withText: text, image: image)
}
override init(frame: CGRect)
{
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
}
func construct(withText text:String?, image:UIImage?)
{
let radius:CGFloat = CGRectGetWidth(self.frame) / 2
if let labelText = text
{
let label = UILabel(frame: CGRectMake(-radius, -radius, radius, radius))
label.center = CGPointMake(radius, radius)
label.textAlignment = .Center
label.text = labelText
self.addSubview(label)
}
if let customImage = image
{
self.imageView = UIImageView(frame: self.frame)
self.imageView!.image = customImage
self.imageView!.center = CGPointMake(radius, radius)
self.addSubview(self.imageView!)
}
self.layer.cornerRadius = radius
if let backgroundColor = self.background
{
self.layer.backgroundColor = backgroundColor.CGColor
}
else
{
self.background = MFDialPadColor.random().padColor
self.layer.backgroundColor = self.background!.CGColor
}
}
func updateImageView(image:UIImage?)
{
guard let imageView = self.imageView else
{
return
}
guard let newImage = image else
{
return
}
imageView.image = newImage
self.setNeedsDisplay()
}
}
| mit | 5dacbc58aa32df0f381d6c89d8aaad49 | 24.792079 | 108 | 0.621881 | 4.460616 | false | false | false | false |
SVKorosteleva/heartRateMonitor | HeartMonitor/HeartMonitor/TrainingsStorageManager.swift | 1 | 2474 | //
// TrainingsStorageManager.swift
// HeartMonitor
//
// Created by Светлана Коростелёва on 9/19/17.
// Copyright © 2017 home. All rights reserved.
//
import CoreData
struct HRMeasurement {
let heartRate: UInt32
let seconds: UInt32
}
class TrainingsStorageManager {
private var context: NSManagedObjectContext
init(context: NSManagedObjectContext) {
self.context = context
}
func createTraining() -> Training? {
guard let training
= NSEntityDescription
.insertNewObject(forEntityName: "Training",
into: context) as? Training else { return nil }
training.dateTimeStart = Date()
training.duration = 0
do {
try context.save()
} catch let e {
print("Unable to create training: \(e.localizedDescription)")
return nil
}
return training
}
func addMeasurement(_ heartRate: UInt32, duration: UInt32, to training: Training) {
guard let measurement =
NSEntityDescription
.insertNewObject(forEntityName: "HeartRateMeasurement",
into: context) as? HeartRateMeasurement else { return }
measurement.heartRate = Int32(heartRate)
measurement.secondsFromBeginning = Int32(duration)
training.measurements = training.measurements?.adding(measurement) as NSSet?
training.duration = Int32(duration)
do {
try context.save()
} catch let e {
print("Unable to add data to training: \(e.localizedDescription)")
}
}
func trainings() -> [Training] {
let fetchRequest = NSFetchRequest<Training>(entityName: "Training")
guard let trainings = try? context.fetch(fetchRequest) else {
return []
}
return trainings.sorted(by: {
($0.dateTimeStart as Date?) ?? Date() > ($1.dateTimeStart as Date?) ?? Date()
})
}
func measurements(of training: Training) -> [HRMeasurement] {
guard let trainingMeasurements
= training.measurements as? Set<HeartRateMeasurement> else {
return []
}
return trainingMeasurements.map {
HRMeasurement(heartRate: UInt32($0.heartRate),
seconds: UInt32($0.secondsFromBeginning))
}.sorted(by: { $0.seconds < $1.seconds })
}
}
| mit | c0d68fe7414182fb11ca5fb21f18d154 | 28.926829 | 89 | 0.594947 | 4.888446 | false | false | false | false |
LightD/ivsa-server | Sources/App/Models/IVSAAdmin.swift | 1 | 3544 | //
// IVSAAdmin.swift
// ivsa
//
// Created by Light Dream on 01/12/2016.
//
//
import Foundation
import Vapor
import Fluent
import Turnstile
import TurnstileCrypto
final class IVSAAdmin: Model {
// this is for fluent ORM
var exists: Bool = false
var id: Node?
var email: String
var password: String
var accessToken: String? // when it's nil, the user is logged out
init(node: Node, in context: Context) throws {
id = try node.extract("_id") // that's mongo's ID
email = try node.extract("email")
password = try node.extract("password")
accessToken = try node.extract("access_token")
}
init(credentials: UsernamePassword) {
self.email = credentials.username
self.password = BCrypt.hash(password: credentials.password)
self.accessToken = BCrypt.hash(password: credentials.password)
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"_id": id,
"email": email,
"password": password,
"access_token": accessToken,
])
}
func generateAccessToken() {
self.accessToken = BCrypt.hash(password: self.password)
}
}
/// Since we are dealing with mongo, we don't need to implement this
extension IVSAAdmin: Preparation {
static func prepare(_ database: Database) throws { }
static func revert(_ database: Database) throws { }
}
import Auth
extension IVSAAdmin: Auth.User {
static func authenticate(credentials: Credentials) throws -> Auth.User {
var user: IVSAAdmin?
switch credentials {
case let credentials as UsernamePassword:
let fetchedUser = try IVSAAdmin.query()
.filter("email", credentials.username)
.first()
if let password = fetchedUser?.password,
password != "",
(try? BCrypt.verify(password: credentials.password, matchesHash: password)) == true {
user = fetchedUser
}
case let credentials as AccessToken:
let fetchedUser = try IVSAAdmin
.query()
.filter("access_token", credentials.string)
.first()
if fetchedUser != nil {
user = fetchedUser
}
default:
throw Abort.custom(status: .badRequest, message: "Unsupported credentials.")
}
guard let u = user else {
throw Abort.custom(status: .badRequest, message: "Incorrect credentials.")
}
return u
}
static func register(credentials: Credentials) throws -> Auth.User {
// create a user and
var newUser: IVSAAdmin
switch credentials {
case let credentials as UsernamePassword:
newUser = IVSAAdmin(credentials: credentials)
default:
throw Abort.custom(status: .badRequest, message: "Unsupported credentials.")
}
if try IVSAAdmin.query().filter("email", newUser.email).first() == nil {
try newUser.save()
return newUser
} else {
throw Abort.custom(status: .badRequest, message: "This email is in use, please login.")
}
}
}
import HTTP
extension Request {
func admin() throws -> IVSAAdmin {
return try self.adminAuth.admin()
}
}
| mit | 6247ce78c42cbb3d217f9b52726e208e | 26.905512 | 101 | 0.569131 | 4.737968 | false | false | false | false |
sxg/Chroma | Source/ImageAnalyzer.swift | 1 | 4248 | //
// ImageAnalyzer.swift
// Chroma
//
// Created by Satyam Ghodasara on 1/31/16.
// Copyright © 2016 Satyam Ghodasara. All rights reserved.
//
import UIKit
public class ImageAnalyzer {
public let image: UIImage
public let colors: Array<UIColor>
public let backgroundColor: UIColor
public let textColors: Array<UIColor>
public init(image: UIImage) {
self.image = image
self.colors = ImageAnalyzer.colorsFor(image: self.image)
self.backgroundColor = ImageAnalyzer.backgroundColorFor(colors: self.colors)
self.textColors = ImageAnalyzer.textColorsFor(colors: self.colors, backgroundColor: self.backgroundColor)
}
private static func colorsFor(image image: UIImage) -> Array<UIColor> {
var colors = [UIColor]()
let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage))
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
for x in 0..<Int(image.size.width) {
for y in 0..<Int(image.size.height) {
let pixel: Int = ((Int(image.size.width) * y) + x) * 4
let r = round(100 * CGFloat(data[pixel]) / CGFloat(255.0)) / 100
let g = round(100 * CGFloat(data[pixel + 1]) / CGFloat(255.0)) / 100
let b = round(100 * CGFloat(data[pixel + 2]) / CGFloat(255.0)) / 100
let a = round (100 * CGFloat(data[pixel + 3]) / CGFloat(255.0)) / 100
colors.append(UIColor(red: r, green: g, blue: b, alpha: a))
}
}
return colors
}
private static func backgroundColorFor(colors colors: Array<UIColor>) -> UIColor {
var colorCounts = [UIColor: Int]()
for color in colors {
if let colorCount = colorCounts[color] {
colorCounts[color] = colorCount + 1
} else {
colorCounts[color] = 1
}
}
let sortedColors = colorCounts.keys.sort {
return colorCounts[$0] > colorCounts[$1]
}
var backgroundColor = sortedColors.first!
for color in sortedColors {
if backgroundColor.isBlackOrWhite() {
if Float(colorCounts[backgroundColor]!) / Float(colorCounts[color]!) > 0.3 && !color.isBlackOrWhite() {
backgroundColor = color
break
}
}
}
return backgroundColor
}
private static func textColorsFor(colors colors: Array<UIColor>, backgroundColor: UIColor) -> Array<UIColor> {
var textColors = [UIColor]()
var colorCounts = [UIColor: Int]()
let findDark = !backgroundColor.isDark()
for aColor in colors {
let color = UIColor(fromColor: aColor, saturation: 0.15)
if color.isDark() == findDark {
if let colorCount = colorCounts[color] {
colorCounts[color] = colorCount + 1
} else {
colorCounts[color] = 1
}
}
}
let sortedColors = colorCounts.keys.sort {
return colorCounts[$0] > colorCounts[$1]
}
for color in sortedColors {
if textColors.count == 0 {
if color.isContrasting(on: backgroundColor) {
textColors.append(color)
}
} else if textColors.count == 1 {
let primaryColor = textColors[0]
if primaryColor.isDistinct(from: color) && color.isContrasting(on: backgroundColor) {
textColors.append(color)
}
} else if textColors.count == 2 {
let primaryColor = textColors[0]
let secondaryColor = textColors[1]
if secondaryColor.isDistinct(from: color) && primaryColor.isDistinct(from: color) && color.isContrasting(on: backgroundColor) {
textColors.append(color)
return textColors
}
}
}
return textColors
}
}
| mit | ba8da1b7154acdd5175d1d47303903f9 | 34.391667 | 143 | 0.538262 | 4.766554 | false | false | false | false |
lenssss/whereAmI | Whereami/Controller/Game/Cell/ScrollBannersTableViewCell.swift | 1 | 7350 | //
// ScrollBannersTableViewCell.swift
// Whereami
//
// Created by WuQifei on 16/2/18.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
import PureLayout
//import SDWebImage
import ReactiveCocoa
import Kingfisher
public protocol BannerViewDelegate:NSObjectProtocol {
func bannerViewDidClicked(index:Int)
}
class ScrollBannersTableViewCell: UITableViewCell,UIScrollViewDelegate {
private var onceToken:dispatch_once_t = 0
var delegate:BannerViewDelegate? = nil
var imageURLs:[NSURL]? = nil
var count:Int = 0
var timerInterval:Int = 0
var currentPageIndicatorTintColor:UIColor? = nil
var pageIndicatorTintColor:UIColor? = nil
var placeholderImage:String? = nil
private var timer:NSTimer? = nil
private var pageControl:UIPageControl? = nil
private var bannerView:UIScrollView? = nil
func viewInit(
delegate:BannerViewDelegate,
imageURLs:[NSURL],
placeholderImage:String,
timeInterval:Int,
currentPageIndicatorTintColor:UIColor,
pageIndicatorTintColor:UIColor) {
self.delegate = delegate
self.imageURLs = imageURLs
self.count = imageURLs.count
self.timerInterval = timeInterval
self.currentPageIndicatorTintColor = currentPageIndicatorTintColor
self.pageIndicatorTintColor = pageIndicatorTintColor
self.placeholderImage = placeholderImage
self.setupMainView()
}
override func layoutSubviews() {
super.layoutSubviews()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupMainView() {
let scrollW = self.frame.size.width
let scrollH = self.frame.size.height
self.bannerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: scrollW, height: scrollH))
for i in 0..<(self.count+2) {
var tag = 0
if i == 0 {
tag = self.count
} else if i == (self.count + 1) {
tag = 1
} else {
tag = i
}
let imageView = UIImageView()
imageView.tag = tag
imageView.kf_setImageWithURL(self.imageURLs![tag - 1], placeholderImage: UIImage(named: self.placeholderImage!), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
imageView.clipsToBounds = true
imageView.userInteractionEnabled = true
imageView.contentMode = UIViewContentMode.ScaleToFill
imageView.frame = CGRect(x: scrollW * CGFloat(i), y: 0, width: scrollW, height: scrollH)
self.bannerView?.addSubview(imageView)
let tap = UITapGestureRecognizer(target: self, action: #selector(ScrollBannersTableViewCell.imageViewTaped(_:)))
imageView.addGestureRecognizer(tap)
}
self.bannerView?.delegate = self
self.bannerView?.scrollsToTop = false
self.bannerView?.pagingEnabled = true
self.bannerView?.showsHorizontalScrollIndicator = false
self.bannerView?.contentOffset = CGPoint(x: scrollW, y: 0)
self.bannerView?.contentSize = CGSize(width: CGFloat(self.count + 2) * scrollW, height: 0)
self.contentView.addSubview(self.bannerView!)
NSNotificationCenter.defaultCenter().rac_addObserverForName(KNotificationMainViewDidShow, object: nil).subscribeNext { (obj) -> Void in
dispatch_once(&self.onceToken) { () -> Void in
self.addTimer()
}
}
self.pageControl = UIPageControl(frame: CGRect(x: 9, y: scrollH-10.0 - 10.0, width: scrollW, height: 10.0))
self.pageControl?.numberOfPages = self.count
self.pageControl?.userInteractionEnabled = false
self.pageControl?.currentPageIndicatorTintColor = self.currentPageIndicatorTintColor
self.pageControl?.pageIndicatorTintColor = self.pageIndicatorTintColor
self.contentView .addSubview(self.pageControl!)
}
func imageViewTaped(tap:UITapGestureRecognizer) {
if ((self.delegate?.respondsToSelector(#selector(ScrollBannersTableViewCell.bannerViewDidClicked(_:)))) != nil) {
self.delegate?.bannerViewDidClicked(tap.view!.tag-1)
}
}
func bannerViewDidClicked(scrollView:UIScrollView){
}
func addTimer() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(Double(self.timerInterval), target: self, selector: #selector(ScrollBannersTableViewCell.nextImage), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(self.timer!, forMode: NSRunLoopCommonModes)
}
func removeTimer() {
if (self.timer != nil) {
self.timer?.invalidate()
self.timer = nil
}
}
func nextImage() {
let currentPage = self.pageControl?.currentPage
self.bannerView?.setContentOffset(CGPoint(x: CGFloat(currentPage! + 2) * self.bannerView!.frame.size.width,y: 0), animated: true)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let scrollW = self.bannerView!.frame.size.width
let currentPage = self.bannerView!.contentOffset.x / scrollW
if(Int(currentPage) == self.count + 1) {
self.pageControl?.currentPage = 0
}else if Int(currentPage) == 0 {
self.pageControl?.currentPage = self.count
}else {
self.pageControl?.currentPage = Int(currentPage) - 1
}
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
self.scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let scrollW = self.bannerView!.frame.width
let currentPage = self.bannerView!.contentOffset.x / scrollW
if Int(currentPage) == self.count + 1 {
self.pageControl!.currentPage = 0
self.bannerView!.setContentOffset(CGPoint(x: scrollW, y: 0), animated: false)
}else if Int(currentPage)==0 {
self.pageControl!.currentPage = self.count
self.bannerView!.setContentOffset(CGPoint(x: CGFloat(self.count) * scrollW, y: 0), animated: false)
}else {
self.pageControl!.currentPage = Int(currentPage) - 1;
}
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self .removeTimer()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.addTimer()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: KNotificationMainViewDidShow, object: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 92f8dc5e52f9610c02a60d782b58407d | 35.014706 | 190 | 0.635361 | 5.141358 | false | false | false | false |
clowwindy/firefox-ios | Storage/Storage/SQL/JoinedHistoryVisitsTable.swift | 2 | 6509 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
let HistoryVisits = "history-visits"
// This isn't a real table. Its an abstraction around the history and visits table
// to simpify queries that should join both tables. It also handles making sure that
// inserts/updates/delete update both tables appropriately. i.e.
// 1.) Deleteing a history entry here will also remove all visits to it
// 2.) Adding a visit here will ensure that a site exists for the visit
// 3.) Updates currently only update site information.
class JoinedHistoryVisitsTable: Table {
typealias Type = (site: Site?, visit: Visit?)
var name: String { return HistoryVisits }
var version: Int { return 1 }
private let visits = VisitsTable<Visit>()
private let history = HistoryTable<Site>()
private let favicons: FaviconsTable<Favicon>
private let faviconSites: JoinedFaviconsHistoryTable<(Site, Favicon)>
init(files: FileAccessor) {
favicons = FaviconsTable<Favicon>(files: files)
faviconSites = JoinedFaviconsHistoryTable<(Site, Favicon)>(files: files)
}
private func getIDFor(db: SQLiteDBConnection, site: Site) -> Int? {
let opts = QueryOptions()
opts.filter = site.url
let cursor = history.query(db, options: opts)
if (cursor.count != 1) {
return nil
}
return (cursor[0] as! Site).id
}
func create(db: SQLiteDBConnection, version: Int) -> Bool {
return history.create(db, version: version) && visits.create(db, version: version) && faviconSites.create(db, version: version)
}
func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
return history.updateTable(db, from: from, to: to) && visits.updateTable(db, from: from, to: to)
}
func exists(db: SQLiteDBConnection) -> Bool {
return history.exists(db) && visits.exists(db)
}
func drop(db: SQLiteDBConnection) -> Bool {
return history.drop(db) && visits.drop(db)
}
private func updateSite(db: SQLiteDBConnection, site: Site, inout err: NSError?) -> Int {
// If our site doesn't have an id, we need to find one
if site.id == nil {
if let id = getIDFor(db, site: site) {
site.id = id
// Update the page title
return history.update(db, item: site, err: &err)
} else {
// Make sure we have a site in the table first
site.id = history.insert(db, item: site, err: &err)
return 1
}
}
// Update the page title
return history.update(db, item: site, err: &err)
}
func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
if let visit = item?.visit {
if updateSite(db, site: visit.site, err: &err) < 0 {
return -1;
}
// Now add a visit
return visits.insert(db, item: visit, err: &err)
} else if let site = item?.site {
if updateSite(db, site: site, err: &err) < 0 {
return -1;
}
// Now add a visit
let visit = Visit(site: site, date: NSDate())
return visits.insert(db, item: visit, err: &err)
}
return -1
}
func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
return visits.update(db, item: item?.visit, err: &err);
}
func delete(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
if let visit = item?.visit {
return visits.delete(db, item: visit, err: &err)
} else if let site = item?.site {
let v = Visit(site: site, date: NSDate())
visits.delete(db, item: v, err: &err)
return history.delete(db, item: site, err: &err)
} else if item == nil {
let site: Site? = nil
let visit: Visit? = nil
history.delete(db, item: site, err: &err);
return visits.delete(db, item: visit, err: &err);
}
return -1
}
func factory(result: SDRow) -> (site: Site, visit: Visit) {
let site = Site(url: result["siteUrl"] as! String, title: result["title"] as! String)
site.guid = result["guid"] as? String
site.id = result["historyId"] as? Int
let d = NSDate(timeIntervalSince1970: result["visitDate"] as! Double)
let type = VisitType(rawValue: result["visitType"] as! Int)
let visit = Visit(site: site, date: d, type: type!)
visit.id = result["visitId"] as? Int
site.latestVisit = visit
if let iconurl = result["iconUrl"] as? String {
let icon = Favicon(url: iconurl, date: NSDate(timeIntervalSince1970: result["iconDate"] as! Double), type: IconType(rawValue: result["iconType"] as! Int)!)
icon.id = result["faviconId"] as? Int
site.icon = icon
}
return (site, visit)
}
func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor {
var args = [AnyObject?]()
var sql = "SELECT \(history.name).id as historyId, \(history.name).url as siteUrl, title, guid, \(visits.name).id as visitId, \(visits.name).date as visitDate, \(visits.name).type as visitType, " +
"\(favicons.name).id as faviconId, \(favicons.name).url as iconUrl, \(favicons.name).date as iconDate, \(favicons.name).type as iconType FROM \(visits.name) " +
"INNER JOIN \(history.name) ON \(history.name).id = \(visits.name).siteId " +
"LEFT JOIN \(faviconSites.name) ON \(faviconSites.name).siteId = \(history.name).id LEFT JOIN \(favicons.name) ON \(faviconSites.name).faviconId = \(favicons.name).id ";
if let filter: AnyObject = options?.filter {
sql += "WHERE siteUrl LIKE ? "
args.append("%\(filter)%")
}
sql += "GROUP BY historyId";
// Trying to do this in one line (i.e. options?.sort == .LastVisit) breaks the Swift compiler
if let sort = options?.sort {
if sort == .LastVisit {
sql += " ORDER BY visitDate DESC"
}
}
// println("Query \(sql) \(args)")
return db.executeQuery(sql, factory: factory, withArgs: args)
}
}
| mpl-2.0 | 54c4f475fd571dbaf5208468bdb9f97b | 39.428571 | 205 | 0.591335 | 4.052927 | false | false | false | false |
TCA-Team/iOS | TUM Campus App/UserData.swift | 1 | 4695 | //
// UserData.swift
// TUM Campus App
//
// This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS
// Copyright (c) 2018 TCA
//
// 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, version 3.
//
// 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 Sweeft
import Contacts
import UIKit
import SWXMLHash
final class UserData: DataElement {
func getCellIdentifier() -> String {
return "person"
}
let name: String
let id: String
let avatar: Image
init(name: String, picture: String?, id: String, maxCache: CacheTime) {
self.name = name
self.id = id
self.avatar = .init(url: picture, maxCache: maxCache)
}
var title: String?
var contactInfo = [(ContactInfoType, String)]()
var text: String {
return name
}
var contactsLoaded: Bool {
get {
return !contactInfo.isEmpty || title != nil
}
}
typealias LabeledValueInit<V: NSCopying & NSSecureCoding> = (V) -> CNLabeledValue<V>
private func getLabeledFunc<V>(label: String) -> LabeledValueInit<V> {
return { value in
CNLabeledValue(label: label, value: value)
}
}
func getPhoneNumbers(_ phones: [String]) -> [CNLabeledValue<CNPhoneNumber>] {
return phones => CNPhoneNumber.init >>> getLabeledFunc(label: CNLabelPhoneNumberMain)
}
func addContact(_ handler: (() -> ())?) {
let contact = CNMutableContact()
contact.givenName = name
var phones = [String]()
var mobiles = [String]()
var emails = [String]()
var websites = [String]()
var fax = [String]()
for item in contactInfo {
switch item.0 {
case .Email: emails.append(item.1)
case .Fax: fax.append(item.1)
case .Mobile: mobiles.append(item.1)
case .Phone: phones.append(item.1)
case .Web: websites.append(item.1)
}
}
contact.emailAddresses = emails => { $0 as NSString } >>> getLabeledFunc(label: CNLabelWork)
contact.phoneNumbers = getPhoneNumbers(phones)
contact.phoneNumbers.append(contentsOf: getPhoneNumbers(mobiles))
contact.urlAddresses = websites => { $0 as NSString } >>> getLabeledFunc(label: CNLabelURLAddressHomePage)
contact.organizationName = "Technische Universität München"
avatar.fetch().onResult(in: .main) { result in
contact.imageData = result.value?
.flatMap { $0 }
.flatMap { $0.pngData() }
let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier:nil)
do {
try store.execute(saveRequest)
handler?()
} catch {
print("Error")
}
}
}
}
extension UserData: XMLDeserializable {
convenience init?(from xml: XMLIndexer, api: TUMOnlineAPI, maxCache: CacheTime) {
guard let name = xml["vorname"].element?.text,
let lastname = xml["familienname"].element?.text,
let id = xml["obfuscated_id"].element?.text else {
return nil
}
let key = CurrentAccountType.value.key
let path = ["obfuscated_ids", key]
let url = xml.get(at: path)?.element?.text.imageURL(in: api) ??
xml["bild_url"].element.map { "\(api.baseURL)/\($0.text)" }
self.init(name: "\(name) \(lastname)", picture: url, id: id, maxCache: maxCache)
}
}
fileprivate extension String {
func imageURL(in api: TUMOnlineAPI) -> String? {
let split = self.components(separatedBy: "*")
guard split.count == 2 else { return nil }
return api.base
.appendingPathComponent("visitenkarte.showImage")
.appendingQuery(key: "pPersonenGruppe", value: split[0])
.appendingQuery(key: "pPersonenId", value: split[1])
.absoluteString
}
}
| gpl-3.0 | 7ccdf5f344ed2cca08e81a1d284c0655 | 30.709459 | 114 | 0.584274 | 4.285845 | false | false | false | false |
AlanEnjoy/Live | Live/Live/Classes/Main/View/PageTitleView.swift | 1 | 6652 | //
// PageTitleView.swift
// Live
//
// Created by Alan's Macbook on 2017/7/2.
// Copyright © 2017年 zhushuai. All rights reserved.
//
import UIKit
//MARK:- 定义协议
protocol PageTitleViewDelegate : class {
//selectedIndex为外部参数,index为内部参数
func pageTitleView(titleView: PageTitleView,selectedIndex index : Int)
}
//MARK:- 定义常量
fileprivate let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85, 85, 85)
fileprivate let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0)
private let kScrollLineH: CGFloat = 2
class PageTitleView: UIView {
//MARK:- 定义属性
fileprivate var currentIndex : Int = 0
fileprivate var titles : [String]
weak var delegate: PageTitleViewDelegate?
//MARK:- 懒加载属性
public lazy var titleLabels: [UILabel] = [UILabel]()
public lazy var scrollLine: UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
public lazy var scrollView : UIScrollView = {
let scrollerView = UIScrollView()
//水平滚动条不显示
scrollerView.showsHorizontalScrollIndicator = false
scrollerView.scrollsToTop = false
scrollerView.bounces = false
return scrollerView
}()
//MARK:- 自定义构造函数
init(frame: CGRect, titles : [String]){
self.titles = titles
super.init(frame: frame)
//设置UI界面
setupUI()
}
//重写或自定义构造函数必须重写init with coder构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:-设置UI界面
extension PageTitleView {
public func setupUI() {
//1.添加UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
//2.添加Title对应的Label
setupTitleLabels()
//3.设置底线和滚动滑块
setupBotttomLineAndScrollLine()
}
private func setupTitleLabels(){
for (index,title) in titles.enumerated() {
//0.确定一些frame的值
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0
//1.设置UILabel
let label = UILabel()
//2.设置Label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.textAlignment = .center
//3.设置label的frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x:labelX,y:labelY,width:labelW,height: labelH)
//4.将label 添加到scrollView中
scrollView.addSubview(label)
titleLabels.append(label)
//5.给Label添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBotttomLineAndScrollLine(){
//1.添加底线
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x:0, y:frame.height - lineH,width: frame.width,height:lineH)
scrollView.addSubview(bottomLine)
//2.添加scrollView
//2.1选取第一个Label
guard let firstLabel = titleLabels.first else {return}
firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//2.2设置scrollView的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x:firstLabel.frame.origin.x,y:frame.height - kScrollLineH,width: firstLabel.frame.width, height:kScrollLineH)
}
}
//MARK:- 监听Label的点击
extension PageTitleView {
@objc fileprivate func titleLabelClick(tapGes: UITapGestureRecognizer){
//0.获取当前label的下标值
guard let currentlabel = tapGes.view as? UILabel else { return }
//0.如果是重复点击同一个title,那么直接返回
if currentlabel.tag == currentIndex { return }
//2.获取之前的label
let oddLabel = titleLabels[currentIndex]
//3.切换文字的颜色
currentlabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oddLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
//4.保存最新Label的下标值
currentIndex = currentlabel.tag
//5.滚动条的位置发生改变
let scrollLineX = CGFloat(currentlabel.tag) * scrollLine.frame.width
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
//6.通知代理
delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex)
}
}
//MARK:- 对外暴露的方法
extension PageTitleView {
func setTitleViewWithProgress(progress:CGFloat, sourceIndex: Int, targetIndex:Int){
//1.取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
//3.TitleViewText颜色变化
//3.1取出变化的范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
//3.2变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
//3.2变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
//4.记录最新的Index
currentIndex = targetIndex
}
}
| mit | d7f83df458e93318c48cd755ad90d172 | 34.809249 | 174 | 0.615819 | 4.633508 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | WhiteBoardCodingChallenges/Challenges/HackerRank/MinMaxSum/MinMaxSum.swift | 1 | 1224 | //
// MinMaxSum.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 27/10/2021.
// Copyright © 2021 Boles. All rights reserved.
//
import Foundation
//https://www.hackerrank.com/challenges/mini-max-sum/problem
class MinMaxSum {
static func minMaxSum(_ arr: [UInt]) -> (UInt, UInt) {
guard arr.count == 5 else {
fatalError("Invalid test data")
}
var minSum = UInt.max
var maxSum = UInt.min
var index = 0
while index != arr.count {
var total: UInt = 0
for offset in 0...3 {
total += arr[(index + offset) % 5]
}
minSum = min(minSum, total)
maxSum = max(maxSum, total)
index += 1
}
return (minSum, maxSum)
}
static func minMaxSumAlt(_ arr: [UInt]) -> (UInt, UInt) {
guard arr.count == 5 else {
fatalError("Invalid test data")
}
let sortedArray = arr.sorted(by: <)
let minSum = sortedArray[0...3].reduce(0, +)
let maxSum = sortedArray[1...4].reduce(0, +)
return (minSum, maxSum)
}
}
| mit | f8e7e4a51d170e56cd2bf86d34923606 | 23.959184 | 61 | 0.499591 | 4.145763 | false | false | false | false |
dnevera/ImageMetalling | ImageMetalling-16/ImageMetalling-16/ImageViewController.swift | 1 | 2976 | //
// ImageViewController.swift
// ImageMetalling-16
//
// Created by denis svinarchuk on 23.06.2018.
// Copyright © 2018 ImageMetalling. All rights reserved.
//
import AppKit
import IMProcessing
import IMProcessingUI
import SnapKit
class ImageViewController: NSViewController {
public lazy var filter:IMPCLutFilter = IMPCLutFilter(context: IMPContext())
public lazy var imageView:TargetView = {
let v = TargetView(frame: self.view.bounds)
v.processingView.filter = self.filter
return v
}()
override func loadView() {
view = NSView(frame: NSRect(x: 0, y: 0, width: 600, height: 400))
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.edges.equalToSuperview().offset(5)
}
clickGesture.numberOfTouchesRequired = 1
imageView.addGestureRecognizer(clickGesture)
filter.addObserver(destinationUpdated: { dest in
self.patchColors.source = dest
})
}
var patchColorHandler:((_ color:float3)->Void)? = nil
/// Создаем фильтр обзёрвера цветов текстуры
private lazy var patchColors:IMPColorObserver = {
let f = IMPColorObserver(context: self.filter.context)
//
// Размер прямоугольной (квадратной) области по которой мы интерполируем
// (на самом деле усредняем) цвет текстуры
//
f.regionSize = 20
//
// Добавляем к фильтру обработку событий пересчета целевой тектстуры,
// которая на самом деле не пересчитывается и читает в шейдере в буфер её RGB-смеплы
//
f.addObserver(destinationUpdated: { (destination) in
//
// Поскольку мы читаем только одну область то берем первый элемент массива
// прочитаных семплов цветов
//
self.patchColorHandler?(f.colors[0])
})
return f
}()
private lazy var clickGesture:NSClickGestureRecognizer = NSClickGestureRecognizer(target: self, action: #selector(clickHandler(recognizer:)))
@objc private func clickHandler(recognizer:NSPanGestureRecognizer) {
let position:NSPoint = recognizer.location(in: imageView.processingView)
let size = imageView.processingView.bounds.size
let point = float2((position.x / size.width).float, 1-(position.y / size.height).float)
patchColors.centers = [point]
}
}
| mit | 1d99c2b1b7edd2cf2c8a9852dd11f141 | 31.604938 | 145 | 0.619084 | 4.04441 | false | false | false | false |
xedin/swift | test/decl/var/property_wrappers.swift | 1 | 23701 | // RUN: %target-typecheck-verify-swift -swift-version 5
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct Wrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(initialValue: T) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperAcceptingAutoclosure<T> {
private let fn: () -> T
var wrappedValue: T {
return fn()
}
init(initialValue fn: @autoclosure @escaping () -> T) {
self.fn = fn
}
init(body fn: @escaping () -> T) {
self.fn = fn
}
}
@propertyWrapper
struct MissingValue<T> { }
// expected-error@-1{{property wrapper type 'MissingValue' does not contain a non-static property named 'wrappedValue'}}
@propertyWrapper
struct StaticValue {
static var wrappedValue: Int = 17
}
// expected-error@-3{{property wrapper type 'StaticValue' does not contain a non-static property named 'wrappedValue'}}
// expected-error@+1{{'@propertyWrapper' attribute cannot be applied to this declaration}}
@propertyWrapper
protocol CannotBeAWrapper {
associatedtype Value
var wrappedValue: Value { get set }
}
@propertyWrapper
struct NonVisibleValueWrapper<Value> {
private var wrappedValue: Value // expected-error{{private property 'wrappedValue' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleValueWrapper' (which is internal)}}
}
@propertyWrapper
struct NonVisibleInitWrapper<Value> {
var wrappedValue: Value
private init(initialValue: Value) { // expected-error{{private initializer 'init(initialValue:)' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleInitWrapper' (which is internal)}}
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct InitialValueTypeMismatch<Value> {
var wrappedValue: Value // expected-note{{'wrappedValue' declared here}}
init(initialValue: Value?) { // expected-error{{'init(initialValue:)' parameter type ('Value?') must be the same as its 'wrappedValue' property type ('Value') or an @autoclosure thereof}}
self.wrappedValue = initialValue!
}
}
@propertyWrapper
struct MultipleInitialValues<Value> { // expected-error{{property wrapper type 'MultipleInitialValues' has multiple initial-value initializers}}
var wrappedValue: Value? = nil
init(initialValue: Int) { // expected-note{{initializer 'init(initialValue:)' declared here}}
}
init(initialValue: Double) { // expected-note{{initializer 'init(initialValue:)' declared here}}
}
}
@propertyWrapper
struct InitialValueFailable<Value> {
var wrappedValue: Value
init?(initialValue: Value) { // expected-error{{'init(initialValue:)' cannot be failable}}
return nil
}
}
@propertyWrapper
struct InitialValueFailableIUO<Value> {
var wrappedValue: Value
init!(initialValue: Value) { // expected-error{{'init(initialValue:)' cannot be failable}}
return nil
}
}
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct _lowercaseWrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct _UppercaseWrapper<T> {
var wrappedValue: T
}
// ---------------------------------------------------------------------------
// Limitations on where property wrappers can be used
// ---------------------------------------------------------------------------
func testLocalContext() {
@WrapperWithInitialValue // expected-error{{property wrappers are not yet supported on local properties}}
var x = 17
x = 42
_ = x
}
enum SomeEnum {
case foo
@Wrapper(wrappedValue: 17)
var bar: Int // expected-error{{property 'bar' declared inside an enum cannot have a wrapper}}
// expected-error@-1{{enums must not contain stored properties}}
@Wrapper(wrappedValue: 17)
static var x: Int
}
protocol SomeProtocol {
@Wrapper(wrappedValue: 17)
var bar: Int // expected-error{{property 'bar' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
@Wrapper(wrappedValue: 17)
static var x: Int // expected-error{{property 'x' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
}
struct HasWrapper { }
extension HasWrapper {
@Wrapper(wrappedValue: 17)
var inExt: Int // expected-error{{property 'inExt' declared inside an extension cannot have a wrapper}}
// expected-error@-1{{extensions must not contain stored properties}}
@Wrapper(wrappedValue: 17)
static var x: Int
}
class ClassWithWrappers {
@Wrapper(wrappedValue: 17)
var x: Int
}
class Superclass {
var x: Int = 0
}
class SubclassOfClassWithWrappers: ClassWithWrappers {
override var x: Int {
get { return super.x }
set { super.x = newValue }
}
}
class SubclassWithWrapper: Superclass {
@Wrapper(wrappedValue: 17)
override var x: Int { get { return 0 } set { } } // expected-error{{property 'x' with attached wrapper cannot override another property}}
}
class C { }
struct BadCombinations {
@WrapperWithInitialValue
lazy var x: C = C() // expected-error{{property 'x' with a wrapper cannot also be lazy}}
@Wrapper
weak var y: C? // expected-error{{property 'y' with a wrapper cannot also be weak}}
@Wrapper
unowned var z: C // expected-error{{property 'z' with a wrapper cannot also be unowned}}
}
struct MultipleWrappers {
@Wrapper(wrappedValue: 17)
@WrapperWithInitialValue // expected-error{{extra argument 'initialValue' in call}}
var x: Int = 17
@WrapperWithInitialValue // expected-error 2{{property wrapper can only apply to a single variable}}
var (y, z) = (1, 2)
}
// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------
struct Initialization {
@Wrapper(wrappedValue: 17)
var x: Int
@Wrapper(wrappedValue: 17)
var x2: Double
@Wrapper(wrappedValue: 17)
var x3 = 42 // expected-error{{extra argument 'initialValue' in call}}
@Wrapper(wrappedValue: 17)
var x4
@WrapperWithInitialValue
var y = true
// FIXME: It would be nice if we had a more detailed diagnostic here.
@WrapperWithInitialValue<Int>
var y2 = true // expected-error{{'Bool' is not convertible to 'Int'}}
mutating func checkTypes(s: String) {
x2 = s // expected-error{{cannot assign value of type 'String' to type 'Double'}}
x4 = s // expected-error{{cannot assign value of type 'String' to type 'Int'}}
y = s // expected-error{{cannot assign value of type 'String' to type 'Bool'}}
}
}
@propertyWrapper
struct Clamping<V: Comparable> {
var value: V
let min: V
let max: V
init(initialValue: V, min: V, max: V) {
value = initialValue
self.min = min
self.max = max
assert(value >= min && value <= max)
}
var wrappedValue: V {
get { return value }
set {
if newValue < min {
value = min
} else if newValue > max {
value = max
} else {
value = newValue
}
}
}
}
struct Color {
@Clamping(min: 0, max: 255) var red: Int = 127
@Clamping(min: 0, max: 255) var green: Int = 127
@Clamping(min: 0, max: 255) var blue: Int = 127
@Clamping(min: 0, max: 255) var alpha: Int = 255
}
func testColor() {
_ = Color(green: 17)
}
// ---------------------------------------------------------------------------
// Wrapper type formation
// ---------------------------------------------------------------------------
@propertyWrapper
struct IntWrapper {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperForHashable<T: Hashable> { // expected-note{{property wrapper type 'WrapperForHashable' declared here}}
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithTwoParams<T, U> {
var wrappedValue: (T, U)
}
struct NotHashable { }
struct UseWrappersWithDifferentForm {
@IntWrapper
var x: Int
// FIXME: Diagnostic should be better here
@WrapperForHashable
var y: NotHashable // expected-error{{property type 'NotHashable' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperForHashable'}}
@WrapperForHashable
var yOkay: Int
@WrapperWithTwoParams
var zOkay: (Int, Float)
// FIXME: Need a better diagnostic here
@HasNestedWrapper.NestedWrapper
var w: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'HasNestedWrapper.NestedWrapper'}}
@HasNestedWrapper<Double>.NestedWrapper
var wOkay: Int
@HasNestedWrapper.ConcreteNestedWrapper
var wOkay2: Int
}
@propertyWrapper
struct Function<T, U> { // expected-note{{property wrapper type 'Function' declared here}}
var wrappedValue: (T) -> U?
}
struct TestFunction {
@Function var f: (Int) -> Float?
@Function var f2: (Int) -> Float // expected-error{{property type '(Int) -> Float' does not match that of the 'wrappedValue' property of its wrapper type 'Function'}}
func test() {
let _: Int = $f // expected-error{{cannot convert value of type 'Function<Int, Float>' to specified type 'Int'}}
}
}
// ---------------------------------------------------------------------------
// Nested wrappers
// ---------------------------------------------------------------------------
struct HasNestedWrapper<T> {
@propertyWrapper
struct NestedWrapper<U> { // expected-note{{property wrapper type 'NestedWrapper' declared here}}
var wrappedValue: U
init(initialValue: U) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct ConcreteNestedWrapper {
var wrappedValue: T
init(initialValue: T) {
self.wrappedValue = initialValue
}
}
@NestedWrapper
var y: [T] = []
}
struct UsesNestedWrapper<V> {
@HasNestedWrapper<V>.NestedWrapper
var y: [V]
}
// ---------------------------------------------------------------------------
// Referencing the backing store
// ---------------------------------------------------------------------------
struct BackingStore<T> {
@Wrapper
var x: T
@WrapperWithInitialValue
private var y = true // expected-note{{'y' declared here}}
func getXStorage() -> Wrapper<T> {
return $x
}
func getYStorage() -> WrapperWithInitialValue<Bool> {
return self.$y
}
}
func testBackingStore<T>(bs: BackingStore<T>) {
_ = bs.x
_ = bs.y // expected-error{{'y' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Explicitly-specified accessors
// ---------------------------------------------------------------------------
struct WrapperWithAccessors {
@Wrapper // expected-error{{property wrapper cannot be applied to a computed property}}
var x: Int {
return 17
}
}
struct UseWillSetDidSet {
@Wrapper
var x: Int {
willSet {
print(newValue)
}
}
@Wrapper
var y: Int {
didSet {
print(oldValue)
}
}
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
// ---------------------------------------------------------------------------
// Mutating/nonmutating
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithNonMutatingSetter<Value> {
class Box {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}
var box: Box
init(initialValue: Value) {
self.box = Box(wrappedValue: initialValue)
}
var wrappedValue: Value {
get { return box.wrappedValue }
nonmutating set { box.wrappedValue = newValue }
}
}
@propertyWrapper
struct WrapperWithMutatingGetter<Value> {
var readCount = 0
var writeCount = 0
var stored: Value
init(initialValue: Value) {
self.stored = initialValue
}
var wrappedValue: Value {
mutating get {
readCount += 1
return stored
}
set {
writeCount += 1
stored = newValue
}
}
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseMutatingnessWrappers {
@WrapperWithNonMutatingSetter
var x = true
@WrapperWithMutatingGetter
var y = 17
@WrapperWithNonMutatingSetter // expected-error{{property wrapper can only be applied to a 'var'}}
let z = 3.14159 // expected-note 2{{change 'let' to 'var' to make it mutable}}
@ClassWrapper
var w = "Hello"
}
func testMutatingness() {
var mutable = UseMutatingnessWrappers()
_ = mutable.x
mutable.x = false
_ = mutable.y
mutable.y = 42
_ = mutable.z
mutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
_ = mutable.w
mutable.w = "Goodbye"
let nonmutable = UseMutatingnessWrappers() // expected-note 2{{change 'let' to 'var' to make it mutable}}
// Okay due to nonmutating setter
_ = nonmutable.x
nonmutable.x = false
_ = nonmutable.y // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
nonmutable.y = 42 // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
_ = nonmutable.z
nonmutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
// Okay due to implicitly nonmutating setter
_ = nonmutable.w
nonmutable.w = "World"
}
// ---------------------------------------------------------------------------
// Access control
// ---------------------------------------------------------------------------
struct HasPrivateWrapper<T> {
@propertyWrapper
private struct PrivateWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(initialValue: U) {
self.wrappedValue = initialValue
}
}
@PrivateWrapper
var y: [T] = []
// expected-error@-1{{property must be declared private because its property wrapper type uses a private type}}
// Okay to reference private entities from a private property
@PrivateWrapper
private var z: [T]
}
public struct HasUsableFromInlineWrapper<T> {
@propertyWrapper
struct InternalWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(initialValue: U) {
self.wrappedValue = initialValue
}
}
@InternalWrapper
@usableFromInline
var y: [T] = []
// expected-error@-1{{property wrapper type referenced from a '@usableFromInline' property must be '@usableFromInline' or public}}
}
@propertyWrapper
class Box<Value> {
private(set) var wrappedValue: Value
init(initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseBox {
@Box
var x = 17 // expected-note{{'$x' declared here}}
}
func testBox(ub: UseBox) {
_ = ub.x
ub.x = 5 // expected-error{{cannot assign to property: 'x' is a get-only property}}
var mutableUB = ub
mutableUB = ub
}
func backingVarIsPrivate(ub: UseBox) {
_ = ub.$x // expected-error{{'$x' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Memberwise initializers
// ---------------------------------------------------------------------------
struct MemberwiseInits<T> {
@Wrapper
var x: Bool
@WrapperWithInitialValue
var y: T
}
func testMemberwiseInits() {
// expected-error@+1{{type '(Wrapper<Bool>, Double) -> MemberwiseInits<Double>'}}
let _: Int = MemberwiseInits<Double>.init
_ = MemberwiseInits(x: Wrapper(wrappedValue: true), y: 17)
}
struct DefaultedMemberwiseInits {
@Wrapper(wrappedValue: true)
var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(initialValue: 17)
var z: Int
}
func testDefaultedMemberwiseInits() {
_ = DefaultedMemberwiseInits()
_ = DefaultedMemberwiseInits(
x: Wrapper(wrappedValue: false),
y: 42,
z: WrapperWithInitialValue(initialValue: 42))
_ = DefaultedMemberwiseInits(y: 42)
_ = DefaultedMemberwiseInits(x: Wrapper(wrappedValue: false))
_ = DefaultedMemberwiseInits(z: WrapperWithInitialValue(initialValue: 42))
}
// ---------------------------------------------------------------------------
// Default initializers
// ---------------------------------------------------------------------------
struct DefaultInitializerStruct {
@Wrapper(wrappedValue: true)
var x
@WrapperWithInitialValue
var y: Int = 10
}
struct NoDefaultInitializerStruct { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Bool
}
class DefaultInitializerClass {
@Wrapper(wrappedValue: true)
var x
@WrapperWithInitialValue
final var y: Int = 10
}
class NoDefaultInitializerClass { // expected-error{{class 'NoDefaultInitializerClass' has no initializers}}
@Wrapper
final var x: Bool // expected-note{{stored property 'x' without initial value prevents synthesized initializers}}
}
func testDefaultInitializers() {
_ = DefaultInitializerStruct()
_ = DefaultInitializerClass()
_ = NoDefaultInitializerStruct() // expected-error{{missing argument for parameter 'x' in call}}
}
struct DefaultedPrivateMemberwiseLets {
@Wrapper(wrappedValue: true)
private var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(initialValue: 17)
private var z: Int
}
func testDefaultedPrivateMemberwiseLets() {
_ = DefaultedPrivateMemberwiseLets()
_ = DefaultedPrivateMemberwiseLets(y: 42)
_ = DefaultedPrivateMemberwiseLets(x: Wrapper(wrappedValue: false)) // expected-error{{incorrect argument label in call (have 'x:', expected 'y:')}}
}
// ---------------------------------------------------------------------------
// Storage references
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithStorageRef<T> {
var wrappedValue: T
var wrapperValue: Wrapper<T> {
return Wrapper(wrappedValue: wrappedValue)
}
}
extension Wrapper {
var wrapperOnlyAPI: Int { return 17 }
}
struct TestStorageRef {
@WrapperWithStorageRef var x: Int // expected-note{{'$$x' declared here}}
init(x: Int) {
self.$$x = WrapperWithStorageRef(wrappedValue: x)
}
mutating func test() {
let _: Wrapper = $x
let i = $x.wrapperOnlyAPI
let _: Int = i
// x is mutable, $x is not
x = 17
$x = Wrapper(wrappedValue: 42) // expected-error{{cannot assign to property: '$x' is immutable}}
}
}
func testStorageRef(tsr: TestStorageRef) {
let _: Wrapper = tsr.$x
_ = tsr.$$x // expected-error{{'$$x' is inaccessible due to 'private' protection level}}
}
struct TestStorageRefPrivate {
@WrapperWithStorageRef private(set) var x: Int
init() {
self.$$x = WrapperWithStorageRef(wrappedValue: 5)
}
}
func testStorageRefPrivate() {
var tsr = TestStorageRefPrivate()
let a = tsr.$x // okay, getter is internal
tsr.$x = a // expected-error{{cannot assign to property: '$x' is immutable}}
}
// rdar://problem/50873275 - crash when using wrapper with wrapperValue in
// generic type.
@propertyWrapper
struct InitialValueWrapperWithStorageRef<T> {
var wrappedValue: T
init(initialValue: T) {
wrappedValue = initialValue
}
var wrapperValue: Wrapper<T> {
return Wrapper(wrappedValue: wrappedValue)
}
}
struct TestGenericStorageRef<T> {
struct Inner { }
@InitialValueWrapperWithStorageRef var inner: Inner = Inner()
}
// ---------------------------------------------------------------------------
// Misc. semantic issues
// ---------------------------------------------------------------------------
@propertyWrapper
struct BrokenLazy { }
// expected-error@-1{{property wrapper type 'BrokenLazy' does not contain a non-static property named 'wrappedValue'}}
// expected-note@-2{{'BrokenLazy' declared here}}
struct S {
@BrokenLazy // expected-error{{struct 'BrokenLazy' cannot be used as an attribute}}
var wrappedValue: Int
}
// ---------------------------------------------------------------------------
// Closures in initializers
// ---------------------------------------------------------------------------
struct UsesExplicitClosures {
@WrapperAcceptingAutoclosure(body: { 42 })
var x: Int
@WrapperAcceptingAutoclosure(body: { return 42 })
var y: Int
}
// ---------------------------------------------------------------------------
// Miscellaneous bugs
// ---------------------------------------------------------------------------
// rdar://problem/50822051 - compiler assertion / hang
@propertyWrapper
struct PD<Value> {
var wrappedValue: Value
init<A>(initialValue: Value, a: A) {
self.wrappedValue = initialValue
}
}
struct TestPD {
@PD(a: "foo") var foo: Int = 42
}
protocol P { }
@propertyWrapper
struct WrapperRequiresP<T: P> {
var wrappedValue: T
var wrapperValue: T { return wrappedValue }
}
struct UsesWrapperRequiringP {
// expected-note@-1{{in declaration of}}
@WrapperRequiresP var x.: UsesWrapperRequiringP
// expected-error@-1{{expected member name following '.'}}
// expected-error@-2{{expected declaration}}
// expected-error@-3{{type annotation missing in pattern}}
}
// SR-10899 / rdar://problem/51588022
@propertyWrapper
struct SR_10899_Wrapper { // expected-note{{property wrapper type 'SR_10899_Wrapper' declared here}}
var wrappedValue: String { "hi" }
}
struct SR_10899_Usage {
@SR_10899_Wrapper var thing: Bool // expected-error{{property type 'Bool' does not match that of the 'wrappedValue' property of its wrapper type 'SR_10899_Wrapper'}}
}
// ---------------------------------------------------------------------------
// Property wrapper composition
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
init(initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
init(initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperC<Value> {
var wrappedValue: Value?
init(initialValue: Value?) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperD<Value, X, Y> { // expected-note{{property wrapper type 'WrapperD' declared here}}
var wrappedValue: Value
}
@propertyWrapper
struct WrapperE<Value> {
var wrappedValue: Value
}
struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperD<WrapperC, Int, String>'}}
func triggerErrors(d: Double) {
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String?'}}
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}
$p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
$p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
$p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
}
}
| apache-2.0 | e01e56ec39f1d880f895db2649a13f7e | 25.963595 | 221 | 0.622379 | 4.369653 | false | false | false | false |
untitledstartup/OAuthSwift | OAuthSwift/OAuthSwiftClient.swift | 1 | 12494 | //
// OAuthSwiftClient.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
import Accounts
var dataEncoding: NSStringEncoding = NSUTF8StringEncoding
public class OAuthSwiftClient {
struct OAuth {
static let version = "1.0"
static let signatureMethod = "HMAC-SHA1"
}
private(set) public var credential: OAuthSwiftCredential
public init(consumerKey: String, consumerSecret: String) {
self.credential = OAuthSwiftCredential(consumer_key: consumerKey, consumer_secret: consumerSecret)
}
public init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.credential = OAuthSwiftCredential(oauth_token: accessToken, oauth_token_secret: accessTokenSecret)
self.credential.consumer_key = consumerKey
self.credential.consumer_secret = consumerSecret
}
public func get(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "GET", parameters: parameters, success: success, failure: failure)
}
public func post(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "POST", parameters: parameters, success: success, failure: failure)
}
public func put(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "PUT", parameters: parameters, success: success, failure: failure)
}
public func delete(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "DELETE", parameters: parameters, success: success, failure: failure)
}
public func patch(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: "PATCH", parameters: parameters, success: success, failure: failure)
}
func request(url: String, method: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let url = NSURL(string: url) {
let request = OAuthSwiftHTTPRequest(URL: url, method: method, parameters: parameters)
if self.credential.oauth2 {
request.headers = ["Authorization": "Bearer \(self.credential.oauth_token)"]
} else {
request.headers = ["Authorization": OAuthSwiftClient.authorizationHeaderForMethod(method, url: url, parameters: parameters, credential: self.credential)]
}
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = dataEncoding
request.encodeParameters = true
request.start()
}
}
public func postImage(urlString: String, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.multiPartRequest(urlString, method: "POST", parameters: parameters, image: image, success: success, failure: failure)
}
func multiPartRequest(url: String, method: String, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let url = NSURL(string: url) {
let request = OAuthSwiftHTTPRequest(URL: url, method: method, parameters: parameters)
if self.credential.oauth2 {
request.headers = ["Authorization": "Bearer \(self.credential.oauth_token)"]
} else {
request.headers = ["Authorization": OAuthSwiftClient.authorizationHeaderForMethod(method, url: url, parameters: parameters, credential: self.credential)]
}
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = dataEncoding
request.encodeParameters = true
var parmaImage = [String: AnyObject]()
parmaImage["media"] = image
let boundary = "AS-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiPartBodyFromParams(parmaImage, boundary: boundary)
request.HTTPBodyMultipart = body
request.contentTypeMultipart = type
request.start()
}
}
public func multiPartBodyFromParams(parameters: [String: AnyObject], boundary: String) -> NSData {
let data = NSMutableData()
let prefixData = "--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
let seperData = "\r\n".dataUsingEncoding(NSUTF8StringEncoding)
for (key, value) in parameters {
var sectionData: NSData?
var sectionType: String?
var sectionFilename = ""
if key == "media" {
let multiData = value as! NSData
sectionData = multiData
sectionType = "image/jpeg"
sectionFilename = " filename=\"file\""
} else {
sectionData = "\(value)".dataUsingEncoding(NSUTF8StringEncoding)
}
data.appendData(prefixData!)
let sectionDisposition = "Content-Disposition: form-data; name=\"media\";\(sectionFilename)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(sectionDisposition!)
if let type = sectionType {
let contentType = "Content-Type: \(type)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentType!)
}
// append data
data.appendData(seperData!)
data.appendData(sectionData!)
data.appendData(seperData!)
}
data.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
return data
}
public func postMultiPartRequest(url: String, method: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let url = NSURL(string: url) {
let request = OAuthSwiftHTTPRequest(URL: url, method: method, parameters: parameters)
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = dataEncoding
request.encodeParameters = true
let boundary = "POST-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiDataFromObject(parameters, boundary: boundary)
request.HTTPBodyMultipart = body
request.contentTypeMultipart = type
request.start()
}
}
func multiDataFromObject(object: [String:AnyObject], boundary: String) -> NSData? {
let data = NSMutableData()
let prefixString = "--\(boundary)\r\n"
let prefixData = prefixString.dataUsingEncoding(NSUTF8StringEncoding)!
let seperatorString = "\r\n"
let seperatorData = seperatorString.dataUsingEncoding(NSUTF8StringEncoding)!
for (key, value) in object {
var valueData: NSData?
let valueType: String = ""
let filenameClause = ""
let stringValue = "\(value)"
valueData = stringValue.dataUsingEncoding(NSUTF8StringEncoding)!
if valueData == nil {
continue
}
data.appendData(prefixData)
let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentDispositionData!)
if let type: String = valueType {
let contentTypeString = "Content-Type: \(type)\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentTypeData!)
}
data.appendData(seperatorData)
data.appendData(valueData!)
data.appendData(seperatorData)
}
let endingString = "--\(boundary)--\r\n"
let endingData = endingString.dataUsingEncoding(NSUTF8StringEncoding)!
data.appendData(endingData)
return data
}
public class func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String {
var authorizationParameters = Dictionary<String, AnyObject>()
authorizationParameters["oauth_version"] = OAuth.version
authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod
authorizationParameters["oauth_consumer_key"] = credential.consumer_key
authorizationParameters["oauth_timestamp"] = String(Int64(NSDate().timeIntervalSince1970))
authorizationParameters["oauth_nonce"] = (NSUUID().UUIDString as NSString).substringToIndex(8)
if (credential.oauth_token != ""){
authorizationParameters["oauth_token"] = credential.oauth_token
}
for (key, value) in parameters {
if key.hasPrefix("oauth_") {
authorizationParameters.updateValue(value, forKey: key)
}
}
let combinedParameters = authorizationParameters.join(parameters)
let finalParameters = combinedParameters
authorizationParameters["oauth_signature"] = self.signatureForMethod(method, url: url, parameters: finalParameters, credential: credential)
var parameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(dataEncoding).componentsSeparatedByString("&") as [String]
parameterComponents.sortInPlace { $0 < $1 }
var headerComponents = [String]()
for component in parameterComponents {
let subcomponent = component.componentsSeparatedByString("=") as [String]
if subcomponent.count == 2 {
headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"")
}
}
return "OAuth " + headerComponents.joinWithSeparator(", ")
}
public class func signatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String {
var tokenSecret: NSString = ""
tokenSecret = credential.oauth_token_secret.urlEncodedStringWithEncoding(dataEncoding)
let encodedConsumerSecret = credential.consumer_secret.urlEncodedStringWithEncoding(dataEncoding)
let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)"
var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(dataEncoding).componentsSeparatedByString("&") as [String]
parameterComponents.sortInPlace { $0 < $1 }
let parameterString = parameterComponents.joinWithSeparator("&")
let encodedParameterString = parameterString.urlEncodedStringWithEncoding(dataEncoding)
let encodedURL = url.absoluteString!.urlEncodedStringWithEncoding(dataEncoding)
let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)"
let key = signingKey.dataUsingEncoding(NSUTF8StringEncoding)!
let msg = signatureBaseString.dataUsingEncoding(NSUTF8StringEncoding)!
let sha1 = HMAC.sha1(key: key, message: msg)!
return sha1.base64EncodedStringWithOptions([])
}
}
| mit | 5de522ee4177a0f55012da59acc5f712 | 45.619403 | 210 | 0.656955 | 5.570218 | false | false | false | false |
snakajima/vs-metal | src/VSFilter.swift | 1 | 3081 | //
// VSFilter.swift
// vs-metal
//
// Created by SATOSHI NAKAJIMA on 6/22/17.
// Copyright © 2017 SATOSHI NAKAJIMA. All rights reserved.
//
import Foundation
import MetalKit
/// VSFilter is a concrete implemtation of VSNode prototol, which represents a filter node.
/// A filter node takes zero or more textures from the stack as input,
/// and push a generated texture to the stack.
/// VSNode objects are created by a Script object when its compile() method is called.
struct VSFilter: VSNode {
private let pipelineState:MTLComputePipelineState
private let paramBuffers:[MTLBuffer]
private let sourceCount:Int
private init(pipelineState:MTLComputePipelineState, buffers:[MTLBuffer], sourceCount:Int) {
self.pipelineState = pipelineState
self.paramBuffers = buffers
self.sourceCount = sourceCount
}
/// Make a filter object, which conforms to VSNode protocol.
/// This function is called by VSSCript during the compilation process.
///
/// - Parameters:
/// - nodeName: name of the node, which is the name of Metal kernel
/// - buffers: named buffers (attributes)
/// - sourceCount: number of input textures
/// - device: metal device
/// - Returns: a VSNode object
static func makeNode(name nodeName:String, buffers:[MTLBuffer], sourceCount:Int, context:VSContext) -> VSNode? {
guard let kernel = context.library.makeFunction(name: nodeName) else {
print("### VSScript:makeNode failed to create kernel", nodeName)
return nil
}
do {
let pipelineState = try context.device.makeComputePipelineState(function: kernel)
return VSFilter(pipelineState: pipelineState, buffers: buffers, sourceCount:sourceCount)
} catch {
print("### VSScript:makeNode failed to create pipeline state", nodeName)
}
return nil
}
/// Encode appropriate GPU instructions into the command buffer.
///
/// - Parameters:
/// - commandBuffer: The command buffer to encode to
/// - context: the video pipeline context
/// - Throws: VSContextError.underUnderflow if pop() was called when the stack is empty
func encode(commandBuffer:MTLCommandBuffer, context:VSContext) {
let encoder = commandBuffer.makeComputeCommandEncoder()
encoder.setComputePipelineState(pipelineState)
let destination = context.get() // must be called before any stack operation
for index in 0..<sourceCount {
if let texture = context.pop() {
encoder.setTexture(texture.texture, at: index)
}
}
encoder.setTexture(destination.texture, at: sourceCount)
for (index, buffer) in paramBuffers.enumerated() {
encoder.setBuffer(buffer, offset: 0, at: sourceCount + 1 + index)
}
encoder.dispatchThreadgroups(context.threadGroupCount, threadsPerThreadgroup: context.threadGroupSize)
encoder.endEncoding()
context.push(texture:destination)
}
}
| mit | 6ad79eb6b4cf210c9f20b932faae7fef | 40.621622 | 116 | 0.671104 | 4.767802 | false | false | false | false |
rafaelcpalmeida/UFP-iOS | UFP/UFP/Carthage/Checkouts/Alamofire/Source/SessionManager.swift | 25 | 37979 | //
// SessionManager.swift
//
// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
open class SessionManager {
// MARK: - Helper Types
/// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
/// associated values.
///
/// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with
/// streaming information.
/// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
/// error.
public enum MultipartFormDataEncodingResult {
case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
// MARK: - Properties
/// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use
/// directly for any ad hoc requests.
open static let `default`: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
/// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
open static let defaultHTTPHeaders: HTTPHeaders = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joined(separator: ", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`
let userAgent: String = {
if let info = Bundle.main.infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = Bundle(for: SessionManager.self).infoDictionary,
let build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
/// Default memory threshold used when encoding `MultipartFormData` in bytes.
open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000
/// The underlying session.
open let session: URLSession
/// The session delegate handling all the task and session delegate callbacks.
open let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
open var startRequestsImmediately: Bool = true
/// The request adapter called each time a new request is created.
open var adapter: RequestAdapter?
/// The request retrier called each time a request encounters an error to determine whether to retry the request.
open var retrier: RequestRetrier? {
get { return delegate.retrier }
set { delegate.retrier = newValue }
}
/// The background completion handler closure provided by the UIApplicationDelegate
/// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
/// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
/// will automatically call the handler.
///
/// If you need to handle your own events before the handler is called, then you need to override the
/// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
///
/// `nil` by default.
open var backgroundCompletionHandler: (() -> Void)?
let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString)
// MARK: - Lifecycle
/// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter configuration: The configuration used to construct the managed session.
/// `URLSessionConfiguration.default` by default.
/// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
/// default.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance.
public init(
configuration: URLSessionConfiguration = URLSessionConfiguration.default,
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`.
///
/// - parameter session: The URL session.
/// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
/// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
/// challenges. `nil` by default.
///
/// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise.
public init?(
session: URLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionManager = self
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Data Request
/// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding`
/// and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
var originalRequest: URLRequest?
do {
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
return request(encodedURLRequest)
} catch {
return request(originalRequest, failedWith: error)
}
}
/// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `DataRequest`.
@discardableResult
open func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
var originalRequest: URLRequest?
do {
originalRequest = try urlRequest.asURLRequest()
let originalTask = DataRequest.Requestable(urlRequest: originalRequest!)
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
let request = DataRequest(session: session, requestTask: .data(originalTask, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return request(originalRequest, failedWith: error)
}
}
// MARK: Private - Request Implementation
private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest {
var requestTask: Request.RequestTask = .data(nil, nil)
if let urlRequest = urlRequest {
let originalTask = DataRequest.Requestable(urlRequest: urlRequest)
requestTask = .data(originalTask, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError)
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: request, with: underlyingError)
} else {
if startRequestsImmediately { request.resume() }
}
return request
}
// MARK: - Download Request
// MARK: URL Request
/// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`,
/// `headers` and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
return download(encodedURLRequest, to: destination)
} catch {
return download(nil, to: destination, failedWith: error)
}
}
/// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save
/// them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter urlRequest: The URL request
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
_ urlRequest: URLRequestConvertible,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
do {
let urlRequest = try urlRequest.asURLRequest()
return download(.request(urlRequest), to: destination)
} catch {
return download(nil, to: destination, failedWith: error)
}
}
// MARK: Resume Data
/// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve
/// the contents of the original request and save them to the `destination`.
///
/// If `destination` is not specified, the contents will remain in the temporary location determined by the
/// underlying URL session.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken
/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the
/// data is written incorrectly and will always fail to resume the download. For more information about the bug and
/// possible workarounds, please refer to the following Stack Overflow post:
///
/// - http://stackoverflow.com/a/39347461/1342462
///
/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for
/// additional information.
/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
///
/// - returns: The created `DownloadRequest`.
@discardableResult
open func download(
resumingWith resumeData: Data,
to destination: DownloadRequest.DownloadFileDestination? = nil)
-> DownloadRequest
{
return download(.resumeData(resumeData), to: destination)
}
// MARK: Private - Download Implementation
private func download(
_ downloadable: DownloadRequest.Downloadable,
to destination: DownloadRequest.DownloadFileDestination?)
-> DownloadRequest
{
do {
let task = try downloadable.task(session: session, adapter: adapter, queue: queue)
let download = DownloadRequest(session: session, requestTask: .download(downloadable, task))
download.downloadDelegate.destination = destination
delegate[task] = download
if startRequestsImmediately { download.resume() }
return download
} catch {
return download(downloadable, to: destination, failedWith: error)
}
}
private func download(
_ downloadable: DownloadRequest.Downloadable?,
to destination: DownloadRequest.DownloadFileDestination?,
failedWith error: Error)
-> DownloadRequest
{
var downloadTask: Request.RequestTask = .download(nil, nil)
if let downloadable = downloadable {
downloadTask = .download(downloadable, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError)
download.downloadDelegate.destination = destination
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: download, with: underlyingError)
} else {
if startRequestsImmediately { download.resume() }
}
return download
}
// MARK: - Upload Request
// MARK: File
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ fileURL: URL,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(fileURL, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter file: The file to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.file(fileURL, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: Data
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ data: Data,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(data, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter data: The data to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.data(data, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: InputStream
/// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(
_ stream: InputStream,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil)
-> UploadRequest
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(stream, with: urlRequest)
} catch {
return upload(nil, failedWith: error)
}
}
/// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter stream: The stream to upload.
/// - parameter urlRequest: The URL request.
///
/// - returns: The created `UploadRequest`.
@discardableResult
open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
do {
let urlRequest = try urlRequest.asURLRequest()
return upload(.stream(stream, urlRequest))
} catch {
return upload(nil, failedWith: error)
}
}
// MARK: MultipartFormData
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `url`, `method` and `headers`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.post` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
do {
let urlRequest = try URLRequest(url: url, method: method, headers: headers)
return upload(
multipartFormData: multipartFormData,
usingThreshold: encodingMemoryThreshold,
with: urlRequest,
encodingCompletion: encodingCompletion
)
} catch {
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
/// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new
/// `UploadRequest` using the `urlRequest`.
///
/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
/// used for larger payloads such as video content.
///
/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
/// technique was used.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
/// `multipartFormDataEncodingMemoryThreshold` by default.
/// - parameter urlRequest: The URL request.
/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
open func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
with urlRequest: URLRequestConvertible,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
DispatchQueue.global(qos: .utility).async {
let formData = MultipartFormData()
multipartFormData(formData)
var tempFileURL: URL?
do {
var urlRequestWithContentType = try urlRequest.asURLRequest()
urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(data, with: urlRequestWithContentType),
streamingFromDisk: false,
streamFileURL: nil
)
DispatchQueue.main.async { encodingCompletion?(encodingResult) }
} else {
let fileManager = FileManager.default
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
tempFileURL = fileURL
var directoryError: Error?
// Create directory inside serial queue to ensure two threads don't do this in parallel
self.queue.sync {
do {
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
directoryError = error
}
}
if let directoryError = directoryError { throw directoryError }
try formData.writeEncodedData(to: fileURL)
let upload = self.upload(fileURL, with: urlRequestWithContentType)
// Cleanup the temp file once the upload is complete
upload.delegate.queue.addOperation {
do {
try FileManager.default.removeItem(at: fileURL)
} catch {
// No-op
}
}
DispatchQueue.main.async {
let encodingResult = MultipartFormDataEncodingResult.success(
request: upload,
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
}
} catch {
// Cleanup the temp file in the event that the multipart form data encoding failed
if let tempFileURL = tempFileURL {
do {
try FileManager.default.removeItem(at: tempFileURL)
} catch {
// No-op
}
}
DispatchQueue.main.async { encodingCompletion?(.failure(error)) }
}
}
}
// MARK: Private - Upload Implementation
private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest {
do {
let task = try uploadable.task(session: session, adapter: adapter, queue: queue)
let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task))
if case let .stream(inputStream, _) = uploadable {
upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }
}
delegate[task] = upload
if startRequestsImmediately { upload.resume() }
return upload
} catch {
return upload(uploadable, failedWith: error)
}
}
private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest {
var uploadTask: Request.RequestTask = .upload(nil, nil)
if let uploadable = uploadable {
uploadTask = .upload(uploadable, nil)
}
let underlyingError = error.underlyingAdaptError ?? error
let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError)
if let retrier = retrier, error is AdaptError {
allowRetrier(retrier, toRetry: upload, with: underlyingError)
} else {
if startRequestsImmediately { upload.resume() }
}
return upload
}
#if !os(watchOS)
// MARK: - Stream Request
// MARK: Hostname and Port
/// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter hostName: The hostname of the server to connect to.
/// - parameter port: The port of the server to connect to.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open func stream(withHostName hostName: String, port: Int) -> StreamRequest {
return stream(.stream(hostName: hostName, port: port))
}
// MARK: NetService
/// Creates a `StreamRequest` for bidirectional streaming using the `netService`.
///
/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
///
/// - parameter netService: The net service used to identify the endpoint.
///
/// - returns: The created `StreamRequest`.
@discardableResult
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
open func stream(with netService: NetService) -> StreamRequest {
return stream(.netService(netService))
}
// MARK: Private - Stream Implementation
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest {
do {
let task = try streamable.task(session: session, adapter: adapter, queue: queue)
let request = StreamRequest(session: session, requestTask: .stream(streamable, task))
delegate[task] = request
if startRequestsImmediately { request.resume() }
return request
} catch {
return stream(failedWith: error)
}
}
@available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
private func stream(failedWith error: Error) -> StreamRequest {
let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error)
if startRequestsImmediately { stream.resume() }
return stream
}
#endif
// MARK: - Internal - Retry Request
func retry(_ request: Request) -> Bool {
guard let originalTask = request.originalTask else { return false }
do {
let task = try originalTask.task(session: session, adapter: adapter, queue: queue)
request.delegate.task = task // resets all task delegate data
request.retryCount += 1
request.startTime = CFAbsoluteTimeGetCurrent()
request.endTime = nil
task.resume()
return true
} catch {
request.delegate.error = error.underlyingAdaptError ?? error
return false
}
}
private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) {
DispatchQueue.utility.async { [weak self] in
guard let strongSelf = self else { return }
retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in
guard let strongSelf = self else { return }
guard shouldRetry else {
if strongSelf.startRequestsImmediately { request.resume() }
return
}
DispatchQueue.utility.after(timeDelay) {
guard let strongSelf = self else { return }
let retrySucceeded = strongSelf.retry(request)
if retrySucceeded, let task = request.task {
strongSelf.delegate[task] = request
} else {
if strongSelf.startRequestsImmediately { request.resume() }
}
}
}
}
}
}
| mit | 163fa5be74d8e1cdff036485523986ae | 41.577354 | 129 | 0.624582 | 5.416286 | false | false | false | false |
kilolumen/DJDemo-swift | 3DTouch/Scale/Scale/ViewController.swift | 1 | 1377 | //
// ViewController.swift
// Scale
//
// Created by Weico on 12/01/2017.
// Copyright © 2017 kilolumen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var forceLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
if #available(iOS 9.0, *) {
if traitCollection.forceTouchCapability == UIForceTouchCapability.available {
if touch.force >= touch.maximumPossibleForce {
forceLabel.text = "385+ grams"
} else {
let force = touch.force / touch.maximumPossibleForce
let grams = force * 385
let roundGrams = Int(grams)
forceLabel.text = "\(roundGrams) grams"
}
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
forceLabel.text = "0 gram"
}
}
| mit | e02a95698a53ff76a7d038425312bf3e | 29.577778 | 93 | 0.561773 | 4.862191 | false | false | false | false |
wscqs/FMDemo- | FMDemo/Classes/Module/Course/PlayCourceMaterialViewController.swift | 1 | 4047 | //
// PlayCourceMaterialViewController.swift
// FMDemo
//
// Created by mba on 17/3/2.
// Copyright © 2017年 mbalib. All rights reserved.
//
import UIKit
import WebKit
class PlayCourceMaterialViewController: UIViewController {
var url: String? = ""
var isMaterial: Bool? = true // 区分播放课程与课程章节
var webView = WKWebView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAVIGATION_AND_STATUSBAR_HEIGHT ))
// 进度条
lazy var progressView:UIProgressView = {
let progress = UIProgressView()
progress.progressTintColor = UIColor.green
progress.trackTintColor = .clear
return progress
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webView)
webView.backgroundColor = UIColor.colorWithHexString(kGlobalBgColor)
webView.scrollView.showsVerticalScrollIndicator = false
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
view.addSubview(self.progressView)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(requst))
}
override func viewWillAppear(_ animated: Bool) {
if isMaterial ?? true {
title = "播放章节"
} else {
title = "播放课程"
}
requst()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
webView.removeObserver(self, forKeyPath: "estimatedProgress")
}
/// 请求
@objc fileprivate func requst() {
self.progressView.frame = CGRect(x:0,y:0,width:self.view.frame.size.width,height:3)
self.progressView.alpha = 1
self.progressView.setProgress(0.1, animated: true)
KeService.actionAccessToken({ (isSucess) in
self.webRequst()
}) { (error) in
self.progressView.alpha = 0.0
// MBAProgressHUD.showErrorWithStatus("加载失败,请重试")
}
}
fileprivate func webRequst() {
guard let url = url,
let accesToken = KeUserAccount.shared?.accessToken else {
return
}
var urlString = ""
if isMaterial ?? true {
urlString = "\(url)&access_token=\(accesToken)"
} else {
urlString = "\(url)?access_token=\(accesToken)"
}
print(urlString)
let requestURL = URL(string: urlString )
let request = URLRequest(url: requestURL!)
webView.load(request)
webView.navigationDelegate = self
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress" {
let progress = change![NSKeyValueChangeKey.newKey] as! Float
if progress >= 1.0 {
self.progressView.setProgress(progress, animated: true)
UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseInOut, animations: {
self.progressView.alpha = 0.0
}, completion: { (_) in
self.progressView.setProgress(0.0, animated: false)
})
}else {
self.progressView.alpha = 1.0
self.progressView.setProgress(progress, animated: true)
}
}
}
}
extension PlayCourceMaterialViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// MBAProgressHUD.dismiss()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
// MBAProgressHUD.dismiss()
MBAProgressHUD.showErrorWithStatus("加载失败,请重试")
}
}
| apache-2.0 | e33c1127a59b480da1d22e8731c60cee | 34.392857 | 159 | 0.615288 | 4.747305 | false | false | false | false |
FuckBoilerplate/RxCache | iOS/Pods/ObjectMapper/ObjectMapper/Core/Map.swift | 5 | 5354 | //
// Map.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// MapContext is available for developers who wish to pass information around during the mapping process.
public protocol MapContext {
}
/// A class used for holding mapping data
public final class Map {
public let mappingType: MappingType
public internal(set) var JSON: [String: Any] = [:]
public internal(set) var isKeyPresent = false
public internal(set) var currentValue: Any?
public internal(set) var currentKey: String?
var keyIsNested = false
public var context: MapContext?
let toObject: Bool // indicates whether the mapping is being applied to an existing object
public init(mappingType: MappingType, JSON: [String: Any], toObject: Bool = false, context: MapContext? = nil) {
self.mappingType = mappingType
self.JSON = JSON
self.toObject = toObject
self.context = context
}
/// Sets the current mapper value and key.
/// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
public subscript(key: String) -> Map {
// save key and value associated to it
let nested = key.contains(".")
return self[key, nested: nested, ignoreNil: false]
}
public subscript(key: String, nested nested: Bool) -> Map {
return self[key, nested: nested, ignoreNil: false]
}
public subscript(key: String, ignoreNil ignoreNil: Bool) -> Map {
let nested = key.contains(".")
return self[key, nested: nested, ignoreNil: ignoreNil]
}
public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> Map {
// save key and value associated to it
currentKey = key
keyIsNested = nested
// check if a value exists for the current key
// do this pre-check for performance reasons
if nested == false {
let object = JSON[key]
let isNSNull = object is NSNull
isKeyPresent = isNSNull ? true : object != nil
currentValue = isNSNull ? nil : object
} else {
// break down the components of the key that are separated by .
(isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: ".")), dictionary: JSON)
}
// update isKeyPresent if ignoreNil is true
if ignoreNil && currentValue == nil {
isKeyPresent = false
}
return self
}
public func value<T>() -> T? {
return currentValue as? T
}
}
/// Fetch value from JSON dictionary, loop through keyPathComponents until we reach the desired object
private func valueFor(_ keyPathComponents: ArraySlice<String>, dictionary: [String: Any]) -> (Bool, Any?) {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return (false, nil)
}
if let keyPath = keyPathComponents.first {
let object = dictionary[keyPath]
if object is NSNull {
return (true, nil)
} else if let dict = object as? [String: Any] , keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
} else if let array = object as? [Any] , keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, array: array)
} else {
return (object != nil, object)
}
}
return (false, nil)
}
/// Fetch value from JSON Array, loop through keyPathComponents them until we reach the desired object
private func valueFor(_ keyPathComponents: ArraySlice<String>, array: [Any]) -> (Bool, Any?) {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return (false, nil)
}
//Try to convert keypath to Int as index
if let keyPath = keyPathComponents.first,
let index = Int(keyPath) , index >= 0 && index < array.count {
let object = array[index]
if object is NSNull {
return (true, nil)
} else if let array = object as? [Any] , keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, array: array)
} else if let dict = object as? [String: Any] , keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
} else {
return (true, object)
}
}
return (false, nil)
}
| mit | e257d5655812472f07b4ad7e05a49091 | 32.886076 | 113 | 0.702092 | 3.919473 | false | false | false | false |
citysite102/kapi-kaffeine | kapi-kaffeine/kapi-kaffeine/KeychainItemWrapper.swift | 1 | 6794 | // KeychainItemWrapper.swift
//
// Copyright (c) 2015 Mihai Costea (http://mcostea.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Security
class KeychainItemWrapper {
var genericPasswordQuery = [NSObject: AnyObject]()
var keychainItemData = [NSObject: AnyObject]()
var values = [String: AnyObject]()
init(identifier: String, accessGroup: String?) {
self.genericPasswordQuery[kSecClass] = kSecClassGenericPassword
self.genericPasswordQuery[kSecAttrAccount] = identifier as AnyObject?
if (accessGroup != nil) {
if TARGET_IPHONE_SIMULATOR != 1 {
self.genericPasswordQuery[kSecAttrAccessGroup] = accessGroup as AnyObject?
}
}
self.genericPasswordQuery[kSecMatchLimit] = kSecMatchLimitOne
self.genericPasswordQuery[kSecReturnAttributes] = kCFBooleanTrue
var outDict: AnyObject?
let copyMatchingResult = SecItemCopyMatching(genericPasswordQuery as CFDictionary, &outDict)
if copyMatchingResult != noErr {
self.resetKeychain()
self.keychainItemData[kSecAttrAccount] = identifier as AnyObject?
if (accessGroup != nil) {
if TARGET_IPHONE_SIMULATOR != 1 {
self.keychainItemData[kSecAttrAccessGroup] = accessGroup as AnyObject?
}
}
} else {
self.keychainItemData = self.secItemDataToDict(data: outDict as! [NSObject: AnyObject])
}
}
subscript(key: String) -> AnyObject? {
get {
return self.values[key]
}
set(newValue) {
self.values[key] = newValue
self.writeKeychainData()
}
}
func resetKeychain() {
if !self.keychainItemData.isEmpty {
let tempDict = self.dictToSecItemData(dict: self.keychainItemData)
var junk = noErr
junk = SecItemDelete(tempDict as CFDictionary)
assert(junk == noErr || junk == errSecItemNotFound, "Failed to delete current dict")
}
self.keychainItemData[kSecAttrAccount] = "" as AnyObject?
self.keychainItemData[kSecAttrLabel] = "" as AnyObject?
self.keychainItemData[kSecAttrDescription] = "" as AnyObject?
self.keychainItemData[kSecValueData] = "" as AnyObject?
}
private func secItemDataToDict(data: [NSObject: AnyObject]) -> [NSObject: AnyObject] {
var returnDict = [NSObject: AnyObject]()
for (key, value) in data {
returnDict[key] = value
}
returnDict[kSecReturnData] = kCFBooleanTrue
returnDict[kSecClass] = kSecClassGenericPassword
var passwordData: AnyObject?
// We could use returnDict like the Apple example but this crashes the app with swift_unknownRelease
// when we try to access returnDict again
let queryDict = returnDict
let copyMatchingResult = SecItemCopyMatching(queryDict as CFDictionary, &passwordData)
if copyMatchingResult != noErr {
assert(false, "No matching item found in keychain")
} else {
let retainedValuesData = passwordData as! NSData
do {
let val = try JSONSerialization.jsonObject(with: retainedValuesData as Data, options: []) as! [String: AnyObject]
returnDict.removeValue(forKey: kSecReturnData)
returnDict[kSecValueData] = val as AnyObject?
self.values = val
} catch let error as NSError {
assert(false, "Error parsing json value. \(error.localizedDescription)")
}
}
return returnDict
}
private func dictToSecItemData(dict: [NSObject: AnyObject]) -> [NSObject: AnyObject] {
var returnDict = [NSObject: AnyObject]()
for (key, value) in self.keychainItemData {
returnDict[key] = value
}
returnDict[kSecClass] = kSecClassGenericPassword
do {
returnDict[kSecValueData] = try JSONSerialization.data(withJSONObject: self.values, options: []) as AnyObject?
} catch let error as NSError {
assert(false, "Error paring json value. \(error.localizedDescription)")
}
return returnDict
}
private func writeKeychainData() {
var attributes: AnyObject?
var updateItem: [String: AnyObject]? = [String: AnyObject]()
var result: OSStatus?
let copyMatchingResult = SecItemCopyMatching(self.genericPasswordQuery as CFDictionary, &attributes)
if copyMatchingResult != noErr {
result = SecItemAdd(self.dictToSecItemData(dict: self.keychainItemData) as CFDictionary, nil)
assert(result == noErr, "Failed to add keychain item")
} else {
for (key, value) in attributes as! [String: AnyObject] {
updateItem![key] = value
}
updateItem![kSecClass as String] = self.genericPasswordQuery[kSecClass]
var tempCheck = self.dictToSecItemData(dict: self.keychainItemData)
tempCheck.removeValue(forKey: kSecClass)
// if TARGET_IPHONE_SIMULATOR == 1 {
// tempCheck.removeValue(forKey: kSecAttrAccessGroup)
// }
result = SecItemUpdate(updateItem! as CFDictionary, tempCheck as CFDictionary)
assert(result == noErr, "Failed to update keychain item")
}
}
}
| mit | e0ed80f7aeaa3c9366c6f900c69f039b | 37.822857 | 129 | 0.622755 | 5.303669 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Errors/Sources/ErrorsUI/ErrorView.swift | 1 | 8923 | import BlockchainComponentLibrary
import BlockchainNamespace
import Localization
import SwiftUI
public struct ErrorView<Fallback: View>: View {
typealias L10n = LocalizationConstants.UX.Error
@BlockchainApp var app
@Environment(\.context) var context
public let ux: UX.Error
public let fallback: () -> Fallback
public let dismiss: (() -> Void)?
public init(
ux: UX.Error,
@ViewBuilder fallback: @escaping () -> Fallback,
dismiss: (() -> Void)? = nil
) {
self.ux = ux
self.fallback = fallback
self.dismiss = dismiss
}
let overlay = 7.5
public var body: some View {
VStack {
VStack(spacing: .none) {
Spacer()
icon
content
Spacer()
metadata
}
.multilineTextAlignment(.center)
actions
}
.padding()
.onAppear {
app.state.transaction { state in
state.set(blockchain.ux.error, to: ux)
state.set(blockchain.ux.error.then.close, to: Session.State.Function { dismiss?() })
}
app.post(
event: blockchain.ux.error,
context: context + ux.context(in: app)
)
}
.apply { view in
#if os(iOS)
view.navigationBarBackButtonHidden(true)
#endif
}
.apply { view in
if let dismiss = dismiss {
#if os(iOS)
view.navigationBarItems(
leading: EmptyView(),
trailing: IconButton(
icon: Icon.closeCirclev2,
action: dismiss
)
)
#endif
}
}
.background(Color.semantic.background)
}
@ViewBuilder
private var icon: some View {
Group {
if let icon = ux.icon {
AsyncMedia(
url: icon.url,
placeholder: {
Image(systemName: "squareshape.squareshape.dashed")
.resizable()
.overlay(ProgressView().opacity(0.3))
.foregroundColor(.semantic.light)
}
)
.accessibilityLabel(icon.accessibility?.description ?? L10n.icon.accessibility)
} else {
fallback()
}
}
.scaledToFit()
.frame(maxHeight: 100.pt)
.padding(floor(overlay / 2).i.vmin)
.overlay(
Group {
ZStack {
Circle()
.foregroundColor(.semantic.background)
.scaleEffect(1.3)
if let status = ux.icon?.status?.url {
AsyncMedia(
url: status,
content: { image in image.scaleEffect(0.9) },
placeholder: {
ProgressView().progressViewStyle(.circular)
}
)
} else {
Icon.alert
.scaledToFit()
.accentColor(.semantic.warning)
}
}
.frame(
width: overlay.vmin,
height: overlay.vmin
)
.offset(x: -overlay, y: overlay)
},
alignment: .topTrailing
)
}
@ViewBuilder
private var content: some View {
if ux.title.isNotEmpty {
Text(rich: ux.title)
.typography(.title3)
.foregroundColor(.semantic.title)
.padding(.bottom, Spacing.padding1.pt)
}
if ux.message.isNotEmpty {
Text(rich: ux.message)
.typography(.body1)
.foregroundColor(.semantic.body)
.padding(.bottom, Spacing.padding2.pt)
}
if let action = ux.actions.dropFirst(2).first, action.title.isNotEmpty {
SmallMinimalButton(
title: action.title,
action: { post(action) }
)
}
}
private var columns: [GridItem] = [
GridItem(.flexible(minimum: 32, maximum: 48), spacing: 16),
GridItem(.flexible(minimum: 100, maximum: .infinity), spacing: 16)
]
@ViewBuilder
private var metadata: some View {
if !ux.metadata.isEmpty {
HStack {
LazyVGrid(columns: columns, alignment: .leading) {
ForEach(Array(ux.metadata), id: \.key) { key, value in
Text(rich: key)
Text(rich: value)
}
}
.frame(maxWidth: .infinity)
Icon.copy.frame(width: 16.pt, height: 16.pt)
.accentColor(.semantic.light)
}
.typography(.micro)
.minimumScaleFactor(0.5)
.lineLimit(1)
.multilineTextAlignment(.leading)
.foregroundColor(.semantic.body)
.padding(8.pt)
.background(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.semantic.light, lineWidth: 1)
.background(Color.semantic.background)
)
.contextMenu {
Button(
action: {
let string = String(ux.metadata.map { "\($0): \($1)" }.joined(by: "\n"))
#if canImport(UIKit)
UIPasteboard.general.string = string
#else
NSPasteboard.general.setString(string, forType: .string)
#endif
},
label: {
Label(L10n.copy, systemImage: "doc.on.doc.fill")
}
)
}
.padding(.bottom)
}
}
@ViewBuilder
private var actions: some View {
VStack(spacing: Spacing.padding1) {
ForEach(ux.actions.prefix(2).indexed(), id: \.element) { index, action in
if action.title.isNotEmpty {
if index == ux.actions.startIndex {
PrimaryButton(
title: action.title,
action: { post(action) }
)
} else {
MinimalButton(
title: action.title,
action: { post(action) }
)
}
}
}
}
}
private func post(_ action: UX.Action) {
switch action.url {
case let url?:
app.post(
event: blockchain.ux.error.then.launch.url,
context: [
blockchain.ui.type.action.then.launch.url: url
]
)
case nil:
app.post(event: blockchain.ux.error.then.close)
}
}
}
extension ErrorView where Fallback == AnyView {
public init(
ux: UX.Error,
dismiss: (() -> Void)? = nil
) {
self.ux = ux
fallback = {
AnyView(
Icon.error.accentColor(.semantic.warning)
)
}
self.dismiss = dismiss
}
}
// swiftlint:disable type_name
// swiftlint:disable line_length
struct ErrorView_Preview: PreviewProvider {
static var previews: some View {
PrimaryNavigationView {
ErrorView(
ux: .init(
title: "Error Title",
message: "Here’s some explainer text that helps the user understand the problem, with a [potential link](http://blockchain.com) for the user to tap to learn more.",
icon: UX.Icon(
url: "https://bitcoin.org/img/icons/opengraph.png",
accessibility: nil
),
metadata: [
"ID": "825ea2c0-9f5f-4e2a-be8f-0e3572f0bec2",
"Request": "825ea2c0-9f5f-4e2a-be8f-0e3572f0bec2"
],
actions: [
.init(
title: "Primary",
url: "http://blockchain.com/app/asset/BTC/buy/change_payment_method"
),
.init(title: "Secondary"),
.init(title: "Small Primary")
]
)
)
.app(App.preview)
}
}
}
| lgpl-3.0 | b37fa133cd6b45c84ab4aaf1032d9aed | 31.089928 | 184 | 0.435489 | 5.147721 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/UIComponents/UIComponentsKit/Images.swift | 1 | 601 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import SwiftUI
public enum ImageAsset: String {
case iconSend = "icon_send"
case iconReceive = "icon_receive"
case iconReceiveGray = "icon_receive_gray"
case iconVerified = "icon_verified"
case iconSwapTransaction = "icon_swap_transaction"
case linkPattern = "link-pattern"
case emptyActivity = "empty_activity"
public var imageResource: ImageResource {
.local(name: rawValue, bundle: .UIComponents)
}
public var image: Image {
Image(rawValue, bundle: .UIComponents)
}
}
| lgpl-3.0 | 829e4411ad1b89b0a9e81b352a0b13d0 | 25.086957 | 62 | 0.688333 | 4.109589 | false | false | false | false |
jopamer/swift | test/SILGen/protocol_extensions.swift | 1 | 39773 |
// RUN: %target-swift-emit-silgen -module-name protocol_extensions -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s
public protocol P1 {
func reqP1a()
subscript(i: Int) -> Int { get set }
}
struct Box {
var number: Int
}
extension P1 {
// CHECK-LABEL: sil hidden @$S19protocol_extensions2P1PAAE6extP1a{{[_0-9a-zA-Z]*}}F : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () {
// CHECK: bb0([[SELF:%[0-9]+]] : @trivial $*Self):
func extP1a() {
// CHECK: [[WITNESS:%[0-9]+]] = witness_method $Self, #P1.reqP1a!1 : {{.*}} : $@convention(witness_method: P1) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
// CHECK-NEXT: apply [[WITNESS]]<Self>([[SELF]]) : $@convention(witness_method: P1) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
reqP1a()
// CHECK: return
}
// CHECK-LABEL: sil @$S19protocol_extensions2P1PAAE6extP1b{{[_0-9a-zA-Z]*}}F : $@convention(method) <Self where Self : P1> (@in_guaranteed Self) -> () {
// CHECK: bb0([[SELF:%[0-9]+]] : @trivial $*Self):
public func extP1b() {
// CHECK: [[FN:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE6extP1a{{[_0-9a-zA-Z]*}}F : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
// CHECK-NEXT: apply [[FN]]<Self>([[SELF]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
extP1a()
// CHECK: return
}
subscript(i: Int) -> Int {
// materializeForSet can do static dispatch to peer accessors (tested later, in the emission of the concrete conformance)
get {
return 0
}
set {}
}
func callSubscript() -> Int {
// But here we have to do a witness method call:
// CHECK-LABEL: sil hidden @$S19protocol_extensions2P1PAAE13callSubscript{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $*Self):
// CHECK: witness_method $Self, #P1.subscript!getter.1
// CHECK: return
return self[0]
}
static var staticReadOnlyProperty: Int {
return 0
}
static var staticReadWrite1: Int {
get { return 0 }
set { }
}
static var staticReadWrite2: Box {
get { return Box(number: 0) }
set { }
}
}
// ----------------------------------------------------------------------------
// Using protocol extension members with concrete types
// ----------------------------------------------------------------------------
class C : P1 {
func reqP1a() { }
}
// (materializeForSet test from above)
// CHECK-LABEL: sil private [transparent] [thunk] @$S19protocol_extensions1CCAA2P1A2aDPyS2icimTW
// CHECK: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $Int, %3 : @trivial $*τ_0_0):
// CHECK: function_ref @$S19protocol_extensions2P1PAAEyS2icig
// CHECK: return
class D : C { }
struct S : P1 {
func reqP1a() { }
}
struct G<T> : P1 {
func reqP1a() { }
}
struct MetaHolder {
var d: D.Type = D.self
var s: S.Type = S.self
}
struct GenericMetaHolder<T> {
var g: G<T>.Type = G<T>.self
}
func inout_func(_ n: inout Int) {}
// CHECK-LABEL: sil hidden @$S19protocol_extensions5testD_2dd1dyAA10MetaHolderV_AA1DCmAHtF : $@convention(thin) (MetaHolder, @thick D.Type, @guaranteed D) -> ()
// CHECK: bb0([[M:%[0-9]+]] : @trivial $MetaHolder, [[DD:%[0-9]+]] : @trivial $@thick D.Type, [[D:%[0-9]+]] : @guaranteed $D):
func testD(_ m: MetaHolder, dd: D.Type, d: D) {
// CHECK: [[D2:%[0-9]+]] = alloc_box ${ var D }
// CHECK: [[RESULT:%.*]] = project_box [[D2]]
// CHECK: [[MATERIALIZED_BORROWED_D:%[0-9]+]] = alloc_stack $D
// CHECK: store_borrow [[D]] to [[MATERIALIZED_BORROWED_D]]
// CHECK: [[FN:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE11returnsSelf{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FN]]<D>([[RESULT]], [[MATERIALIZED_BORROWED_D]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0
// CHECK-NEXT: dealloc_stack [[MATERIALIZED_BORROWED_D]]
var d2: D = d.returnsSelf()
// CHECK: metatype $@thick D.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = D.staticReadOnlyProperty
// CHECK: metatype $@thick D.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
D.staticReadWrite1 = 1
// CHECK: metatype $@thick D.Type
// CHECK: alloc_stack $Int
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
D.staticReadWrite1 += 1
// CHECK: metatype $@thick D.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
D.staticReadWrite2 = Box(number: 2)
// CHECK: metatype $@thick D.Type
// CHECK: alloc_stack $Box
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
D.staticReadWrite2.number += 5
// CHECK: metatype $@thick D.Type
// CHECK: alloc_stack $Box
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&D.staticReadWrite2.number)
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = dd.staticReadOnlyProperty
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
dd.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
dd.staticReadWrite1 += 1
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
dd.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
dd.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&dd.staticReadWrite2.number)
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = m.d.staticReadOnlyProperty
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
m.d.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
m.d.staticReadWrite1 += 1
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
m.d.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
m.d.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&m.d.staticReadWrite2.number)
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions5testS_2ssyAA10MetaHolderV_AA1SVmtF
func testS(_ m: MetaHolder, ss: S.Type) {
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = S.staticReadOnlyProperty
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
S.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
S.staticReadWrite1 += 1
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
S.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
S.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&S.staticReadWrite2.number)
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = ss.staticReadOnlyProperty
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
ss.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
ss.staticReadWrite1 += 1
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
ss.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
ss.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&ss.staticReadWrite2.number)
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = m.s.staticReadOnlyProperty
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
m.s.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
m.s.staticReadWrite1 += 1
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
m.s.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
m.s.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick S.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&m.s.staticReadWrite2.number)
// CHECK: return
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions5testG{{[_0-9a-zA-Z]*}}F
func testG<T>(_ m: GenericMetaHolder<T>, gg: G<T>.Type) {
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = G<T>.staticReadOnlyProperty
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
G<T>.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
G<T>.staticReadWrite1 += 1
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
G<T>.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
G<T>.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&G<T>.staticReadWrite2.number)
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = gg.staticReadOnlyProperty
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
gg.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
gg.staticReadWrite1 += 1
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
gg.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
gg.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&gg.staticReadWrite2.number)
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE22staticReadOnlyPropertySivgZ
let _ = m.g.staticReadOnlyProperty
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
m.g.staticReadWrite1 = 1
// CHECK: alloc_stack $Int
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite1SivsZ
// CHECK: dealloc_stack
m.g.staticReadWrite1 += 1
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
m.g.staticReadWrite2 = Box(number: 2)
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
m.g.staticReadWrite2.number += 5
// CHECK: alloc_stack $Box
// CHECK: metatype $@thick G<T>.Type
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvgZ
// CHECK: store
// CHECK: function_ref @$S19protocol_extensions10inout_funcyySizF
// CHECK: load
// CHECK: function_ref @$S19protocol_extensions2P1PAAE16staticReadWrite2AA3BoxVvsZ
// CHECK: dealloc_stack
inout_func(&m.g.staticReadWrite2.number)
// CHECK: return
}
// ----------------------------------------------------------------------------
// Using protocol extension members with existentials
// ----------------------------------------------------------------------------
extension P1 {
func f1() { }
subscript (i: Int64) -> Bool {
get { return true }
}
var prop: Bool {
get { return true }
}
func returnsSelf() -> Self { return self }
var prop2: Bool {
get { return true }
set { }
}
subscript (b: Bool) -> Bool {
get { return b }
set { }
}
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions17testExistentials1{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%[0-9]+]] : @trivial $*P1, [[B:%[0-9]+]] : @trivial $Bool, [[I:%[0-9]+]] : @trivial $Int64):
func testExistentials1(_ p1: P1, b: Bool, i: Int64) {
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]])
// CHECK: [[F1:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE2f1{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[F1]]<@opened([[UUID]]) P1>([[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> ()
p1.f1()
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
// CHECK: [[GETTER:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAEySbs5Int64Vcig
// CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[I]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Int64, @in_guaranteed τ_0_0) -> Bool
// CHECK: store{{.*}} : $*Bool
// CHECK: destroy_addr [[POPENED_COPY]]
// CHECK: dealloc_stack [[POPENED_COPY]]
var b2 = p1[i]
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
// CHECK: [[GETTER:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE4propSbvg
// CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool
// CHECK: store{{.*}} : $*Bool
// CHECK: dealloc_stack [[POPENED_COPY]]
var b3 = p1.prop
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions17testExistentials2{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%[0-9]+]] : @trivial $*P1):
func testExistentials2(_ p1: P1) {
// CHECK: [[P1A:%[0-9]+]] = alloc_box ${ var P1 }
// CHECK: [[PB:%.*]] = project_box [[P1A]]
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: [[P1AINIT:%[0-9]+]] = init_existential_addr [[PB]] : $*P1, $@opened([[UUID2:".*"]]) P1
// CHECK: [[FN:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE11returnsSelf{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[FN]]<@opened([[UUID]]) P1>([[P1AINIT]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> @out τ_0_0
var p1a: P1 = p1.returnsSelf()
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions23testExistentialsGetters{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%[0-9]+]] : @trivial $*P1):
func testExistentialsGetters(_ p1: P1) {
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
// CHECK: [[FN:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE5prop2Sbvg
// CHECK: [[B:%[0-9]+]] = apply [[FN]]<@opened([[UUID]]) P1>([[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (@in_guaranteed τ_0_0) -> Bool
let b: Bool = p1.prop2
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr immutable_access [[P]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: copy_addr [[POPENED]] to [initialization] [[POPENED_COPY:%.*]] :
// CHECK: [[GETTER:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAEyS2bcig
// CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED_COPY]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @in_guaranteed τ_0_0) -> Bool
let b2: Bool = p1[b]
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions22testExistentialSetters{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[P:%[0-9]+]] : @trivial $*P1, [[B:%[0-9]+]] : @trivial $Bool):
func testExistentialSetters(_ p1: P1, b: Bool) {
var p1 = p1
// CHECK: [[PBOX:%[0-9]+]] = alloc_box ${ var P1 }
// CHECK: [[PBP:%[0-9]+]] = project_box [[PBOX]]
// CHECK-NEXT: copy_addr [[P]] to [initialization] [[PBP]] : $*P1
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBP]]
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr mutable_access [[WRITE]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: [[GETTER:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE5prop2Sbvs
// CHECK: apply [[GETTER]]<@opened([[UUID]]) P1>([[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> ()
// CHECK-NOT: deinit_existential_addr
p1.prop2 = b
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBP]]
// CHECK: [[POPENED:%[0-9]+]] = open_existential_addr mutable_access [[WRITE]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: [[SUBSETTER:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAEyS2bcis
// CHECK: apply [[SUBSETTER]]<@opened([[UUID]]) P1>([[B]], [[B]], [[POPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, Bool, @inout τ_0_0) -> ()
// CHECK-NOT: deinit_existential_addr [[PB]] : $*P1
p1[b] = b
// CHECK: return
}
struct HasAP1 {
var p1: P1
var someP1: P1 {
get { return p1 }
set { p1 = newValue }
}
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions29testLogicalExistentialSetters{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[HASP1:%[0-9]+]] : @trivial $*HasAP1, [[B:%[0-9]+]] : @trivial $Bool)
func testLogicalExistentialSetters(_ hasAP1: HasAP1, _ b: Bool) {
var hasAP1 = hasAP1
// CHECK: [[HASP1_BOX:%[0-9]+]] = alloc_box ${ var HasAP1 }
// CHECK: [[PBHASP1:%[0-9]+]] = project_box [[HASP1_BOX]]
// CHECK-NEXT: copy_addr [[HASP1]] to [initialization] [[PBHASP1]] : $*HasAP1
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBHASP1]]
// CHECK: [[P1_COPY:%[0-9]+]] = alloc_stack $P1
// CHECK-NEXT: [[HASP1_COPY:%[0-9]+]] = alloc_stack $HasAP1
// CHECK-NEXT: copy_addr [[WRITE]] to [initialization] [[HASP1_COPY]] : $*HasAP1
// CHECK: [[SOMEP1_GETTER:%[0-9]+]] = function_ref @$S19protocol_extensions6HasAP1V6someP1AA0F0_pvg : $@convention(method) (@in_guaranteed HasAP1) -> @out P1
// CHECK: [[RESULT:%[0-9]+]] = apply [[SOMEP1_GETTER]]([[P1_COPY]], [[HASP1_COPY]]) : $@convention(method) (@in_guaranteed HasAP1) -> @out P1
// CHECK: [[P1_OPENED:%[0-9]+]] = open_existential_addr mutable_access [[P1_COPY]] : $*P1 to $*@opened([[UUID:".*"]]) P1
// CHECK: [[PROP2_SETTER:%[0-9]+]] = function_ref @$S19protocol_extensions2P1PAAE5prop2Sbvs : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> ()
// CHECK: apply [[PROP2_SETTER]]<@opened([[UUID]]) P1>([[B]], [[P1_OPENED]]) : $@convention(method) <τ_0_0 where τ_0_0 : P1> (Bool, @inout τ_0_0) -> ()
// CHECK: [[SOMEP1_SETTER:%[0-9]+]] = function_ref @$S19protocol_extensions6HasAP1V6someP1AA0F0_pvs : $@convention(method) (@in P1, @inout HasAP1) -> ()
// CHECK: apply [[SOMEP1_SETTER]]([[P1_COPY]], [[WRITE]]) : $@convention(method) (@in P1, @inout HasAP1) -> ()
// CHECK-NOT: deinit_existential_addr
hasAP1.someP1.prop2 = b
// CHECK: return
}
func plusOneP1() -> P1 {}
// CHECK-LABEL: sil hidden @$S19protocol_extensions38test_open_existential_semantics_opaque{{[_0-9a-zA-Z]*}}F
func test_open_existential_semantics_opaque(_ guaranteed: P1,
immediate: P1) {
var immediate = immediate
// CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var P1 }
// CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
// CHECK: [[VALUE:%.*]] = open_existential_addr immutable_access %0
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
guaranteed.f1()
// -- Need a guaranteed copy because it's immutable
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: copy_addr [[READ]] to [initialization] [[IMMEDIATE:%.*]] :
// CHECK: [[VALUE:%.*]] = open_existential_addr immutable_access [[IMMEDIATE]]
// CHECK: [[METHOD:%.*]] = function_ref
// -- Can consume the value from our own copy
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK: destroy_addr [[IMMEDIATE]]
// CHECK: dealloc_stack [[IMMEDIATE]]
immediate.f1()
// CHECK: [[PLUS_ONE:%.*]] = alloc_stack $P1
// CHECK: [[VALUE:%.*]] = open_existential_addr immutable_access [[PLUS_ONE]]
// CHECK: [[METHOD:%.*]] = function_ref
// -- Can consume the value from our own copy
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK: destroy_addr [[PLUS_ONE]]
// CHECK: dealloc_stack [[PLUS_ONE]]
plusOneP1().f1()
}
protocol CP1: class {}
extension CP1 {
func f1() { }
}
func plusOneCP1() -> CP1 {}
// CHECK-LABEL: sil hidden @$S19protocol_extensions37test_open_existential_semantics_class{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $CP1, [[ARG1:%.*]] : @guaranteed $CP1):
func test_open_existential_semantics_class(_ guaranteed: CP1,
immediate: CP1) {
var immediate = immediate
// CHECK: [[IMMEDIATE_BOX:%.*]] = alloc_box ${ var CP1 }
// CHECK: [[PB:%.*]] = project_box [[IMMEDIATE_BOX]]
// CHECK-NOT: copy_value [[ARG0]]
// CHECK: [[VALUE:%.*]] = open_existential_ref [[ARG0]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK-NOT: destroy_value [[VALUE]]
// CHECK-NOT: destroy_value [[ARG0]]
guaranteed.f1()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: [[IMMEDIATE:%.*]] = load [copy] [[READ]]
// CHECK: [[VALUE:%.*]] = open_existential_ref [[IMMEDIATE]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK: destroy_value [[VALUE]]
// CHECK-NOT: destroy_value [[IMMEDIATE]]
immediate.f1()
// CHECK: [[F:%.*]] = function_ref {{.*}}plusOneCP1
// CHECK: [[PLUS_ONE:%.*]] = apply [[F]]()
// CHECK: [[VALUE:%.*]] = open_existential_ref [[PLUS_ONE]]
// CHECK: [[METHOD:%.*]] = function_ref
// CHECK: apply [[METHOD]]<{{.*}}>([[VALUE]])
// CHECK: destroy_value [[VALUE]]
// CHECK-NOT: destroy_value [[PLUS_ONE]]
plusOneCP1().f1()
}
// CHECK: } // end sil function '$S19protocol_extensions37test_open_existential_semantics_class{{[_0-9a-zA-Z]*}}F'
protocol InitRequirement {
init(c: C)
}
extension InitRequirement {
// CHECK-LABEL: sil hidden @$S19protocol_extensions15InitRequirementPAAE1dxAA1DC_tcfC : $@convention(method) <Self where Self : InitRequirement> (@owned D, @thick Self.Type) -> @out Self
// CHECK: bb0([[OUT:%.*]] : @trivial $*Self, [[ARG:%.*]] : @owned $D, [[SELF_TYPE:%.*]] : @trivial $@thick Self.Type):
init(d: D) {
// CHECK: [[SELF_BOX:%.*]] = alloc_box
// CHECK-NEXT: [[UNINIT_SELF:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK-NEXT: [[SELF_BOX_ADDR:%.*]] = project_box [[UNINIT_SELF]]
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $Self
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK-NEXT: [[ARG_COPY_CAST:%.*]] = upcast [[ARG_COPY]]
// CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator.1 : {{.*}} : $@convention(witness_method: InitRequirement) <τ_0_0 where τ_0_0 : InitRequirement> (@owned C, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK-NEXT: apply [[DELEGATEE]]<Self>([[SELF_BOX]], [[ARG_COPY_CAST]], [[SELF_TYPE]])
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [[SELF_BOX_ADDR]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: copy_addr [[SELF_BOX_ADDR]] to [initialization] [[OUT]]
// CHECK-NEXT: destroy_value [[ARG]]
// CHECK-NEXT: destroy_value [[UNINIT_SELF]]
// CHECK: return
self.init(c: d)
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions15InitRequirementPAAE2d2xAA1DC_tcfC : $@convention(method)
// CHECK: bb0([[OUT:%.*]] : @trivial $*Self, [[ARG:%.*]] : @owned $D, [[SELF_TYPE:%.*]] : @trivial $@thick Self.Type):
init(d2: D) {
// CHECK: [[SELF_BOX:%.*]] = alloc_box
// CHECK-NEXT: [[UNINIT_SELF:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK-NEXT: [[SELF_BOX_ADDR:%.*]] = project_box [[UNINIT_SELF]]
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $Self
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[DELEGATEE:%.*]] = function_ref @$S19protocol_extensions15InitRequirementPAAE1dxAA1DC_tcfC
// CHECK-NEXT: apply [[DELEGATEE]]<Self>([[SELF_BOX]], [[ARG_COPY]], [[SELF_TYPE]])
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [[SELF_BOX_ADDR]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: copy_addr [[SELF_BOX_ADDR]] to [initialization] [[OUT]]
// CHECK-NEXT: destroy_value [[ARG]]
// CHECK-NEXT: destroy_value [[UNINIT_SELF]]
// CHECK: return
self.init(d: d2)
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions15InitRequirementPAAE2c2xAA1CC_tcfC : $@convention(method)
// CHECK: bb0([[OUT:%.*]] : @trivial $*Self, [[ARG:%.*]] : @owned $C, [[SELF_TYPE:%.*]] : @trivial $@thick Self.Type):
init(c2: C) {
// CHECK: [[SELF_BOX:%.*]] = alloc_box
// CHECK-NEXT: [[UNINIT_SELF:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK-NEXT: [[SELF_BOX_ADDR:%.*]] = project_box [[UNINIT_SELF]]
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $Self
// CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thick Self.Type
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #InitRequirement.init!allocator.1
// CHECK-NEXT: apply [[DELEGATEE]]<Self>([[SELF_BOX]], [[ARG_COPY]], [[SELF_TYPE]])
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF_BOX_ADDR]]
// CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: copy_addr [[SELF_BOX_ADDR]] to [initialization] [[OUT]]
// CHECK-NEXT: destroy_value [[ARG]]
// CHECK-NEXT: destroy_value [[UNINIT_SELF]]
// CHECK: return
self = Self(c: c2)
}
}
protocol ClassInitRequirement: class {
init(c: C)
}
extension ClassInitRequirement {
// CHECK-LABEL: sil hidden @$S19protocol_extensions20ClassInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC : $@convention(method) <Self where Self : ClassInitRequirement> (@owned D, @thick Self.Type) -> @owned Self
// CHECK: bb0([[ARG:%.*]] : @owned $D, [[SELF_TYPE:%.*]] : @trivial $@thick Self.Type):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[ARG_COPY_CAST:%.*]] = upcast [[ARG_COPY]]
// CHECK: [[DELEGATEE:%.*]] = witness_method $Self, #ClassInitRequirement.init!allocator.1 : {{.*}} : $@convention(witness_method: ClassInitRequirement) <τ_0_0 where τ_0_0 : ClassInitRequirement> (@owned C, @thick τ_0_0.Type) -> @owned τ_0_0
// CHECK: apply [[DELEGATEE]]<Self>([[ARG_COPY_CAST]], [[SELF_TYPE]])
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: } // end sil function '$S19protocol_extensions20ClassInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC'
init(d: D) {
self.init(c: d)
}
}
@objc class OC {}
@objc class OD: OC {}
@objc protocol ObjCInitRequirement {
init(c: OC, d: OC)
}
func foo(_ t: ObjCInitRequirement.Type, c: OC) -> ObjCInitRequirement {
return t.init(c: OC(), d: OC())
}
extension ObjCInitRequirement {
// CHECK-LABEL: sil hidden @$S19protocol_extensions19ObjCInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC : $@convention(method) <Self where Self : ObjCInitRequirement> (@owned OD, @thick Self.Type) -> @owned Self
// CHECK: bb0([[ARG:%.*]] : @owned $OD, [[SELF_TYPE:%.*]] : @trivial $@thick Self.Type):
// CHECK: [[OBJC_SELF_TYPE:%.*]] = thick_to_objc_metatype [[SELF_TYPE]]
// CHECK: [[SELF:%.*]] = alloc_ref_dynamic [objc] [[OBJC_SELF_TYPE]] : $@objc_metatype Self.Type, $Self
// CHECK: [[BORROWED_ARG_1:%.*]] = begin_borrow [[ARG]]
// CHECK: [[BORROWED_ARG_1_UPCAST:%.*]] = upcast [[BORROWED_ARG_1]]
// CHECK: [[BORROWED_ARG_2:%.*]] = begin_borrow [[ARG]]
// CHECK: [[BORROWED_ARG_2_UPCAST:%.*]] = upcast [[BORROWED_ARG_2]]
// CHECK: [[WITNESS:%.*]] = objc_method [[SELF]] : $Self, #ObjCInitRequirement.init!initializer.1.foreign : {{.*}}, $@convention(objc_method) <τ_0_0 where τ_0_0 : ObjCInitRequirement> (OC, OC, @owned τ_0_0) -> @owned τ_0_0
// CHECK: apply [[WITNESS]]<Self>([[BORROWED_ARG_1_UPCAST]], [[BORROWED_ARG_2_UPCAST]], [[SELF]])
// CHECK: end_borrow [[BORROWED_ARG_2]] from [[ARG]]
// CHECK: end_borrow [[BORROWED_ARG_1]] from [[ARG]]
// CHECK: } // end sil function '$S19protocol_extensions19ObjCInitRequirementPAAE{{[_0-9a-zA-Z]*}}fC'
init(d: OD) {
self.init(c: d, d: d)
}
}
// rdar://problem/21370992 - delegation from an initializer in a
// protocol extension to an @objc initializer in a class.
class ObjCInitClass {
@objc required init() { }
}
protocol ProtoDelegatesToObjC { }
extension ProtoDelegatesToObjC where Self : ObjCInitClass {
// CHECK-LABEL: sil hidden @$S19protocol_extensions20ProtoDelegatesToObjCPA2A0F10CInitClassC{{[_0-9a-zA-Z]*}}fC
// CHECK: bb0([[STR:%[0-9]+]] : @owned $String, [[SELF_META:%[0-9]+]] : @trivial $@thick Self.Type):
init(string: String) {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : ObjCInitClass, τ_0_0 : ProtoDelegatesToObjC> { var τ_0_0 } <Self>
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[SELF_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[SELF_META]] : $@thick Self.Type to $@objc_metatype Self.Type
// CHECK: [[SELF_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[SELF_META_OBJC]] : $@objc_metatype Self.Type, $Self
// CHECK: [[SELF_ALLOC_C:%[0-9]+]] = upcast [[SELF_ALLOC]] : $Self to $ObjCInitClass
// CHECK: [[OBJC_INIT:%[0-9]+]] = class_method [[SELF_ALLOC_C]] : $ObjCInitClass, #ObjCInitClass.init!initializer.1 : (ObjCInitClass.Type) -> () -> ObjCInitClass, $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass
// CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[OBJC_INIT]]([[SELF_ALLOC_C]]) : $@convention(method) (@owned ObjCInitClass) -> @owned ObjCInitClass
// CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $ObjCInitClass to $Self
// CHECK: assign [[SELF_RESULT_AS_SELF]] to [[PB_SELF_BOX]] : $*Self
self.init()
}
}
// Delegating from an initializer in a protocol extension where Self
// has a superclass to a required initializer of that class.
class RequiredInitClass {
required init() { }
}
protocol ProtoDelegatesToRequired { }
extension ProtoDelegatesToRequired where Self : RequiredInitClass {
// CHECK-LABEL: sil hidden @$S19protocol_extensions24ProtoDelegatesToRequiredPA2A0F9InitClassC{{[_0-9a-zA-Z]*}}fC
// CHECK: bb0([[STR:%[0-9]+]] : @owned $String, [[SELF_META:%[0-9]+]] : @trivial $@thick Self.Type):
init(string: String) {
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : RequiredInitClass, τ_0_0 : ProtoDelegatesToRequired> { var τ_0_0 } <Self>
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK: [[SELF_META_AS_CLASS_META:%[0-9]+]] = upcast [[SELF_META]] : $@thick Self.Type to $@thick RequiredInitClass.Type
// CHECK: [[INIT:%[0-9]+]] = class_method [[SELF_META_AS_CLASS_META]] : $@thick RequiredInitClass.Type, #RequiredInitClass.init!allocator.1 : (RequiredInitClass.Type) -> () -> RequiredInitClass, $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass
// CHECK: [[SELF_RESULT:%[0-9]+]] = apply [[INIT]]([[SELF_META_AS_CLASS_META]]) : $@convention(method) (@thick RequiredInitClass.Type) -> @owned RequiredInitClass
// CHECK: [[SELF_RESULT_AS_SELF:%[0-9]+]] = unchecked_ref_cast [[SELF_RESULT]] : $RequiredInitClass to $Self
// CHECK: assign [[SELF_RESULT_AS_SELF]] to [[PB_SELF_BOX]] : $*Self
self.init()
}
}
// ----------------------------------------------------------------------------
// Default implementations via protocol extensions
// ----------------------------------------------------------------------------
protocol P2 {
associatedtype A
func f1(_ a: A)
func f2(_ a: A)
var x: A { get }
}
extension P2 {
// CHECK-LABEL: sil hidden @$S19protocol_extensions2P2PAAE2f1{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Self, #P2.f2!1
// CHECK: function_ref @$S19protocol_extensions2P2PAAE2f3{{[_0-9a-zA-Z]*}}F
// CHECK: return
func f1(_ a: A) {
f2(a)
f3(a)
}
// CHECK-LABEL: sil hidden @$S19protocol_extensions2P2PAAE2f2{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Self, #P2.f1!1
// CHECK: function_ref @$S19protocol_extensions2P2PAAE2f3{{[_0-9a-zA-Z]*}}F
// CHECK: return
func f2(_ a: A) {
f1(a)
f3(a)
}
func f3(_ a: A) {}
// CHECK-LABEL: sil hidden @$S19protocol_extensions2P2PAAE2f4{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Self, #P2.f1!1
// CHECK: witness_method $Self, #P2.f2!1
// CHECK: return
func f4() {
f1(x)
f2(x)
}
}
| apache-2.0 | 059594dcbc4c525aa6cec80b2f429136 | 43.067703 | 279 | 0.644654 | 3.27545 | false | false | false | false |
lukaskollmer/RuntimeKit | RuntimeKit/Sources/GetClasses.swift | 1 | 1726 | //
// GetClasses.swift
// RuntimeKit
//
// Created by Lukas Kollmer on 31.03.17.
// Copyright © 2017 Lukas Kollmer. All rights reserved.
//
import Foundation
import ObjectiveC
/// Struct describing an Objective-C class
public struct ObjCClassDescription {
/// The classes name
public let name: String
/// The actual class object (`AnyClass`)
public let `class`: AnyClass
/// All protocols implemented by the class
private let protocols: [Protocol]
/// Create a new `ObjCClassDescription` from an `AnyClass` object
///
/// - Parameter `class`: A class
public init(_ `class`: AnyClass) {
self.name = String(cString: class_getName(`class`))
self.class = `class`
self.protocols = [] // TODO
}
}
public extension Runtime {
/// All classes registered with the Objective-C runtime
public static var allClasses: [ObjCClassDescription] {
var count: UInt32 = 0
guard let classList = objc_copyClassList(&count) else { return [] }
var allClasses = [ObjCClassDescription]()
for i in 0..<count {
allClasses.append(ObjCClassDescription(classList[Int(i)]))
}
return allClasses
}
/// Check whether a class with the given name exists
///
/// - Parameter name: A class name
/// - Returns: `true` if the class exists, otherwise `false`
public static func classExists(_ name: String) -> Bool {
return objc_getClass(name.cString(using: .utf8)!) != nil
}
public static func getClass(_ name: String) -> NSObject.Type? {
return objc_getClass(name.cString(using: .utf8)!) as? NSObject.Type
}
}
| mit | a7d684e9bce0af9bc6a40ca4a8f8150b | 27.278689 | 75 | 0.618551 | 4.356061 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/data types/enumerable/XGPokemart.swift | 1 | 2020 | //
// XGPokemart.swift
// GoD Tool
//
// Created by The Steez on 01/11/2017.
//
//
import Foundation
final class XGPokemart: NSObject, Codable {
var index = 0
var items = [XGItems]()
var firstItemIndex = 0
var itemsStartOffset : Int {
get {
return PocketIndexes.MartItems.startOffset + (firstItemIndex * 2)
}
}
init(index: Int) {
super.init()
let data = pocket.data!
self.index = index
self.firstItemIndex = data.get2BytesAtOffset(PocketIndexes.MartStartIndexes.startOffset + (index * 4) + 2)
var nextItemOffset = itemsStartOffset
var nextItem = data.get2BytesAtOffset(nextItemOffset)
while nextItem != 0 {
self.items.append(.index(nextItem))
nextItemOffset += 2
nextItem = data.get2BytesAtOffset(nextItemOffset)
}
}
func save() {
let data = pocket.data!
data.replace2BytesAtOffset(PocketIndexes.MartStartIndexes.startOffset + (index * 4) + 2, withBytes: self.firstItemIndex)
var nextItemOffset = itemsStartOffset
for item in self.items {
data.replace2BytesAtOffset(nextItemOffset, withBytes: item.scriptIndex)
nextItemOffset += 2
}
data.replace2BytesAtOffset(nextItemOffset, withBytes: 0)
data.save()
}
}
extension XGPokemart: XGEnumerable {
var enumerableName: String {
return "Mart " + String(format: "%03d", index)
}
var enumerableValue: String? {
return nil
}
static var className: String {
return "Pokemarts"
}
static var allValues: [XGPokemart] {
var values = [XGPokemart]()
for i in 0 ..< PocketIndexes.numberOfMarts.value {
values.append(XGPokemart(index: i))
}
return values
}
}
extension XGPokemart: XGDocumentable {
var documentableName: String {
return "Mart \(self.index)"
}
static var DocumentableKeys: [String] {
return ["items"]
}
func documentableValue(for key: String) -> String {
switch key {
case "item":
var itemsString = ""
for item in items {
itemsString += "\n" + item.name.string
}
return itemsString
default: return ""
}
}
}
| gpl-2.0 | c3f65ad6ea5922776343357d27fa20ca | 18.803922 | 122 | 0.687129 | 3.216561 | false | false | false | false |
richy486/ReactiveReSwiftRouter | ReSwiftRouterTests/ReSwiftRouterIntegrationTests.swift | 1 | 12426 | //
// SwiftFlowRouterTests.swift
// SwiftFlowRouterTests
//
// Created by Benjamin Encz on 12/2/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import Quick
import Nimble
import ReactiveReSwift
@testable import ReactiveReSwiftRouter
class MockRoutable: Routable {
var callsToPushRouteSegment: [(routeElement: RouteElementIdentifier, animated: Bool)] = []
var callsToPopRouteSegment: [(routeElement: RouteElementIdentifier, animated: Bool)] = []
var callsToChangeRouteSegment: [(
from: RouteElementIdentifier,
to: RouteElementIdentifier,
animated: Bool
)] = []
func pushRouteSegment(
_ routeElementIdentifier: RouteElementIdentifier,
routeSpecificStateObserver: RouteSpecificStateObserver?,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler
) -> Routable {
callsToPushRouteSegment.append(
(routeElement: routeElementIdentifier, animated: animated)
)
completionHandler()
return MockRoutable()
}
func popRouteSegment(
_ routeElementIdentifier: RouteElementIdentifier,
routeSpecificStateObserver: RouteSpecificStateObserver?,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler) {
callsToPopRouteSegment.append(
(routeElement: routeElementIdentifier, animated: animated)
)
completionHandler()
}
func changeRouteSegment(
_ from: RouteElementIdentifier,
to: RouteElementIdentifier,
routeSpecificStateObserver: RouteSpecificStateObserver?,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler
) -> Routable {
completionHandler()
callsToChangeRouteSegment.append((from: from, to: to, animated: animated))
return MockRoutable()
}
}
struct FakeAppState {
var navigationState = NavigationState()
}
func fakeReducer(action: Action, state: FakeAppState?) -> FakeAppState {
return state ?? FakeAppState()
}
func appReducer(action: Action, state: FakeAppState?) -> FakeAppState {
return FakeAppState(
navigationState: NavigationReducer.handleAction(action, state: state?.navigationState)
)
}
class TestStoreSubscriber<T> {
var receivedStates: [T] = []
var subscription: ((T) -> Void)!
init() {
subscription = { self.receivedStates.append($0) }
}
}
struct MockRouteSpecificStateObserver: RouteSpecificStateObserver {
public var value: Any
init(withValue value: Any) {
self.value = value
}
}
class SwiftFlowRouterIntegrationTests: QuickSpec {
override func spec() {
describe("routing calls") {
var store: Store<ObservableProperty<FakeAppState>>!
enum Routes: RouteElement {
case tabBarViewController
case secondViewController
}
beforeEach {
store = Store(reducer: appReducer, observable: ObservableProperty(FakeAppState()))
}
describe("setup") {
it("does not request the root view controller when no route is provided") {
class FakeRootRoutable: Routable {
var called = false
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier,
completionHandler: RoutingCompletionHandler) -> Routable {
called = true
return MockRoutable()
}
}
let routable = FakeRootRoutable()
let _ = Router<Any>(rootRoutable: routable)
expect(routable.called).to(beFalse())
}
it("requests the root with identifier when an initial route is provided") {
store.dispatch(
SetRouteAction([RouteIdentifiable(element: Routes.tabBarViewController)])
)
class FakeRootRoutable: Routable {
var calledWithIdentifier: (RouteElementIdentifier?) -> Void
init(calledWithIdentifier: @escaping (RouteElementIdentifier?) -> Void) {
self.calledWithIdentifier = calledWithIdentifier
}
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier,
routeSpecificStateObserver: RouteSpecificStateObserver?,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler) -> Routable {
calledWithIdentifier(routeElementIdentifier)
completionHandler()
return MockRoutable()
}
}
waitUntil(timeout: 2.0) { fullfill in
let rootRoutable = FakeRootRoutable { identifier in
guard let identifier = identifier else {
return
}
if Routes.tabBarViewController == identifier.element{
fullfill()
}
}
let router = Router<Any>(rootRoutable: rootRoutable)
store.observable.subscribe({ state in
router.newState(state: state.navigationState)
})
}
}
it("calls push on the root for a route with two elements") {
store.dispatch(
SetRouteAction([RouteIdentifiable(element: Routes.tabBarViewController),
RouteIdentifiable(element: Routes.secondViewController)])
)
class FakeChildRoutable: Routable {
var calledWithIdentifier: (RouteElementIdentifier?) -> Void
init(calledWithIdentifier: @escaping (RouteElementIdentifier?) -> Void) {
self.calledWithIdentifier = calledWithIdentifier
}
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier,
routeSpecificStateObserver: RouteSpecificStateObserver?,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler) -> Routable {
calledWithIdentifier(routeElementIdentifier)
completionHandler()
return MockRoutable()
}
}
waitUntil(timeout: 5.0) { completion in
let fakeChildRoutable = FakeChildRoutable() { identifier in
guard let identifier = identifier else {
return
}
if identifier.element == Routes.secondViewController {
completion()
}
}
class FakeRootRoutable: Routable {
let injectedRoutable: Routable
init(injectedRoutable: Routable) {
self.injectedRoutable = injectedRoutable
}
func pushRouteSegment(_ routeElementIdentifier: RouteElementIdentifier,
routeSpecificStateObserver: RouteSpecificStateObserver?,
animated: Bool,
completionHandler: @escaping RoutingCompletionHandler) -> Routable {
completionHandler()
return injectedRoutable
}
}
let router = Router<Any>(rootRoutable: FakeRootRoutable(injectedRoutable: fakeChildRoutable))
store.observable.subscribe({ state in
router.newState(state: state.navigationState)
})
}
}
}
}
describe("route specific data") {
var store: Store<ObservableProperty<FakeAppState>>!
enum Routes: RouteElement {
case part1
case part2
}
beforeEach {
store = Store(reducer: appReducer, observable: ObservableProperty(FakeAppState()))
store.observable.subscribe({ state in
print("state update: \(state)")
})
}
context("when setting route specific data") {
let route = [RouteIdentifiable(element: Routes.part1), RouteIdentifiable(element: Routes.part1)]
beforeEach {
store.dispatch(SetRouteSpecificData(route: route,
routeSpecificStateObserver: MockRouteSpecificStateObserver(withValue: "UserID_10")))
}
it("allows accessing the data when providing the expected type") {
var data: String? = nil
if let mockObserver = store.observable.value.navigationState.getRouteSpecificStateObserver(route) as? MockRouteSpecificStateObserver {
data = mockObserver.value as? String
}
expect(data).toEventually(equal("UserID_10"))
}
}
}
describe("configuring animated/unanimated navigation") {
var store: Store<ObservableProperty<FakeAppState>>!
var mockRoutable: MockRoutable!
var router: Router<FakeAppState>!
enum Routes: RouteElement {
case someRoute
}
beforeEach {
store = Store(reducer: appReducer, observable: ObservableProperty(FakeAppState()))
mockRoutable = MockRoutable()
router = Router(rootRoutable: mockRoutable)
store.observable.subscribe({ state in
router.newState(state: state.navigationState)
})
_ = router
}
context("when dispatching an animated route change") {
beforeEach {
store.dispatch(SetRouteAction([RouteIdentifiable(element: Routes.someRoute)], animated: true))
}
it("calls routables asking for an animated presentation") {
expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beTrue())
}
}
context("when dispatching an unanimated route change") {
beforeEach {
store.dispatch(SetRouteAction([RouteIdentifiable(element: Routes.someRoute)], animated: false))
}
it("calls routables asking for an animated presentation") {
expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beFalse())
}
}
context("when dispatching a default route change") {
beforeEach {
store.dispatch(SetRouteAction([RouteIdentifiable(element: Routes.someRoute)]))
}
it("calls routables asking for an animated presentation") {
expect(mockRoutable.callsToPushRouteSegment.last?.animated).toEventually(beTrue())
}
}
}
}
}
| mit | 80f36c19946b8cfc32b60a2cb84d0fe4 | 36.312312 | 154 | 0.515252 | 7.067691 | false | false | false | false |
CCIP-App/CCIP-iOS | OPass/OPassApp.swift | 1 | 3898 | //
// OPassApp.swift
// OPass
//
// Created by 張智堯 on 2022/2/28.
// 2022 OPass.
//
import SwiftUI
import OneSignal
import Firebase
import FirebaseAnalytics
import OSLog
@main
struct OPassApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@AppStorage("UserInterfaceStyle") var interfaceStyle: UIUserInterfaceStyle = .unspecified
@State var url: URL? = nil
init() {
FirebaseApp.configure()
Analytics.setAnalyticsCollectionEnabled(true)
UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).overrideUserInterfaceStyle = interfaceStyle
}
var body: some Scene {
WindowGroup {
ContentView(url: $url)
.onOpenURL { url in
//It seems that both universal link and custom schemed url from firebase are received via onOpenURL, so we must try parse it in both ways.
if DynamicLinks.dynamicLinks().handleUniversalLink(url, completion: { dynamicLink, _ in
if let url = dynamicLink?.url {
UIApplication.currentUIWindow()?.rootViewController?.dismiss(animated: true)
self.url = url
}
}) { return }
if let url = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url)?.url {
UIApplication.currentUIWindow()?.rootViewController?.dismiss(animated: true)
self.url = url
return
}
}
.preferredColorScheme(.init(interfaceStyle))
}
}
}
// Only use this as a last resort. Always try to use SwiftUI lifecycle
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Configure OneSignal
let logger = Logger(subsystem: "app.opass.ccip", category: "OneSignal")
let notificationReceiverBlock: OSNotificationWillShowInForegroundBlock = { notification,_ in
logger.info("Received Notification - \(notification.notificationId ?? "")")
}
let notificationOpenedBlock: OSNotificationOpenedBlock = { result in
// This block gets called when the user reacts to a notification received
let notification: OSNotification = result.notification
var messageTitle = "OneSignal Message"
var fullMessage = notification.body?.copy() as? String ?? ""
if notification.additionalData != nil {
if notification.title != nil {
messageTitle = notification.title ?? ""
}
if let additionData = notification.additionalData as? Dictionary<String, String> {
if let actionSelected = additionData["actionSelected"] {
fullMessage = "\(fullMessage)\nPressed ButtonId:\(actionSelected)"
}
}
}
logger.info("OneSignal Notification \(messageTitle): \(fullMessage)")
}
OneSignal.initWithLaunchOptions(launchOptions)
OneSignal.setAppId("b6213f49-e356-4b48-aa9d-7cf10ce1904d")
OneSignal.setNotificationWillShowInForegroundHandler(notificationReceiverBlock)
OneSignal.setNotificationOpenedHandler(notificationOpenedBlock)
OneSignal.setLocationShared(false)
OneSignal.promptForPushNotifications(userResponse: { accepted in
logger.info("User accepted notifications: \(accepted)")
}, fallbackToSettings: false)
return true
}
}
| gpl-3.0 | 934bcd88c0f53b2f4eb94efe1b97d39c | 40.404255 | 158 | 0.612025 | 5.536273 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/Sensors/SoundIntensitySensor.swift | 1 | 2829 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// A sensor that measures the intensity of sound reaching the microphone.
class SoundIntensitySensor: AudioSensor {
// MARK: - Public
/// Designated initializer.
///
/// - Parameters:
/// - audioCapture: The audio capture to use for measuring sound.
/// - sensorTimer: The sensor timer to use for this sensor.
init(audioCapture: AudioCapture, sensorTimer: SensorTimer) {
let animatingIconView = RelativeScaleAnimationView(iconName: "sensor_audio")
let learnMore = LearnMore(firstParagraph: String.sensorDescFirstParagraphDecibel,
secondParagraph: String.sensorDescSecondParagraphDecibel,
imageName: "learn_more_audio")
super.init(sensorId: "DecibelSource",
name: String.decibel,
textDescription: String.sensorDescShortDecibel,
iconName: "ic_sensor_audio",
animatingIconView: animatingIconView,
unitDescription: String.decibelUnits,
learnMore: learnMore,
audioCapture: audioCapture,
sensorTimer: sensorTimer)
}
// swiftlint:disable vertical_parameter_alignment
override func callListenerBlocksWithAudioSampleBuffer(_
audioSampleBuffer: UnsafeBufferPointer<Int16>,
atMilliseconds milliseconds: Int64) {
// Calculate decibel level. Also, capture the sample count separately to avoid a potential
// divide by zero crash if something were to happen to the unsafe buffer.
var totalSquared: Int64 = 0
var count: Int64 = 0
for sample in audioSampleBuffer {
totalSquared += Int64(sample) * Int64(sample)
count += 1
}
guard count > 0 else { return }
let quadraticMeanPressure = sqrt(Double(totalSquared / count))
// Ensure that the quadratic mean pressure is not zero, which would result in an infinite
// decibel level value.
guard quadraticMeanPressure > 0 else { return }
let decibelLevel = 20 * log10(quadraticMeanPressure)
let dataPoint = DataPoint(x: milliseconds, y: decibelLevel)
callListenerBlocksWithDataPoint(dataPoint)
}
// swiftlint:enable vertical_parameter_alignment
}
| apache-2.0 | 53a2558284847674774243ab84d1de74 | 38.291667 | 94 | 0.696359 | 4.490476 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/TrialDetailHeaderCell.swift | 1 | 5591 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Palettes_Palettes
import third_party_objective_c_material_components_ios_components_Typography_Typography
/// The cell describing a trial, used above the pinned sensor info in TrialDetailViewController.
/// This cell contains a title, timestamp and duration.
class TrialDetailHeaderCell: UICollectionViewCell {
// MARK: - Constants
static let valueFontSize: CGFloat = 22.0
static let descriptionFontSize: CGFloat = 14.0
static let edgeInsets = UIEdgeInsets(top: 8.0, left: 16.0, bottom: 10.0, right: 16.0)
let innerHorizontalSpacing: CGFloat = 10.0
// MARK: - Properties
let durationLabel = UILabel()
let timestampLabel = UILabel()
let titleLabel = UILabel()
/// The total height of this view. Ideally, controllers would cache this value as it will not
/// change for different instances of this view type.
static var height: CGFloat {
var totalHeight = TrialDetailHeaderCell.edgeInsets.top +
TrialDetailHeaderCell.edgeInsets.bottom
let valueFont =
MDCTypography.fontLoader().mediumFont(ofSize: TrialDetailHeaderCell.valueFontSize) ??
UIFont.boldSystemFont(ofSize: TrialDetailHeaderCell.valueFontSize)
totalHeight +=
String.runReviewActivityLabel.labelHeight(withConstrainedWidth: 0, font: valueFont) * 2
totalHeight += SeparatorView.Metrics.dimension
return ceil(totalHeight)
}
// MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
// MARK: - Private
private func configureView() {
backgroundColor = .white
// The title of this trial.
titleLabel.font =
MDCTypography.fontLoader().mediumFont(ofSize: TrialDetailHeaderCell.valueFontSize) ??
UIFont.boldSystemFont(ofSize: TrialDetailHeaderCell.valueFontSize)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
// The duration header.
let durationHeaderLabel = UILabel()
durationHeaderLabel.text = String.runReviewDuration
durationHeaderLabel.font =
MDCTypography.fontLoader().regularFont(ofSize: TrialDetailHeaderCell.descriptionFontSize)
durationHeaderLabel.textAlignment = .right
durationHeaderLabel.textColor = MDCPalette.grey.tint700
durationHeaderLabel.translatesAutoresizingMaskIntoConstraints = false
durationHeaderLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
durationHeaderLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
// The stack view that holds the title on the left and duration header label on the right.
let topStack = UIStackView(arrangedSubviews: [titleLabel, durationHeaderLabel])
topStack.alignment = .center
topStack.spacing = innerHorizontalSpacing
topStack.translatesAutoresizingMaskIntoConstraints = false
// The timestamp for this trial.
timestampLabel.font =
MDCTypography.fontLoader().regularFont(ofSize: TrialDetailHeaderCell.descriptionFontSize)
timestampLabel.textColor = MDCPalette.grey.tint700
timestampLabel.translatesAutoresizingMaskIntoConstraints = false
timestampLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
// The duration of this trial.
durationLabel.font =
MDCTypography.fontLoader().mediumFont(ofSize: TrialDetailHeaderCell.valueFontSize)
durationLabel.textAlignment =
UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? .left : .right
durationLabel.textColor = UIColor.appBarReviewBackgroundColor
durationLabel.translatesAutoresizingMaskIntoConstraints = false
// The stack view that holds the timestamp on the left and the duration on the right.
let bottomStack = UIStackView(arrangedSubviews: [timestampLabel, durationLabel])
bottomStack.alignment = .lastBaseline
bottomStack.spacing = innerHorizontalSpacing
bottomStack.translatesAutoresizingMaskIntoConstraints = false
// The outer stack view that vertically stacks the two rows and pins to the edges of the cell.
let stackView = UIStackView(arrangedSubviews: [topStack, bottomStack])
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.layoutMargins = TrialDetailHeaderCell.edgeInsets
stackView.isLayoutMarginsRelativeArrangement = true
let separator = SeparatorView(direction: .horizontal, style: .dark)
separator.translatesAutoresizingMaskIntoConstraints = false
let outerStackView = UIStackView(arrangedSubviews: [stackView, separator])
contentView.addSubview(outerStackView)
outerStackView.axis = .vertical
outerStackView.translatesAutoresizingMaskIntoConstraints = false
outerStackView.pinToEdgesOfView(contentView)
}
}
| apache-2.0 | 1622f7c2d31a68959c196fc8c44cd263 | 41.356061 | 98 | 0.767483 | 5.134068 | false | false | false | false |
zinyakov/ebmRadio-ios | ebmRadio-ios/StationInfoViewController.swift | 1 | 1926 | //
// StationInfoViewController.swift
// ebmRadio-ios
//
// Created by George Zinyakov on 10/2/16.
// Copyright © 2016 George Zinyakov. All rights reserved.
//
import UIKit
class StationInfoViewController: UIViewController {
var station: Station!
@IBOutlet weak var stationNameLabel: UILabel!
@IBOutlet weak var stationInfoLabel: UILabel!
@IBOutlet weak var stationUrlButton: UIButton!
@IBAction func closeButtonPressed(sender: AnyObject) {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func stationButtonPressed(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: station.websiteURL)!)
}
@IBAction func githubButtonPressed(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "https://github.com/zinyakov")!)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barStyle = .BlackTranslucent
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.backgroundColor = UIColor.blackColor()
self.navigationController?.navigationBar.shadowImage = UIImage()
setUpInfo()
}
func setUpInfo() {
stationNameLabel.text = station.name
stationInfoLabel.text = station.info
let attributes = [NSForegroundColorAttributeName : UIColor.whiteColor(),
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let attributedText = NSAttributedString(string: "ebm-radio.de", attributes: attributes)
stationUrlButton.setAttributedTitle(attributedText, forState: .Normal)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
| mit | 08edf86a14e8006b0b4fdf9195bfc87c | 34 | 103 | 0.708052 | 5.362117 | false | false | false | false |
miktap/pepe-p06 | PePeP06/PePeP06/Taso/Models/TasoPlayer.swift | 1 | 1402 | //
// TasoPlayer.swift
// PePeP06
//
// Created by Mikko Tapaninen on 24/12/2017.
//
import Foundation
import ObjectMapper
struct TasoPlayer: Mappable, Hashable, CustomStringConvertible {
// MARK: - Properties
var player_id: String!
var player_name: String?
var first_name: String?
var last_name: String?
var shirt_number: String?
var matches: String?
var goals: String?
var assists: String?
var warnings: String?
var suspensions: String?
var hashValue: Int {return player_id.hashValue}
var description: String {return "\(player_id!)/\(first_name ?? "")"}
// MARK: - Mappable
init?(map: Map) {
if map.JSON["player_id"] == nil {
return nil
}
}
mutating func mapping(map: Map) {
player_id <- map["player_id"]
player_name <- map["player_name"]
first_name <- map["first_name"]
last_name <- map["last_name"]
shirt_number <- map["shirt_number"]
matches <- map["matches"]
goals <- map["goals"]
assists <- map["assists"]
warnings <- map["warnings"]
suspensions <- map["suspensions"]
}
// MARK: - Equatable
static func ==(lhs: TasoPlayer, rhs: TasoPlayer) -> Bool {
return lhs.player_id == rhs.player_id
}
}
| mit | 577cafa4d054c280db9dd895ced31460 | 24.035714 | 72 | 0.547789 | 3.949296 | false | false | false | false |
alessioros/mobilecodegenerator3 | examples/BookShelf/ios/completed/BookShelf/BookShelf/ShelfViewController.swift | 1 | 2731 | //
// ShelfViewController.swift
// BookShelf
//
// Created by alessio rossotti on 22/08/17.
// Copyright © 2017 polimi. All rights reserved.
//
import UIKit
class ShelfViewController: UITableViewController
{
@IBOutlet weak var navBarItem: UINavigationItem!
@IBOutlet weak var addButton: UIBarButtonItem!
var shelfName: String = ""
var bookTitle: String = ""
var book: Book? = nil
var bookListContents: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.reloadBooks()
navBarItem.title = shelfName
}
override func viewWillAppear(_ animated: Bool) {
self.reloadBooks()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = bookListContents[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bookListContents.count
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
tableView.deleteRows(at: [indexPath], with: .bottom)
DatabaseHandler().deleteBook(isbn: bookListContents[indexPath.row])
bookListContents.remove(at: indexPath.row)
}
}
func reloadBooks(){
bookListContents = []
let books = DatabaseHandler().loadShelfBooks(shelfName: shelfName)
for book in books {
bookListContents.append(book.title!)
}
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRow(at: indexPath!) as UITableViewCell!;
bookTitle = (currentCell?.textLabel?.text!)!
book = DatabaseHandler().loadBookByTitle(title: bookTitle)
performSegue(withIdentifier: "BookDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "BookDetail") {
let vc = segue.destination as! BookDetailViewController
vc.book = book
}
if (segue.identifier == "addBook") {
let vc = segue.destination as! AddBookViewController
vc.shelfName = shelfName
}
}
}
| gpl-3.0 | 687763c85c4ea402a02a7f32efb5cfff | 29.333333 | 136 | 0.632601 | 5.180266 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTReferenceTimeInformation.swift | 1 | 3921 | //
// GATTReferenceTimeInformation.swift
// Bluetooth
//
// Created by Carlos Duclos on 7/6/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Reference Time Information
- SeeAlso: [Reference Time Information](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.reference_time_information.xml)
*/
@frozen
public struct GATTReferenceTimeInformation: GATTCharacteristic, Equatable {
internal static let length = GATTTimeSource.length + GATTTimeAccuracy.length + 1 + 1
public static var uuid: BluetoothUUID { return .referenceTimeInformation }
public var timeSource: GATTTimeSource
public var timeAccuracy: GATTTimeAccuracy
public var daysSinceUpdate: Day
public var hoursSinceUpdate: Hour
public init(timeSource: GATTTimeSource,
timeAccuracy: GATTTimeAccuracy,
daysSinceUpdate: Day,
hoursSinceUpdate: Hour) {
self.timeSource = timeSource
self.timeAccuracy = timeAccuracy
self.daysSinceUpdate = daysSinceUpdate
self.hoursSinceUpdate = hoursSinceUpdate
}
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
guard let timeSource = GATTTimeSource(data: data.subdataNoCopy(in: (0 ..< GATTTimeSource.length)))
else { return nil }
guard let timeAccuracy = GATTTimeAccuracy(data: data.subdataNoCopy(in: (GATTTimeAccuracy.length ..< 2)))
else { return nil }
let daysSinceUpdate = Day(rawValue: data[2])
guard let hoursSinceUpdate = Hour(rawValue: data[3])
else { return nil }
self.init(timeSource: timeSource,
timeAccuracy: timeAccuracy,
daysSinceUpdate: daysSinceUpdate,
hoursSinceUpdate: hoursSinceUpdate)
}
public var data: Data {
return timeSource.data +
timeAccuracy.data +
Data([daysSinceUpdate.rawValue]) +
Data([hoursSinceUpdate.rawValue])
}
}
extension GATTReferenceTimeInformation {
public struct Day: BluetoothUnit, Equatable, Hashable {
public static var unitType: UnitIdentifier { return .day }
public static var more: Day { return 255 }
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
}
extension GATTReferenceTimeInformation.Day: CustomStringConvertible {
public var description: String {
return rawValue.description
}
}
extension GATTReferenceTimeInformation.Day: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt8) {
self.init(rawValue: value)
}
}
extension GATTReferenceTimeInformation {
public struct Hour: BluetoothUnit, Equatable, Hashable {
public static var unitType: UnitIdentifier { return .hour }
public static let min = Hour(0)
public static let max = Hour(23)
public static let moreHours = Hour(255)
public let rawValue: UInt8
public init?(rawValue: UInt8) {
guard rawValue == Hour.moreHours.rawValue
|| (Hour.min.rawValue <= rawValue && Hour.max.rawValue >= rawValue)
else { return nil }
self.rawValue = rawValue
}
fileprivate init(_ unsafe: UInt8) {
self.rawValue = unsafe
}
}
}
extension GATTReferenceTimeInformation.Hour: CustomStringConvertible {
public var description: String {
return rawValue.description
}
}
| mit | 67639979ba31279767dccf0ac1bdcee8 | 26.605634 | 171 | 0.607653 | 5.084306 | false | false | false | false |
think-dev/MadridBUS | MadridBUS/Source/UI/Commons/SpinnerPresentation.swift | 1 | 2203 | import UIKit
enum SpinnerTransitionType {
case presenting, dismissing
}
class SpinnerPresentationBase: NSObject, UIViewControllerAnimatedTransitioning {
var duration: TimeInterval
var isPresenting: Bool
var originFrame: CGRect
init(withDuration duration: TimeInterval, forTransitionType type: SpinnerTransitionType, originFrame: CGRect) {
self.duration = duration
self.isPresenting = type == .presenting
self.originFrame = originFrame
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromView = transitionContext.viewController(forKey: .from)!.view
let toView = transitionContext.viewController(forKey: .to)!.view
fromView?.isUserInteractionEnabled = false
toView?.isUserInteractionEnabled = false
let detailView = self.isPresenting ? toView : fromView
detailView?.alpha = self.isPresenting ? 0.0 : 1.0
if self.isPresenting {
containerView.addSubview(toView!)
} else {
containerView.insertSubview(toView!, belowSubview: fromView!)
}
detailView?.frame.origin = self.isPresenting ? self.originFrame.origin : CGPoint(x: 0, y: 0)
detailView?.frame.size.width = self.isPresenting ? self.originFrame.size.width : containerView.bounds.width
detailView?.layoutIfNeeded()
UIView.animate(withDuration: self.duration, animations: { () -> Void in
detailView?.frame = self.isPresenting ? containerView.bounds : self.originFrame
detailView?.layoutIfNeeded()
detailView?.alpha = self.isPresenting ? 1.0 : 0.0
}) { (completed: Bool) -> Void in
fromView?.isUserInteractionEnabled = true
toView?.isUserInteractionEnabled = true
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit | 16c84458f9cc6fb27b0a3a4ff579f128 | 38.339286 | 115 | 0.677258 | 5.828042 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.